Index: trunk/source/Lib/TAppCommon/program_options_lite.cpp
===================================================================
--- trunk/source/Lib/TAppCommon/program_options_lite.cpp	(revision 499)
+++ trunk/source/Lib/TAppCommon/program_options_lite.cpp	(revision 540)
@@ -38,4 +38,5 @@
 #include <list>
 #include <map>
+#include <algorithm>
 #include "program_options_lite.h"
 
Index: trunk/source/Lib/TLibCommon/CommonDef.h
===================================================================
--- trunk/source/Lib/TLibCommon/CommonDef.h	(revision 499)
+++ trunk/source/Lib/TLibCommon/CommonDef.h	(revision 540)
@@ -40,5 +40,4 @@
 
 #include <algorithm>
-
 #if _MSC_VER > 1000
 // disable "signed and unsigned mismatch"
@@ -57,7 +56,8 @@
 
 #if SVC_EXTENSION
-#define NV_VERSION        "4.0"                 ///< Current software version
+#include <vector>
+#define NV_VERSION        "4.1"                 ///< Current software version
 #else
-#define NV_VERSION        "12.0"                ///< Current software version
+#define NV_VERSION        "12.1"                ///< Current software version
 #endif
 
@@ -209,5 +209,5 @@
   
   NAL_UNIT_CODED_SLICE_TSA_N,     // 2
-  NAL_UNIT_CODED_SLICE_TLA_R,       // 3
+  NAL_UNIT_CODED_SLICE_TSA_R,       // 3
   
   NAL_UNIT_CODED_SLICE_STSA_N,    // 4
@@ -280,4 +280,33 @@
 };
 
+#if OUTPUT_LAYER_SET_INDEX
+class CommonDecoderParams
+{
+  Int m_targetLayerId;
+  Int m_outputLayerSetIdx;
+  std::vector<Int> *m_targetDecLayerIdSet; 
+  Bool m_valueCheckedFlag;
+public:
+  CommonDecoderParams(): 
+    m_targetLayerId(0)
+    , m_outputLayerSetIdx(-1)
+    , m_targetDecLayerIdSet(NULL)
+    , m_valueCheckedFlag(false)
+ {}
+
+  Void setTargetLayerId(const Int x) { m_targetLayerId = x;   }
+  Int  getTargetLayerId()            { return m_targetLayerId;}
+  
+  Void setOutputLayerSetIdx(const Int x) { m_outputLayerSetIdx = x;   }
+  Int  getOutputLayerSetIdx()            { return m_outputLayerSetIdx;}
+
+  Void               setTargetDecLayerIdSet(std::vector<Int> *x) { m_targetDecLayerIdSet = x;   }
+  std::vector<Int>*  getTargetDecLayerIdSet()                    { return m_targetDecLayerIdSet;}
+  
+  Void setValueCheckedFlag(const Bool x) { m_valueCheckedFlag = x;   }
+  Bool getValueCheckedFlag()            { return m_valueCheckedFlag;}
+  
+};
+#endif
 //! \}
 
Index: trunk/source/Lib/TLibCommon/NAL.h
===================================================================
--- trunk/source/Lib/TLibCommon/NAL.h	(revision 499)
+++ trunk/source/Lib/TLibCommon/NAL.h	(revision 540)
@@ -76,5 +76,5 @@
     return m_nalUnitType == NAL_UNIT_CODED_SLICE_TRAIL_R
         || m_nalUnitType == NAL_UNIT_CODED_SLICE_TRAIL_N
-        || m_nalUnitType == NAL_UNIT_CODED_SLICE_TLA_R
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_TSA_R
         || m_nalUnitType == NAL_UNIT_CODED_SLICE_TSA_N
         || m_nalUnitType == NAL_UNIT_CODED_SLICE_STSA_R
Index: trunk/source/Lib/TLibCommon/TComDataCU.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComDataCU.cpp	(revision 499)
+++ trunk/source/Lib/TLibCommon/TComDataCU.cpp	(revision 540)
@@ -309,5 +309,5 @@
   }
 }
-
+#if !HM_CLEANUP_SAO
 const NDBFBlockInfo& NDBFBlockInfo::operator= (const NDBFBlockInfo& src)
 {
@@ -328,5 +328,5 @@
 }
 
-
+#endif
 // ====================================================================================================================
 // Public member functions
@@ -3638,5 +3638,5 @@
   return getPic()->getPicSym()->getInverseCUOrderMap(m_uiCUAddr)*(1<<(m_pcSlice->getSPS()->getMaxCUDepth()<<1))+m_uiAbsIdxInLCU; 
 }
-
+#if !HM_CLEANUP_SAO
 /** Set neighboring blocks availabilities for non-deblocked filtering 
  * \param numLCUInPicWidth number of LCUs in picture width
@@ -4008,4 +4008,6 @@
 }
 
+#endif
+
 #if SVC_EXTENSION
 TComDataCU*  TComDataCU::getBaseColCU( UInt refLayerIdc, UInt uiCuAbsPartIdx, UInt &uiCUAddrBase, UInt &uiAbsPartIdxBase, Int iMotionMapping )
@@ -4028,6 +4030,11 @@
 #endif
 
+#if O0098_SCALED_REF_LAYER_ID
+  Int leftStartL = getSlice()->getSPS()->getScaledRefLayerWindowForLayer(getSlice()->getVPS()->getRefLayerId(getSlice()->getLayerId(), refLayerIdc)).getWindowLeftOffset();
+  Int topStartL  = getSlice()->getSPS()->getScaledRefLayerWindowForLayer(getSlice()->getVPS()->getRefLayerId(getSlice()->getLayerId(), refLayerIdc)).getWindowTopOffset();
+#else
   Int leftStartL = this->getSlice()->getSPS()->getScaledRefLayerWindow(refLayerIdc).getWindowLeftOffset();
   Int topStartL  = this->getSlice()->getSPS()->getScaledRefLayerWindow(refLayerIdc).getWindowTopOffset();
+#endif
   Int iBX = ((uiPelX - leftStartL)*g_posScalingFactor[refLayerIdc][0] + (1<<15)) >> 16;
   Int iBY = ((uiPelY - topStartL )*g_posScalingFactor[refLayerIdc][1] + (1<<15)) >> 16;
Index: trunk/source/Lib/TLibCommon/TComDataCU.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComDataCU.h	(revision 499)
+++ trunk/source/Lib/TLibCommon/TComDataCU.h	(revision 540)
@@ -55,4 +55,5 @@
 //! \{
 
+#if !HM_CLEANUP_SAO
 // ====================================================================================================================
 // Non-deblocking in-loop filter processing block data structure
@@ -92,4 +93,5 @@
   const NDBFBlockInfo& operator= (const NDBFBlockInfo& src);  //!< "=" operator
 };
+#endif
 
 
@@ -159,7 +161,8 @@
   Pel*          m_pcIPCMSampleCr;     ///< PCM sample buffer (Cr)
 
+#if !HM_CLEANUP_SAO
   Int*          m_piSliceSUMap;       ///< pointer of slice ID map
   std::vector<NDBFBlockInfo> m_vNDFBlock;
-
+#endif
   // -------------------------------------------------------------------------------------------------------------------
   // neighbour access variables
@@ -389,4 +392,5 @@
   Void          setIPCMFlagSubParts   (Bool bIpcmFlag, UInt uiAbsPartIdx, UInt uiDepth);
 
+#if !HM_CLEANUP_SAO
   /// get slice ID for SU
   Int           getSUSliceID          (UInt uiIdx)              {return m_piSliceSUMap[uiIdx];      } 
@@ -403,4 +407,5 @@
                                           ,Bool bTopTileBoundary, Bool bDownTileBoundary, Bool bLeftTileBoundary, Bool bRightTileBoundary
                                           ,Bool bIndependentTileBoundaryEnabled );
+#endif
   // -------------------------------------------------------------------------------------------------------------------
   // member functions for accessing partition information
Index: trunk/source/Lib/TLibCommon/TComPic.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComPic.cpp	(revision 499)
+++ trunk/source/Lib/TLibCommon/TComPic.cpp	(revision 540)
@@ -59,4 +59,5 @@
 , m_bNeededForOutput                      (false)
 , m_uiCurrSliceIdx                        (0)
+#if !HM_CLEANUP_SAO
 , m_pSliceSUMap                           (NULL)
 , m_pbValidSlice                          (NULL)
@@ -65,4 +66,5 @@
 , m_bIndependentTileBoundaryForNDBFilter  (false)
 , m_pNDBFilterYuvTmp                      (NULL)
+#endif
 , m_bCheckLTMSB                           (false)
 {
@@ -212,5 +214,12 @@
   } 
 }
-
+#if HM_CLEANUP_SAO
+Bool  TComPic::getSAOMergeAvailability(Int currAddr, Int mergeAddr)
+{
+  Bool mergeCtbInSliceSeg = (mergeAddr >= getPicSym()->getCUOrderMap(getCU(currAddr)->getSlice()->getSliceCurStartCUAddr()/getNumPartInCU()));
+  Bool mergeCtbInTile     = (getPicSym()->getTileIdxMap(mergeAddr) == getPicSym()->getTileIdxMap(currAddr));
+  return (mergeCtbInSliceSeg && mergeCtbInTile);
+}
+#else
 /** Create non-deblocked filter information
  * \param pSliceStartAddress array for storing slice start addresses
@@ -548,4 +557,5 @@
 
 }
+#endif
 
 #if SVC_EXTENSION
Index: trunk/source/Lib/TLibCommon/TComPic.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComPic.h	(revision 499)
+++ trunk/source/Lib/TLibCommon/TComPic.h	(revision 540)
@@ -75,4 +75,5 @@
   Bool                  m_bNeededForOutput;
   UInt                  m_uiCurrSliceIdx;         // Index of current slice
+#if !HM_CLEANUP_SAO
   Int*                  m_pSliceSUMap;
   Bool*                 m_pbValidSlice;
@@ -81,4 +82,5 @@
   Bool                  m_bIndependentTileBoundaryForNDBFilter;
   TComPicYuv*           m_pNDBFilterYuvTmp;    //!< temporary picture buffer when non-cross slice/tile boundary in-loop filtering is enabled
+#endif
   Bool                  m_bCheckLTMSB;
   
@@ -199,4 +201,7 @@
   Window&       getDefDisplayWindow()   { return m_defaultDisplayWindow; }
 
+#if HM_CLEANUP_SAO
+  Bool          getSAOMergeAvailability(Int currAddr, Int mergeAddr);
+#else
   Void          createNonDBFilterInfo   (std::vector<Int> sliceStartAddress, Int sliceGranularityDepth
                                         ,std::vector<Bool>* LFCrossSliceBoundary
@@ -211,4 +216,5 @@
   TComPicYuv*   getYuvPicBufferForIndependentBoundaryProcessing()             {return m_pNDBFilterYuvTmp;}
   std::vector<TComDataCU*>& getOneSliceCUDataForNDBFilter      (Int sliceID) { return m_vSliceCUDataLink[sliceID];}
+#endif
 
   /* field coding parameters*/
Index: trunk/source/Lib/TLibCommon/TComPicSym.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComPicSym.cpp	(revision 499)
+++ trunk/source/Lib/TLibCommon/TComPicSym.cpp	(revision 540)
@@ -67,4 +67,7 @@
 ,m_puiTileIdxMap(NULL)
 ,m_puiInverseCUOrderMap(NULL)
+#if HM_CLEANUP_SAO
+,m_saoBlkParams(NULL)
+#endif
 {};
 
@@ -127,5 +130,10 @@
     m_puiInverseCUOrderMap[i] = i;
   }
+
+#if HM_CLEANUP_SAO
+  m_saoBlkParams = new SAOBlkParam[m_uiNumCUsInFrame];
+#else
   m_saoParam = NULL;
+#endif
 }
 
@@ -183,4 +191,10 @@
   m_puiInverseCUOrderMap = NULL;
   
+#if HM_CLEANUP_SAO
+  if(m_saoBlkParams)
+  {
+    delete[] m_saoBlkParams; m_saoBlkParams = NULL;
+  }
+#else
   if (m_saoParam)
   {
@@ -189,4 +203,5 @@
     m_saoParam = NULL;
   }
+#endif
 }
 
@@ -332,4 +347,114 @@
 }
 
+
+#if HM_CLEANUP_SAO
+Void TComPicSym::deriveLoopFilterBoundaryAvailibility(Int ctu,
+                                                      Bool& isLeftAvail,
+                                                      Bool& isRightAvail,
+                                                      Bool& isAboveAvail,
+                                                      Bool& isBelowAvail,
+                                                      Bool& isAboveLeftAvail,
+                                                      Bool& isAboveRightAvail,
+                                                      Bool& isBelowLeftAvail,
+                                                      Bool& isBelowRightAvail
+                                                      )
+{
+
+  isLeftAvail      = (ctu % m_uiWidthInCU != 0);
+  isRightAvail     = (ctu % m_uiWidthInCU != m_uiWidthInCU-1);
+  isAboveAvail     = (ctu >= m_uiWidthInCU );
+  isBelowAvail     = (ctu <  m_uiNumCUsInFrame - m_uiWidthInCU);
+  isAboveLeftAvail = (isAboveAvail && isLeftAvail);
+  isAboveRightAvail= (isAboveAvail && isRightAvail);
+  isBelowLeftAvail = (isBelowAvail && isLeftAvail);
+  isBelowRightAvail= (isBelowAvail && isRightAvail);
+
+  Bool isLoopFiltAcrossTilePPS = getCU(ctu)->getSlice()->getPPS()->getLoopFilterAcrossTilesEnabledFlag();
+
+  {
+    TComDataCU* ctuCurr  = getCU(ctu);
+    TComDataCU* ctuLeft  = isLeftAvail ?getCU(ctu-1):NULL;
+    TComDataCU* ctuRight = isRightAvail?getCU(ctu+1):NULL;
+    TComDataCU* ctuAbove = isAboveAvail?getCU(ctu-m_uiWidthInCU):NULL;
+    TComDataCU* ctuBelow = isBelowAvail?getCU(ctu+m_uiWidthInCU):NULL;
+    TComDataCU* ctuAboveLeft  = isAboveLeftAvail ? getCU(ctu-m_uiWidthInCU-1):NULL;
+    TComDataCU* ctuAboveRigtht= isAboveRightAvail? getCU(ctu-m_uiWidthInCU+1):NULL;
+    TComDataCU* ctuBelowLeft  = isBelowLeftAvail ? getCU(ctu+m_uiWidthInCU-1):NULL;
+    TComDataCU* ctuBelowRight = isBelowRightAvail? getCU(ctu+m_uiWidthInCU+1):NULL;
+
+    {
+      //left
+      if(ctuLeft != NULL)
+      {
+        isLeftAvail = (ctuCurr->getSlice()->getSliceCurStartCUAddr() != ctuLeft->getSlice()->getSliceCurStartCUAddr())?ctuCurr->getSlice()->getLFCrossSliceBoundaryFlag():true;
+      }
+      //above
+      if(ctuAbove != NULL)
+      {
+        isAboveAvail = (ctuCurr->getSlice()->getSliceCurStartCUAddr() != ctuAbove->getSlice()->getSliceCurStartCUAddr())?ctuCurr->getSlice()->getLFCrossSliceBoundaryFlag():true;
+      }
+      //right
+      if(ctuRight != NULL)
+      {
+        isRightAvail = (ctuCurr->getSlice()->getSliceCurStartCUAddr() != ctuRight->getSlice()->getSliceCurStartCUAddr())?ctuRight->getSlice()->getLFCrossSliceBoundaryFlag():true;
+      }
+      //below
+      if(ctuBelow != NULL)
+      {
+        isBelowAvail = (ctuCurr->getSlice()->getSliceCurStartCUAddr() != ctuBelow->getSlice()->getSliceCurStartCUAddr())?ctuBelow->getSlice()->getLFCrossSliceBoundaryFlag():true;
+      }
+      //above-left
+      if(ctuAboveLeft != NULL)
+      {
+        isAboveLeftAvail = (ctuCurr->getSlice()->getSliceCurStartCUAddr() != ctuAboveLeft->getSlice()->getSliceCurStartCUAddr())?ctuCurr->getSlice()->getLFCrossSliceBoundaryFlag():true;
+      }
+      //below-right
+      if(ctuBelowRight != NULL)
+      {
+        isBelowRightAvail = (ctuCurr->getSlice()->getSliceCurStartCUAddr() != ctuBelowRight->getSlice()->getSliceCurStartCUAddr())?ctuBelowRight->getSlice()->getLFCrossSliceBoundaryFlag():true;
+      }
+
+
+      //above-right
+      if(ctuAboveRigtht != NULL)
+      {
+        Int curSliceStartTS  = getCUOrderMap(ctuCurr->getSlice()->getSliceCurStartCUAddr()/m_uiNumPartitions);
+        Int aboveRigthtSliceStartTS = getCUOrderMap(ctuAboveRigtht->getSlice()->getSliceCurStartCUAddr()/m_uiNumPartitions);
+
+        isAboveRightAvail = (curSliceStartTS == aboveRigthtSliceStartTS)?(true):
+          (
+          (curSliceStartTS > aboveRigthtSliceStartTS)?(ctuCurr->getSlice()->getLFCrossSliceBoundaryFlag())
+          :(ctuAboveRigtht->getSlice()->getLFCrossSliceBoundaryFlag())
+          );          
+      }
+      //below-left
+      if(ctuBelowLeft != NULL)
+      {
+        Int curSliceStartTS       = getCUOrderMap(ctuCurr->getSlice()->getSliceCurStartCUAddr()/m_uiNumPartitions);
+        Int belowLeftSliceStartTS = getCUOrderMap(ctuBelowLeft->getSlice()->getSliceCurStartCUAddr()/m_uiNumPartitions);
+
+        isBelowLeftAvail = (curSliceStartTS == belowLeftSliceStartTS)?(true):
+          (
+          (curSliceStartTS > belowLeftSliceStartTS)?(ctuCurr->getSlice()->getLFCrossSliceBoundaryFlag())
+          :(ctuBelowLeft->getSlice()->getLFCrossSliceBoundaryFlag())
+          );
+      }        
+    }
+
+    if(!isLoopFiltAcrossTilePPS)
+    {      
+      isLeftAvail      = (!isLeftAvail      ) ?false:(getTileIdxMap( ctuLeft->getAddr()         ) == getTileIdxMap( ctu ));
+      isAboveAvail     = (!isAboveAvail     ) ?false:(getTileIdxMap( ctuAbove->getAddr()        ) == getTileIdxMap( ctu ));
+      isRightAvail     = (!isRightAvail     ) ?false:(getTileIdxMap( ctuRight->getAddr()        ) == getTileIdxMap( ctu ));
+      isBelowAvail     = (!isBelowAvail     ) ?false:(getTileIdxMap( ctuBelow->getAddr()        ) == getTileIdxMap( ctu ));
+      isAboveLeftAvail = (!isAboveLeftAvail ) ?false:(getTileIdxMap( ctuAboveLeft->getAddr()    ) == getTileIdxMap( ctu ));
+      isAboveRightAvail= (!isAboveRightAvail) ?false:(getTileIdxMap( ctuAboveRigtht->getAddr()  ) == getTileIdxMap( ctu ));
+      isBelowLeftAvail = (!isBelowLeftAvail ) ?false:(getTileIdxMap( ctuBelowLeft->getAddr()    ) == getTileIdxMap( ctu ));
+      isBelowRightAvail= (!isBelowRightAvail) ?false:(getTileIdxMap( ctuBelowRight->getAddr()   ) == getTileIdxMap( ctu ));
+    }
+  }
+
+}
+#else
 Void TComPicSym::allocSaoParam(TComSampleAdaptiveOffset *sao)
 {
@@ -337,4 +462,5 @@
   sao->allocSaoParam(m_saoParam);
 }
+#endif
 
 TComTile::TComTile()
Index: trunk/source/Lib/TLibCommon/TComPicSym.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComPicSym.h	(revision 499)
+++ trunk/source/Lib/TLibCommon/TComPicSym.h	(revision 540)
@@ -112,5 +112,10 @@
   UInt*         m_puiInverseCUOrderMap;
 
+#if HM_CLEANUP_SAO
+  SAOBlkParam *m_saoBlkParams;
+#else
   SAOParam *m_saoParam;
+#endif
+
 public:
   Void        create  ( Int iPicWidth, Int iPicHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth );
@@ -171,6 +176,13 @@
   Void         xInitTiles();
   UInt         xCalculateNxtCUAddr( UInt uiCurrCUAddr );
+#if HM_CLEANUP_SAO
+  SAOBlkParam* getSAOBlkParam() { return m_saoBlkParams;}
+  Void deriveLoopFilterBoundaryAvailibility(Int ctu, Bool& isLeftAvail,Bool& isRightAvail,Bool& isAboveAvail,Bool& isBelowAvail,Bool& isAboveLeftAvail,Bool& isAboveRightAvail,Bool& isBelowLeftAvail,Bool& isBelowRightAvail);
+#else
   Void allocSaoParam(TComSampleAdaptiveOffset *sao);
   SAOParam *getSaoParam() { return m_saoParam; }
+#endif
+
+
 };// END CLASS DEFINITION TComPicSym
 
Index: trunk/source/Lib/TLibCommon/TComRdCost.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComRdCost.cpp	(revision 499)
+++ trunk/source/Lib/TLibCommon/TComRdCost.cpp	(revision 540)
@@ -330,9 +330,5 @@
 
 // Setting the Distortion Parameter for Inter (subpel ME with step)
-#if NS_HAD
-Void TComRdCost::setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, Int iStep, DistParam& rcDistParam, Bool bHADME, Bool bUseNSHAD )
-#else
 Void TComRdCost::setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, Int iStep, DistParam& rcDistParam, Bool bHADME )
-#endif
 {
 #if O0194_WEIGHTED_PREDICTION_CGS
@@ -353,7 +349,4 @@
   rcDistParam.iCols    = pcPatternKey->getROIYWidth();
   rcDistParam.iRows    = pcPatternKey->getROIYHeight();
-#if NS_HAD
-  rcDistParam.bUseNSHAD = bUseNSHAD;
-#endif
 
   // set distortion function
@@ -386,9 +379,5 @@
 
 Void
-#if NS_HAD
-TComRdCost::setDistParam( DistParam& rcDP, Pel* p1, Int iStride1, Pel* p2, Int iStride2, Int iWidth, Int iHeight, Bool bHadamard, Bool bUseNSHAD )
-#else
 TComRdCost::setDistParam( DistParam& rcDP, Int bitDepth, Pel* p1, Int iStride1, Pel* p2, Int iStride2, Int iWidth, Int iHeight, Bool bHadamard )
-#endif
 {
   rcDP.pOrg       = p1;
@@ -402,7 +391,4 @@
   rcDP.bitDepth   = bitDepth;
   rcDP.DistFunc   = m_afpDistortFunc[ ( bHadamard ? DF_HADS : DF_SADS ) + g_aucConvertToBit[ iWidth ] + 1 ];
-#if NS_HAD
-  rcDP.bUseNSHAD  = bUseNSHAD;
-#endif
 }
 
@@ -453,9 +439,5 @@
 }
 
-#if WEIGHTED_CHROMA_DISTORTION
 UInt TComRdCost::getDistPart(Int bitDepth, Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, TextType eText, DFunc eDFunc)
-#else
-UInt TComRdCost::getDistPart(Int bitDepth, Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, DFunc eDFunc )
-#endif
 {
   DistParam cDtParam;
@@ -471,5 +453,4 @@
   cDtParam.bitDepth = bitDepth;
 
-#if WEIGHTED_CHROMA_DISTORTION
   if (eText == TEXT_CHROMA_U)
   {
@@ -484,26 +465,5 @@
     return cDtParam.DistFunc( &cDtParam );
   }
-#else
-  return cDtParam.DistFunc( &cDtParam );
-#endif
-}
-
-#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
-UInt TComRdCost::getSADPart ( Int bitDepth, Pel* pelCur, Int curStride,  Pel* pelOrg, Int orgStride, UInt width, UInt height )
-{
-  UInt SAD = 0;
-  Int shift = DISTORTION_PRECISION_ADJUSTMENT(bitDepth-8);
-  for ( Int i=0; i<height; i++ )
-  {
-    for( Int j=0; j<width; j++ )
-    {
-      SAD += abs((pelCur[j] - pelOrg[j])) >> shift;
-    }
-    pelCur = pelCur + curStride;
-    pelOrg = pelOrg + orgStride;
-  }
-  return SAD;
-}
-#endif
+}
 
 // ====================================================================================================================
@@ -1579,252 +1539,4 @@
 }
 
-#if NS_HAD
-UInt TComRdCost::xCalcHADs16x4( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
-{
-  Int k, i, j, jj, sad=0;
-  Int diff[64], m1[4][16], m2[4][16];
-  assert( iStep == 1 );
-  for( k = 0; k < 64; k += 16 )
-  {
-    diff[k+0] = piOrg[0] - piCur[0];
-    diff[k+1] = piOrg[1] - piCur[1];
-    diff[k+2] = piOrg[2] - piCur[2];
-    diff[k+3] = piOrg[3] - piCur[3];
-    diff[k+4] = piOrg[4] - piCur[4];
-    diff[k+5] = piOrg[5] - piCur[5];
-    diff[k+6] = piOrg[6] - piCur[6];
-    diff[k+7] = piOrg[7] - piCur[7];
-
-    diff[k+8]  = piOrg[8]  - piCur[8] ;
-    diff[k+9]  = piOrg[9]  - piCur[9] ;
-    diff[k+10] = piOrg[10] - piCur[10];
-    diff[k+11] = piOrg[11] - piCur[11];
-    diff[k+12] = piOrg[12] - piCur[12];
-    diff[k+13] = piOrg[13] - piCur[13];
-    diff[k+14] = piOrg[14] - piCur[14];
-    diff[k+15] = piOrg[15] - piCur[15];
-
-    piCur += iStrideCur;
-    piOrg += iStrideOrg;
-  }
-
-  //horizontal
-  for (j=0; j < 4; j++)
-  {
-    jj = j << 4;
-
-    m2[j][0]  = diff[jj  ] + diff[jj+8];
-    m2[j][1]  = diff[jj+1] + diff[jj+9];
-    m2[j][2]  = diff[jj+2] + diff[jj+10];
-    m2[j][3]  = diff[jj+3] + diff[jj+11];
-    m2[j][4]  = diff[jj+4] + diff[jj+12];
-    m2[j][5]  = diff[jj+5] + diff[jj+13];
-    m2[j][6]  = diff[jj+6] + diff[jj+14];
-    m2[j][7]  = diff[jj+7] + diff[jj+15];
-    m2[j][8]  = diff[jj  ] - diff[jj+8];
-    m2[j][9]  = diff[jj+1] - diff[jj+9];
-    m2[j][10] = diff[jj+2] - diff[jj+10];
-    m2[j][11] = diff[jj+3] - diff[jj+11];
-    m2[j][12] = diff[jj+4] - diff[jj+12];
-    m2[j][13] = diff[jj+5] - diff[jj+13];
-    m2[j][14] = diff[jj+6] - diff[jj+14];
-    m2[j][15] = diff[jj+7] - diff[jj+15];
-
-    m1[j][0]  = m2[j][0]  + m2[j][4];
-    m1[j][1]  = m2[j][1]  + m2[j][5];
-    m1[j][2]  = m2[j][2]  + m2[j][6];
-    m1[j][3]  = m2[j][3]  + m2[j][7];
-    m1[j][4]  = m2[j][0]  - m2[j][4];
-    m1[j][5]  = m2[j][1]  - m2[j][5];
-    m1[j][6]  = m2[j][2]  - m2[j][6];
-    m1[j][7]  = m2[j][3]  - m2[j][7];
-    m1[j][8]  = m2[j][8]  + m2[j][12];
-    m1[j][9]  = m2[j][9]  + m2[j][13];
-    m1[j][10] = m2[j][10] + m2[j][14];
-    m1[j][11] = m2[j][11] + m2[j][15];
-    m1[j][12] = m2[j][8]  - m2[j][12];
-    m1[j][13] = m2[j][9]  - m2[j][13];
-    m1[j][14] = m2[j][10] - m2[j][14];
-    m1[j][15] = m2[j][11] - m2[j][15];
-
-    m2[j][0]  = m1[j][0]  + m1[j][2];
-    m2[j][1]  = m1[j][1]  + m1[j][3];
-    m2[j][2]  = m1[j][0]  - m1[j][2];
-    m2[j][3]  = m1[j][1]  - m1[j][3];
-    m2[j][4]  = m1[j][4]  + m1[j][6];
-    m2[j][5]  = m1[j][5]  + m1[j][7];
-    m2[j][6]  = m1[j][4]  - m1[j][6];
-    m2[j][7]  = m1[j][5]  - m1[j][7];
-    m2[j][8]  = m1[j][8]  + m1[j][10];
-    m2[j][9]  = m1[j][9]  + m1[j][11];
-    m2[j][10] = m1[j][8]  - m1[j][10];
-    m2[j][11] = m1[j][9]  - m1[j][11];
-    m2[j][12] = m1[j][12] + m1[j][14];
-    m2[j][13] = m1[j][13] + m1[j][15];
-    m2[j][14] = m1[j][12] - m1[j][14];
-    m2[j][15] = m1[j][13] - m1[j][15];
-
-    m1[j][0]  = m2[j][0]  + m2[j][1];
-    m1[j][1]  = m2[j][0]  - m2[j][1];
-    m1[j][2]  = m2[j][2]  + m2[j][3];
-    m1[j][3]  = m2[j][2]  - m2[j][3];
-    m1[j][4]  = m2[j][4]  + m2[j][5];
-    m1[j][5]  = m2[j][4]  - m2[j][5];
-    m1[j][6]  = m2[j][6]  + m2[j][7];
-    m1[j][7]  = m2[j][6]  - m2[j][7];
-    m1[j][8]  = m2[j][8]  + m2[j][9];
-    m1[j][9]  = m2[j][8]  - m2[j][9];
-    m1[j][10] = m2[j][10] + m2[j][11];
-    m1[j][11] = m2[j][10] - m2[j][11];
-    m1[j][12] = m2[j][12] + m2[j][13];
-    m1[j][13] = m2[j][12] - m2[j][13];
-    m1[j][14] = m2[j][14] + m2[j][15];
-    m1[j][15] = m2[j][14] - m2[j][15];
-  }
-
-  //vertical
-  for (i=0; i < 16; i++)
-  {
-    m2[0][i] = m1[0][i] + m1[2][i];
-    m2[1][i] = m1[1][i] + m1[3][i];
-    m2[2][i] = m1[0][i] - m1[2][i];
-    m2[3][i] = m1[1][i] - m1[3][i];
-
-    m1[0][i] = m2[0][i] + m2[1][i];
-    m1[1][i] = m2[0][i] - m2[1][i];
-    m1[2][i] = m2[2][i] + m2[3][i];
-    m1[3][i] = m2[2][i] - m2[3][i];
-  }
-
-  for (i = 0; i < 4; i++)
-  {
-    for (j = 0; j < 16; j++)
-    {
-      sad += abs(m1[i][j]);
-    }
-  }
-
-  sad=((sad+2)>>2);
-
-  return sad;
-}
-
-UInt TComRdCost::xCalcHADs4x16( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
-{
-  Int k, i, j, jj, sad=0;
-  Int diff[64], m1[16][4], m2[16][4], m3[16][4];
-  assert( iStep == 1 );
-  for( k = 0; k < 64; k += 4 )
-  {
-    diff[k+0] = piOrg[0] - piCur[0];
-    diff[k+1] = piOrg[1] - piCur[1];
-    diff[k+2] = piOrg[2] - piCur[2];
-    diff[k+3] = piOrg[3] - piCur[3];
-
-    piCur += iStrideCur;
-    piOrg += iStrideOrg;
-  }
-
-  //horizontal
-  for (j=0; j < 16; j++)
-  {
-    jj = j << 2;
-    m2[j][0] = diff[jj  ] + diff[jj+2];
-    m2[j][1] = diff[jj+1] + diff[jj+3];
-    m2[j][2] = diff[jj  ] - diff[jj+2];
-    m2[j][3] = diff[jj+1] - diff[jj+3];
-
-    m1[j][0] = m2[j][0] + m2[j][1];
-    m1[j][1] = m2[j][0] - m2[j][1];
-    m1[j][2] = m2[j][2] + m2[j][3];
-    m1[j][3] = m2[j][2] - m2[j][3];
-  }
-
-  //vertical
-  for (i=0; i < 4; i++)
-  {
-    m2[0][i]  = m1[0][i] + m1[8][i];
-    m2[1][i]  = m1[1][i] + m1[9][i];
-    m2[2][i]  = m1[2][i] + m1[10][i];
-    m2[3][i]  = m1[3][i] + m1[11][i];
-    m2[4][i]  = m1[4][i] + m1[12][i];
-    m2[5][i]  = m1[5][i] + m1[13][i];
-    m2[6][i]  = m1[6][i] + m1[14][i];
-    m2[7][i]  = m1[7][i] + m1[15][i];
-    m2[8][i]  = m1[0][i] - m1[8][i];
-    m2[9][i]  = m1[1][i] - m1[9][i];
-    m2[10][i] = m1[2][i] - m1[10][i];
-    m2[11][i] = m1[3][i] - m1[11][i];
-    m2[12][i] = m1[4][i] - m1[12][i];
-    m2[13][i] = m1[5][i] - m1[13][i];
-    m2[14][i] = m1[6][i] - m1[14][i];
-    m2[15][i] = m1[7][i] - m1[15][i];
-
-    m3[0][i]  = m2[0][i]  + m2[4][i];
-    m3[1][i]  = m2[1][i]  + m2[5][i];
-    m3[2][i]  = m2[2][i]  + m2[6][i];
-    m3[3][i]  = m2[3][i]  + m2[7][i];
-    m3[4][i]  = m2[0][i]  - m2[4][i];
-    m3[5][i]  = m2[1][i]  - m2[5][i];
-    m3[6][i]  = m2[2][i]  - m2[6][i];
-    m3[7][i]  = m2[3][i]  - m2[7][i];
-    m3[8][i]  = m2[8][i]  + m2[12][i];
-    m3[9][i]  = m2[9][i]  + m2[13][i];
-    m3[10][i] = m2[10][i] + m2[14][i];
-    m3[11][i] = m2[11][i] + m2[15][i];
-    m3[12][i] = m2[8][i]  - m2[12][i];
-    m3[13][i] = m2[9][i]  - m2[13][i];
-    m3[14][i] = m2[10][i] - m2[14][i];
-    m3[15][i] = m2[11][i] - m2[15][i];
-
-    m1[0][i]  = m3[0][i]  + m3[2][i];
-    m1[1][i]  = m3[1][i]  + m3[3][i];
-    m1[2][i]  = m3[0][i]  - m3[2][i];
-    m1[3][i]  = m3[1][i]  - m3[3][i];
-    m1[4][i]  = m3[4][i]  + m3[6][i];
-    m1[5][i]  = m3[5][i]  + m3[7][i];
-    m1[6][i]  = m3[4][i]  - m3[6][i];
-    m1[7][i]  = m3[5][i]  - m3[7][i];
-    m1[8][i]  = m3[8][i]  + m3[10][i];
-    m1[9][i]  = m3[9][i]  + m3[11][i];
-    m1[10][i] = m3[8][i]  - m3[10][i];
-    m1[11][i] = m3[9][i]  - m3[11][i];
-    m1[12][i] = m3[12][i] + m3[14][i];
-    m1[13][i] = m3[13][i] + m3[15][i];
-    m1[14][i] = m3[12][i] - m3[14][i];
-    m1[15][i] = m3[13][i] - m3[15][i];
-
-    m2[0][i]  = m1[0][i]  + m1[1][i];
-    m2[1][i]  = m1[0][i]  - m1[1][i];
-    m2[2][i]  = m1[2][i]  + m1[3][i];
-    m2[3][i]  = m1[2][i]  - m1[3][i];
-    m2[4][i]  = m1[4][i]  + m1[5][i];
-    m2[5][i]  = m1[4][i]  - m1[5][i];
-    m2[6][i]  = m1[6][i]  + m1[7][i];
-    m2[7][i]  = m1[6][i]  - m1[7][i];
-    m2[8][i]  = m1[8][i]  + m1[9][i];
-    m2[9][i]  = m1[8][i]  - m1[9][i];
-    m2[10][i] = m1[10][i] + m1[11][i];
-    m2[11][i] = m1[10][i] - m1[11][i];
-    m2[12][i] = m1[12][i] + m1[13][i];
-    m2[13][i] = m1[12][i] - m1[13][i];
-    m2[14][i] = m1[14][i] + m1[15][i];
-    m2[15][i] = m1[14][i] - m1[15][i];
-  }
-
-  for (i = 0; i < 16; i++)
-  {
-    for (j = 0; j < 4; j++)
-    {
-      sad += abs(m2[i][j]);
-    }
-  }
-
-  sad=((sad+2)>>2);
-
-  return sad;
-}
-#endif
-
 UInt TComRdCost::xGetHADs4( DistParam* pcDtParam )
 {
@@ -1909,9 +1621,5 @@
   UInt uiSum = 0;
 
-#if NS_HAD
-  if( ( ( iRows % 8 == 0) && (iCols % 8 == 0) && ( iRows == iCols ) ) || ( ( iRows % 8 == 0 ) && (iCols % 8 == 0) && !pcDtParam->bUseNSHAD ) )
-#else
   if( ( iRows % 8 == 0) && (iCols % 8 == 0) )
-#endif
   {
     Int  iOffsetOrg = iStrideOrg<<3;
@@ -1927,34 +1635,4 @@
     }
   }
-#if NS_HAD
-  else if ( ( iCols > 8 ) && ( iCols > iRows ) && pcDtParam->bUseNSHAD )
-  {
-    Int  iOffsetOrg = iStrideOrg<<2;
-    Int  iOffsetCur = iStrideCur<<2;
-    for ( y=0; y<iRows; y+= 4 )
-    {
-      for ( x=0; x<iCols; x+= 16 )
-      {
-        uiSum += xCalcHADs16x4( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
-      }
-      piOrg += iOffsetOrg;
-      piCur += iOffsetCur;
-    }
-  }
-  else if ( ( iRows > 8 ) && ( iCols < iRows ) && pcDtParam->bUseNSHAD )
-  {
-    Int  iOffsetOrg = iStrideOrg<<4;
-    Int  iOffsetCur = iStrideCur<<4;
-    for ( y=0; y<iRows; y+= 16 )
-    {
-      for ( x=0; x<iCols; x+= 4 )
-      {
-        uiSum += xCalcHADs4x16( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
-      }
-      piOrg += iOffsetOrg;
-      piCur += iOffsetCur;
-    }
-  }
-#endif
   else if( ( iRows % 4 == 0) && (iCols % 4 == 0) )
   {
Index: trunk/source/Lib/TLibCommon/TComRdCost.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComRdCost.h	(revision 499)
+++ trunk/source/Lib/TLibCommon/TComRdCost.h	(revision 540)
@@ -84,8 +84,4 @@
   UInt            uiComp;           // uiComp = 0 (luma Y), 1 (chroma U), 2 (chroma V)
 
-#if NS_HAD
-  Bool            bUseNSHAD;
-#endif
-
   // (vertical) subsampling shift (for reducing complexity)
   // - 0 = no subsampling, 1 = even rows, 2 = every 4th, etc.
@@ -104,7 +100,4 @@
     iSubShift = 0;
     bitDepth = 0;
-#if NS_HAD
-    bUseNSHAD = false;
-#endif
   }
 };
@@ -123,8 +116,6 @@
 #endif  
   
-#if WEIGHTED_CHROMA_DISTORTION
   Double                  m_cbDistortionWeight; 
   Double                  m_crDistortionWeight; 
-#endif
   Double                  m_dLambda;
   Double                  m_sqrtLambda;
@@ -155,8 +146,6 @@
   Double  calcRdCost64( UInt64 uiBits, UInt64 uiDistortion, Bool bFlag = false, DFunc eDFunc = DF_DEFAULT );
   
-#if WEIGHTED_CHROMA_DISTORTION
   Void    setCbDistortionWeight      ( Double cbDistortionWeight) { m_cbDistortionWeight = cbDistortionWeight; };
   Void    setCrDistortionWeight      ( Double crDistortionWeight) { m_crDistortionWeight = crDistortionWeight; };
-#endif
   Void    setLambda      ( Double dLambda );
   Void    setFrameLambda ( Double dLambda ) { m_dFrameLambda = dLambda; }
@@ -164,10 +153,6 @@
   Double  getSqrtLambda ()   { return m_sqrtLambda; }
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
   Double  getLambda() { return m_dLambda; }
-#if M0036_RC_IMPROVEMENT
   Double  getChromaWeight () {return((m_cbDistortionWeight+m_crDistortionWeight)/2.0);}
-#endif
-#endif
   
   // Distortion Functions
@@ -176,11 +161,6 @@
   Void    setDistParam( UInt uiBlkWidth, UInt uiBlkHeight, DFunc eDFunc, DistParam& rcDistParam );
   Void    setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride,            DistParam& rcDistParam );
-#if NS_HAD
-  Void    setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, Int iStep, DistParam& rcDistParam, Bool bHADME=false, Bool bUseNSHAD=false );
-  Void    setDistParam( DistParam& rcDP, Int bitDepth, Pel* p1, Int iStride1, Pel* p2, Int iStride2, Int iWidth, Int iHeight, Bool bHadamard = false, Bool bUseNSHAD=false );
-#else
   Void    setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, Int iStep, DistParam& rcDistParam, Bool bHADME=false );
   Void    setDistParam( DistParam& rcDP, Int bitDepth, Pel* p1, Int iStride1, Pel* p2, Int iStride2, Int iWidth, Int iHeight, Bool bHadamard = false );
-#endif
   
   UInt    calcHAD(Int bitDepth, Pel* pi0, Int iStride0, Pel* pi1, Int iStride1, Int iWidth, Int iHeight );
@@ -253,19 +233,8 @@
   static UInt xCalcHADs4x4      ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
   static UInt xCalcHADs8x8      ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
-#if NS_HAD
-  static UInt xCalcHADs16x4     ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
-  static UInt xCalcHADs4x16     ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
-#endif
   
 public:
-#if WEIGHTED_CHROMA_DISTORTION
   UInt   getDistPart(Int bitDepth, Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, TextType eText = TEXT_LUMA, DFunc eDFunc = DF_SSE );
-#else
-  UInt   getDistPart(Int bitDepth, Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, DFunc eDFunc = DF_SSE );
-#endif
-
-#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
-  UInt   getSADPart ( Int bitDepth, Pel* pelCur, Int curStride,  Pel* pelOrg, Int orgStride, UInt width, UInt height );
-#endif
+
 };// END CLASS DEFINITION TComRdCost
 
Index: trunk/source/Lib/TLibCommon/TComRom.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComRom.cpp	(revision 499)
+++ trunk/source/Lib/TLibCommon/TComRom.cpp	(revision 540)
@@ -363,15 +363,4 @@
 const UInt g_uiGroupIdx[ 32 ]   = {0,1,2,3,4,4,5,5,6,6,6,6,7,7,7,7,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9};
 
-// Rice parameters for absolute transform levels
-const UInt g_auiGoRiceRange[5] =
-{
-  7, 14, 26, 46, 78
-};
-
-const UInt g_auiGoRicePrefixLen[5] =
-{
-  8, 7, 6, 5, 4
-};
-
 Void initSigLastScan(UInt* pBuffD, UInt* pBuffH, UInt* pBuffV, Int iWidth, Int iHeight)
 {
@@ -541,11 +530,4 @@
 Int g_mvScalingFactor  [MAX_LAYERS][2] = {{0,0}, {0,0}};
 Int g_posScalingFactor [MAX_LAYERS][2] = {{0,0}, {0,0}};
-
-#if IL_SL_SIGNALLING_N0371
-Int ref_scalingListDC         [MAX_LAYERS][SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM];
-Int ref_scalingListCoef       [MAX_LAYERS][SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM][MAX_MATRIX_COEF_NUM];
-Int activeRefPPSId            [MAX_LAYERS];
-Int activeRefSPSId            [MAX_LAYERS];
-#endif 
 #endif
 
Index: trunk/source/Lib/TLibCommon/TComRom.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComRom.h	(revision 499)
+++ trunk/source/Lib/TLibCommon/TComRom.h	(revision 540)
@@ -131,7 +131,4 @@
 extern const UInt   g_uiMinInGroup[ 10 ];
 
-extern const UInt   g_auiGoRiceRange[5];                  //!< maximum value coded with Rice codes
-extern const UInt   g_auiGoRicePrefixLen[5];              //!< prefix length for each maximum value
-  
 extern const UInt   g_sigLastScan8x8[ 3 ][ 4 ];           //!< coefficient group scan order for 8x8 TUs
 extern       UInt   g_sigLastScanCG32x32[ 64 ];
@@ -291,12 +288,5 @@
 #if SVC_EXTENSION
 extern Int g_mvScalingFactor  [MAX_LAYERS][2];
-extern Int g_posScalingFactor [MAX_LAYERS][2];
-
-#if IL_SL_SIGNALLING_N0371
-extern Int ref_scalingListDC         [MAX_LAYERS][SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM];
-extern Int ref_scalingListCoef       [MAX_LAYERS][SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM][MAX_MATRIX_COEF_NUM];
-extern Int activeRefPPSId            [MAX_LAYERS];
-extern Int activeRefSPSId            [MAX_LAYERS];  
-#endif   
+extern Int g_posScalingFactor [MAX_LAYERS][2]; 
 #endif
 
Index: trunk/source/Lib/TLibCommon/TComSampleAdaptiveOffset.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComSampleAdaptiveOffset.cpp	(revision 499)
+++ trunk/source/Lib/TLibCommon/TComSampleAdaptiveOffset.cpp	(revision 540)
@@ -44,4 +44,659 @@
 //! \ingroup TLibCommon
 //! \{
+#if HM_CLEANUP_SAO
+UInt g_saoMaxOffsetQVal[NUM_SAO_COMPONENTS]; 
+
+SAOOffset::SAOOffset()
+{ 
+  reset();
+}
+
+SAOOffset::~SAOOffset()
+{
+
+}
+
+Void SAOOffset::reset()
+{
+  modeIdc = SAO_MODE_OFF;
+  typeIdc = -1;
+  typeAuxInfo = -1;
+  ::memset(offset, 0, sizeof(Int)* MAX_NUM_SAO_CLASSES);
+}
+
+const SAOOffset& SAOOffset::operator= (const SAOOffset& src)
+{
+  modeIdc = src.modeIdc;
+  typeIdc = src.typeIdc;
+  typeAuxInfo = src.typeAuxInfo;
+  ::memcpy(offset, src.offset, sizeof(Int)* MAX_NUM_SAO_CLASSES);
+
+  return *this;
+}
+
+
+SAOBlkParam::SAOBlkParam()
+{
+  reset();
+}
+
+SAOBlkParam::~SAOBlkParam()
+{
+
+}
+
+Void SAOBlkParam::reset()
+{
+  for(Int compIdx=0; compIdx< 3; compIdx++)
+  {
+    offsetParam[compIdx].reset();
+  }
+}
+
+const SAOBlkParam& SAOBlkParam::operator= (const SAOBlkParam& src)
+{
+  for(Int compIdx=0; compIdx< 3; compIdx++)
+  {
+    offsetParam[compIdx] = src.offsetParam[compIdx];
+  }
+  return *this;
+
+}
+
+TComSampleAdaptiveOffset::TComSampleAdaptiveOffset()
+{
+  m_tempPicYuv = NULL;
+  for(Int compIdx=0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
+  {
+    m_offsetClipTable[compIdx] = NULL;
+  }
+  m_signTable = NULL; 
+
+  
+  m_lineBufWidth = 0;
+  m_signLineBuf1 = NULL;
+  m_signLineBuf2 = NULL;
+}
+
+
+TComSampleAdaptiveOffset::~TComSampleAdaptiveOffset()
+{
+  destroy();
+  
+  if (m_signLineBuf1) delete[] m_signLineBuf1; m_signLineBuf1 = NULL;
+  if (m_signLineBuf2) delete[] m_signLineBuf2; m_signLineBuf2 = NULL;
+}
+
+#if AUXILIARY_PICTURES
+Void TComSampleAdaptiveOffset::create( Int picWidth, Int picHeight, ChromaFormat chromaFormatIDC, UInt maxCUWidth, UInt maxCUHeight, UInt maxCUDepth )
+#else
+Void TComSampleAdaptiveOffset::create( Int picWidth, Int picHeight, UInt maxCUWidth, UInt maxCUHeight, UInt maxCUDepth )
+#endif
+{
+  destroy();
+
+  m_picWidth = picWidth;    
+  m_picHeight= picHeight;
+  m_maxCUWidth= maxCUWidth; 
+  m_maxCUHeight= maxCUHeight;
+
+  m_numCTUInWidth = (m_picWidth/m_maxCUWidth) + ((m_picWidth % m_maxCUWidth)?1:0);
+  m_numCTUInHeight= (m_picHeight/m_maxCUHeight) + ((m_picHeight % m_maxCUHeight)?1:0);
+  m_numCTUsPic = m_numCTUInHeight*m_numCTUInWidth;
+
+  //temporary picture buffer
+  if ( !m_tempPicYuv )
+  {
+    m_tempPicYuv = new TComPicYuv;
+#if AUXILIARY_PICTURES
+    m_tempPicYuv->create( m_picWidth, m_picHeight, chromaFormatIDC, m_maxCUWidth, m_maxCUHeight, maxCUDepth );
+#else
+    m_tempPicYuv->create( m_picWidth, m_picHeight, m_maxCUWidth, m_maxCUHeight, maxCUDepth );
+#endif
+  }
+
+  //bit-depth related
+  for(Int compIdx =0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
+  {
+    Int bitDepthSample = (compIdx == SAO_Y)?g_bitDepthY:g_bitDepthC;
+    m_offsetStepLog2  [compIdx] = max(bitDepthSample - MAX_SAO_TRUNCATED_BITDEPTH, 0);
+    g_saoMaxOffsetQVal[compIdx] = (1<<(min(bitDepthSample,MAX_SAO_TRUNCATED_BITDEPTH)-5))-1; //Table 9-32, inclusive
+  }
+
+  //look-up table for clipping
+  for(Int compIdx =0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
+  {
+    Int bitDepthSample = (compIdx == SAO_Y)?g_bitDepthY:g_bitDepthC; //exclusive
+    Int maxSampleValue = (1<< bitDepthSample); //exclusive
+    Int maxOffsetValue = (g_saoMaxOffsetQVal[compIdx] << m_offsetStepLog2[compIdx]); 
+
+    m_offsetClipTable[compIdx] = new Int[(maxSampleValue + maxOffsetValue -1)+ (maxOffsetValue)+1 ]; //positive & negative range plus 0
+    m_offsetClip[compIdx] = &(m_offsetClipTable[compIdx][maxOffsetValue]);
+
+    //assign clipped values 
+    Int* offsetClipPtr = m_offsetClip[compIdx];
+    for(Int k=0; k< maxSampleValue; k++)
+    {
+      *(offsetClipPtr + k) = k;
+    }
+    for(Int k=0; k< maxOffsetValue; k++ )
+    {
+      *(offsetClipPtr + maxSampleValue+ k) = maxSampleValue-1;
+      *(offsetClipPtr -k -1 )              = 0;
+    }
+    if(compIdx == SAO_Y) //g_bitDepthY is always larger than or equal to g_bitDepthC
+    {
+      m_signTable = new Short[ 2*(maxSampleValue-1) + 1 ];
+      m_sign = &(m_signTable[maxSampleValue-1]);
+
+      m_sign[0] = 0;
+      for(Int k=1; k< maxSampleValue; k++)
+      {
+        m_sign[k] = 1;
+        m_sign[-k]= -1;
+      }
+    }
+  }  
+
+}
+
+Void TComSampleAdaptiveOffset::destroy()
+{
+  if ( m_tempPicYuv )
+  {
+    m_tempPicYuv->destroy();
+    delete m_tempPicYuv;
+    m_tempPicYuv = NULL;
+  }
+
+  for(Int compIdx=0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
+  {
+    if(m_offsetClipTable[compIdx])
+    {
+      delete[] m_offsetClipTable[compIdx]; m_offsetClipTable[compIdx] = NULL;
+    }
+  }
+  if( m_signTable )
+  {
+    delete[] m_signTable; m_signTable = NULL;
+  }
+}
+
+Void TComSampleAdaptiveOffset::invertQuantOffsets(Int compIdx, Int typeIdc, Int typeAuxInfo, Int* dstOffsets, Int* srcOffsets)
+{
+  Int codedOffset[MAX_NUM_SAO_CLASSES];
+
+  ::memcpy(codedOffset, srcOffsets, sizeof(Int)*MAX_NUM_SAO_CLASSES);
+  ::memset(dstOffsets, 0, sizeof(Int)*MAX_NUM_SAO_CLASSES);
+
+  if(typeIdc == SAO_TYPE_START_BO)
+  {
+    for(Int i=0; i< 4; i++)
+    {
+      dstOffsets[(typeAuxInfo+ i)%NUM_SAO_BO_CLASSES] = codedOffset[(typeAuxInfo+ i)%NUM_SAO_BO_CLASSES]*(1<<m_offsetStepLog2[compIdx]);
+    }
+  }
+  else //EO
+  {
+    for(Int i=0; i< NUM_SAO_EO_CLASSES; i++)
+    {
+      dstOffsets[i] = codedOffset[i] *(1<<m_offsetStepLog2[compIdx]);
+    }
+    assert(dstOffsets[SAO_CLASS_EO_PLAIN] == 0); //keep EO plain offset as zero
+  }
+
+}
+
+Int TComSampleAdaptiveOffset::getMergeList(TComPic* pic, Int ctu, SAOBlkParam* blkParams, std::vector<SAOBlkParam*>& mergeList)
+{
+  Int ctuX = ctu % m_numCTUInWidth;
+  Int ctuY = ctu / m_numCTUInWidth;
+  Int mergedCTUPos;
+  Int numValidMergeCandidates = 0;
+
+  for(Int mergeType=0; mergeType< NUM_SAO_MERGE_TYPES; mergeType++)
+  {
+    SAOBlkParam* mergeCandidate = NULL;
+
+    switch(mergeType)
+    {
+    case SAO_MERGE_ABOVE:
+      {
+        if(ctuY > 0)
+        {
+          mergedCTUPos = ctu- m_numCTUInWidth;
+          if( pic->getSAOMergeAvailability(ctu, mergedCTUPos) )
+          {
+            mergeCandidate = &(blkParams[mergedCTUPos]);
+          }
+        }
+      }
+      break;
+    case SAO_MERGE_LEFT:
+      {
+        if(ctuX > 0)
+        {
+          mergedCTUPos = ctu- 1;
+          if( pic->getSAOMergeAvailability(ctu, mergedCTUPos) )
+          {
+            mergeCandidate = &(blkParams[mergedCTUPos]);
+          }
+        }
+      }
+      break;
+    default:
+      {
+        printf("not a supported merge type");
+        assert(0);
+        exit(-1);
+      }
+    }
+
+    mergeList.push_back(mergeCandidate);
+    if (mergeCandidate != NULL)
+    {
+      numValidMergeCandidates++;
+    }
+  }
+
+  return numValidMergeCandidates;
+}
+
+
+Void TComSampleAdaptiveOffset::reconstructBlkSAOParam(SAOBlkParam& recParam, std::vector<SAOBlkParam*>& mergeList)
+{
+  for(Int compIdx=0; compIdx< NUM_SAO_COMPONENTS; compIdx++)
+  {
+    SAOOffset& offsetParam = recParam[compIdx];
+
+    if(offsetParam.modeIdc == SAO_MODE_OFF)
+    {
+      continue;
+    }
+
+    switch(offsetParam.modeIdc)
+    {
+    case SAO_MODE_NEW:
+      {
+        invertQuantOffsets(compIdx, offsetParam.typeIdc, offsetParam.typeAuxInfo, offsetParam.offset, offsetParam.offset);
+      }
+      break;
+    case SAO_MODE_MERGE:
+      {
+        SAOBlkParam* mergeTarget = mergeList[offsetParam.typeIdc];
+        assert(mergeTarget != NULL);
+
+        offsetParam = (*mergeTarget)[compIdx];
+      }
+      break;
+    default:
+      {
+        printf("Not a supported mode");
+        assert(0);
+        exit(-1);
+      }
+    }
+  }
+}
+
+Void TComSampleAdaptiveOffset::reconstructBlkSAOParams(TComPic* pic, SAOBlkParam* saoBlkParams)
+{
+  m_picSAOEnabled[SAO_Y] = m_picSAOEnabled[SAO_Cb] = m_picSAOEnabled[SAO_Cr] = false;
+
+  for(Int ctu=0; ctu< m_numCTUsPic; ctu++)
+  {
+    std::vector<SAOBlkParam*> mergeList;
+    getMergeList(pic, ctu, saoBlkParams, mergeList);
+
+    reconstructBlkSAOParam(saoBlkParams[ctu], mergeList);
+
+    for(Int compIdx=0; compIdx< NUM_SAO_COMPONENTS; compIdx++)
+    {
+      if(saoBlkParams[ctu][compIdx].modeIdc != SAO_MODE_OFF)
+      {
+        m_picSAOEnabled[compIdx] = true;
+      }
+    }
+  }
+
+
+}
+
+
+Void TComSampleAdaptiveOffset::offsetBlock(Int compIdx, Int typeIdx, Int* offset  
+                                          , Pel* srcBlk, Pel* resBlk, Int srcStride, Int resStride,  Int width, Int height
+                                          , Bool isLeftAvail,  Bool isRightAvail, Bool isAboveAvail, Bool isBelowAvail, Bool isAboveLeftAvail, Bool isAboveRightAvail, Bool isBelowLeftAvail, Bool isBelowRightAvail)
+{
+  if(m_lineBufWidth != m_maxCUWidth)
+  {
+    m_lineBufWidth = m_maxCUWidth;
+    
+    if (m_signLineBuf1) delete[] m_signLineBuf1; m_signLineBuf1 = NULL;
+    m_signLineBuf1 = new Char[m_lineBufWidth+1];
+    
+    if (m_signLineBuf2) delete[] m_signLineBuf2; m_signLineBuf2 = NULL;
+    m_signLineBuf2 = new Char[m_lineBufWidth+1];
+  }
+
+  Int* offsetClip = m_offsetClip[compIdx];
+
+  Int x,y, startX, startY, endX, endY, edgeType;
+  Int firstLineStartX, firstLineEndX, lastLineStartX, lastLineEndX;
+  Char signLeft, signRight, signDown;
+
+  Pel* srcLine = srcBlk;
+  Pel* resLine = resBlk;
+
+  switch(typeIdx)
+  {
+  case SAO_TYPE_EO_0:
+    {
+      offset += 2;
+      startX = isLeftAvail ? 0 : 1;
+      endX   = isRightAvail ? width : (width -1);
+      for (y=0; y< height; y++)
+      {
+        signLeft = (Char)m_sign[srcLine[startX] - srcLine[startX-1]];
+        for (x=startX; x< endX; x++)
+        {
+          signRight = (Char)m_sign[srcLine[x] - srcLine[x+1]]; 
+          edgeType =  signRight + signLeft;
+          signLeft  = -signRight;
+
+          resLine[x] = offsetClip[srcLine[x] + offset[edgeType]];
+        }
+        srcLine  += srcStride;
+        resLine += resStride;
+      }
+
+    }
+    break;
+  case SAO_TYPE_EO_90:
+    {
+      offset += 2;
+      Char *signUpLine = m_signLineBuf1;
+
+      startY = isAboveAvail ? 0 : 1;
+      endY   = isBelowAvail ? height : height-1;
+      if (!isAboveAvail)
+      {
+        srcLine += srcStride;
+        resLine += resStride;
+      }
+
+      Pel* srcLineAbove= srcLine- srcStride;
+      for (x=0; x< width; x++)
+      {
+        signUpLine[x] = (Char)m_sign[srcLine[x] - srcLineAbove[x]];
+      }
+
+      Pel* srcLineBelow;
+      for (y=startY; y<endY; y++)
+      {
+        srcLineBelow= srcLine+ srcStride;
+
+        for (x=0; x< width; x++)
+        {
+          signDown  = (Char)m_sign[srcLine[x] - srcLineBelow[x]]; 
+          edgeType = signDown + signUpLine[x];
+          signUpLine[x]= -signDown;
+
+          resLine[x] = offsetClip[srcLine[x] + offset[edgeType]];
+        }
+        srcLine += srcStride;
+        resLine += resStride;
+      }
+
+    }
+    break;
+  case SAO_TYPE_EO_135:
+    {
+      offset += 2;
+      Char *signUpLine, *signDownLine, *signTmpLine;
+
+      signUpLine  = m_signLineBuf1;
+      signDownLine= m_signLineBuf2;
+
+      startX = isLeftAvail ? 0 : 1 ;
+      endX   = isRightAvail ? width : (width-1);
+
+      //prepare 2nd line's upper sign
+      Pel* srcLineBelow= srcLine+ srcStride;
+      for (x=startX; x< endX+1; x++)
+      {
+        signUpLine[x] = (Char)m_sign[srcLineBelow[x] - srcLine[x- 1]];
+      }
+
+      //1st line
+      Pel* srcLineAbove= srcLine- srcStride;
+      firstLineStartX = isAboveLeftAvail ? 0 : 1;
+      firstLineEndX   = isAboveAvail? endX: 1;
+      for(x= firstLineStartX; x< firstLineEndX; x++)
+      {
+        edgeType  =  m_sign[srcLine[x] - srcLineAbove[x- 1]] - signUpLine[x+1];
+        resLine[x] = offsetClip[srcLine[x] + offset[edgeType]];
+      }
+      srcLine  += srcStride;
+      resLine  += resStride;
+
+
+      //middle lines
+      for (y= 1; y< height-1; y++)
+      {
+        srcLineBelow= srcLine+ srcStride;
+
+        for (x=startX; x<endX; x++)
+        {
+          signDown =  (Char)m_sign[srcLine[x] - srcLineBelow[x+ 1]] ;
+          edgeType =  signDown + signUpLine[x];
+          resLine[x] = offsetClip[srcLine[x] + offset[edgeType]];
+
+          signDownLine[x+1] = -signDown; 
+        }
+        signDownLine[startX] = (Char)m_sign[srcLineBelow[startX] - srcLine[startX-1]];
+
+        signTmpLine  = signUpLine;
+        signUpLine   = signDownLine;
+        signDownLine = signTmpLine;
+
+        srcLine += srcStride;
+        resLine += resStride;
+      }
+
+      //last line
+      srcLineBelow= srcLine+ srcStride;
+      lastLineStartX = isBelowAvail ? startX : (width -1);
+      lastLineEndX   = isBelowRightAvail ? width : (width -1);
+      for(x= lastLineStartX; x< lastLineEndX; x++)
+      {
+        edgeType =  m_sign[srcLine[x] - srcLineBelow[x+ 1]] + signUpLine[x];
+        resLine[x] = offsetClip[srcLine[x] + offset[edgeType]];
+
+      }
+    }
+    break;
+  case SAO_TYPE_EO_45:
+    {
+      offset += 2;
+      Char *signUpLine = m_signLineBuf1+1;
+
+      startX = isLeftAvail ? 0 : 1;
+      endX   = isRightAvail ? width : (width -1);
+
+      //prepare 2nd line upper sign
+      Pel* srcLineBelow= srcLine+ srcStride;
+      for (x=startX-1; x< endX; x++)
+      {
+        signUpLine[x] = (Char)m_sign[srcLineBelow[x] - srcLine[x+1]];
+      }
+
+
+      //first line
+      Pel* srcLineAbove= srcLine- srcStride;
+      firstLineStartX = isAboveAvail ? startX : (width -1 );
+      firstLineEndX   = isAboveRightAvail ? width : (width-1);
+      for(x= firstLineStartX; x< firstLineEndX; x++)
+      {
+        edgeType = m_sign[srcLine[x] - srcLineAbove[x+1]] -signUpLine[x-1];
+        resLine[x] = offsetClip[srcLine[x] + offset[edgeType]];
+      }
+      srcLine += srcStride;
+      resLine += resStride;
+
+      //middle lines
+      for (y= 1; y< height-1; y++)
+      {
+        srcLineBelow= srcLine+ srcStride;
+
+        for(x= startX; x< endX; x++)
+        {
+          signDown =  (Char)m_sign[srcLine[x] - srcLineBelow[x-1]] ;
+          edgeType =  signDown + signUpLine[x];
+          resLine[x] = offsetClip[srcLine[x] + offset[edgeType]];
+          signUpLine[x-1] = -signDown; 
+        }
+        signUpLine[endX-1] = (Char)m_sign[srcLineBelow[endX-1] - srcLine[endX]];
+        srcLine  += srcStride;
+        resLine += resStride;
+      }
+
+      //last line
+      srcLineBelow= srcLine+ srcStride;
+      lastLineStartX = isBelowLeftAvail ? 0 : 1;
+      lastLineEndX   = isBelowAvail ? endX : 1;
+      for(x= lastLineStartX; x< lastLineEndX; x++)
+      {
+        edgeType = m_sign[srcLine[x] - srcLineBelow[x-1]] + signUpLine[x];
+        resLine[x] = offsetClip[srcLine[x] + offset[edgeType]];
+
+      }
+    }
+    break;
+  case SAO_TYPE_BO:
+    {
+      Int shiftBits = ((compIdx == SAO_Y)?g_bitDepthY:g_bitDepthC)- NUM_SAO_BO_CLASSES_LOG2;
+      for (y=0; y< height; y++)
+      {
+        for (x=0; x< width; x++)
+        {
+          resLine[x] = offsetClip[ srcLine[x] + offset[srcLine[x] >> shiftBits] ];
+        }
+        srcLine += srcStride;
+        resLine += resStride;
+      }
+    }
+    break;
+  default:
+    {
+      printf("Not a supported SAO types\n");
+      assert(0);
+      exit(-1);
+    }
+  }
+
+
+}
+
+Void TComSampleAdaptiveOffset::offsetCTU(Int ctu, TComPicYuv* srcYuv, TComPicYuv* resYuv, SAOBlkParam& saoblkParam, TComPic* pPic)
+{
+  Bool isLeftAvail,isRightAvail,isAboveAvail,isBelowAvail,isAboveLeftAvail,isAboveRightAvail,isBelowLeftAvail,isBelowRightAvail;
+
+  if( 
+    (saoblkParam[SAO_Y ].modeIdc == SAO_MODE_OFF) &&
+    (saoblkParam[SAO_Cb].modeIdc == SAO_MODE_OFF) &&
+    (saoblkParam[SAO_Cr].modeIdc == SAO_MODE_OFF)
+    )
+  {
+    return;
+  }
+
+  //block boundary availability
+  pPic->getPicSym()->deriveLoopFilterBoundaryAvailibility(ctu, isLeftAvail,isRightAvail,isAboveAvail,isBelowAvail,isAboveLeftAvail,isAboveRightAvail,isBelowLeftAvail,isBelowRightAvail);
+
+  Int yPos   = (ctu / m_numCTUInWidth)*m_maxCUHeight;
+  Int xPos   = (ctu % m_numCTUInWidth)*m_maxCUWidth;
+  Int height = (yPos + m_maxCUHeight > m_picHeight)?(m_picHeight- yPos):m_maxCUHeight;
+  Int width  = (xPos + m_maxCUWidth  > m_picWidth )?(m_picWidth - xPos):m_maxCUWidth;
+
+  for(Int compIdx= 0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
+  {
+    SAOOffset& ctbOffset = saoblkParam[compIdx];
+
+    if(ctbOffset.modeIdc != SAO_MODE_OFF)
+    {
+      Bool isLuma     = (compIdx == SAO_Y);
+      Int  formatShift= isLuma?0:1;
+
+      Int  blkWidth   = (width  >> formatShift);
+      Int  blkHeight  = (height >> formatShift);
+      Int  blkYPos    = (yPos   >> formatShift);
+      Int  blkXPos    = (xPos   >> formatShift);
+
+      Int  srcStride = isLuma?srcYuv->getStride():srcYuv->getCStride();
+      Pel* srcBlk    = getPicBuf(srcYuv, compIdx)+ (yPos >> formatShift)*srcStride+ (xPos >> formatShift);
+
+      Int  resStride  = isLuma?resYuv->getStride():resYuv->getCStride();
+      Pel* resBlk     = getPicBuf(resYuv, compIdx)+ blkYPos*resStride+ blkXPos;
+
+      offsetBlock( compIdx, ctbOffset.typeIdc, ctbOffset.offset
+                  , srcBlk, resBlk, srcStride, resStride, blkWidth, blkHeight
+                  , isLeftAvail, isRightAvail
+                  , isAboveAvail, isBelowAvail
+                  , isAboveLeftAvail, isAboveRightAvail
+                  , isBelowLeftAvail, isBelowRightAvail
+                  );
+    }
+  } //compIdx
+
+}
+
+
+Void TComSampleAdaptiveOffset::SAOProcess(TComPic* pDecPic)
+{
+  if(!m_picSAOEnabled[SAO_Y] && !m_picSAOEnabled[SAO_Cb] && !m_picSAOEnabled[SAO_Cr])
+  {
+    return;
+  }
+  TComPicYuv* resYuv = pDecPic->getPicYuvRec();
+  TComPicYuv* srcYuv = m_tempPicYuv;
+  resYuv->copyToPic(srcYuv);
+  for(Int ctu= 0; ctu < m_numCTUsPic; ctu++)
+  {
+    offsetCTU(ctu, srcYuv, resYuv, (pDecPic->getPicSym()->getSAOBlkParam())[ctu], pDecPic);
+  } //ctu
+}
+
+
+Pel* TComSampleAdaptiveOffset::getPicBuf(TComPicYuv* pPicYuv, Int compIdx)
+{
+  Pel* pBuf = NULL;
+  switch(compIdx)
+  {
+  case SAO_Y:
+    {
+      pBuf = pPicYuv->getLumaAddr();
+    }
+    break;
+  case SAO_Cb:
+    {
+      pBuf = pPicYuv->getCbAddr();
+    }
+    break;
+  case SAO_Cr:
+    {
+      pBuf = pPicYuv->getCrAddr();
+    }
+    break;
+  default:
+    {
+      printf("Not a legal component ID for SAO\n");
+      assert(0);
+      exit(-1);
+    }
+  }
+
+  return pBuf;
+}
+#else
 
 SAOParam::~SAOParam()
@@ -1364,5 +2019,5 @@
   }
 }
-
+#endif
 /** PCM LF disable process. 
  * \param pcPic picture (TComPic) pointer
Index: trunk/source/Lib/TLibCommon/TComSampleAdaptiveOffset.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComSampleAdaptiveOffset.h	(revision 499)
+++ trunk/source/Lib/TLibCommon/TComSampleAdaptiveOffset.h	(revision 540)
@@ -45,4 +45,66 @@
 //! \{
 
+
+#if HM_CLEANUP_SAO
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+#define MAX_SAO_TRUNCATED_BITDEPTH     10 
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+extern UInt g_saoMaxOffsetQVal[NUM_SAO_COMPONENTS]; 
+
+class TComSampleAdaptiveOffset
+{
+public:
+  TComSampleAdaptiveOffset();
+  virtual ~TComSampleAdaptiveOffset();
+  Void SAOProcess(TComPic* pDecPic);
+#if AUXILIARY_PICTURES
+  Void create( Int picWidth, Int picHeight, ChromaFormat chromaFormatIDC, UInt maxCUWidth, UInt maxCUHeight, UInt maxCUDepth );
+#else
+  Void create( Int picWidth, Int picHeight, UInt maxCUWidth, UInt maxCUHeight, UInt maxCUDepth );
+#endif
+  Void destroy();
+  Void reconstructBlkSAOParams(TComPic* pic, SAOBlkParam* saoBlkParams);
+  Void PCMLFDisableProcess (TComPic* pcPic);
+protected:
+  Void offsetBlock(Int compIdx, Int typeIdx, Int* offset, Pel* srcBlk, Pel* resBlk, Int srcStride, Int resStride,  Int width, Int height
+                  , Bool isLeftAvail, Bool isRightAvail, Bool isAboveAvail, Bool isBelowAvail, Bool isAboveLeftAvail, Bool isAboveRightAvail, Bool isBelowLeftAvail, Bool isBelowRightAvail);
+  Pel* getPicBuf(TComPicYuv* pPicYuv, Int compIdx);
+  Void invertQuantOffsets(Int compIdx, Int typeIdc, Int typeAuxInfo, Int* dstOffsets, Int* srcOffsets);
+  Void reconstructBlkSAOParam(SAOBlkParam& recParam, std::vector<SAOBlkParam*>& mergeList);
+  Int  getMergeList(TComPic* pic, Int ctu, SAOBlkParam* blkParams, std::vector<SAOBlkParam*>& mergeList);
+  Void offsetCTU(Int ctu, TComPicYuv* srcYuv, TComPicYuv* resYuv, SAOBlkParam& saoblkParam, TComPic* pPic);
+  Void xPCMRestoration(TComPic* pcPic);
+  Void xPCMCURestoration ( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth );
+  Void xPCMSampleRestoration (TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, TextType ttText);
+protected:
+  UInt m_offsetStepLog2[NUM_SAO_COMPONENTS]; //offset step  
+  Int* m_offsetClip[NUM_SAO_COMPONENTS]; //clip table for fast operation
+  Short* m_sign; //sign table for fast operation
+  TComPicYuv*   m_tempPicYuv; //temporary buffer
+  Int m_picWidth;
+  Int m_picHeight;
+  Int m_maxCUWidth;
+  Int m_maxCUHeight;
+  Int m_numCTUInWidth;
+  Int m_numCTUInHeight;
+  Int m_numCTUsPic;
+  
+  
+  Int m_lineBufWidth;
+  Char* m_signLineBuf1;
+  Char* m_signLineBuf2;
+private:
+  Bool m_picSAOEnabled[NUM_SAO_COMPONENTS];
+  Int*   m_offsetClipTable[NUM_SAO_COMPONENTS];
+  Short* m_signTable;
+
+};
+#else
+
 // ====================================================================================================================
 // Constants
@@ -145,4 +207,6 @@
 };
 
+#endif
+
 //! \}
 #endif
Index: trunk/source/Lib/TLibCommon/TComSlice.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComSlice.cpp	(revision 499)
+++ trunk/source/Lib/TLibCommon/TComSlice.cpp	(revision 540)
@@ -48,8 +48,4 @@
 ParameterSetMap<TComVPS> ParameterSetManager::m_vpsMap(MAX_NUM_VPS);
 Int ParameterSetManager::m_activeVPSId = -1;
-#if IL_SL_SIGNALLING_N0371
-TComSPS* TComSPS::m_pcSPS[MAX_LAYERS];
-TComPPS* TComPPS::m_pcPPS[MAX_LAYERS];
-#endif
 #endif
 
@@ -80,10 +76,4 @@
 , m_colFromL0Flag                 ( 1 )
 , m_colRefIdx                     ( 0 )
-#if SAO_CHROMA_LAMBDA
-, m_dLambdaLuma( 0.0 )
-, m_dLambdaChroma( 0.0 )
-#else
-, m_dLambda                       ( 0.0 )
-#endif
 , m_uiTLayer                      ( 0 )
 , m_bTLayerSwitchingFlag          ( false )
@@ -118,4 +108,7 @@
 #endif
 , m_bDiscardableFlag              ( false )
+#if O0149_CROSS_LAYER_BLA_FLAG
+, m_bCrossLayerBLAFlag            ( false )
+#endif
 #endif //SVC_EXTENSION
 {
@@ -143,4 +136,9 @@
   initEqualRef();
   
+  for (Int component = 0; component < 3; component++)
+  {
+    m_lambdas[component] = 0.0;
+  }
+  
   for ( Int idx = 0; idx < MAX_NUM_REF; idx++ )
   {
@@ -157,4 +155,7 @@
   initWpAcDcParam();
   m_saoEnabledFlag = false;
+#if HM_CLEANUP_SAO
+  m_saoEnabledFlagChroma = false;
+#endif
 }
 
@@ -276,4 +277,11 @@
     }
     iterPic++;
+#if SVC_EXTENSION
+    // return NULL, if picture with requested POC is not in the list, otherwise iterator goes outside of the list
+    if( iterPic == rcListPic.end() )
+    {
+      return NULL;
+    }
+#endif
     pcPic = *(iterPic);
   }
@@ -308,5 +316,9 @@
       }
       
+#if POC_RESET_RPS
+      if( ((!pocHasMsb) && ((poc & (pocCycle-1)) == picPoc)) || ( pocHasMsb && (poc == picPoc)) )
+#else
       if (poc == picPoc)
+#endif
       {
        if (pcPic->getIsLongTerm())
@@ -357,5 +369,4 @@
 }
 
-#if FIX1071
 #if SVC_EXTENSION
 Void TComSlice::setRefPicList( TComList<TComPic*>& rcListPic, Bool checkNumPocTotalCurr, TComPic** ilpPic)
@@ -363,11 +374,6 @@
 Void TComSlice::setRefPicList( TComList<TComPic*>& rcListPic, Bool checkNumPocTotalCurr )
 #endif
-#else
-Void TComSlice::setRefPicList( TComList<TComPic*>& rcListPic )
-#endif
-{
-#if FIX1071
+{
   if (!checkNumPocTotalCurr)
-#endif
   {
     if (m_eSliceType == I_SLICE)
@@ -522,4 +528,5 @@
       memset( refResamplingLayer, 0, sizeof( refResamplingLayer ) );
 #endif
+#if !RESAMPLING_CONSTRAINT_BUG_FIX
       const Window &scalEL = getSPS()->getScaledRefLayerWindow(m_interLayerPredLayerIdc[i]);
       Int scalingOffset = ((scalEL.getWindowLeftOffset()   == 0 ) && 
@@ -528,8 +535,21 @@
                            (scalEL.getWindowBottomOffset() == 0 ) 
                           );
+#endif
 
       for( i=0; i < m_activeNumILRRefIdx; i++ )
       {
         UInt refLayerIdc = m_interLayerPredLayerIdc[i];
+#if RESAMPLING_CONSTRAINT_BUG_FIX
+#if O0098_SCALED_REF_LAYER_ID
+        const Window &scalEL = getSPS()->getScaledRefLayerWindowForLayer(m_pcVPS->getRefLayerId( m_layerId, m_interLayerPredLayerIdc[i] ));
+#else
+        const Window &scalEL = getSPS()->getScaledRefLayerWindow(m_interLayerPredLayerIdc[i]);
+#endif
+        Int scalingOffset = ((scalEL.getWindowLeftOffset()   == 0 ) && 
+                             (scalEL.getWindowRightOffset()  == 0 ) && 
+                             (scalEL.getWindowTopOffset()    == 0 ) && 
+                             (scalEL.getWindowBottomOffset() == 0 ) 
+                            );
+#endif
         if(!( g_posScalingFactor[refLayerIdc][0] == 65536 && g_posScalingFactor[refLayerIdc][1] == 65536 ) || (!scalingOffset)) // ratio 1x
         {
@@ -585,5 +605,5 @@
   Int numPocTotalCurr = NumPocStCurr0 + NumPocStCurr1 + NumPocLtCurr;
 #endif //SVC_EXTENSION
-#if FIX1071
+
   if (checkNumPocTotalCurr)
   {
@@ -615,5 +635,4 @@
     m_aiNumRefIdx[1] = getNumRefIdx(REF_PIC_LIST_1);
   }
-#endif
 
 #if M0457_IL_SAMPLE_PRED_ONLY_FLAG
@@ -932,5 +951,5 @@
     numRpsCurrTempList += getNumILRRefIdx();
 #endif
-  }
+}
 #endif
 
@@ -1038,5 +1057,9 @@
  * If the current picture has a nal_ref_idc that is not 0, it will remain marked as "used for reference".
  */
+#if NO_CLRAS_OUTPUT_FLAG
+Void TComSlice::decodingRefreshMarking(Int& pocCRA, Bool& bRefreshPending, TComList<TComPic*>& rcListPic, Bool noClrasOutputFlag)
+#else
 Void TComSlice::decodingRefreshMarking(Int& pocCRA, Bool& bRefreshPending, TComList<TComPic*>& rcListPic)
+#endif
 {
   TComPic*                 rpcPic;
@@ -1056,5 +1079,16 @@
       rpcPic = *(iterPic);
       rpcPic->setCurrSliceIdx(0);
+#if NO_CLRAS_OUTPUT_FLAG
+      if (noClrasOutputFlag)
+      {
+        if (rpcPic->getPOC() != pocCurr) rpcPic->getSlice(0)->setReferenced(false);  // all layers
+      }
+      else
+      {
+        if (rpcPic->getPOC() != pocCurr && rpcPic->getLayerId() == m_layerId) rpcPic->getSlice(0)->setReferenced(false);  // only current layer
+      }
+#else
       if (rpcPic->getPOC() != pocCurr) rpcPic->getSlice(0)->setReferenced(false);
+#endif
       iterPic++;
     }
@@ -1160,10 +1194,5 @@
   m_colFromL0Flag        = pSrc->m_colFromL0Flag;
   m_colRefIdx            = pSrc->m_colRefIdx;
-#if SAO_CHROMA_LAMBDA 
-  m_dLambdaLuma          = pSrc->m_dLambdaLuma;
-  m_dLambdaChroma        = pSrc->m_dLambdaChroma;
-#else
-  m_dLambda              = pSrc->m_dLambda;
-#endif
+  setLambdas(pSrc->getLambdas());
   for (i = 0; i < 2; i++)
   {
@@ -1490,5 +1519,5 @@
     assert(rpcPic->getSlice( 0 )->isReferenced()==0||rpcPic->getUsedByCurr()==0||rpcPic->getTLayer()<=this->getTLayer());
     //check that pictures of higher or equal temporal layer are not in the RPS if the current picture is a TSA picture
-    if(this->getNalUnitType() == NAL_UNIT_CODED_SLICE_TLA_R || this->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_N)
+    if(this->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_R || this->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_N)
     {
       assert(rpcPic->getSlice( 0 )->isReferenced()==0||rpcPic->getTLayer()<this->getTLayer());
@@ -1649,9 +1678,5 @@
 /** Function for constructing an explicit Reference Picture Set out of the available pictures in a referenced Reference Picture Set
 */
-#if FIX1071
 Void TComSlice::createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool isRAP)
-#else
-Void TComSlice::createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet)
-#endif
 {
   TComPic* rpcPic;
@@ -1678,9 +1703,5 @@
         // and should be added to the explicit Reference Picture Set
         pcRPS->setDeltaPOC(k, pReferencePictureSet->getDeltaPOC(i));
-#if FIX1071
         pcRPS->setUsed(k, pReferencePictureSet->getUsed(i) && (!isRAP));
-#else
-        pcRPS->setUsed(k, pReferencePictureSet->getUsed(i));
-#endif
         if(pcRPS->getDeltaPOC(k) < 0)
         {
@@ -1834,4 +1855,14 @@
   TComVPS *vps = getVPS();
   UInt retVal, layerId = getLayerId();
+#if O0096_REP_FORMAT_INDEX
+  if ( layerId == 0 )
+  {
+    retVal = sps->getPicWidthInLumaSamples();
+  }
+  else
+  {
+    retVal = vps->getVpsRepFormat( vps->getVpsRepFormatIdx(sps->getUpdateRepFormatFlag() ? sps->getUpdateRepFormatIndex() : layerId) )->getPicWidthVpsInLumaSamples();
+  }
+#else
   if( ( layerId == 0 ) || sps->getUpdateRepFormatFlag() )
   {
@@ -1842,4 +1873,5 @@
     retVal = vps->getVpsRepFormat( vps->getVpsRepFormatIdx(layerId) )->getPicWidthVpsInLumaSamples();
   }
+#endif
   return retVal;
 }
@@ -1849,4 +1881,14 @@
   TComVPS *vps = getVPS();
   UInt retVal, layerId = getLayerId();
+#if O0096_REP_FORMAT_INDEX
+  if( layerId == 0 )
+  {
+    retVal = sps->getPicHeightInLumaSamples();
+  }
+  else
+  {
+    retVal = vps->getVpsRepFormat( vps->getVpsRepFormatIdx(sps->getUpdateRepFormatFlag() ? sps->getUpdateRepFormatIndex() : layerId) )->getPicHeightVpsInLumaSamples();
+  }
+#else
   if( ( layerId == 0 ) || sps->getUpdateRepFormatFlag() )
   {
@@ -1857,4 +1899,5 @@
     retVal = vps->getVpsRepFormat( vps->getVpsRepFormatIdx(layerId) )->getPicHeightVpsInLumaSamples();
   }
+#endif
   return retVal;
 }
@@ -1873,4 +1916,14 @@
   UInt retVal, layerId = getLayerId();
 #endif
+#if O0096_REP_FORMAT_INDEX
+  if( layerId == 0 )
+  {
+    retVal = sps->getChromaFormatIdc();
+  }
+  else
+  {
+    retVal = vps->getVpsRepFormat( vps->getVpsRepFormatIdx(sps->getUpdateRepFormatFlag() ? sps->getUpdateRepFormatIndex() : layerId) )->getChromaFormatVpsIdc();
+  }
+#else
   if( ( layerId == 0 ) || sps->getUpdateRepFormatFlag() )
   {
@@ -1881,4 +1934,5 @@
     retVal = vps->getVpsRepFormat( vps->getVpsRepFormatIdx(layerId) )->getChromaFormatVpsIdc();
   }
+#endif
   return retVal;
 }
@@ -1888,4 +1942,14 @@
   TComVPS *vps = getVPS();
   UInt retVal, layerId = getLayerId();
+#if O0096_REP_FORMAT_INDEX
+  if( layerId == 0 )
+  {
+    retVal = sps->getBitDepthY();
+  }
+  else
+  {
+    retVal = vps->getVpsRepFormat( vps->getVpsRepFormatIdx(sps->getUpdateRepFormatFlag() ? sps->getUpdateRepFormatIndex() : layerId) )->getBitDepthVpsLuma();
+  }
+#else
   if( ( layerId == 0 ) || sps->getUpdateRepFormatFlag() )
   {
@@ -1896,4 +1960,5 @@
     retVal = vps->getVpsRepFormat( vps->getVpsRepFormatIdx(layerId) )->getBitDepthVpsLuma();
   }
+#endif
   return retVal;
 }
@@ -1903,4 +1968,14 @@
   TComVPS *vps = getVPS();
   UInt retVal, layerId = getLayerId();
+#if O0096_REP_FORMAT_INDEX
+  if( layerId == 0 )
+  {
+    retVal = sps->getBitDepthC();
+  }
+  else
+  {
+    retVal = vps->getVpsRepFormat( vps->getVpsRepFormatIdx(sps->getUpdateRepFormatFlag() ? sps->getUpdateRepFormatIndex() : layerId) )->getBitDepthVpsChroma();
+  }
+#else
   if( ( layerId == 0 ) || sps->getUpdateRepFormatFlag() )
   {
@@ -1911,4 +1986,5 @@
     retVal = vps->getVpsRepFormat( vps->getVpsRepFormatIdx(layerId) )->getBitDepthVpsChroma();
   }
+#endif
   return retVal;
 }
@@ -2023,4 +2099,7 @@
   ::memset(m_pocLsbNotPresentFlag, 0, sizeof(m_pocLsbNotPresentFlag));
 #endif
+#if O0223_PICTURE_TYPES_ALIGN_FLAG
+  m_crossLayerPictureTypeAlignFlag = true;
+#endif 
 #if N0147_IRAP_ALIGN_FLAG
   m_crossLayerIrapAlignFlag = true;
@@ -2042,7 +2121,16 @@
   }
 #endif
+#if VPS_VUI_TILES_NOT_IN_USE__FLAG
+   m_tilesNotInUseFlag = true;
+   ::memset(m_tilesInUseFlag,  0, sizeof(m_tilesInUseFlag));
+   ::memset(m_loopFilterNotAcrossTilesFlag,  0, sizeof(m_loopFilterNotAcrossTilesFlag));
+#endif
 #if TILE_BOUNDARY_ALIGNED_FLAG
    ::memset(m_tileBoundariesAlignedFlag,  0, sizeof(m_tileBoundariesAlignedFlag));
 #endif 
+#if VPS_VUI_WPP_NOT_IN_USE__FLAG
+   m_wppNotInUseFlag = true;
+   ::memset(m_wppInUseFlag,  0, sizeof(m_wppInUseFlag));
+#endif
 #if N0160_VUI_EXT_ILP_REF
    m_numIlpRestrictedRefLayers = false;
@@ -2050,4 +2138,18 @@
    ::memset(m_ctuBasedOffsetEnabledFlag,     0, sizeof(m_ctuBasedOffsetEnabledFlag));
    ::memset(m_minHorizontalCtuOffsetPlus1,   0, sizeof(m_minHorizontalCtuOffsetPlus1));
+#endif
+#if VPS_VUI_VIDEO_SIGNAL
+    m_vidSigPresentVpsFlag=true;
+    m_vpsVidSigInfo=1;
+    ::memset( m_vpsVidSigIdx, 0, sizeof(m_vpsVidSigIdx) );
+    m_vpsVidSigIdx[0]=0;
+    for (Int i=0; i < 16; i++)
+    {
+      m_vpsVidFormat[i] = 5;
+      m_vpsFullRangeFlag[i] = false;
+      m_vpsColorPrimaries[i] = 2;
+      m_vpsTransChar[i] = 2;
+      m_vpsMatCoeff[i] = 2;
+    }
 #endif
 #if VPS_VUI_BITRATE_PICRATE  
@@ -2064,4 +2166,22 @@
 #if VIEW_ID_RELATED_SIGNALING 
   ::memset(m_viewIdVal, 0, sizeof(m_viewIdVal));
+#endif
+#if O0092_0094_DEPENDENCY_CONSTRAINT
+  for (Int i = 0; i < MAX_NUM_LAYER_IDS; i++)
+  {
+    m_numberRefLayers[i] = 0;
+    for (Int j = 0; j < MAX_NUM_LAYER_IDS; j++)
+    {
+      m_recursiveRefLayerFlag[i][j] = 0;
+    }
+  }
+#endif
+#if VPS_DPB_SIZE_TABLE
+  ::memset( m_subLayerFlagInfoPresentFlag,  0, sizeof(m_subLayerFlagInfoPresentFlag ) );
+  ::memset( m_subLayerDpbInfoPresentFlag,   0, sizeof(m_subLayerDpbInfoPresentFlag )  );
+  ::memset( m_maxVpsDecPicBufferingMinus1,  0, sizeof(m_maxVpsDecPicBufferingMinus1 ) );
+  ::memset( m_maxVpsNumReorderPics,         0, sizeof(m_maxVpsNumReorderPics )        );
+  ::memset( m_maxVpsLatencyIncreasePlus1,   0, sizeof(m_maxVpsLatencyIncreasePlus1 )  );
+  ::memset( m_numSubDpbs                ,   0, sizeof(m_numSubDpbs)                   );
 #endif
 }
@@ -2117,23 +2237,80 @@
 }
 #endif
-
-#if IL_SL_SIGNALLING_N0371
-Bool TComVPS::checkLayerDependency(UInt i, UInt j)
-{
-  if( this->getDirectDependencyFlag(i, j) == true )
-  {                                                                                                                                    
-    return true;                                                                                                                       
-  }                                                                                                                                    
-  else                                                                                                                                   
-  {                                                                                                                                    
-    for(UInt k=i-1; k>j; k--)
-    {                                                                                                                                
-      if( this->getDirectDependencyFlag(i, k) == true )
-      {                                                                                                                            
-        checkLayerDependency( k,j );                                                                                           
-      }
-    }
-  }
-  return false;        
+#if VPS_DPB_SIZE_TABLE
+Void TComVPS::deriveNumberOfSubDpbs()
+{
+  // Derive number of sub-DPBs
+  // For output layer set 0
+  setNumSubDpbs(0, 1);
+  // For other output layer sets
+  for( Int i = 1; i < getNumOutputLayerSets(); i++)
+  {
+    setNumSubDpbs( i, getNumLayersInIdList( getOutputLayerSetIdx(i)) );
+  }
+}
+#endif
+#if VPS_VUI_TILES_NOT_IN_USE__FLAG
+Void TComVPS::setTilesNotInUseFlag(Bool x)
+{
+  m_tilesNotInUseFlag = x;
+  if (m_tilesNotInUseFlag)
+  {
+    for (int i = 0; i < getMaxLayers(); i++)
+    {
+      m_tilesInUseFlag[i] = m_loopFilterNotAcrossTilesFlag[i] = m_tilesNotInUseFlag;
+    }
+  }
+#if TILE_BOUNDARY_ALIGNED_FLAG  
+  if (m_tilesNotInUseFlag)
+  {
+    for (int i = 1; i < getMaxLayers(); i++)
+    {
+      for(int j = 0; j < getNumDirectRefLayers(getLayerIdInNuh(i)); j++)
+      {
+        setTileBoundariesAlignedFlag(i, j, m_tilesNotInUseFlag);
+      }
+    }
+  }
+#endif
+}
+#endif
+#if VPS_VUI_WPP_NOT_IN_USE__FLAG
+Void TComVPS::setWppNotInUseFlag(Bool x)
+{
+  m_wppNotInUseFlag = x;
+  if (m_wppNotInUseFlag)
+  {
+    for (int i = 0; i < getMaxLayers(); i++)
+    {
+      m_wppInUseFlag[i] = m_wppNotInUseFlag;
+    }
+  }
+}
+#endif
+#if O0092_0094_DEPENDENCY_CONSTRAINT
+Void TComVPS::setRefLayersFlags(Int currLayerId)
+{
+  for (Int i = 0; i < getNumDirectRefLayers(currLayerId); i++)
+  {
+    UInt refLayerId = getRefLayerId(currLayerId, i);
+    setRecursiveRefLayerFlag(currLayerId, refLayerId, true);
+    for (Int k = 0; k < MAX_NUM_LAYER_IDS; k++)
+    {
+      setRecursiveRefLayerFlag(currLayerId, k, (getRecursiveRefLayerFlag(currLayerId, k) | getRecursiveRefLayerFlag(refLayerId, k)));
+    }
+  }
+}
+
+Void TComVPS::setNumRefLayers(Int currLayerId)
+{
+  for (Int i = 0; i <= getMaxLayers(); i++)
+  {
+    UInt iNuhLId = getLayerIdInNuh(i);
+    setRefLayersFlags(iNuhLId);
+    for (UInt j = 0; j < MAX_NUM_LAYER_IDS; j++)
+    {
+      m_numberRefLayers[iNuhLId] += (getRecursiveRefLayerFlag(iNuhLId, j) == true ? 1 : 0);
+    }
+  }
 }
 #endif
@@ -2224,4 +2401,11 @@
 #if REPN_FORMAT_IN_VPS
 , m_updateRepFormatFlag       (false)
+#if O0096_REP_FORMAT_INDEX
+, m_updateRepFormatIndex      (0)
+#endif
+#endif
+#if SCALINGLIST_INFERRING
+, m_inferScalingListFlag ( false )
+, m_scalingListRefLayerId ( 0 )
 #endif
 #endif //SVC_EXTENSION
@@ -2248,4 +2432,7 @@
 TComSPS::~TComSPS()
 {
+#if SCALINGLIST_INFERRING
+  if( !m_inferScalingListFlag )
+#endif
   delete m_scalingList;
   m_RPSList.destroy();
@@ -2373,4 +2560,22 @@
 const Int TComSPS::m_winUnitX[]={1,2,2,1};
 const Int TComSPS::m_winUnitY[]={1,2,1,1};
+
+#if O0098_SCALED_REF_LAYER_ID
+Window& TComSPS::getScaledRefLayerWindowForLayer(Int layerId)
+{
+  static Window win;
+
+  for (Int i = 0; i < m_numScaledRefLayerOffsets; i++)
+  {
+    if (layerId == m_scaledRefLayerId[i])
+    {
+      return m_scaledRefLayerWindow[i];
+    }
+  }
+
+  win.resetWindow();  // scaled reference layer offsets are inferred to be zero when not present
+  return win;
+}
+#endif
 
 TComPPS::TComPPS()
@@ -2407,4 +2612,8 @@
 , m_listsModificationPresentFlag(  0)
 , m_numExtraSliceHeaderBits(0)
+#if SCALINGLIST_INFERRING
+, m_inferScalingListFlag ( false )
+, m_scalingListRefLayerId ( 0 )
+#endif
 {
   m_scalingList = new TComScalingList;
@@ -2423,4 +2632,8 @@
     m_puiRowHeight = NULL;
   }
+
+#if SCALINGLIST_INFERRING
+  if( !m_inferScalingListFlag )
+#endif
   delete m_scalingList;
 }
@@ -2640,9 +2853,5 @@
 /** set default quantization matrix to array
 */
-#if IL_SL_SIGNALLING_N0371
-Void TComSlice::setDefaultScalingList( UInt layerId )
-#else
 Void TComSlice::setDefaultScalingList()
-#endif
 {
   for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
@@ -2650,9 +2859,5 @@
     for(UInt listId=0;listId<g_scalingListNum[sizeId];listId++)
     {
-#if IL_SL_SIGNALLING_N0371
-      getScalingList()->processDefaultMarix(sizeId, listId, layerId);
-#else
-      getScalingList()->processDefaultMarix(sizeId, listId);
-#endif
+      getScalingList()->processDefaultMatrix(sizeId, listId);
     }
   }
@@ -2829,38 +3034,13 @@
  * \param Index of input matrix
  */
-#if IL_SL_SIGNALLING_N0371
-Void TComScalingList::processDefaultMarix(UInt sizeId, UInt listId, UInt layerId)
-#else
-Void TComScalingList::processDefaultMarix(UInt sizeId, UInt listId)
-#endif
-{
-#if IL_SL_SIGNALLING_N0371
-  Int i,coefNum = min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]);
-  UInt* scan  = (sizeId == 0) ? g_auiSigLastScan [ SCAN_DIAG ] [ 1 ] :  g_sigLastScanCG32x32; 
-  Int *src = getScalingListDefaultAddress(sizeId, listId);   
-#endif
-
+Void TComScalingList::processDefaultMatrix(UInt sizeId, UInt listId)
+{
   ::memcpy(getScalingListAddress(sizeId, listId),getScalingListDefaultAddress(sizeId,listId),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]));
-
-#if IL_SL_SIGNALLING_N0371
-  for(i = 0; i < coefNum; i++) 
-  {
-    ref_scalingListCoef[layerId][sizeId][listId][i] = src[scan[i]];
-  }
-#endif
-
   setScalingListDC(sizeId,listId,SCALING_LIST_DC);
-#if IL_SL_SIGNALLING_N0371
-  ref_scalingListDC[layerId][sizeId][listId] = SCALING_LIST_DC;
-#endif
 }
 
 /** check DC value of matrix for default matrix signaling
  */
-#if IL_SL_SIGNALLING_N0371
-Void TComScalingList::checkDcOfMatrix( UInt layerId )
-#else
 Void TComScalingList::checkDcOfMatrix()
-#endif
 {
   for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
@@ -2871,9 +3051,5 @@
       if(getScalingListDC(sizeId,listId) == 0)
       {
-#if IL_SL_SIGNALLING_N0371
-        processDefaultMarix(sizeId, listId, layerId);
-#else
-        processDefaultMarix(sizeId, listId);
-#endif
+        processDefaultMatrix(sizeId, listId);
       }
     }
@@ -2956,9 +3132,4 @@
         m_activeVPSId = vpsId;
         m_activeSPSId = spsId;
-
-#if IL_SL_SIGNALLING_N0371
-        activeRefPPSId[ sps->getLayerId() ] = ppsId;
-        activeRefSPSId[ sps->getLayerId() ] = spsId;
-#endif
 
         return true;
@@ -3068,20 +3239,24 @@
 #endif
 
-Void TComSlice::setBaseColPic(  TComList<TComPic*>& rcListPic, UInt refLayerIdc )
+Bool TComSlice::setBaseColPic(  TComList<TComPic*>& rcListPic, UInt refLayerIdc )
 {  
   if(m_layerId == 0)
   {
     memset( m_pcBaseColPic, 0, sizeof( m_pcBaseColPic ) );
-    return;
+    return false;
   }        
 #if POC_RESET_FLAG
-  if( this->getPocResetFlag() )
-  {
-    setBaseColPic(refLayerIdc, xGetRefPic(rcListPic, 0)); 
+  TComPic* pic = xGetRefPic( rcListPic, m_bPocResetFlag ? 0 : m_iPOC );
+
+  if( pic )
+  {
+    setBaseColPic(refLayerIdc, pic );
   }
   else
   {
-    setBaseColPic(refLayerIdc, xGetRefPic(rcListPic, getPOC())); 
-  }
+    return false;
+  }
+  
+  return true;
 #else
   setBaseColPic(refLayerIdc, xGetRefPic(rcListPic, getPOC())); 
Index: trunk/source/Lib/TLibCommon/TComSlice.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComSlice.h	(revision 499)
+++ trunk/source/Lib/TLibCommon/TComSlice.h	(revision 540)
@@ -156,14 +156,4 @@
   Void     setScalingListPresentFlag    (Bool b)                               { m_scalingListPresentFlag = b;    }
   Bool     getScalingListPresentFlag    ()                                     { return m_scalingListPresentFlag; }
-
-#if IL_SL_SIGNALLING_N0371
-  UInt     m_layerId;
-
-  Void     setPredScalingListFlag    (Bool b)                               { m_predScalingListFlag = b;    }
-  Bool     getPredScalingListFlag    ()                                     { return m_predScalingListFlag; }
-  Void     setScalingListRefLayerId  (UInt b)                               { m_scalingListRefLayerId = b;  }
-  UInt     getScalingListRefLayerId  ()                                     { return m_scalingListRefLayerId; }
-#endif
-
   Int*     getScalingListAddress          (UInt sizeId, UInt listId)           { return m_scalingListCoef[sizeId][listId]; } //!< get matrix coefficient
   Bool     checkPredMode                  (UInt sizeId, UInt listId);
@@ -171,23 +161,9 @@
   UInt     getRefMatrixId                 (UInt sizeId, UInt listId)           { return m_refMatrixId[sizeId][listId]; }     //!< get reference matrix ID
   Int*     getScalingListDefaultAddress   (UInt sizeId, UInt listId);                                                        //!< get default matrix coefficient
-
-#if IL_SL_SIGNALLING_N0371
-  Void     processDefaultMarix            (UInt sizeId, UInt listId, UInt layerId );
-#else
-  Void     processDefaultMarix            (UInt sizeId, UInt listId);
-#endif
-
+  Void     processDefaultMatrix            (UInt sizeId, UInt listId);
   Void     setScalingListDC               (UInt sizeId, UInt listId, UInt u)   { m_scalingListDC[sizeId][listId] = u; }      //!< set DC value
 
   Int      getScalingListDC               (UInt sizeId, UInt listId)           { return m_scalingListDC[sizeId][listId]; }   //!< get DC value
-
-#if IL_SL_SIGNALLING_N0371
-  Void     setLayerId(UInt layerId) { m_layerId = layerId; }
-  UInt     getLayerId() { return m_layerId; }
-  Void     checkDcOfMatrix                ( UInt m_layerId );
-#else
   Void     checkDcOfMatrix                ();
-#endif
-
   Void     processRefMatrix               (UInt sizeId, UInt listId , UInt refListId );
   Bool     xParseScalingList              (Char* pchFile);
@@ -200,10 +176,4 @@
   UInt     m_refMatrixId                 [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM]; //!< RefMatrixID
   Bool     m_scalingListPresentFlag;                                                //!< flag for using default matrix
-
-#if IL_SL_SIGNALLING_N0371
-  Bool     m_predScalingListFlag;                                                   //!< flag for inter-layer scaling-list prediction
-  UInt     m_scalingListRefLayerId;                                                 //!< scaling_list_ref_layer_id  
-#endif
-
   UInt     m_predMatrixId                [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM]; //!< reference list index
   Int      *m_scalingListCoef            [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM]; //!< quantization matrix                                            
@@ -436,4 +406,7 @@
 class RepFormat
 {
+#if REPN_FORMAT_CONTROL_FLAG
+  Bool m_chromaAndBitDepthVpsPresentFlag;
+#endif 
 #if AUXILIARY_PICTURES
   ChromaFormat m_chromaFormatVpsIdc;
@@ -449,4 +422,9 @@
 public:
   RepFormat();
+
+#if REPN_FORMAT_CONTROL_FLAG
+  Bool getChromaAndBitDepthVpsPresentFlag() { return m_chromaAndBitDepthVpsPresentFlag; }
+  void setChromaAndBitDepthVpsPresentFlag(Bool x) { m_chromaAndBitDepthVpsPresentFlag = x; }
+#endif 
 
 #if AUXILIARY_PICTURES
@@ -504,7 +482,4 @@
   Int         m_layerSetLayerIdList[MAX_VPS_LAYER_SETS_PLUS1][MAX_VPS_LAYER_ID_PLUS1];
   Int         m_numLayerInIdList[MAX_VPS_LAYER_SETS_PLUS1];
-#endif
-#if IL_SL_SIGNALLING_N0371
-  Bool        m_scalingListLayerDependency[MAX_LAYERS][MAX_LAYERS];  // layer dependency for scaling list
 #endif
 #if VPS_EXTN_OFFSET
@@ -555,4 +530,8 @@
 #if M0457_PREDICTION_INDICATIONS
   UInt       m_directDepTypeLen;
+#if O0096_DEFAULT_DEPENDENCY_TYPE
+  Bool       m_defaultDirectDependencyTypeFlag;
+  UInt       m_defaultDirectDependencyType;
+#endif
   UInt       m_directDependencyType[MAX_VPS_LAYER_ID_PLUS1][MAX_VPS_LAYER_ID_PLUS1];
 #endif
@@ -569,4 +548,7 @@
   Bool       m_pocLsbNotPresentFlag[MAX_VPS_LAYER_ID_PLUS1];
 #endif
+#if O0223_PICTURE_TYPES_ALIGN_FLAG
+  Bool       m_crossLayerPictureTypeAlignFlag;
+#endif
 #if N0147_IRAP_ALIGN_FLAG
   Bool       m_crossLayerIrapAlignFlag;
@@ -582,9 +564,25 @@
   Bool       m_maxTidRefPresentFlag;
 #endif 
+#if VPS_TSLAYERS
+  Bool       m_maxTSLayersPresentFlag;
+  UInt       m_maxTSLayerMinus1[MAX_VPS_LAYER_ID_PLUS1 - 1];
+#endif
 #if M0040_ADAPTIVE_RESOLUTION_CHANGE
   Bool       m_singleLayerForNonIrapFlag;
 #endif
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+  Bool       m_higherLayerIrapSkipFlag;
+#endif
+#if VPS_VUI_TILES_NOT_IN_USE__FLAG
+  Bool       m_tilesNotInUseFlag;
+  Bool       m_tilesInUseFlag[MAX_VPS_LAYER_ID_PLUS1];
+  Bool       m_loopFilterNotAcrossTilesFlag[MAX_VPS_LAYER_ID_PLUS1];
+#endif 
 #if TILE_BOUNDARY_ALIGNED_FLAG
   Bool       m_tileBoundariesAlignedFlag[MAX_VPS_LAYER_ID_PLUS1][MAX_VPS_LAYER_ID_PLUS1];
+#endif 
+#if VPS_VUI_WPP_NOT_IN_USE__FLAG
+  Bool       m_wppNotInUseFlag;
+  Bool       m_wppInUseFlag[MAX_VPS_LAYER_ID_PLUS1];
 #endif 
 #if N0160_VUI_EXT_ILP_REF    
@@ -593,4 +591,14 @@
   Bool        m_ctuBasedOffsetEnabledFlag   [MAX_VPS_LAYER_ID_PLUS1][MAX_VPS_LAYER_ID_PLUS1];
   Int         m_minHorizontalCtuOffsetPlus1 [MAX_VPS_LAYER_ID_PLUS1][MAX_VPS_LAYER_ID_PLUS1];
+#endif 
+#if VPS_VUI_VIDEO_SIGNAL
+    Bool        m_vidSigPresentVpsFlag;
+    Int         m_vpsVidSigInfo;
+    Int         m_vpsVidSigIdx[MAX_VPS_LAYER_ID_PLUS1];
+    Int         m_vpsVidFormat[16];
+    Bool        m_vpsFullRangeFlag[16];
+    Int         m_vpsColorPrimaries[16];
+    Int         m_vpsTransChar[16];
+    Int         m_vpsMatCoeff[16];
 #endif 
 #if VPS_VUI_BITRATE_PICRATE
@@ -604,4 +612,7 @@
   Int         m_avgPicRate          [MAX_VPS_LAYER_SETS_PLUS1][MAX_TLAYER];
 #endif
+#if O0153_ALT_OUTPUT_LAYER_FLAG
+  Bool       m_altOutputLayerFlag;
+#endif
 #if REPN_FORMAT_IN_VPS
   Bool       m_repFormatIdxPresentFlag;
@@ -617,4 +628,17 @@
 #if O0215_PHASE_ALIGNMENT
   Bool       m_phaseAlignFlag;
+#endif
+
+#if O0092_0094_DEPENDENCY_CONSTRAINT
+  Int        m_numberRefLayers[MAX_NUM_LAYER_IDS];  // number of direct and indirect reference layers of a coding layer
+  Bool       m_recursiveRefLayerFlag[MAX_NUM_LAYER_IDS][MAX_NUM_LAYER_IDS];  // flag to indicate if j-th layer is a direct or indirect reference layer of i-th layer
+#endif
+#if VPS_DPB_SIZE_TABLE
+  Bool    m_subLayerFlagInfoPresentFlag [MAX_VPS_OP_LAYER_SETS_PLUS1];
+  Bool    m_subLayerDpbInfoPresentFlag  [MAX_VPS_OP_LAYER_SETS_PLUS1][MAX_LAYERS];
+  Int     m_maxVpsDecPicBufferingMinus1 [MAX_VPS_OP_LAYER_SETS_PLUS1][MAX_LAYERS][MAX_TLAYER];
+  Int     m_maxVpsNumReorderPics        [MAX_VPS_OP_LAYER_SETS_PLUS1][MAX_LAYERS];
+  Int     m_maxVpsLatencyIncreasePlus1  [MAX_VPS_OP_LAYER_SETS_PLUS1][MAX_LAYERS];
+  Int     m_numSubDpbs                  [MAX_VPS_OP_LAYER_SETS_PLUS1];
 #endif
 #endif //SVC_EXTENSION
@@ -683,11 +707,15 @@
   Void    deriveLayerIdListVariables();
 #endif
-
-#if IL_SL_SIGNALLING_N0371
-  Bool    checkLayerDependency(UInt i, UInt j);
-  Bool    getScalingListLayerDependency  ( UInt layerId, UInt refLayerId )            { return m_scalingListLayerDependency[layerId][refLayerId]; }
-  Void    setScalingListLayerDependency  ( UInt layerId, UInt refLayerId, Bool val  ) { m_scalingListLayerDependency[layerId][refLayerId] = val;  }
-#endif
-
+#if VPS_DPB_SIZE_TABLE
+Void      deriveNumberOfSubDpbs();
+#endif
+
+#if O0092_0094_DEPENDENCY_CONSTRAINT
+  Void    setRefLayersFlags(Int currLayerId);
+  Bool    getRecursiveRefLayerFlag(Int currLayerId, Int refLayerId)              { return m_recursiveRefLayerFlag[currLayerId][refLayerId];}
+  Void    setRecursiveRefLayerFlag(Int currLayerId, Int refLayerId, Bool x)      { m_recursiveRefLayerFlag[currLayerId][refLayerId] = x;   }
+  Int     getNumRefLayers(Int currLayerId)                                       { return m_numberRefLayers[currLayerId];                  }
+  Void    setNumRefLayers(Int currLayerId);
+#endif
 #if VPS_RENAME
   UInt    getMaxLayerId()                                       { return m_maxLayerId; }
@@ -764,5 +792,10 @@
   UInt   getDirectDepTypeLen()                                                  { return m_directDepTypeLen;                              }
   Void   setDirectDepTypeLen(UInt x)                                            { m_directDepTypeLen = x;                                 }
-
+#if O0096_DEFAULT_DEPENDENCY_TYPE
+  Bool   getDefaultDirectDependencyTypeFlag()                                   { return m_defaultDirectDependencyTypeFlag;               }
+  Void   setDefaultDirectDependecyTypeFlag(Bool x)                              { m_defaultDirectDependencyTypeFlag = x;                  }
+  UInt   getDefaultDirectDependencyType()                                       { return m_defaultDirectDependencyType;                   }
+  Void   setDefaultDirectDependecyType(UInt x)                                  { m_defaultDirectDependencyType = x;                      }
+#endif
   UInt   getDirectDependencyType(Int currLayerId, Int refLayerId)               { return m_directDependencyType[currLayerId][refLayerId]; }
   Void   setDirectDependencyType(Int currLayerId, Int refLayerId, UInt x)       { m_directDependencyType[currLayerId][refLayerId] = x;    }
@@ -791,4 +824,8 @@
   Void   setPocLsbNotPresentFlag(Int i, Bool x)                                 { m_pocLsbNotPresentFlag[i] = x;    }
 #endif
+#if O0223_PICTURE_TYPES_ALIGN_FLAG
+  Bool   getCrossLayerPictureTypeAlignFlag()                                    { return m_crossLayerPictureTypeAlignFlag;                      }
+  Void   setCrossLayerPictureTypeAlignFlag(Bool x)                              { m_crossLayerPictureTypeAlignFlag = x;                         }
+#endif 
 #if N0147_IRAP_ALIGN_FLAG
   Bool   getCrossLayerIrapAlignFlag()                                           { return m_crossLayerIrapAlignFlag;                      }
@@ -808,12 +845,36 @@
   Void   setMaxTidRefPresentFlag(Bool x)                            { m_maxTidRefPresentFlag = x;}
 #endif 
+#if VPS_TSLAYERS
+    Bool   getMaxTSLayersPresentFlag()                                  { return m_maxTSLayersPresentFlag ;}
+    Void   setMaxTSLayersPresentFlag(Bool x)                            { m_maxTSLayersPresentFlag = x;}
+    UInt   getMaxTSLayersMinus1(Int layerId)                            { return m_maxTSLayerMinus1[layerId];}
+    Void   setMaxTSLayersMinus1(Int layerId, UInt maxTSublayer)         { m_maxTSLayerMinus1[layerId] = maxTSublayer;}
+#endif
 #if M0040_ADAPTIVE_RESOLUTION_CHANGE
   Bool   getSingleLayerForNonIrapFlag()                             { return m_singleLayerForNonIrapFlag; }
   Void   setSingleLayerForNonIrapFlag(Bool x)                       { m_singleLayerForNonIrapFlag = x;    }
 #endif
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+  Bool   getHigherLayerIrapSkipFlag()                             { return m_higherLayerIrapSkipFlag; }
+  Void   setHigherLayerIrapSkipFlag(Bool x)                       { m_higherLayerIrapSkipFlag = x;    }
+#endif
+#if VPS_VUI_TILES_NOT_IN_USE__FLAG  
+  Bool   getTilesNotInUseFlag()         { return m_tilesNotInUseFlag; }
+  Void   setTilesNotInUseFlag(Bool x); 
+  Bool   getTilesInUseFlag(Int currLayerId)    { return m_tilesInUseFlag[currLayerId]; }
+  Void   setTilesInUseFlag(Int currLayerId, Bool x)    { m_tilesInUseFlag[currLayerId] = x; } 
+  Bool   getLoopFilterNotAcrossTilesFlag(Int currLayerId)    { return m_loopFilterNotAcrossTilesFlag[currLayerId]; }
+  Void   setLoopFilterNotAcrossTilesFlag(Int currLayerId, Bool x)    { m_loopFilterNotAcrossTilesFlag[currLayerId] = x; } 
+#endif 
 #if TILE_BOUNDARY_ALIGNED_FLAG  
   Bool   getTileBoundariesAlignedFlag(Int currLayerId, Int refLayerId)           { return m_tileBoundariesAlignedFlag[currLayerId][refLayerId]; }
   Void   setTileBoundariesAlignedFlag(Int currLayerId, Int refLayerId, Bool x)   { m_tileBoundariesAlignedFlag[currLayerId][refLayerId] = x; } 
 #endif 
+#if VPS_VUI_WPP_NOT_IN_USE__FLAG  
+  Bool   getWppNotInUseFlag()         { return m_wppNotInUseFlag; }
+  Void   setWppNotInUseFlag(Bool x); 
+  Bool   getWppInUseFlag(Int currLayerId)    { return m_wppInUseFlag[currLayerId]; }
+  Void   setWppInUseFlag(Int currLayerId, Bool x)    { m_wppInUseFlag[currLayerId] = x; } 
+#endif 
 #if N0160_VUI_EXT_ILP_REF  
   Bool  getNumIlpRestrictedRefLayers   ( )                                         { return m_numIlpRestrictedRefLayers        ;}
@@ -828,4 +889,22 @@
   Int  getMinHorizontalCtuOffsetPlus1 ( Int currLayerId, Int refLayerId )            { return m_minHorizontalCtuOffsetPlus1[currLayerId][refLayerId];}
   Void setMinHorizontalCtuOffsetPlus1 ( Int currLayerId, Int refLayerId, Int val )   { m_minHorizontalCtuOffsetPlus1[currLayerId][refLayerId] = val;}  
+#endif
+#if VPS_VUI_VIDEO_SIGNAL
+    Bool   getVideoSigPresentVpsFlag()           { return m_vidSigPresentVpsFlag; }
+    Void   setVideoSigPresentVpsFlag(Bool x)     { m_vidSigPresentVpsFlag = x;    }
+    Int    getNumVideoSignalInfo()               { return m_vpsVidSigInfo;        }
+    Void   setNumVideoSignalInfo(Int x)          { m_vpsVidSigInfo = x;           }
+    Int    getVideoSignalInfoIdx(Int idx)        { return m_vpsVidSigIdx[idx];    }
+    Void   setVideoSignalInfoIdx(Int idx, Int x) { m_vpsVidSigIdx[idx] = x;       }
+    Int    getVideoVPSFormat(Int idx)            { return m_vpsVidFormat[idx];    }
+    Void   setVideoVPSFormat(Int idx, Int x)     { m_vpsVidFormat[idx] = x;       }
+    Bool   getVideoFullRangeVpsFlag(Int idx)     { return m_vpsFullRangeFlag[idx];}
+    Void   setVideoFullRangeVpsFlag(Int idx, Bool x) { m_vpsFullRangeFlag[idx] = x;   }
+    Int    getColorPrimaries(Int idx)            { return m_vpsColorPrimaries[idx];   }
+    Void   setColorPrimaries(Int idx, Int x)     { m_vpsColorPrimaries[idx] = x;      }
+    Int    getTransCharacter(Int idx)            { return m_vpsTransChar[idx];    }
+    Void   setTransCharacter(Int idx, Int x)     { m_vpsTransChar[idx] = x;       }
+    Int    getMaxtrixCoeff(Int idx)              { return m_vpsMatCoeff[idx];     }
+    Void   setMaxtrixCoeff(Int idx, Int x)       { m_vpsMatCoeff[idx] = x;        }
 #endif
 #if VPS_VUI_BITRATE_PICRATE
@@ -850,5 +929,8 @@
   Void setAvgPicRate(Int i, Int j, Int x)   { m_avgPicRate[i][j] = x;    }
 #endif
-
+#if O0153_ALT_OUTPUT_LAYER_FLAG
+  Bool   getAltOuputLayerFlag()             { return m_altOutputLayerFlag; }
+  Void   setAltOuputLayerFlag(Bool x)       { m_altOutputLayerFlag = x;    }
+#endif
 #if REPN_FORMAT_IN_VPS
   Bool   getRepFormatIdxPresentFlag()       { return m_repFormatIdxPresentFlag; }
@@ -883,4 +965,24 @@
   Bool   getPhaseAlignFlag()                             { return m_phaseAlignFlag; }
   Void   setPhaseAlignFlag(Bool x)                       { m_phaseAlignFlag = x;    }
+#endif
+#if VPS_DPB_SIZE_TABLE
+  Bool    getSubLayerFlagInfoPresentFlag(Int i)         {return m_subLayerFlagInfoPresentFlag[i]; }
+  Void    setSubLayerFlagInfoPresentFlag(Int i, Bool x) {m_subLayerFlagInfoPresentFlag[i] = x;    }
+
+  Bool    getSubLayerDpbInfoPresentFlag(Int i, Int j)         {return m_subLayerDpbInfoPresentFlag[i][j]; }
+  Void    setSubLayerDpbInfoPresentFlag(Int i, Int j, Bool x) {m_subLayerDpbInfoPresentFlag[i][j] = x;    }
+
+  // For the 0-th output layer set, use the date from the active SPS for base layer.
+  Int     getMaxVpsDecPicBufferingMinus1(Int i, Int k, Int j)         { assert(i != 0); return m_maxVpsDecPicBufferingMinus1[i][k][j]; }
+  Void    setMaxVpsDecPicBufferingMinus1(Int i, Int k, Int j, Int x) { m_maxVpsDecPicBufferingMinus1[i][k][j] = x;    }
+
+  Int     getMaxVpsNumReorderPics(Int i, Int j)         { assert(i != 0); return m_maxVpsNumReorderPics[i][j]; }
+  Void    setMaxVpsNumReorderPics(Int i, Int j, Int x) { m_maxVpsNumReorderPics[i][j] = x;    }
+
+  Int     getMaxVpsLatencyIncreasePlus1(Int i, Int j)         { assert(i != 0); return m_maxVpsLatencyIncreasePlus1[i][j]; }
+  Void    setMaxVpsLatencyIncreasePlus1(Int i, Int j, Int x) { m_maxVpsLatencyIncreasePlus1[i][j] = x;    }
+
+  Int     getNumSubDpbs(Int i)                          { return m_numSubDpbs[i]; }
+  Void    setNumSubDpbs(Int i, Int x)                   { m_numSubDpbs[i] = x;    }
 #endif
 #endif //SVC_EXTENSION
@@ -1185,11 +1287,4 @@
   UInt m_layerId;
 
-#if IL_SL_SIGNALLING_N0371
-  TComVPS*    m_pVPS;
-  static TComSPS* m_pcSPS[MAX_LAYERS];
-  Bool        m_predScalingListFlag;
-  UInt        m_scalingListRefLayerId;
-#endif
-
 #if REF_IDX_MFM
 #if !M0457_COL_PICTURE_SIGNALING
@@ -1198,7 +1293,17 @@
 #endif
   UInt        m_numScaledRefLayerOffsets;
+#if O0098_SCALED_REF_LAYER_ID
+  UInt        m_scaledRefLayerId[MAX_LAYERS];
+#endif
   Window      m_scaledRefLayerWindow[MAX_LAYERS];
 #if REPN_FORMAT_IN_VPS
   Bool m_updateRepFormatFlag;
+#if O0096_REP_FORMAT_INDEX
+  UInt m_updateRepFormatIndex;
+#endif
+#endif
+#if SCALINGLIST_INFERRING
+  Bool       m_inferScalingListFlag;
+  UInt       m_scalingListRefLayerId;
 #endif
 #endif //SVC_EXTENSION
@@ -1322,17 +1427,9 @@
   Void setScalingListPresentFlag( Bool b ) { m_scalingListPresentFlag  = b;       }
 
-#if IL_SL_SIGNALLING_N0371
-  Bool getPredScalingListFlag()         { return m_predScalingListFlag;     }
-  Void setPredScalingListFlag( Bool b ) { m_predScalingListFlag  = b;       }
-  UInt getScalingListRefLayerId()         { return m_scalingListRefLayerId;   }
-  Void setScalingListRefLayerId( UInt b ) { m_scalingListRefLayerId  = b;       }
-
-  TComVPS*  getVPS()                      { return  m_pVPS; }
-  Void      setVPS( TComVPS* vps )        { m_pVPS = vps;   }
-  static   TComSPS* getSPS(UInt layerId)               { return m_pcSPS[layerId]; }
-  static   Void     setSPS(UInt layerId, TComSPS* sps) { m_pcSPS[layerId] = sps;  }
-#endif
-
+#if SCALINGLIST_INFERRING
+  Void setScalingList( TComScalingList *scalingList ) { m_scalingList = scalingList; }
+#else
   Void setScalingList      ( TComScalingList *scalingList);
+#endif
   TComScalingList* getScalingList ()       { return m_scalingList; }               //!< get ScalingList class pointer in SPS
 
@@ -1380,8 +1477,23 @@
   UInt     getNumScaledRefLayerOffsets()  { return m_numScaledRefLayerOffsets; }
   Void     setNumScaledRefLayerOffsets(Int x)  { m_numScaledRefLayerOffsets = x; }
+#if O0098_SCALED_REF_LAYER_ID
+  UInt     getScaledRefLayerId(Int x)          { return m_scaledRefLayerId[x]; }
+  Void     setScaledRefLayerId(Int x, UInt id) { m_scaledRefLayerId[x] = id; }
+  Window&  getScaledRefLayerWindowForLayer( Int layerId );
+#endif
   Window&  getScaledRefLayerWindow( Int x )   { return m_scaledRefLayerWindow[x]; }
 #if REPN_FORMAT_IN_VPS
   Bool     getUpdateRepFormatFlag()       { return m_updateRepFormatFlag; }
   Void     setUpdateRepFormatFlag(Bool x) { m_updateRepFormatFlag = x;    }
+#if O0096_REP_FORMAT_INDEX
+  Int      getUpdateRepFormatIndex()      { return m_updateRepFormatIndex; }
+  Void     setUpdateRepFormatIndex(UInt index)  { m_updateRepFormatIndex = index; }
+#endif
+#endif
+#if SCALINGLIST_INFERRING
+  Bool     getInferScalingListFlag()  { return m_inferScalingListFlag;  }
+  UInt     getScalingListRefLayerId() { return m_scalingListRefLayerId; }
+  Void     setInferScalingListFlag( Bool flag )     { m_inferScalingListFlag = flag;     }
+  Void     setScalingListRefLayerId( UInt layerId ) { m_scalingListRefLayerId = layerId; }
 #endif
 #endif //SVC_EXTENSION
@@ -1468,21 +1580,16 @@
   Int      m_deblockingFilterTcOffsetDiv2;      //< tc offset for deblocking filter
   Bool     m_scalingListPresentFlag;
-
-#if SVC_EXTENSION
-  UInt m_layerId;
-
-#if IL_SL_SIGNALLING_N0371
-  static TComPPS* m_pcPPS[MAX_LAYERS];
-  Bool     m_predScalingListFlag;
-  UInt     m_scalingListRefLayerId;
-#endif
-
-#endif
-
   TComScalingList*     m_scalingList;   //!< ScalingList class pointer
-
   Bool m_listsModificationPresentFlag;
   UInt m_log2ParallelMergeLevelMinus2;
   Int m_numExtraSliceHeaderBits;
+
+#if SVC_EXTENSION
+#if SCALINGLIST_INFERRING
+  UInt     m_layerId;
+  Bool     m_inferScalingListFlag;
+  UInt     m_scalingListRefLayerId;
+#endif
+#endif
 
 public:
@@ -1596,18 +1703,18 @@
   Void     setScalingListPresentFlag( Bool b ) { m_scalingListPresentFlag  = b;       }
 
-#if IL_SL_SIGNALLING_N0371
-  Void     setLayerId(UInt layerId) { m_layerId = layerId; }
+#if SCALINGLIST_INFERRING
   UInt     getLayerId() { return m_layerId; }
-
-  Bool     getPredScalingListFlag()         { return m_predScalingListFlag;     }
-  Void     setPredScalingListFlag( Bool b ) { m_predScalingListFlag  = b;       }
-  UInt     getScalingListRefLayerId()         { return m_scalingListRefLayerId;     }
-  Void     setScalingListRefLayerId( UInt b ) { m_scalingListRefLayerId  = b;       }
-
-  static   TComPPS* getPPS(UInt layerId)               { return m_pcPPS[layerId]; }
-  static   Void     setPPS(UInt layerId, TComPPS* pps) { m_pcPPS[layerId] = pps;  }
-#endif
-
+  Void     setLayerId( UInt layerId ) { m_layerId = layerId;            }
+  Bool     getInferScalingListFlag()  { return m_inferScalingListFlag;  }
+  UInt     getScalingListRefLayerId() { return m_scalingListRefLayerId; }
+  Void     setInferScalingListFlag( Bool flag )     { m_inferScalingListFlag = flag;     }
+  Void     setScalingListRefLayerId( UInt layerId ) { m_scalingListRefLayerId = layerId; }
+#endif
+
+#if SCALINGLIST_INFERRING
+  Void     setScalingList( TComScalingList *scalingList ) { m_scalingList = scalingList; }
+#else
   Void     setScalingList      ( TComScalingList *scalingList);
+#endif
   TComScalingList* getScalingList ()          { return m_scalingList; }         //!< get ScalingList class pointer in PPS
   Bool getListsModificationPresentFlag ()          { return m_listsModificationPresentFlag; }
@@ -1705,10 +1812,5 @@
   UInt        m_maxNumMergeCand;
 
-#if SAO_CHROMA_LAMBDA
-  Double      m_dLambdaLuma;
-  Double      m_dLambdaChroma;
-#else
-  Double      m_dLambda;
-#endif
+  Double      m_lambdas[3];
 
   Bool        m_abEqualRef  [2][MAX_NUM_REF][MAX_NUM_REF];
@@ -1780,4 +1882,7 @@
 #endif  
   Bool        m_bDiscardableFlag;
+#if O0149_CROSS_LAYER_BLA_FLAG
+  Bool        m_bCrossLayerBLAFlag;
+#endif
 #endif //SVC_EXTENSION
 
@@ -1819,4 +1924,7 @@
   Int       getRPSidx          () { return m_iBDidx; }
   Int       getPrevTid0POC      ()                        { return  m_prevTid0POC;       }
+#if PREVTID0_POC_RESET
+    Void     adjustPrevTid0POC      (Int adj)             { m_prevTid0POC=m_prevTid0POC-adj; }
+#endif
   TComRefPicListModification* getRefPicListModification() { return &m_RefPicListModification; }
   Void      setLastIDR(Int iIDRPOC)                       { m_iLastIDR = iIDRPOC; }
@@ -1866,5 +1974,9 @@
   Bool      isIRAP              () const                        { return (getNalUnitType() >= 16) && (getNalUnitType() <= 23); }  
   Void      checkCRA(TComReferencePictureSet *pReferencePictureSet, Int& pocCRA, NalUnitType& associatedIRAPType, TComList<TComPic *>& rcListPic);
+#if NO_CLRAS_OUTPUT_FLAG
+  Void      decodingRefreshMarking(Int& pocCRA, Bool& bRefreshPending, TComList<TComPic*>& rcListPic, Bool noClrasOutputFlag);
+#else
   Void      decodingRefreshMarking(Int& pocCRA, Bool& bRefreshPending, TComList<TComPic*>& rcListPic);
+#endif
   Void      setSliceType        ( SliceType e )                 { m_eSliceType        = e;      }
   Void      setSliceQp          ( Int i )                       { m_iSliceQp          = i;      }
@@ -1886,12 +1998,8 @@
   Void      setDepth            ( Int iDepth )                  { m_iDepth            = iDepth; }
 
-#if FIX1071
 #if SVC_EXTENSION
   Void      setRefPicList       ( TComList<TComPic*>& rcListPic, Bool checkNumPocTotalCurr = false, TComPic** ilpPic = NULL );
 #else
   Void      setRefPicList       ( TComList<TComPic*>& rcListPic, Bool checkNumPocTotalCurr = false );
-#endif
-#else
-  Void      setRefPicList       ( TComList<TComPic*>& rcListPic );
 #endif
   Void      setRefPOCList       ();
@@ -1905,12 +2013,6 @@
   Bool      isInterP        ()                          { return  m_eSliceType == P_SLICE;  }
   
-#if SAO_CHROMA_LAMBDA  
-  Void      setLambda( Double d, Double e ) { m_dLambdaLuma = d; m_dLambdaChroma = e;}
-  Double    getLambdaLuma() { return m_dLambdaLuma;        }
-  Double    getLambdaChroma() { return m_dLambdaChroma;        }
-#else
-  Void      setLambda( Double d ) { m_dLambda = d; }
-  Double    getLambda() { return m_dLambda;        }
-#endif
+  Void      setLambdas ( const Double lambdas[3] ) { for (Int component = 0; component < 3; component++) m_lambdas[component] = lambdas[component]; }
+  const Double* getLambdas() const { return m_lambdas; }
   
   Void      initEqualRef();
@@ -1939,9 +2041,5 @@
   Bool isStepwiseTemporalLayerSwitchingPointCandidate( TComList<TComPic*>& rcListPic );
   Int       checkThatAllRefPicsAreAvailable( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool printErrors, Int pocRandomAccess = 0);
-#if FIX1071
   Void      createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool isRAP);
-#else
-  Void      createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet);
-#endif
 
   Void setMaxNumMergeCand               (UInt val )         { m_maxNumMergeCand = val;                    }
@@ -2001,11 +2099,5 @@
   Void  setScalingList              ( TComScalingList* scalingList ) { m_scalingList = scalingList; }
   TComScalingList*   getScalingList ()                               { return m_scalingList; }
-
-#if IL_SL_SIGNALLING_N0371
-  Void  setDefaultScalingList       ( UInt m_layerId );
-#else
   Void  setDefaultScalingList       ();
-#endif
-
   Bool  checkDefaultScalingList     ();
   Void      setCabacInitFlag  ( Bool val ) { m_cabacInitFlag = val;      }  //!< set CABAC initial flag 
@@ -2022,5 +2114,5 @@
 
 #if SVC_EXTENSION
-  Void      setBaseColPic       ( TComList<TComPic*>& rcListPic , UInt refLayerIdc );
+  Bool      setBaseColPic       ( TComList<TComPic*>& rcListPic , UInt refLayerIdc );
   Void      setBaseColPic       (UInt refLayerIdc, TComPic* p)     { m_pcBaseColPic[refLayerIdc] = p; }
   TComPic*  getBaseColPic       (UInt refLayerIdc)                { return m_pcBaseColPic[refLayerIdc]; }
@@ -2099,4 +2191,8 @@
   Bool      getDiscardableFlag  ()                           { return m_bDiscardableFlag;    }
   Void      setDiscardableFlag  (Bool b)                     { m_bDiscardableFlag = b;       }
+#if O0149_CROSS_LAYER_BLA_FLAG
+  Bool      getCrossLayerBLAFlag  ()                         { return m_bCrossLayerBLAFlag;  }
+  Void      setCrossLayerBLAFlag  (Bool b)                   { m_bCrossLayerBLAFlag = b;     }
+#endif
 
 #if RPL_INIT_N0316_N0082
Index: trunk/source/Lib/TLibCommon/TComTrQuant.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComTrQuant.cpp	(revision 499)
+++ trunk/source/Lib/TLibCommon/TComTrQuant.cpp	(revision 540)
@@ -54,8 +54,8 @@
   {
     iNNZbeforePos0 = 0;
-  d64CodedLevelandDist = 0;
-  d64UncodedDist = 0;
-  d64SigCost = 0;
-  d64SigCost_0 = 0;
+    d64CodedLevelandDist = 0;
+    d64UncodedDist = 0;
+    d64SigCost = 0;
+    d64SigCost_0 = 0;
   }
 #endif
@@ -1944,5 +1944,5 @@
               Int64 costUp   = rdFactor * ( - deltaU[uiBlkPos] ) + rateIncUp[uiBlkPos] ;
               Int64 costDown = rdFactor * (   deltaU[uiBlkPos] ) + rateIncDown[uiBlkPos] 
-              -   ( abs(piDstCoeff[uiBlkPos])==1?((1<<15)+sigRateDelta[uiBlkPos]):0 );
+              -   ((abs(piDstCoeff[uiBlkPos]) == 1) ? sigRateDelta[uiBlkPos] : 0);
               
               if(lastCG==1 && lastNZPosInCG==n && abs(piDstCoeff[uiBlkPos])==1)
@@ -2163,5 +2163,5 @@
   {
     Double dErr         = Double( lLevelDouble  - ( uiAbsLevel << iQBits ) );
-    Double dCurrCost    = dErr * dErr * dTemp + xGetICRateCost( uiAbsLevel, ui16CtxNumOne, ui16CtxNumAbs, ui16AbsGoRice, c1Idx, c2Idx );
+    Double dCurrCost    = dErr * dErr * dTemp + xGetICost(xGetICRate( uiAbsLevel, ui16CtxNumOne, ui16CtxNumAbs, ui16AbsGoRice, c1Idx, c2Idx ));
     dCurrCost          += dCurrCostSig;
 
@@ -2184,5 +2184,5 @@
  * \returns cost of given absolute transform level
  */
-__inline Double TComTrQuant::xGetICRateCost  ( UInt                            uiAbsLevel,
+__inline Int TComTrQuant::xGetICRate  ( UInt                            uiAbsLevel,
                                                UShort                          ui16CtxNumOne,
                                                UShort                          ui16CtxNumAbs,
@@ -2192,5 +2192,5 @@
                                                ) const
 {
-  Double iRate = xGetIEPRate();
+  Int iRate = Int(xGetIEPRate());
   UInt baseLevel  =  (c1Idx < C1FLAG_NUMBER)? (2 + (c2Idx < C2FLAG_NUMBER)) : 1;
 
@@ -2236,66 +2236,5 @@
   else
   {
-    assert (0);
-  }
-  return xGetICost( iRate );
-}
-
-__inline Int TComTrQuant::xGetICRate  ( UInt                            uiAbsLevel,
-                                       UShort                          ui16CtxNumOne,
-                                       UShort                          ui16CtxNumAbs,
-                                       UShort                          ui16AbsGoRice
-                                     , UInt                            c1Idx,
-                                       UInt                            c2Idx
-                                       ) const
-{
-  Int iRate = 0;
-  UInt baseLevel  =  (c1Idx < C1FLAG_NUMBER)? (2 + (c2Idx < C2FLAG_NUMBER)) : 1;
-
-  if ( uiAbsLevel >= baseLevel )
-  {
-    UInt uiSymbol     = uiAbsLevel - baseLevel;
-    UInt uiMaxVlc     = g_auiGoRiceRange[ ui16AbsGoRice ];
-    Bool bExpGolomb   = ( uiSymbol > uiMaxVlc );
-
-    if( bExpGolomb )
-    {
-      uiAbsLevel  = uiSymbol - uiMaxVlc;
-      Int iEGS    = 1;  for( UInt uiMax = 2; uiAbsLevel >= uiMax; uiMax <<= 1, iEGS += 2 );
-      iRate      += iEGS << 15;
-      uiSymbol    = min<UInt>( uiSymbol, ( uiMaxVlc + 1 ) );
-    }
-
-    UShort ui16PrefLen = UShort( uiSymbol >> ui16AbsGoRice ) + 1;
-    UShort ui16NumBins = min<UInt>( ui16PrefLen, g_auiGoRicePrefixLen[ ui16AbsGoRice ] ) + ui16AbsGoRice;
-
-    iRate += ui16NumBins << 15;
-
-    if (c1Idx < C1FLAG_NUMBER)
-    {
-      iRate += m_pcEstBitsSbac->m_greaterOneBits[ ui16CtxNumOne ][ 1 ];
-
-      if (c2Idx < C2FLAG_NUMBER)
-      {
-        iRate += m_pcEstBitsSbac->m_levelAbsBits[ ui16CtxNumAbs ][ 1 ];
-      }
-    }
-  }
-  else
-  if( uiAbsLevel == 0 )
-  {
-    return 0;
-  }
-  else if( uiAbsLevel == 1 )
-  {
-    iRate += m_pcEstBitsSbac->m_greaterOneBits[ ui16CtxNumOne ][ 0 ];
-  }
-  else if( uiAbsLevel == 2 )
-  {
-    iRate += m_pcEstBitsSbac->m_greaterOneBits[ ui16CtxNumOne ][ 1 ];
-    iRate += m_pcEstBitsSbac->m_levelAbsBits[ ui16CtxNumAbs ][ 0 ];
-  }
-  else
-  {
-    assert(0);
+    iRate = 0;
   }
   return iRate;
@@ -2494,9 +2433,5 @@
 /** set flat matrix value to quantized coefficient
  */
-#if IL_SL_SIGNALLING_N0371
-Void TComTrQuant::setFlatScalingList( UInt m_layerId )
-#else
 Void TComTrQuant::setFlatScalingList()
-#endif
 {
   UInt size,list;
@@ -2507,12 +2442,4 @@
     for(list = 0; list <  g_scalingListNum[size]; list++)
     {
-#if IL_SL_SIGNALLING_N0371
-      ref_scalingListDC[m_layerId][size][list] = SCALING_LIST_DC;
-      for(UInt i=0; i<MAX_MATRIX_COEF_NUM; i++)
-      {
-        ref_scalingListCoef[m_layerId][size][list][i] = SCALING_LIST_DC;
-      }
-#endif
-
       for(qp=0;qp<SCALING_LIST_REM_NUM;qp++)
       {
Index: trunk/source/Lib/TLibCommon/TComTrQuant.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComTrQuant.h	(revision 499)
+++ trunk/source/Lib/TLibCommon/TComTrQuant.h	(revision 540)
@@ -150,6 +150,6 @@
 
 #if RDOQ_CHROMA_LAMBDA 
-  Void setLambda(Double dLambdaLuma, Double dLambdaChroma) { m_dLambdaLuma = dLambdaLuma; m_dLambdaChroma = dLambdaChroma; }
-  Void selectLambda(TextType eTType) { m_dLambda = (eTType == TEXT_LUMA) ? m_dLambdaLuma : m_dLambdaChroma; }
+  Void setLambdas ( const Double lambdas[3] ) { for (Int component = 0; component < 3; component++) m_lambdas[component] = lambdas[component]; }
+  Void selectLambda(TextType eTType) { m_dLambda = (eTType == TEXT_LUMA) ? m_lambdas[0] : ((eTType == TEXT_CHROMA_U) ? m_lambdas[1] : m_lambdas[2]); }
 #else
   Void setLambda(Double dLambda) { m_dLambda = dLambda;}
@@ -181,11 +181,5 @@
   Void setUseScalingList   ( Bool bUseScalingList){ m_scalingListEnabledFlag = bUseScalingList; };
   Bool getUseScalingList   (){ return m_scalingListEnabledFlag; };
-
-#if IL_SL_SIGNALLING_N0371
-  Void setFlatScalingList  ( UInt m_layerId );
-#else
   Void setFlatScalingList  ();
-#endif
-
   Void xsetFlatScalingList ( UInt list, UInt size, UInt qp);
   Void xSetScalingListEnc  ( TComScalingList *scalingList, UInt list, UInt size, UInt qp);
@@ -213,6 +207,5 @@
   QpParam  m_cQP;
 #if RDOQ_CHROMA_LAMBDA
-  Double   m_dLambdaLuma;
-  Double   m_dLambdaChroma;
+  Double   m_lambdas[3];
 #endif
   Double   m_dLambda;
@@ -279,11 +272,4 @@
                                              Double                          dTemp,
                                              Bool                            bLast        ) const;
-  __inline Double xGetICRateCost   ( UInt                            uiAbsLevel,
-                                     UShort                          ui16CtxNumOne,
-                                     UShort                          ui16CtxNumAbs,
-                                     UShort                          ui16AbsGoRice 
-                                   , UInt                            c1Idx,
-                                     UInt                            c2Idx
-                                     ) const;
 __inline Int xGetICRate  ( UInt                            uiAbsLevel,
                            UShort                          ui16CtxNumOne,
Index: trunk/source/Lib/TLibCommon/TypeDef.h
===================================================================
--- trunk/source/Lib/TLibCommon/TypeDef.h	(revision 499)
+++ trunk/source/Lib/TLibCommon/TypeDef.h	(revision 540)
@@ -51,5 +51,5 @@
 #define O0194_JOINT_US_BITSHIFT          1      ///< JCTVC-O0194: Joint Upsampling and bit-shift
 #endif
-#define O0194_WEIGHTED_PREDICTION_CGS    1      ///< JCTVC-O0194: Weighted prediciton for color gamut scalability
+#define O0194_WEIGHTED_PREDICTION_CGS    0      ///< JCTVC-O0194: Weighted prediciton for color gamut scalability
 #define MFM_ENCCONSTRAINT                1      ///< JCTVC-O0216: Encoder constraint for motion field mapping
 #define VPS_NUH_LAYER_ID                 1      ///< JCTVC-N0085: Assert that the nuh_layer_id of VPS NAL unit should be 0
@@ -57,13 +57,23 @@
 #define ALIGN_TSA_STSA_PICS              1      ///< JCTVC-N0084: Alignment of TSA and STSA pictures across AU.
 #define REPN_FORMAT_IN_VPS               1      ///< JCTVC-N0092: Signal represenation format (spatial resolution, bit depth, colour format) in the VPS
+#if REPN_FORMAT_IN_VPS
+#define REPN_FORMAT_CONTROL_FLAG         1      ///< JCTVC-O0179: Add control flag in representation format to control sending of chroma and bitdepth parameters
+#endif 
 #define TIMING_INFO_NONZERO_LAYERID_SPS  1      ///< JCTVC-N0085: Semantics of vui_timing_info_present_flag to always set that flag to zero for non-zero layer ID SPS 
 #define RPL_INIT_N0316_N0082             1      ///< JCTVC-N0316, JCTVC-N0082: initial reference picture list construction 
 
-#define IL_SL_SIGNALLING_N0371           0      ///< JCTVC-N0371: inter-layer scaling list
+#define SCALINGLIST_INFERRING            1      ///< JCTVC-N0371: inter-layer scaling list
 #define M0463_VUI_EXT_ILP_REF            0      ///< JCTVC-M0463: VUI extension inter-layer dependency offset signalling
 #define SPS_EXTENSION                    1      ///< Define sps_extension() syntax structure
+#if SPS_EXTENSION
+#define O0142_CONDITIONAL_SPS_EXTENSION  1      ///< JCTVC-O0142: Conditional SPS extension
+#endif
 #define VERT_MV_CONSTRAINT               1      ///< Vertical MV component constraint flag
 #define SCALABILITY_MASK_E0104           1      ///< JCT3V-E0104: scalability mask for depth
 #define LAYER_CTB                        0      ///< enable layer-specific CTB structure
+#if POC_RESET_FLAG
+#define PREVTID0_POC_RESET               1      ///< JCTVC-O0117 Modification of the PicOrderCntVal of prevTid0Pic
+#define POC_RESET_RPS                    1      ///< JCTVC-O0117 Modification to the decoding process for rps
+#endif
 
 #define ILP_SSH_SIG                      1      ///< JCTVC-N0195 proposal 2, JCTVC-N0118: add presence flag in VPS ext to condition inter-layer prediction signaling in slice segment header
@@ -86,7 +96,13 @@
 
 #if VPS_VUI
+#define VPS_VUI_TILES_NOT_IN_USE__FLAG    1      ///< JCTVC-O0226: VPS VUI flag to indicate tile not in use
+#define VPS_VUI_WPP_NOT_IN_USE__FLAG    1      ///< JCTVC-O0226: VPS VUI flag to indicate tile not in use
 #define TILE_BOUNDARY_ALIGNED_FLAG       1      ///< JCTVC-N0160/JCTVC-N0199 proposal 2 variant 2: VPS VUI flag to indicate tile boundary alignment
 #define N0160_VUI_EXT_ILP_REF            1      ///< VUI extension inter-layer dependency offset signalling
 #define VPS_VUI_BITRATE_PICRATE          1      ///< JCTVC-N0085: Signal bit rate and picture in VPS VUI
+#if M0040_ADAPTIVE_RESOLUTION_CHANGE
+#define HIGHER_LAYER_IRAP_SKIP_FLAG      1      ///< JCTVC-O0199: Indication that higher layer IRAP picture uses skip blocks only
+#endif
+#define VPS_VUI_VIDEO_SIGNAL             1      ///< JCTVC-O0118 video signal information
 #endif //VPS_VUI
 
@@ -127,4 +143,8 @@
 #define N0120_MAX_TID_REF_CFG            1      ///< set max_tid_il_ref_pics_plus1 and max_tid_ref_present_flag in the config. file (configuration setting)
 #define O0225_MAX_TID_FOR_REF_LAYERS     1
+#define O0225_TID_BASED_IL_RPS_DERIV     1
+
+#define VPS_TSLAYERS                     1      ///< JCTVC-O0120 signal max temporal sub-layers for each layer
+#define TSLAYERS_IL_RPS                  1      ///< JCTVC-O0120 IL RPS based on max temporal sub-layers
 #endif
 #if REF_IDX_MFM
@@ -139,4 +159,6 @@
 #define M0457_IL_SAMPLE_PRED_ONLY_FLAG   0      ///< shall be 0, JCTVC-N0107
 #endif
+
+#define O0223_PICTURE_TYPES_ALIGN_FLAG   1  ///< a flag to indicatate whether picture types are aligned across layers.
 
 #define N0147_IRAP_ALIGN_FLAG            1      ///< a flag to indicatate whether IRAPs are aligned across layers
@@ -166,4 +188,27 @@
 #define SHM_FIX7                         1      ///< fix for SHVC WD ticket #7
 
+#define O0092_0094_DEPENDENCY_CONSTRAINT 1      ///< JCTVC-O0092: constraint on the layer_id of SPS/PPS
+#if O0092_0094_DEPENDENCY_CONSTRAINT
+#define MAX_REF_LAYERS                   7
+#endif
+#define O0096_REP_FORMAT_INDEX           1      ///< JCTVC-O0096: identify SPS rep_format() with an index into the lists of formats in VPS extension.
+#define O0096_DEFAULT_DEPENDENCY_TYPE    1      ///< JCTVC-O0096: specify default dependency type for all direct reference layers
+
+#define RESAMPLING_CONSTRAINT_BUG_FIX    1
+#define O0098_SCALED_REF_LAYER_ID        1      ///< JCTVC-O0098: signal scaled reference id
+
+#define O0153_ALT_OUTPUT_LAYER_FLAG      1      ///< JCTVC-O0153: alt output layer flag
+
+#define VPS_DPB_SIZE_TABLE               1      ///< JCTVC-O0217: DPB operations: signaling DPB-related parameters
+#if VPS_DPB_SIZE_TABLE 
+#define OUTPUT_LAYER_SET_INDEX           1      ///< JCTVC-O0217: DPB operations: Inference/input of output layer set index
+#if OUTPUT_LAYER_SET_INDEX
+#define USE_DPB_SIZE_TABLE               1      ///< JCTVC-O0217: DPB operations: Use signaled DPB-size table parameters in the decoder
+#endif
+#endif
+
+#define NO_CLRAS_OUTPUT_FLAG             1
+#define O0149_CROSS_LAYER_BLA_FLAG       1      ///< JCTVC-O0149: signal cross_layer_bla_flag in slice header
+
 #else
 #define SYNTAX_OUTPUT                    0
@@ -174,5 +219,8 @@
 //! \{
 
-#define FIX1071 1 ///< fix for issue #1071
+#define HM_CLEANUP_SAO                  1  ///< JCTVC-N0230, 1) three SAO encoder-only software bugfixes. 2) new SAO implementation without picture quadtree, fine-grained slice legacies, and other redundancies.
+#if HM_CLEANUP_SAO  
+#define SAO_ENCODE_ALLOW_USE_PREDEBLOCK 1
+#endif
 
 #define MAX_NUM_PICS_IN_SOP           1024
@@ -184,4 +232,5 @@
 #define MAX_VPS_NUM_SCALABILITY_TYPES             16
 #endif
+#define MAX_VPS_OP_LAYER_SETS_PLUS1               3
 #if VPS_RENAME
 #define MAX_VPS_LAYER_SETS_PLUS1                  1024
@@ -192,10 +241,4 @@
 #define MAX_VPS_NUH_RESERVED_ZERO_LAYER_ID_PLUS1  1
 #endif
-#define RATE_CONTROL_LAMBDA_DOMAIN                  1  ///< JCTVC-K0103, rate control by R-lambda model
-#define M0036_RC_IMPROVEMENT                        1  ///< JCTVC-M0036, improvement for R-lambda model based rate control
-#define TICKET_1090_FIX                             1
-
-#define RC_FIX                                      1  /// suggested fix for M0036
-#define RATE_CONTROL_INTRA                          1  ///< JCTVC-M0257, rate control for intra 
 
 #define MAX_CPB_CNT                     32  ///< Upper bound of (cpb_cnt_minus1 + 1)
@@ -216,7 +259,7 @@
 #define C1FLAG_NUMBER               8 // maximum number of largerThan1 flag coded in one chunk :  16 in HM5
 #define C2FLAG_NUMBER               1 // maximum number of largerThan2 flag coded in one chunk:  16 in HM5 
-
+#if !HM_CLEANUP_SAO
 #define REMOVE_SAO_LCU_ENC_CONSTRAINTS_3 1  ///< disable the encoder constraint that conditionally disable SAO for chroma for entire slice in interleaved mode
-
+#endif
 #define SAO_ENCODING_CHOICE              1  ///< I0184: picture early termination
 #if SAO_ENCODING_CHOICE
@@ -232,7 +275,5 @@
 #define MAX_NUM_PPS                64
 
-#define WEIGHTED_CHROMA_DISTORTION  1   ///< F386: weighting of chroma for RDO
 #define RDOQ_CHROMA_LAMBDA          1   ///< F386: weighting of chroma for RDOQ
-#define SAO_CHROMA_LAMBDA           1   ///< F386: weighting of chroma for SAO
 
 #define MIN_SCAN_POS_CROSS          4
@@ -248,6 +289,4 @@
 #define LEVEL_RANGE                         30     ///< G382: max coefficient level in statistics collection
 #endif
-
-#define NS_HAD                               0
 
 #define HHI_RQT_INTRA_SPEEDUP             1           ///< tests one best mode with full rqt
@@ -316,6 +355,4 @@
 #define AMP_MRG                               1           ///< encoder only force merge for AMP partition (no motion search for AMP)
 #endif
-
-#define SCALING_LIST_OUTPUT_RESULT    0 //JCTVC-G880/JCTVC-G1016 quantization matrices
 
 #define CABAC_INIT_PRESENT_FLAG     1
@@ -377,4 +414,97 @@
 };
 
+#if HM_CLEANUP_SAO
+enum SAOComponentIdx
+{
+  SAO_Y =0,
+  SAO_Cb,
+  SAO_Cr,
+  NUM_SAO_COMPONENTS
+};
+
+enum SAOMode //mode
+{
+  SAO_MODE_OFF = 0,
+  SAO_MODE_NEW,
+  SAO_MODE_MERGE,
+  NUM_SAO_MODES
+};
+
+enum SAOModeMergeTypes 
+{
+  SAO_MERGE_LEFT =0,
+  SAO_MERGE_ABOVE,
+  NUM_SAO_MERGE_TYPES
+};
+
+
+enum SAOModeNewTypes 
+{
+  SAO_TYPE_START_EO =0,
+  SAO_TYPE_EO_0 = SAO_TYPE_START_EO,
+  SAO_TYPE_EO_90,
+  SAO_TYPE_EO_135,
+  SAO_TYPE_EO_45,
+  
+  SAO_TYPE_START_BO,
+  SAO_TYPE_BO = SAO_TYPE_START_BO,
+
+  NUM_SAO_NEW_TYPES
+};
+#define NUM_SAO_EO_TYPES_LOG2 2
+
+enum SAOEOClasses 
+{
+  SAO_CLASS_EO_FULL_VALLEY = 0,
+  SAO_CLASS_EO_HALF_VALLEY = 1,
+  SAO_CLASS_EO_PLAIN       = 2,
+  SAO_CLASS_EO_HALF_PEAK   = 3,
+  SAO_CLASS_EO_FULL_PEAK   = 4,
+  NUM_SAO_EO_CLASSES,
+};
+
+
+#define NUM_SAO_BO_CLASSES_LOG2  5
+enum SAOBOClasses
+{
+  //SAO_CLASS_BO_BAND0 = 0,
+  //SAO_CLASS_BO_BAND1,
+  //SAO_CLASS_BO_BAND2,
+  //...
+  //SAO_CLASS_BO_BAND31,
+
+  NUM_SAO_BO_CLASSES = (1<<NUM_SAO_BO_CLASSES_LOG2),
+};
+#define MAX_NUM_SAO_CLASSES  32  //(NUM_SAO_EO_GROUPS > NUM_SAO_BO_GROUPS)?NUM_SAO_EO_GROUPS:NUM_SAO_BO_GROUPS
+
+struct SAOOffset
+{
+  Int modeIdc; //NEW, MERGE, OFF
+  Int typeIdc; //NEW: EO_0, EO_90, EO_135, EO_45, BO. MERGE: left, above
+  Int typeAuxInfo; //BO: starting band index
+  Int offset[MAX_NUM_SAO_CLASSES];
+
+  SAOOffset();
+  ~SAOOffset();
+  Void reset();
+
+  const SAOOffset& operator= (const SAOOffset& src);
+};
+
+struct SAOBlkParam
+{
+
+  SAOBlkParam();
+  ~SAOBlkParam();
+  Void reset();
+  const SAOBlkParam& operator= (const SAOBlkParam& src);
+  SAOOffset& operator[](Int compIdx){ return offsetParam[compIdx];}
+private:
+  SAOOffset offsetParam[NUM_SAO_COMPONENTS];
+
+};
+
+
+#else
 #define NUM_DOWN_PART 4
 
@@ -448,5 +578,5 @@
   ~SAOParam();
 };
-
+#endif
 /// parameters for deblocking filter
 typedef struct _LFCUParam
Index: trunk/source/Lib/TLibDecoder/NALread.cpp
===================================================================
--- trunk/source/Lib/TLibDecoder/NALread.cpp	(revision 499)
+++ trunk/source/Lib/TLibDecoder/NALread.cpp	(revision 540)
@@ -126,5 +126,5 @@
   else
   {
-    assert( nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_TLA_R
+    assert( nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_TSA_R
          && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_TSA_N
          && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_STSA_R
Index: trunk/source/Lib/TLibDecoder/TDecCAVLC.cpp
===================================================================
--- trunk/source/Lib/TLibDecoder/TDecCAVLC.cpp	(revision 499)
+++ trunk/source/Lib/TLibDecoder/TDecCAVLC.cpp	(revision 540)
@@ -290,57 +290,35 @@
     }
   }
+
+#if SCALINGLIST_INFERRING
+  if( pcPPS->getLayerId() > 0 )
+  {
+    READ_FLAG( uiCode, "pps_infer_scaling_list_flag" );
+    pcPPS->setInferScalingListFlag( uiCode );
+  }
+
+  if( pcPPS->getInferScalingListFlag() )
+  {
+    READ_UVLC( uiCode, "pps_scaling_list_ref_layer_id" ); pcPPS->setScalingListRefLayerId( uiCode );
+
+    // The value of pps_scaling_list_ref_layer_id shall be in the range of 0 to 62, inclusive
+    assert( pcPPS->getScalingListRefLayerId() <= 62 );
+
+    pcPPS->setScalingListPresentFlag( false );
+  }
+  else
+  {
+#endif
+
   READ_FLAG( uiCode, "pps_scaling_list_data_present_flag" );           pcPPS->setScalingListPresentFlag( uiCode ? true : false );
 
-#if IL_SL_SIGNALLING_N0371
-  pcPPS->setPPS( pcPPS->getLayerId(), pcPPS );
-#endif
-
   if(pcPPS->getScalingListPresentFlag ())
   {
-#if IL_SL_SIGNALLING_N0371
-    pcPPS->getScalingList()->setLayerId( pcPPS->getLayerId() );
-
-    if( pcPPS->getLayerId() > 0 )
-    {
-      READ_FLAG( uiCode, "pps_pred_scaling_list_flag" );           pcPPS->setPredScalingListFlag( uiCode ? true : false );
-      pcPPS->getScalingList()->setPredScalingListFlag( pcPPS->getPredScalingListFlag() );
-
-      if( pcPPS->getPredScalingListFlag() )
-      {
-        READ_UVLC ( uiCode, "scaling_list_pps_ref_layer_id" );   pcPPS->setScalingListRefLayerId( uiCode );
-
-        // The value of pps_scaling_list_ref_layer_id shall be in the range of 0 to 62, inclusive
-        assert( /*pcPPS->getScalingListRefLayerId() >= 0 &&*/ pcPPS->getScalingListRefLayerId() <= 62 );
-
-        // When avc_base_layer_flag is equal to 1, it is a requirement of bitstream conformance that the value of pps_scaling_list_ref_layer_id shall be greater than 0
-        if( pcPPS->getSPS()->getVPS()->getAvcBaseLayerFlag() )
-        {
-          assert( pcPPS->getScalingListRefLayerId() > 0 );
-        }
-
-        // It is a requirement of bitstream conformance that, when a PPS with nuh_layer_id equal to nuhLayerIdA is active for a layer with nuh_layer_id equal to nuhLayerIdB and
-        // pps_infer_scaling_list_flag in the PPS is equal to 1, pps_infer_scaling_list_flag shall be equal to 0 for the PPS that is active for the layer with nuh_layer_id equal to pps_scaling_list_ref_layer_id
-        assert( pcPPS->getPPS( pcPPS->getScalingListRefLayerId() )->getPredScalingListFlag() == false );
-
-        // It is a requirement of bitstream conformance that, when a PPS with nuh_layer_id equal to nuhLayerIdA is active for a layer with nuh_layer_id equal to nuhLayerIdB,
-        // the layer with nuh_layer_id equal to pps_scaling_list_ref_layer_id shall be a direct or indirect reference layer of the layer with nuh_layer_id equal to nuhLayerIdB
-        assert( pcPPS->getSPS()->getVPS()->getScalingListLayerDependency( pcPPS->getLayerId(), pcPPS->getScalingListRefLayerId() ) == true );
-
-        pcPPS->getScalingList()->setScalingListRefLayerId( pcPPS->getScalingListRefLayerId() );
-        parseScalingList( pcPPS->getScalingList() );
-      }
-      else
-      {
-        parseScalingList( pcPPS->getScalingList() );
-      }
-    }
-    else
-    {
-      parseScalingList( pcPPS->getScalingList() );
-    }
-#else
     parseScalingList( pcPPS->getScalingList() );
-#endif
-  }
+  }
+
+#if SCALINGLIST_INFERRING
+  }
+#endif
 
   READ_FLAG( uiCode, "lists_modification_present_flag");
@@ -563,8 +541,4 @@
     pcSPS->setTemporalIdNestingFlag( parameterSetManager->getPrefetchedVPS(pcSPS->getVPSId())->getTemporalNestingFlag() );
   }
-#if IL_SL_SIGNALLING_N0371
-  pcSPS->setVPS( parameterSetManager->getPrefetchedVPS(pcSPS->getVPSId()) );
-  pcSPS->setSPS( pcSPS->getLayerId(), pcSPS );
-#endif
 #endif
   if ( pcSPS->getMaxTLayers() == 1 )
@@ -599,5 +573,9 @@
     pcSPS->setUpdateRepFormatFlag( true );
   }
+#if O0096_REP_FORMAT_INDEX
+  if( pcSPS->getLayerId() == 0 )
+#else
   if( pcSPS->getLayerId() == 0 || pcSPS->getUpdateRepFormatFlag() )
+#endif
   {
 #endif
@@ -619,4 +597,11 @@
 #if REPN_FORMAT_IN_VPS
   }
+#if O0096_REP_FORMAT_INDEX
+  else if ( pcSPS->getUpdateRepFormatFlag() )
+  {
+    READ_CODE(8, uiCode, "update_rep_format_index");
+    pcSPS->setUpdateRepFormatIndex(uiCode);
+  }
+#endif
 #endif
   READ_FLAG(     uiCode, "conformance_window_flag");
@@ -637,5 +622,9 @@
   }
 #if REPN_FORMAT_IN_VPS
+#if O0096_REP_FORMAT_INDEX
+  if( pcSPS->getLayerId() == 0 )
+#else
   if(  pcSPS->getLayerId() == 0 || pcSPS->getUpdateRepFormatFlag() )
+#endif
   {
 #endif
@@ -701,54 +690,30 @@
   if(pcSPS->getScalingListFlag())
   {
+#if SCALINGLIST_INFERRING
+    if( pcSPS->getLayerId() > 0 )
+    {
+      READ_FLAG( uiCode, "sps_infer_scaling_list_flag" ); pcSPS->setInferScalingListFlag( uiCode );
+    }
+
+    if( pcSPS->getInferScalingListFlag() )
+    {
+      READ_UVLC( uiCode, "sps_scaling_list_ref_layer_id" ); pcSPS->setScalingListRefLayerId( uiCode );
+
+      // The value of pps_scaling_list_ref_layer_id shall be in the range of 0 to 62, inclusive
+      assert( pcSPS->getScalingListRefLayerId() <= 62 );
+
+      pcSPS->setScalingListPresentFlag( false );
+    }
+    else
+    {
+#endif
     READ_FLAG( uiCode, "sps_scaling_list_data_present_flag" );                 pcSPS->setScalingListPresentFlag ( uiCode );
     if(pcSPS->getScalingListPresentFlag ())
     {
-
-#if IL_SL_SIGNALLING_N0371
-      pcSPS->getScalingList()->setLayerId( pcSPS->getLayerId() );
-
-      if( pcSPS->getLayerId() > 0 )
-      {
-        READ_FLAG( uiCode, "sps_pred_scaling_list_flag" );  pcSPS->setPredScalingListFlag ( uiCode );
-        pcSPS->getScalingList()->setPredScalingListFlag( pcSPS->getPredScalingListFlag() );
-
-        if( pcSPS->getPredScalingListFlag() )
-        {
-          READ_UVLC( uiCode, "scaling_list_sps_ref_layer_id" );    pcSPS->setScalingListRefLayerId( uiCode );
-
-          // The value of sps_scaling_list_ref_layer_id shall be in the range of 0 to 62, inclusive
-          assert( /*pcSPS->getScalingListRefLayerId() >= 0 &&*/ pcSPS->getScalingListRefLayerId() <= 62 );
-
-          // When avc_base_layer_flag is equal to 1, it is a requirement of bitstream conformance that the value of sps_scaling_list_ref_layer_id shall be greater than 0
-          if( pcSPS->getVPS()->getAvcBaseLayerFlag() )
-          {
-            assert( pcSPS->getScalingListRefLayerId() > 0 );
-          }
-
-          // It is a requirement of bitstream conformance that, when an SPS with nuh_layer_id equal to nuhLayerIdA is active for a layer with nuh_layer_id equal to nuhLayerIdB and
-          // sps_infer_scaling_list_flag in the SPS is equal to 1, sps_infer_scaling_list_flag shall be equal to 0 for the SPS that is active for the layer with nuh_layer_id equal to sps_scaling_list_ref_layer_id
-          assert( pcSPS->getSPS( pcSPS->getScalingListRefLayerId() )->getPredScalingListFlag() == false );
-
-          // It is a requirement of bitstream conformance that, when an SPS with nuh_layer_id equal to nuhLayerIdA is active for a layer with nuh_layer_id equal to nuhLayerIdB,
-          // the layer with nuh_layer_id equal to sps_scaling_list_ref_layer_id shall be a direct or indirect reference layer of the layer with nuh_layer_id equal to nuhLayerIdB
-          assert( pcSPS->getVPS()->getScalingListLayerDependency( pcSPS->getLayerId(), pcSPS->getScalingListRefLayerId() ) == true );
-
-          pcSPS->getScalingList()->setScalingListRefLayerId( pcSPS->getScalingListRefLayerId() );
-          parseScalingList( pcSPS->getScalingList() );
-        }
-        else
-        {
-          parseScalingList( pcSPS->getScalingList() );
-        }
-      }
-      else
-      {
-        parseScalingList( pcSPS->getScalingList() );
-      }
-#else
       parseScalingList( pcSPS->getScalingList() );
-#endif
-
-    }
+    }
+#if SCALINGLIST_INFERRING
+    }
+#endif
   }
   READ_FLAG( uiCode, "amp_enabled_flag" );                          pcSPS->setUseAMP( uiCode );
@@ -813,8 +778,24 @@
   {
 #if SPS_EXTENSION
+
+#if O0142_CONDITIONAL_SPS_EXTENSION
+    UInt spsExtensionTypeFlag[8];
+    for (UInt i = 0; i < 8; i++)
+    {
+      READ_FLAG( spsExtensionTypeFlag[i], "sps_extension_type_flag" );
+    }
+    if (spsExtensionTypeFlag[1])
+    {
+      parseSPSExtension( pcSPS );
+    }
+    if (spsExtensionTypeFlag[7])
+    {
+#else
     parseSPSExtension( pcSPS );
     READ_FLAG( uiCode, "sps_extension2_flag");
     if(uiCode)
     {
+#endif
+
 #endif
       while ( xMoreRbspData() )
@@ -846,4 +827,7 @@
     {
       Window& scaledWindow = pcSPS->getScaledRefLayerWindow(i);
+#if O0098_SCALED_REF_LAYER_ID
+      READ_CODE( 6,  uiCode,  "scaled_ref_layer_left_id" );  pcSPS->setScaledRefLayerId( i, uiCode );
+#endif
       READ_SVLC( iCode, "scaled_ref_layer_left_offset" );    scaledWindow.setWindowLeftOffset  (iCode << 1);
       READ_SVLC( iCode, "scaled_ref_layer_top_offset" );     scaledWindow.setWindowTopOffset   (iCode << 1);
@@ -1090,4 +1074,21 @@
     vps->setNumDirectRefLayers(layerCtr, numDirectRefLayers);
   }
+#endif
+#if VPS_TSLAYERS
+    READ_FLAG( uiCode, "vps_sub_layers_max_minus1_present_flag"); vps->setMaxTSLayersPresentFlag(uiCode ? true : false);
+    if (vps->getMaxTSLayersPresentFlag())
+    {
+        for(i = 0; i < vps->getMaxLayers() - 1; i++)
+        {
+            READ_CODE( 3, uiCode, "sub_layers_vps_max_minus1[i]" ); vps->setMaxTSLayersMinus1(i, uiCode);
+        }
+    }
+    else
+    {
+        for( i = 0; i < vps->getMaxLayers() - 1; i++)
+        {
+            vps->setMaxTSLayersMinus1(i, vps->getMaxTLayers()-1);
+        }
+    }
 #endif
 #if JCTVC_M0203_INTERLAYER_PRED_IDC
@@ -1208,4 +1209,7 @@
     else
     {
+#if VPS_DPB_SIZE_TABLE 
+      vps->setOutputLayerSetIdx( i, i );
+#endif
       // i <= (vps->getNumLayerSets() - 1)
       // Assign OutputLayerFlag depending on default_one_target_output_layer_flag
@@ -1234,4 +1238,12 @@
   }
 
+#if O0153_ALT_OUTPUT_LAYER_FLAG
+  if( vps->getMaxLayers() > 1 )
+  {
+    READ_FLAG( uiCode, "alt_output_layer_flag");
+    vps->setAltOuputLayerFlag( uiCode ? true : false );
+  }
+#endif
+
 #if REPN_FORMAT_IN_VPS
   READ_FLAG( uiCode, "rep_format_idx_present_flag");
@@ -1240,5 +1252,9 @@
   if( vps->getRepFormatIdxPresentFlag() )
   {
+#if O0096_REP_FORMAT_INDEX
+    READ_CODE( 8, uiCode, "vps_num_rep_formats_minus1" );
+#else
     READ_CODE( 4, uiCode, "vps_num_rep_formats_minus1" );
+#endif
     vps->setVpsNumRepFormats( uiCode + 1 );
   }
@@ -1263,5 +1279,9 @@
       if( vps->getVpsNumRepFormats() > 1 )
       {
+#if O0096_REP_FORMAT_INDEX
+        READ_CODE( 8, uiCode, "vps_rep_format_idx[i]" );
+#else
         READ_CODE( 4, uiCode, "vps_rep_format_idx[i]" );
+#endif
         vps->setVpsRepFormatIdx( i, uiCode );
       }
@@ -1305,6 +1325,49 @@
 #endif
 
+#if VPS_DPB_SIZE_TABLE
+  vps->deriveNumberOfSubDpbs();
+  for(i = 1; i < vps->getNumOutputLayerSets(); i++)
+  {
+    READ_FLAG( uiCode, "sub_layer_flag_info_present_flag[i]");  vps->setSubLayerFlagInfoPresentFlag( i, uiCode ? true : false );
+    for(j = 0; j < vps->getMaxTLayers(); j++)
+    {
+      if( j > 0 && vps->getSubLayerFlagInfoPresentFlag(i) )
+      {
+        READ_FLAG( uiCode, "sub_layer_dpb_info_present_flag[i]");  vps->setSubLayerDpbInfoPresentFlag( i, j, uiCode ? true : false);
+      }
+      else
+      {
+        if( j == 0 )  // Always signal for the first sub-layer
+        {
+          vps->setSubLayerDpbInfoPresentFlag( i, j, true );
+        }
+        else // if (j != 0) && !vps->getSubLayerFlagInfoPresentFlag(i)
+        {
+          vps->setSubLayerDpbInfoPresentFlag( i, j, false );
+        }
+      }
+      if( vps->getSubLayerDpbInfoPresentFlag(i, j) )  // If sub-layer DPB information is present
+      {
+        for(Int k = 0; k < vps->getNumSubDpbs(i); k++)
+        {
+          READ_UVLC( uiCode, "max_vps_dec_pic_buffering_minus1[i][k][j]" ); vps->setMaxVpsDecPicBufferingMinus1( i, k, j, uiCode );
+        }
+        READ_UVLC( uiCode, "max_vps_num_reorder_pics[i][j]" );              vps->setMaxVpsNumReorderPics( i, j, uiCode);
+        READ_UVLC( uiCode, "max_vps_latency_increase_plus1[i][j]" );        vps->setMaxVpsLatencyIncreasePlus1( i, j, uiCode);
+      }
+    }
+  }
+#endif
 #if VPS_EXTN_DIRECT_REF_LAYERS && M0457_PREDICTION_INDICATIONS
   READ_UVLC( uiCode,           "direct_dep_type_len_minus2"); vps->setDirectDepTypeLen(uiCode+2);
+#if O0096_DEFAULT_DEPENDENCY_TYPE
+  READ_FLAG(uiCode, "default_direct_dependency_type_flag"); 
+  vps->setDefaultDirectDependecyTypeFlag(uiCode == 1? true : false);
+  if (vps->getDefaultDirectDependencyTypeFlag())
+  {
+    READ_CODE( vps->getDirectDepTypeLen(), uiCode, "default_direct_dependency_type" ); 
+    vps->setDefaultDirectDependecyType(uiCode);
+  }
+#endif
   for(i = 1; i < vps->getMaxLayers(); i++)
   {
@@ -1313,19 +1376,34 @@
       if (vps->getDirectDependencyFlag(i, j))
       {
-        READ_CODE( vps->getDirectDepTypeLen(), uiCode, "direct_dependency_type[i][j]" ); vps->setDirectDependencyType(i, j, uiCode);
-      }
-    }
-  }
-
-#endif
-
-#if IL_SL_SIGNALLING_N0371
+#if O0096_DEFAULT_DEPENDENCY_TYPE
+        if (vps->getDefaultDirectDependencyTypeFlag())
+        {
+          vps->setDirectDependencyType(i, j, vps->getDefaultDirectDependencyType());
+        }
+        else
+        {
+          READ_CODE( vps->getDirectDepTypeLen(), uiCode, "direct_dependency_type[i][j]" ); 
+          vps->setDirectDependencyType(i, j, uiCode);
+        }
+#else
+        READ_CODE( vps->getDirectDepTypeLen(), uiCode, "direct_dependency_type[i][j]" ); 
+        vps->setDirectDependencyType(i, j, uiCode);
+#endif
+      }
+    }
+  }
+#endif
+#if O0092_0094_DEPENDENCY_CONSTRAINT
   for(i = 1; i < vps->getMaxLayers(); i++)
-    {
-      for(j = 0; j < i; j++)
-        {
-          vps->setScalingListLayerDependency( i, j, vps->checkLayerDependency( i,j ) );
-        }
-    }
+  {
+    vps->setNumRefLayers(vps->getLayerIdInNuh(i));   // identify the number of direct and indirect reference layers of current layer and set recursiveRefLayersFlags
+  }
+  if(vps->getMaxLayers() > MAX_REF_LAYERS)
+  {
+    for(i = 1;i < vps->getMaxLayers(); i++)
+    {
+      assert( vps->getNumRefLayers(vps->getLayerIdInNuh(i)) <= MAX_REF_LAYERS);
+    }
+  }
 #endif
 
@@ -1333,4 +1411,7 @@
   READ_FLAG(uiCode, "single_layer_for_non_irap_flag" ); vps->setSingleLayerForNonIrapFlag(uiCode == 1 ? true : false);
 #endif
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+  READ_FLAG(uiCode, "higher_layer_irap_skip_flag" ); vps->setHigherLayerIrapSkipFlag(uiCode == 1 ? true : false);
+#endif
 
   READ_FLAG( uiCode,  "vps_vui_present_flag" );
@@ -1351,4 +1432,27 @@
 {
   UInt uiCode;
+#if REPN_FORMAT_CONTROL_FLAG
+  READ_FLAG ( uiCode, "chroma_and_bit_depth_vps_present_flag");   repFormat->setChromaAndBitDepthVpsPresentFlag(uiCode ? true : false); 
+  READ_CODE ( 16, uiCode, "pic_width_in_luma_samples" );          repFormat->setPicWidthVpsInLumaSamples ( uiCode );
+  READ_CODE ( 16, uiCode, "pic_height_in_luma_samples" );         repFormat->setPicHeightVpsInLumaSamples( uiCode );
+
+  if( repFormat->getChromaAndBitDepthVpsPresentFlag() )
+  {
+#if AUXILIARY_PICTURES
+    READ_CODE( 2, uiCode, "chroma_format_idc" );               repFormat->setChromaFormatVpsIdc( ChromaFormat(uiCode) );
+#else
+    READ_CODE( 2, uiCode, "chroma_format_idc" );               repFormat->setChromaFormatVpsIdc( uiCode );
+#endif
+
+    if( repFormat->getChromaFormatVpsIdc() == 3 )
+    {
+      READ_FLAG( uiCode, "separate_colour_plane_flag");        repFormat->setSeparateColourPlaneVpsFlag(uiCode ? true : false);
+    }
+
+
+    READ_CODE( 4, uiCode, "bit_depth_luma_minus8" );           repFormat->setBitDepthVpsLuma  ( uiCode + 8 );
+    READ_CODE( 4, uiCode, "bit_depth_chroma_minus8" );         repFormat->setBitDepthVpsChroma( uiCode + 8 );
+  }
+#else 
 #if AUXILIARY_PICTURES
   READ_CODE( 2, uiCode, "chroma_format_idc" );               repFormat->setChromaFormatVpsIdc( ChromaFormat(uiCode) );
@@ -1367,5 +1471,5 @@
   READ_CODE( 4, uiCode, "bit_depth_luma_minus8" );           repFormat->setBitDepthVpsLuma  ( uiCode + 8 );
   READ_CODE( 4, uiCode, "bit_depth_chroma_minus8" );         repFormat->setBitDepthVpsChroma( uiCode + 8 );
-
+#endif 
 }
 #endif
@@ -1375,7 +1479,20 @@
   UInt i,j;
   UInt uiCode;
+#if O0223_PICTURE_TYPES_ALIGN_FLAG
+  READ_FLAG(uiCode, "cross_layer_pic_type_aligned_flag" );
+  vps->setCrossLayerPictureTypeAlignFlag(uiCode);
+  if (!uiCode) 
+  {
+#endif
 #if IRAP_ALIGN_FLAG_IN_VPS_VUI
-  READ_FLAG(uiCode, "cross_layer_irap_aligned_flag" );
-  vps->setCrossLayerIrapAlignFlag(uiCode);
+    READ_FLAG(uiCode, "cross_layer_irap_aligned_flag" );
+    vps->setCrossLayerIrapAlignFlag(uiCode);
+#endif
+#if O0223_PICTURE_TYPES_ALIGN_FLAG
+  }
+  else
+  {
+    vps->setCrossLayerIrapAlignFlag(true);
+  }
 #endif
 #if VPS_VUI_BITRATE_PICRATE
@@ -1429,10 +1546,48 @@
   }
 #endif
+#if VPS_VUI_TILES_NOT_IN_USE__FLAG
+  UInt layerIdx;
+  READ_FLAG( uiCode, "tiles_not_in_use_flag" ); vps->setTilesNotInUseFlag(uiCode == 1);
+  if (!uiCode)
+  {
+    for(i = 0; i < vps->getMaxLayers(); i++)
+    {
+      READ_FLAG( uiCode, "tiles_in_use_flag[ i ]" ); vps->setTilesInUseFlag(i, (uiCode == 1));
+      if (uiCode)
+      {
+        READ_FLAG( uiCode, "loop_filter_not_across_tiles_flag[ i ]" ); vps->setLoopFilterNotAcrossTilesFlag(i, (uiCode == 1));
+      }
+      else
+      {
+        vps->setLoopFilterNotAcrossTilesFlag(i, false);
+      }
+    }
+#endif
 #if TILE_BOUNDARY_ALIGNED_FLAG
-  for(i = 1; i < vps->getMaxLayers(); i++)
-  {
-    for(j = 0; j < vps->getNumDirectRefLayers(vps->getLayerIdInNuh(i)); j++)
-    {
-      READ_FLAG( uiCode, "tile_boundaries_aligned_flag[i][j]" ); vps->setTileBoundariesAlignedFlag(i,j,(uiCode == 1));
+    for(i = 1; i < vps->getMaxLayers(); i++)
+    {
+      for(j = 0; j < vps->getNumDirectRefLayers(vps->getLayerIdInNuh(i)); j++)
+      {
+#if VPS_VUI_TILES_NOT_IN_USE__FLAG
+        layerIdx = vps->getLayerIdInVps(vps->getRefLayerId(vps->getLayerIdInNuh(i), j));
+        if (vps->getTilesInUseFlag(i) && vps->getTilesInUseFlag(layerIdx)) {
+          READ_FLAG( uiCode, "tile_boundaries_aligned_flag[i][j]" ); vps->setTileBoundariesAlignedFlag(i,j,(uiCode == 1));
+        }
+#else
+        READ_FLAG( uiCode, "tile_boundaries_aligned_flag[i][j]" ); vps->setTileBoundariesAlignedFlag(i,j,(uiCode == 1));
+#endif
+      }
+    }
+#endif
+#if VPS_VUI_TILES_NOT_IN_USE__FLAG
+  }
+#endif
+#if VPS_VUI_WPP_NOT_IN_USE__FLAG
+  READ_FLAG( uiCode, "wpp_not_in_use_flag" ); vps->setWppNotInUseFlag(uiCode == 1);
+  if (!uiCode)
+  {
+    for(i = 0; i < vps->getMaxLayers(); i++)
+    {
+      READ_FLAG( uiCode, "wpp_in_use_flag[ i ]" ); vps->setWppInUseFlag(i, (uiCode == 1));
     }
   }
@@ -1458,4 +1613,46 @@
     }
   }
+#endif
+#if VPS_VUI_VIDEO_SIGNAL
+    READ_FLAG( uiCode, "video_signal_info_idx_present_flag" ); vps->setVideoSigPresentVpsFlag( uiCode == 1 );
+    if (vps->getVideoSigPresentVpsFlag())
+    {
+        READ_CODE(4, uiCode, "vps_num_video_signal_info_minus1" ); vps->setNumVideoSignalInfo(uiCode + 1);
+    }
+    else
+    {
+        vps->setNumVideoSignalInfo(vps->getMaxLayers());
+    }
+    
+    
+    for(i = 0; i < vps->getNumVideoSignalInfo(); i++)
+    {
+        READ_CODE(3, uiCode, "video_vps_format" ); vps->setVideoVPSFormat(i,uiCode);
+        READ_FLAG(uiCode, "video_full_range_vps_flag" ); vps->setVideoFullRangeVpsFlag(i,uiCode);
+        READ_CODE(8, uiCode, "color_primaries_vps" ); vps->setColorPrimaries(i,uiCode);
+        READ_CODE(8, uiCode, "transfer_characteristics_vps" ); vps->setTransCharacter(i,uiCode);
+        READ_CODE(8, uiCode, "matrix_coeffs_vps" );vps->setMaxtrixCoeff(i,uiCode);
+    }
+    if(!vps->getVideoSigPresentVpsFlag())
+    {
+        for (i=0; i < vps->getMaxLayers(); i++)
+        {
+            vps->setVideoSignalInfoIdx(i,i);
+        }
+    }
+    else {
+        vps->setVideoSignalInfoIdx(0,0);
+        if (vps->getNumVideoSignalInfo() > 1 )
+        {
+            for (i=1; i < vps->getMaxLayers(); i++)
+                READ_CODE(4, uiCode, "vps_video_signal_info_idx" ); vps->setVideoSignalInfoIdx(i, uiCode);
+        }
+        else {
+          for (i=1; i < vps->getMaxLayers(); i++)
+          {
+            vps->setVideoSignalInfoIdx(i,0);
+          }
+        }
+    }
 #endif
 }
@@ -1548,4 +1745,11 @@
       iBits++;
     }
+#if O0149_CROSS_LAYER_BLA_FLAG
+    if(rpcSlice->getPPS()->getNumExtraSliceHeaderBits() > iBits)
+    {
+      READ_FLAG(uiCode, "cross_layer_bla_flag");  rpcSlice->setCrossLayerBLAFlag( uiCode ? true : false );
+      iBits++;
+    }
+#endif
     for (; iBits < rpcSlice->getPPS()->getNumExtraSliceHeaderBits(); iBits++)
     {
@@ -1734,5 +1938,4 @@
             Int pocLTCurr = rpcSlice->getPOC() - deltaPocMSBCycleLT * maxPicOrderCntLSB
                                         - iPOClsb + pocLsbLt;
-
             rps->setPOC     (j, pocLTCurr);
             rps->setDeltaPOC(j, - rpcSlice->getPOC() + pocLTCurr);
@@ -1837,6 +2040,14 @@
         else
         {
+#if O0225_TID_BASED_IL_RPS_DERIV && TSLAYERS_IL_RPS
+          if( (rpcSlice->getVPS()->getMaxTidIlRefPicsPlus1(0,rpcSlice->getLayerId()) >  rpcSlice->getTLayer()) &&
+             (rpcSlice->getVPS()->getMaxTSLayersMinus1(0) >=  rpcSlice->getTLayer()) )
+        {
+#endif
           rpcSlice->setActiveNumILRRefIdx(1);
           rpcSlice->setInterLayerPredLayerIdc(0,0);
+#if O0225_TID_BASED_IL_RPS_DERIV && TSLAYERS_IL_RPS
+        }
+#endif
         }
       }
@@ -1844,5 +2055,5 @@
 #if ILP_SSH_SIG
 #if ILP_SSH_SIG_FIX
-    else if( rpcSlice->getVPS()->getIlpSshSignalingEnabledFlag() == true )
+    else if( rpcSlice->getVPS()->getIlpSshSignalingEnabledFlag() == true &&  (rpcSlice->getLayerId() > 0 ))
 #else
     else if( rpcSlice->getVPS()->getIlpSshSignalingEnabledFlag() == false )
@@ -1850,4 +2061,23 @@
     {
       rpcSlice->setInterLayerPredEnabledFlag(true);
+
+#if O0225_TID_BASED_IL_RPS_DERIV && TSLAYERS_IL_RPS
+      Int   numRefLayerPics = 0;
+      Int   i = 0;
+      Int   refLayerPicIdc  [MAX_VPS_LAYER_ID_PLUS1];
+      for(i = 0, numRefLayerPics = 0;  i < rpcSlice->getNumILRRefIdx(); i++ ) 
+      {
+        if(rpcSlice->getVPS()->getMaxTidIlRefPicsPlus1(rpcSlice->getVPS()->getLayerIdInVps(i),rpcSlice->getLayerId()) >  rpcSlice->getTLayer() &&
+           (rpcSlice->getVPS()->getMaxTSLayersMinus1(rpcSlice->getVPS()->getLayerIdInVps(i)) >=  rpcSlice->getTLayer()) )
+        {          
+          refLayerPicIdc[ numRefLayerPics++ ] = i;
+        }
+      }
+      rpcSlice->setActiveNumILRRefIdx(numRefLayerPics);
+      for( i = 0; i < rpcSlice->getActiveNumILRRefIdx(); i++ )
+      {
+        rpcSlice->setInterLayerPredLayerIdc(refLayerPicIdc[i],i);
+      }      
+#else
       rpcSlice->setActiveNumILRRefIdx(rpcSlice->getNumILRRefIdx());
       for( Int i = 0; i < rpcSlice->getActiveNumILRRefIdx(); i++ )
@@ -1855,4 +2085,5 @@
         rpcSlice->setInterLayerPredLayerIdc(i,i);
       }
+#endif 
     }
 #endif
@@ -1879,4 +2110,14 @@
       ChromaFormat format;
 #if REPN_FORMAT_IN_VPS
+#if O0096_REP_FORMAT_INDEX
+      if( sps->getLayerId() == 0 )
+      {
+        format = sps->getChromaFormatIdc();
+      }
+      else
+      {
+        format = rpcSlice->getVPS()->getVpsRepFormat( sps->getUpdateRepFormatFlag() ? sps->getUpdateRepFormatIndex() : rpcSlice->getVPS()->getVpsRepFormatIdx(sps->getLayerId()) )->getChromaFormatVpsIdc();
+      }
+#else
       if( ( sps->getLayerId() == 0 ) || sps->getUpdateRepFormatFlag() )
       {
@@ -1887,4 +2128,5 @@
         format = rpcSlice->getVPS()->getVpsRepFormat( rpcSlice->getVPS()->getVpsRepFormatIdx(sps->getLayerId()) )->getChromaFormatVpsIdc();
       }
+#endif
 #else
       format = sps->getChromaFormatIdc();
@@ -2039,5 +2281,5 @@
 #if M0457_COL_PICTURE_SIGNALING
 #if REMOVE_COL_PICTURE_SIGNALING
-      rpcSlice->setMFMEnabledFlag( rpcSlice->getNumMotionPredRefLayers() > 0 ? true : false );
+      rpcSlice->setMFMEnabledFlag( ( rpcSlice->getNumMotionPredRefLayers() > 0 && rpcSlice->getActiveNumILRRefIdx() ) ? true : false );
 #else
       rpcSlice->setMFMEnabledFlag( false );
@@ -2633,5 +2875,4 @@
   UInt  code, sizeId, listId;
   Bool scalingListPredModeFlag;
-
   //for each size
   for(sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
@@ -2639,46 +2880,4 @@
     for(listId = 0; listId <  g_scalingListNum[sizeId]; listId++)
     {
-#if IL_SL_SIGNALLING_N0371
-      if ( scalingList->getLayerId() > 0 && scalingList->getPredScalingListFlag() )
-      {
-        READ_FLAG( code, "scaling_list_pred_mode_flag");
-        scalingListPredModeFlag = (code) ? true : false;
-        if(!scalingListPredModeFlag) //Copy Mode
-        {
-          READ_UVLC( code, "scaling_list_pred_matrix_id_delta");
-          scalingList->setRefMatrixId (sizeId,listId,(UInt)((Int)(listId)-(code)));
-          if( sizeId > SCALING_LIST_8x8 )
-          {
-            scalingList->setScalingListDC(sizeId,listId,((listId == scalingList->getRefMatrixId (sizeId,listId))? 16 :scalingList->getScalingListDC(sizeId, scalingList->getRefMatrixId (sizeId,listId))));
-          }
-          scalingList->processRefMatrix( sizeId, listId, scalingList->getRefMatrixId (sizeId,listId));
-
-        }
-        else //DPCM Mode
-        {
-          xDecodeScalingList(scalingList, sizeId, listId);
-        }
-      }
-      else
-      {
-        READ_FLAG( code, "scaling_list_pred_mode_flag");
-        scalingListPredModeFlag = (code) ? true : false;
-        if(!scalingListPredModeFlag) //Copy Mode
-        {
-          READ_UVLC( code, "scaling_list_pred_matrix_id_delta");
-          scalingList->setRefMatrixId (sizeId,listId,(UInt)((Int)(listId)-(code)));
-          if( sizeId > SCALING_LIST_8x8 )
-          {
-            scalingList->setScalingListDC(sizeId,listId,((listId == scalingList->getRefMatrixId (sizeId,listId))? 16 :scalingList->getScalingListDC(sizeId, scalingList->getRefMatrixId (sizeId,listId))));
-          }
-          scalingList->processRefMatrix( sizeId, listId, scalingList->getRefMatrixId (sizeId,listId));
-
-        }
-        else //DPCM Mode
-        {
-          xDecodeScalingList(scalingList, sizeId, listId);
-        }
-      }
-#else
       READ_FLAG( code, "scaling_list_pred_mode_flag");
       scalingListPredModeFlag = (code) ? true : false;
@@ -2698,5 +2897,4 @@
         xDecodeScalingList(scalingList, sizeId, listId);
       }
-#endif
     }
   }
@@ -2720,44 +2918,14 @@
   if( sizeId > SCALING_LIST_8x8 )
   {
-#if IL_SL_SIGNALLING_N0371
-    if( scalingList->getLayerId() > 0 && scalingList->getPredScalingListFlag() )
-    {
-      ref_scalingListDC[scalingList->getLayerId()][sizeId][listId] = scalingList->getScalingListDC(sizeId,listId);
-      scalingList->setScalingListDC(sizeId,listId,ref_scalingListDC[scalingList->getScalingListRefLayerId()][sizeId][listId]);
-    }
-    else
-    {
-      READ_SVLC( scalingListDcCoefMinus8, "scaling_list_dc_coef_minus8");
-      scalingList->setScalingListDC(sizeId,listId,scalingListDcCoefMinus8 + 8);
-      nextCoef = scalingList->getScalingListDC(sizeId,listId);
-      ref_scalingListDC[scalingList->getLayerId()][sizeId][listId] = scalingList->getScalingListDC(sizeId,listId);
-    }
-#else
     READ_SVLC( scalingListDcCoefMinus8, "scaling_list_dc_coef_minus8");
     scalingList->setScalingListDC(sizeId,listId,scalingListDcCoefMinus8 + 8);
     nextCoef = scalingList->getScalingListDC(sizeId,listId);
-#endif
   }
 
   for(i = 0; i < coefNum; i++)
   {
-#if IL_SL_SIGNALLING_N0371
-    if( scalingList->getLayerId() > 0 && scalingList->getPredScalingListFlag() )
-    {
-      ref_scalingListCoef[scalingList->getLayerId()][sizeId][listId][i] = dst[scan[i]];
-      dst[scan[i]] = ref_scalingListCoef[scalingList->getScalingListRefLayerId()][sizeId][listId][i];
-    }
-    else
-    {
-      READ_SVLC( data, "scaling_list_delta_coef");
-      nextCoef = (nextCoef + data + 256 ) % 256;
-      dst[scan[i]] = nextCoef;
-      ref_scalingListCoef[scalingList->getLayerId()][sizeId][listId][i] = dst[scan[i]];
-    }
-#else
     READ_SVLC( data, "scaling_list_delta_coef");
     nextCoef = (nextCoef + data + 256 ) % 256;
     dst[scan[i]] = nextCoef;
-#endif
   }
 }
@@ -2791,4 +2959,5 @@
   return (cnt>0);
 }
+
 //! \}
 
Index: trunk/source/Lib/TLibDecoder/TDecCu.cpp
===================================================================
--- trunk/source/Lib/TLibDecoder/TDecCu.cpp	(revision 499)
+++ trunk/source/Lib/TLibDecoder/TDecCu.cpp	(revision 540)
@@ -317,4 +317,22 @@
   }
  
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+  if (pcCU->getSlice()->getVPS()->getHigherLayerIrapSkipFlag() && pcCU->getSlice()->getVPS()->getSingleLayerForNonIrapFlag() && pcCU->getLayerId() > 0)
+  {
+    Bool lowerLayerExist = false;
+    for(int i=0;i<pcCU->getLayerId();i++)
+    {
+      if(pcCU->getSlice()->getBaseColPic(pcCU->getSlice()->getInterLayerPredLayerIdc(i)))
+      {
+        lowerLayerExist = true;
+      }
+    }
+    if(lowerLayerExist)
+    {
+      assert(pcCU->isSkipped(uiAbsPartIdx));
+    }
+  }
+#endif
+ 
   if( pcCU->isSkipped(uiAbsPartIdx) )
   {
@@ -945,3 +963,4 @@
 
 }
+
 //! \}
Index: trunk/source/Lib/TLibDecoder/TDecEntropy.h
===================================================================
--- trunk/source/Lib/TLibDecoder/TDecEntropy.h	(revision 499)
+++ trunk/source/Lib/TLibDecoder/TDecEntropy.h	(revision 540)
@@ -106,5 +106,4 @@
   virtual Void parseCoeffNxN( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType ) = 0;
   virtual Void parseTransformSkipFlags ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, UInt uiDepth, TextType eTType) = 0;
-
   virtual Void updateContextTables( SliceType eSliceType, Int iQp ) = 0;
   
@@ -166,4 +165,5 @@
   Void updateContextTables    ( SliceType eSliceType, Int iQp ) { m_pcEntropyDecoderIf->updateContextTables( eSliceType, iQp ); }
   
+  
 private:
   Void xDecodeTransform        ( TComDataCU* pcCU, UInt offsetLuma, UInt offsetChroma, UInt uiAbsPartIdx, UInt uiDepth, UInt width, UInt height, UInt uiTrIdx, Bool& bCodeDQP );
Index: trunk/source/Lib/TLibDecoder/TDecGop.cpp
===================================================================
--- trunk/source/Lib/TLibDecoder/TDecGop.cpp	(revision 499)
+++ trunk/source/Lib/TLibDecoder/TDecGop.cpp	(revision 540)
@@ -128,5 +128,5 @@
   //-- For time output for each slice
   long iBeforeTime = clock();
-  
+#if !HM_CLEANUP_SAO
   UInt uiStartCUAddr   = pcSlice->getSliceSegmentCurStartCUAddr();
 
@@ -136,5 +136,5 @@
     m_sliceStartCUAddress.push_back(uiSliceStartCuAddr);
   }
-
+#endif
   m_pcSbacDecoder->init( (TDecBinIf*)m_pcBinCABAC );
   m_pcEntropyDecoder->setEntropyDecoder (m_pcSbacDecoder);
@@ -163,9 +163,10 @@
   m_pcEntropyDecoder->setBitstream      ( ppcSubstreams[0] );
   m_pcEntropyDecoder->resetEntropy      (pcSlice);
-
+#if !HM_CLEANUP_SAO
   if(uiSliceStartCuAddr == uiStartCUAddr)
   {
     m_LFCrossSliceBoundaryFlag.push_back( pcSlice->getLFCrossSliceBoundaryFlag());
   }
+#endif
   m_pcSbacDecoders[0].load(m_pcSbacDecoder);
   m_pcSliceDecoder->decompressSlice( ppcSubstreams, rpcPic, m_pcSbacDecoder, m_pcSbacDecoders);
@@ -195,5 +196,5 @@
   m_pcLoopFilter->setCfg(bLFCrossTileBoundary);
   m_pcLoopFilter->loopFilterPic( rpcPic );
-
+#if !HM_CLEANUP_SAO
   if(pcSlice->getSPS()->getUseSAO())
   {
@@ -201,7 +202,12 @@
     rpcPic->createNonDBFilterInfo(m_sliceStartCUAddress, 0, &m_LFCrossSliceBoundaryFlag, rpcPic->getPicSym()->getNumTiles(), bLFCrossTileBoundary);
   }
-
+#endif
   if( pcSlice->getSPS()->getUseSAO() )
   {
+#if HM_CLEANUP_SAO
+    m_pcSAO->reconstructBlkSAOParams(rpcPic, rpcPic->getPicSym()->getSAOBlkParam());
+    m_pcSAO->SAOProcess(rpcPic);
+    m_pcSAO->PCMLFDisableProcess(rpcPic);
+#else
     {
       SAOParam *saoParam = rpcPic->getPicSym()->getSaoParam();
@@ -214,11 +220,12 @@
       m_pcSAO->destroyPicSaoInfo();
     }
-  }
-
+#endif
+  }
+#if !HM_CLEANUP_SAO
   if(pcSlice->getSPS()->getUseSAO())
   {
     rpcPic->destroyNonDBFilterInfo();
   }
-
+#endif
   rpcPic->compressMotion(); 
   Char c = (pcSlice->isIntra() ? 'I' : pcSlice->isInterP() ? 'P' : 'B');
@@ -283,6 +290,8 @@
   rpcPic->setOutputMark(true);
   rpcPic->setReconMark(true);
+#if !HM_CLEANUP_SAO
   m_sliceStartCUAddress.clear();
   m_LFCrossSliceBoundaryFlag.clear();
+#endif
 }
 
Index: trunk/source/Lib/TLibDecoder/TDecGop.h
===================================================================
--- trunk/source/Lib/TLibDecoder/TDecGop.h	(revision 499)
+++ trunk/source/Lib/TLibDecoder/TDecGop.h	(revision 540)
@@ -83,8 +83,9 @@
   Int                   m_decodedPictureHashSEIEnabled;  ///< Checksum(3)/CRC(2)/MD5(1)/disable(0) acting on decoded picture hash SEI message
 
+#if !HM_CLEANUP_SAO
   //! list that contains the CU address of each slice plus the end address 
   std::vector<Int> m_sliceStartCUAddress;
   std::vector<Bool> m_LFCrossSliceBoundaryFlag;
-
+#endif
 #if SVC_EXTENSION
   UInt                  m_layerId;
Index: trunk/source/Lib/TLibDecoder/TDecSbac.cpp
===================================================================
--- trunk/source/Lib/TLibDecoder/TDecSbac.cpp	(revision 499)
+++ trunk/source/Lib/TLibDecoder/TDecSbac.cpp	(revision 540)
@@ -368,5 +368,7 @@
 #if AUXILIARY_PICTURES
         if (format == CHROMA_400)
+        {
           uiSample = uiGrayVal;
+        }
         else
 #endif
@@ -389,5 +391,7 @@
 #if AUXILIARY_PICTURES
         if (format == CHROMA_400)
+        {
           uiSample = uiGrayVal;
+        }
         else
 #endif
@@ -1378,12 +1382,154 @@
     if (uiCode == 0)
     {
+#if HM_CLEANUP_SAO
+      ruiVal = 1;
+#else
       ruiVal = 5;
+#endif
     }
     else
     {
+#if HM_CLEANUP_SAO
+      ruiVal = 2;
+#else
       ruiVal = 1;
-    }
-  }
-}
+#endif
+    }
+  }
+}
+
+#if HM_CLEANUP_SAO
+
+Void TDecSbac::parseSaoSign(UInt& val)
+{
+  m_pcTDecBinIf->decodeBinEP ( val ); 
+}
+
+Void TDecSbac::parseSAOBlkParam (SAOBlkParam& saoBlkParam
+                                , Bool* sliceEnabled
+                                , Bool leftMergeAvail
+                                , Bool aboveMergeAvail
+                                )
+{
+  UInt uiSymbol;
+
+  Bool isLeftMerge = false;
+  Bool isAboveMerge= false;
+
+  if(leftMergeAvail)
+  {
+    parseSaoMerge(uiSymbol); //sao_merge_left_flag
+    isLeftMerge = (uiSymbol?true:false);
+  }
+
+  if( aboveMergeAvail && !isLeftMerge)
+  {
+    parseSaoMerge(uiSymbol); //sao_merge_up_flag
+    isAboveMerge = (uiSymbol?true:false);
+  }
+
+  if(isLeftMerge || isAboveMerge) //merge mode
+  {
+    saoBlkParam[SAO_Y].modeIdc = saoBlkParam[SAO_Cb].modeIdc = saoBlkParam[SAO_Cr].modeIdc = SAO_MODE_MERGE;
+    saoBlkParam[SAO_Y].typeIdc = saoBlkParam[SAO_Cb].typeIdc = saoBlkParam[SAO_Cr].typeIdc = (isLeftMerge)?SAO_MERGE_LEFT:SAO_MERGE_ABOVE;
+  }
+  else //new or off mode
+  {    
+    for(Int compIdx=0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
+    {
+      SAOOffset& ctbParam = saoBlkParam[compIdx];
+
+      if(!sliceEnabled[compIdx])
+      {
+        //off
+        ctbParam.modeIdc = SAO_MODE_OFF;
+        continue;
+      }
+
+      //type
+      if(compIdx == SAO_Y || compIdx == SAO_Cb)
+      {
+        parseSaoTypeIdx(uiSymbol); //sao_type_idx_luma or sao_type_idx_chroma
+
+        assert(uiSymbol ==0 || uiSymbol ==1 || uiSymbol ==2);
+
+        if(uiSymbol ==0) //OFF
+        {
+          ctbParam.modeIdc = SAO_MODE_OFF;
+        }
+        else if(uiSymbol == 1) //BO
+        {
+          ctbParam.modeIdc = SAO_MODE_NEW;
+          ctbParam.typeIdc = SAO_TYPE_START_BO;
+        }
+        else //2, EO
+        {
+          ctbParam.modeIdc = SAO_MODE_NEW;
+          ctbParam.typeIdc = SAO_TYPE_START_EO;
+        }
+
+      }
+      else //Cr, follow Cb SAO type
+      {
+        ctbParam.modeIdc = saoBlkParam[SAO_Cb].modeIdc;
+        ctbParam.typeIdc = saoBlkParam[SAO_Cb].typeIdc;
+      }
+
+      if(ctbParam.modeIdc == SAO_MODE_NEW)
+      {
+        Int offset[4];
+        for(Int i=0; i< 4; i++)
+        {
+          parseSaoMaxUvlc(uiSymbol,  g_saoMaxOffsetQVal[compIdx] ); //sao_offset_abs
+          offset[i] = (Int)uiSymbol;
+        }
+
+        if(ctbParam.typeIdc == SAO_TYPE_START_BO)
+        {
+          for(Int i=0; i< 4; i++)
+          {
+            if(offset[i] != 0)
+            {
+              parseSaoSign(uiSymbol); //sao_offset_sign
+              if(uiSymbol)
+              {
+                offset[i] = -offset[i];
+              }
+            }
+          }
+          parseSaoUflc(NUM_SAO_BO_CLASSES_LOG2, uiSymbol ); //sao_band_position
+          ctbParam.typeAuxInfo = uiSymbol;
+        
+          for(Int i=0; i<4; i++)
+          {
+            ctbParam.offset[(ctbParam.typeAuxInfo+i)%MAX_NUM_SAO_CLASSES] = offset[i];
+          }      
+        
+        }
+        else //EO
+        {
+          ctbParam.typeAuxInfo = 0;
+
+          if(compIdx == SAO_Y || compIdx == SAO_Cb)
+          {
+            parseSaoUflc(NUM_SAO_EO_TYPES_LOG2, uiSymbol ); //sao_eo_class_luma or sao_eo_class_chroma
+            ctbParam.typeIdc += uiSymbol;
+          }
+          else
+          {
+            ctbParam.typeIdc = saoBlkParam[SAO_Cb].typeIdc;
+          }
+          ctbParam.offset[SAO_CLASS_EO_FULL_VALLEY] = offset[0];
+          ctbParam.offset[SAO_CLASS_EO_HALF_VALLEY] = offset[1];
+          ctbParam.offset[SAO_CLASS_EO_PLAIN      ] = 0;
+          ctbParam.offset[SAO_CLASS_EO_HALF_PEAK  ] = -offset[2];
+          ctbParam.offset[SAO_CLASS_EO_FULL_PEAK  ] = -offset[3];
+        }
+      }
+    }
+  }
+}
+
+#else
 
 inline Void copySaoOneLcuParam(SaoLcuParam* psDst,  SaoLcuParam* psSrc)
@@ -1559,4 +1705,6 @@
 }
 
+#endif
+
 /**
  - Initialize our contexts from the nominated source.
Index: trunk/source/Lib/TLibDecoder/TDecSbac.h
===================================================================
--- trunk/source/Lib/TLibDecoder/TDecSbac.h	(revision 499)
+++ trunk/source/Lib/TLibDecoder/TDecSbac.h	(revision 540)
@@ -90,6 +90,11 @@
   Void  parseSaoTypeIdx           ( UInt&  ruiVal  );
   Void  parseSaoUflc              ( UInt uiLength, UInt& ruiVal     );
+#if HM_CLEANUP_SAO
+  Void parseSAOBlkParam (SAOBlkParam& saoBlkParam, Bool* sliceEnabled, Bool leftMergeAvail, Bool aboveMergeAvail);
+  Void parseSaoSign(UInt& val);
+#else
   Void  parseSaoOneLcuInterleaving(Int rx, Int ry, SAOParam* pSaoParam, TComDataCU* pcCU, Int iCUAddrInSlice, Int iCUAddrUpInSlice, Int allowMergeLeft, Int allowMergeUp);
   Void  parseSaoOffset            (SaoLcuParam* psSaoLcuParam, UInt compIdx);
+#endif
 private:
   Void  xReadUnarySymbol    ( UInt& ruiSymbol, ContextModel* pcSCModel, Int iOffset );
Index: trunk/source/Lib/TLibDecoder/TDecSlice.cpp
===================================================================
--- trunk/source/Lib/TLibDecoder/TDecSlice.cpp	(revision 499)
+++ trunk/source/Lib/TLibDecoder/TDecSlice.cpp	(revision 540)
@@ -197,5 +197,4 @@
   UInt uiTileLCUX;
   Int iNumSubstreamsPerTile = 1; // if independent.
-
   Bool depSliceSegmentsEnabled = rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getPPS()->getDependentSliceSegmentsEnabledFlag();
   uiTileStartLCU = rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(iStartCUAddr))->getFirstCUAddr();
@@ -323,4 +322,41 @@
     g_bJustDoIt = g_bEncDecTraceEnable;
 #endif
+
+#if HM_CLEANUP_SAO
+    if ( pcSlice->getSPS()->getUseSAO() )
+    {
+      SAOBlkParam& saoblkParam = (rpcPic->getPicSym()->getSAOBlkParam())[iCUAddr];
+      if (pcSlice->getSaoEnabledFlag()||pcSlice->getSaoEnabledFlagChroma())
+      {
+        Bool sliceEnabled[NUM_SAO_COMPONENTS];
+        sliceEnabled[SAO_Y] = pcSlice->getSaoEnabledFlag();
+        sliceEnabled[SAO_Cb]= sliceEnabled[SAO_Cr]= pcSlice->getSaoEnabledFlagChroma();
+
+        Bool leftMergeAvail = false;
+        Bool aboveMergeAvail= false;
+
+        //merge left condition
+        Int rx = (iCUAddr % uiWidthInLCUs);
+        if(rx > 0)
+        {
+          leftMergeAvail = rpcPic->getSAOMergeAvailability(iCUAddr, iCUAddr-1);
+        }
+        //merge up condition
+        Int ry = (iCUAddr / uiWidthInLCUs);
+        if(ry > 0)
+        {
+          aboveMergeAvail = rpcPic->getSAOMergeAvailability(iCUAddr, iCUAddr-uiWidthInLCUs);
+        }
+
+        pcSbacDecoder->parseSAOBlkParam( saoblkParam, sliceEnabled, leftMergeAvail, aboveMergeAvail);
+      }
+      else 
+      {
+        saoblkParam[SAO_Y ].modeIdc = SAO_MODE_OFF;
+        saoblkParam[SAO_Cb].modeIdc = SAO_MODE_OFF;
+        saoblkParam[SAO_Cr].modeIdc = SAO_MODE_OFF;
+      }
+    }
+#else
     if ( pcSlice->getSPS()->getUseSAO() && (pcSlice->getSaoEnabledFlag()||pcSlice->getSaoEnabledFlagChroma()) )
     {
@@ -374,4 +410,6 @@
       }
     }
+#endif
+
     m_pcCuDecoder->decodeCU     ( pcCU, uiIsLast );
     m_pcCuDecoder->decompressCU ( pcCU );
Index: trunk/source/Lib/TLibDecoder/TDecTop.cpp
===================================================================
--- trunk/source/Lib/TLibDecoder/TDecTop.cpp	(revision 499)
+++ trunk/source/Lib/TLibDecoder/TDecTop.cpp	(revision 540)
@@ -79,4 +79,11 @@
   m_prevSliceSkipped = false;
   m_skippedPOC = 0;
+#if NO_CLRAS_OUTPUT_FLAG
+  m_noClrasOutputFlag          = false;
+  m_layerInitializedFlag       = false;
+  m_firstPicInLayerDecodedFlag = false;
+  m_noOutputOfPriorPicsFlags   = false;
+  m_bRefreshPending            = false;
+#endif
 }
 
@@ -170,5 +177,19 @@
     for( Int temporalLayer=0; temporalLayer < MAX_TLAYER; temporalLayer++) 
     {
+#if USE_DPB_SIZE_TABLE
+      if( getCommonDecoderParams()->getOutputLayerSetIdx() == 0 )
+      {
+        assert( this->getLayerId() == 0 );
+        numReorderPics[temporalLayer] = pcSPS->getNumReorderPics(temporalLayer);
+      }
+      else
+      {
+        TComVPS *vps = slice->getVPS();
+        // SHM decoders will use DPB size table in the VPS to determine the number of reorder pictures.
+        numReorderPics[temporalLayer] = vps->getMaxVpsNumReorderPics( getCommonDecoderParams()->getOutputLayerSetIdx() , temporalLayer);
+      }
+#else
       numReorderPics[temporalLayer] = pcSPS->getNumReorderPics(temporalLayer);
+#endif
     }
 
@@ -260,8 +281,34 @@
   for( Int temporalLayer=0; temporalLayer < MAX_TLAYER; temporalLayer++) 
   {
+#if USE_DPB_SIZE_TABLE
+    if( getCommonDecoderParams()->getOutputLayerSetIdx() == 0 )
+    {
+      assert( this->getLayerId() == 0 );
+      numReorderPics[temporalLayer] = pcSlice->getSPS()->getNumReorderPics(temporalLayer);
+    }
+    else
+    {
+      TComVPS *vps = pcSlice->getVPS();
+      // SHM decoders will use DPB size table in the VPS to determine the number of reorder pictures.
+      numReorderPics[temporalLayer] = vps->getMaxVpsNumReorderPics( getCommonDecoderParams()->getOutputLayerSetIdx() , temporalLayer);
+    }
+#else
     numReorderPics[temporalLayer] = pcSlice->getSPS()->getNumReorderPics(temporalLayer);
-  }
-
+#endif
+  }
+
+#if USE_DPB_SIZE_TABLE
+  if( getCommonDecoderParams()->getOutputLayerSetIdx() == 0 )
+  {
+    assert( this->getLayerId() == 0 );
+    m_iMaxRefPicNum = pcSlice->getSPS()->getMaxDecPicBuffering(pcSlice->getTLayer());     // m_uiMaxDecPicBuffering has the space for the picture currently being decoded
+  }
+  else
+  {
+    m_iMaxRefPicNum = pcSlice->getVPS()->getMaxVpsDecPicBufferingMinus1( getCommonDecoderParams()->getOutputLayerSetIdx(), pcSlice->getLayerId(), pcSlice->getTLayer() ) + 1; // m_uiMaxDecPicBuffering has the space for the picture currently being decoded
+  }
+#else
   m_iMaxRefPicNum = pcSlice->getSPS()->getMaxDecPicBuffering(pcSlice->getTLayer());     // m_uiMaxDecPicBuffering has the space for the picture currently being decoded
+#endif
 
 #if SVC_EXTENSION
@@ -278,5 +325,9 @@
       for(UInt i = 0; i < pcSlice->getVPS()->getNumDirectRefLayers( m_layerId ); i++ )
       {
+#if O0098_SCALED_REF_LAYER_ID
+        const Window scalEL = pcSlice->getSPS()->getScaledRefLayerWindowForLayer(pcSlice->getVPS()->getRefLayerId(m_layerId, i));
+#else
         const Window scalEL = pcSlice->getSPS()->getScaledRefLayerWindow(i);
+#endif
         Bool zeroOffsets = ( scalEL.getWindowLeftOffset() == 0 && scalEL.getWindowRightOffset() == 0 && scalEL.getWindowTopOffset() == 0 && scalEL.getWindowBottomOffset() == 0 );
 
@@ -344,6 +395,7 @@
 #endif
 #endif
-
+#if !HM_CLEANUP_SAO
     rpcPic->getPicSym()->allocSaoParam(&m_cSAO);
+#endif
     m_cListPic.pushBack( rpcPic );
     
@@ -425,5 +477,7 @@
 #endif
 #endif
+#if !HM_CLEANUP_SAO
   rpcPic->getPicSym()->allocSaoParam(&m_cSAO);
+#endif
 }
 
@@ -531,24 +585,20 @@
   printf("\ninserting lost poc : %d\n",iLostPoc);
   TComSlice cFillSlice;
-#if SVC_EXTENSION
-  cFillSlice.setSPS( m_parameterSetManagerDecoder[m_layerId].getFirstSPS() );
-  cFillSlice.setPPS( m_parameterSetManagerDecoder[m_layerId].getFirstPPS() );
-  cFillSlice.setVPS( m_parameterSetManagerDecoder[m_layerId].getFirstVPS() );
-  cFillSlice.initSlice( m_layerId );
-#else
   cFillSlice.setSPS( m_parameterSetManagerDecoder.getFirstSPS() );
   cFillSlice.setPPS( m_parameterSetManagerDecoder.getFirstPPS() );
+#if SVC_EXTENSION
+  cFillSlice.setVPS( m_parameterSetManagerDecoder.getFirstVPS() );
+  cFillSlice.initSlice( m_layerId );
+#else
   cFillSlice.initSlice();
 #endif
   TComPic *cFillPic;
   xGetNewPicBuffer(&cFillSlice,cFillPic);
-#if SVC_EXTENSION
-  cFillPic->getSlice(0)->setSPS( m_parameterSetManagerDecoder[m_layerId].getFirstSPS() );
-  cFillPic->getSlice(0)->setPPS( m_parameterSetManagerDecoder[m_layerId].getFirstPPS() );
-  cFillPic->getSlice(0)->setVPS( m_parameterSetManagerDecoder[m_layerId].getFirstVPS() );
-  cFillPic->getSlice(0)->initSlice( m_layerId );
-#else
   cFillPic->getSlice(0)->setSPS( m_parameterSetManagerDecoder.getFirstSPS() );
   cFillPic->getSlice(0)->setPPS( m_parameterSetManagerDecoder.getFirstPPS() );
+#if SVC_EXTENSION
+  cFillPic->getSlice(0)->setVPS( m_parameterSetManagerDecoder.getFirstVPS() );
+  cFillPic->getSlice(0)->initSlice( m_layerId );
+#else
   cFillPic->getSlice(0)->initSlice();
 #endif
@@ -593,15 +643,4 @@
 Void TDecTop::xActivateParameterSets()
 {
-#if SVC_EXTENSION
-  m_parameterSetManagerDecoder[m_layerId].applyPrefetchedPS();
-  
-  TComPPS *pps = m_parameterSetManagerDecoder[m_layerId].getPPS(m_apcSlicePilot->getPPSId());
-  assert (pps != 0);
-
-  TComSPS *sps = m_parameterSetManagerDecoder[m_layerId].getSPS(pps->getSPSId());
-  assert (sps != 0);
-
-  if( false == m_parameterSetManagerDecoder[m_layerId].activatePPS(m_apcSlicePilot->getPPSId(), m_apcSlicePilot->isIRAP()) )
-#else
   m_parameterSetManagerDecoder.applyPrefetchedPS();
   
@@ -613,9 +652,74 @@
 
   if (false == m_parameterSetManagerDecoder.activatePPS(m_apcSlicePilot->getPPSId(),m_apcSlicePilot->isIRAP()))
-#endif
   {
     printf ("Parameter set activation failed!");
     assert (0);
   }
+
+#if SCALINGLIST_INFERRING
+  // scaling list settings and checks
+  TComVPS *activeVPS = m_parameterSetManagerDecoder.getActiveVPS();
+  TComSPS *activeSPS = m_parameterSetManagerDecoder.getActiveSPS();
+  TComPPS *activePPS = m_parameterSetManagerDecoder.getActivePPS();
+
+  if( activeSPS->getInferScalingListFlag() )
+  {
+    UInt refLayerId = activeSPS->getScalingListRefLayerId();
+    TComSPS *refSps = m_ppcTDecTop[refLayerId]->getParameterSetManager()->getActiveSPS(); assert( refSps != NULL );
+
+    // When avc_base_layer_flag is equal to 1, it is a requirement of bitstream conformance that the value of sps_scaling_list_ref_layer_id shall be greater than 0
+    if( activeVPS->getAvcBaseLayerFlag() )
+    {
+      assert( refLayerId > 0 );
+    }
+
+    // It is a requirement of bitstream conformance that, when an SPS with nuh_layer_id equal to nuhLayerIdA is active for a layer with nuh_layer_id equal to nuhLayerIdB and
+    // sps_infer_scaling_list_flag in the SPS is equal to 1, sps_infer_scaling_list_flag shall be equal to 0 for the SPS that is active for the layer with nuh_layer_id equal to sps_scaling_list_ref_layer_id
+    assert( refSps->getInferScalingListFlag() == false );
+
+    // It is a requirement of bitstream conformance that, when an SPS with nuh_layer_id equal to nuhLayerIdA is active for a layer with nuh_layer_id equal to nuhLayerIdB,
+    // the layer with nuh_layer_id equal to sps_scaling_list_ref_layer_id shall be a direct or indirect reference layer of the layer with nuh_layer_id equal to nuhLayerIdB
+    assert( activeVPS->getRecursiveRefLayerFlag( activeSPS->getLayerId(), refLayerId ) == true );
+    
+    if( activeSPS->getScalingList() != refSps->getScalingList() )
+    {
+      // delete created instance of scaling list since it will be inferred
+      delete activeSPS->getScalingList();
+
+      // infer scaling list
+      activeSPS->setScalingList( refSps->getScalingList() );
+    }
+  }
+
+  if( activePPS->getInferScalingListFlag() )
+  {
+    UInt refLayerId = activePPS->getScalingListRefLayerId();
+    TComPPS *refPps = m_ppcTDecTop[refLayerId]->getParameterSetManager()->getActivePPS(); assert( refPps != NULL );
+
+    // When avc_base_layer_flag is equal to 1, it is a requirement of bitstream conformance that the value of sps_scaling_list_ref_layer_id shall be greater than 0
+    if( activeVPS->getAvcBaseLayerFlag() )
+    {
+      assert( refLayerId > 0 );
+    }
+
+    // It is a requirement of bitstream conformance that, when an PPS with nuh_layer_id equal to nuhLayerIdA is active for a layer with nuh_layer_id equal to nuhLayerIdB and
+    // pps_infer_scaling_list_flag in the PPS is equal to 1, pps_infer_scaling_list_flag shall be equal to 0 for the PPS that is active for the layer with nuh_layer_id equal to pps_scaling_list_ref_layer_id
+    assert( refPps->getInferScalingListFlag() == false );
+
+    // It is a requirement of bitstream conformance that, when an PPS with nuh_layer_id equal to nuhLayerIdA is active for a layer with nuh_layer_id equal to nuhLayerIdB,
+    // the layer with nuh_layer_id equal to pps_scaling_list_ref_layer_id shall be a direct or indirect reference layer of the layer with nuh_layer_id equal to nuhLayerIdB
+    assert( activeVPS->getRecursiveRefLayerFlag( activePPS->getLayerId(), refLayerId ) == true );
+    
+    if( activePPS->getScalingList() != refPps->getScalingList() )
+    {
+      // delete created instance of scaling list since it will be inferred
+      delete activePPS->getScalingList();
+
+      // infer scaling list
+      activePPS->setScalingList( refPps->getScalingList() );
+    }
+
+  }
+#endif
 
   if( pps->getDependentSliceSegmentsEnabledFlag() )
@@ -670,7 +774,23 @@
   m_cSAO.destroy();
 #if REPN_FORMAT_IN_VPS
+#if AUXILIARY_PICTURES
+#if HM_CLEANUP_SAO
+  m_cSAO.create( m_apcSlicePilot->getPicWidthInLumaSamples(), m_apcSlicePilot->getPicHeightInLumaSamples(), sps->getChromaFormatIdc(), sps->getMaxCUWidth(), sps->getMaxCUHeight(), sps->getMaxCUDepth() );
+#else
   m_cSAO.create( m_apcSlicePilot->getPicWidthInLumaSamples(), m_apcSlicePilot->getPicHeightInLumaSamples(), sps->getMaxCUWidth(), sps->getMaxCUHeight() );
+#endif
+#else
+#if HM_CLEANUP_SAO
+  m_cSAO.create( m_apcSlicePilot->getPicWidthInLumaSamples(), m_apcSlicePilot->getPicHeightInLumaSamples(), sps->getMaxCUWidth(), sps->getMaxCUHeight(), sps->getMaxCUDepth() );
+#else
+  m_cSAO.create( m_apcSlicePilot->getPicWidthInLumaSamples(), m_apcSlicePilot->getPicHeightInLumaSamples(), sps->getMaxCUWidth(), sps->getMaxCUHeight() );
+#endif
+#endif
+#else
+#if HM_CLEANUP_SAO
+  m_cSAO.create( sps->getPicWidthInLumaSamples(), sps->getPicHeightInLumaSamples(), sps->getMaxCUWidth(), sps->getMaxCUHeight(), sps->getMaxCUDepth() );
 #else
   m_cSAO.create( sps->getPicWidthInLumaSamples(), sps->getPicHeightInLumaSamples(), sps->getMaxCUWidth(), sps->getMaxCUHeight() );
+#endif
 #endif
   m_cLoopFilter.create( sps->getMaxCUDepth() );
@@ -688,6 +808,13 @@
 {
   TComPic*&   pcPic         = m_pcPic;
+#if NO_CLRAS_OUTPUT_FLAG
+  Bool bFirstSliceInSeq;
+#endif
 #if SVC_EXTENSION
-  m_apcSlicePilot->setVPS( m_parameterSetManagerDecoder[m_layerId].getPrefetchedVPS(0) );
+  m_apcSlicePilot->setVPS( m_parameterSetManagerDecoder.getPrefetchedVPS(0) );
+#if OUTPUT_LAYER_SET_INDEX
+  // Following check should go wherever the VPS is activated
+  checkValueOfOutputLayerSetIdx( m_apcSlicePilot->getVPS());
+#endif
   m_apcSlicePilot->initSlice( nalu.m_layerId );
 #else
@@ -727,8 +854,6 @@
   m_apcSlicePilot->setNumSamplePredRefLayers( getNumSamplePredRefLayers() );
 #endif
-  m_cEntropyDecoder.decodeSliceHeader (m_apcSlicePilot, &m_parameterSetManagerDecoder[m_layerId]);
-#else
+#endif
   m_cEntropyDecoder.decodeSliceHeader (m_apcSlicePilot, &m_parameterSetManagerDecoder);
-#endif
 
   // set POC for dependent slices in skipped pictures
@@ -788,5 +913,5 @@
   // actual decoding starts here
   xActivateParameterSets();
-#if !O0223_O0139_IRAP_ALIGN_NO_CONTRAINTS
+#if !O0223_O0139_IRAP_ALIGN_NO_CONTRAINTS && N0147_IRAP_ALIGN_FLAG
   //Note setting O0223_O0139_IRAP_ALIGN_NO_CONTRAINTS to 0 may cause decoder to crash.
   //When cross_layer_irap_aligned_flag is equal to 0, num_extra_slice_header_bits >=1 
@@ -801,5 +926,4 @@
   }
 #endif 
-
 #if REPN_FORMAT_IN_VPS
   // Initialize ILRP if needed, only for the current layer  
@@ -816,4 +940,7 @@
 #endif
   }
+#if NO_CLRAS_OUTPUT_FLAG
+  bFirstSliceInSeq = m_bFirstSliceInSequence;
+#endif
   m_bFirstSliceInSequence = false;
 #if POC_RESET_FLAG
@@ -829,4 +956,7 @@
       Int pocAdjustValue = m_apcSlicePilot->getPOC();
 
+#if PREVTID0_POC_RESET
+      m_apcSlicePilot->adjustPrevTid0POC(pocAdjustValue);
+#endif
       // If poc reset flag is set to 1, reset all POC for DPB -> basically do it for each slice in the picutre
       TComList<TComPic*>::iterator  iterPic = m_cListPic.begin();  
@@ -882,5 +1012,5 @@
     // Check for TSA alignment
     if( m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_N ||
-        m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_TLA_R 
+        m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_R 
          )
     {
@@ -892,5 +1022,5 @@
         {
           assert( m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_N ||
-                    m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_TLA_R );    // TSA pictures should be aligned among depenedent layers
+                    m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_R );    // TSA pictures should be aligned among depenedent layers
         } 
       }
@@ -924,7 +1054,8 @@
   {
 #if AVC_BASE
-    if( m_layerId == 1 && m_parameterSetManagerDecoder[0].getPrefetchedVPS(0)->getAvcBaseLayerFlag() )
+    if( m_layerId == 1 && m_parameterSetManagerDecoder.getPrefetchedVPS(0)->getAvcBaseLayerFlag() )
     {
       TComPic* pBLPic = (*m_ppcTDecTop[0]->getListPic()->begin());
+      pBLPic->getSlice(0)->setReferenced(true);
       fstream* pFile  = m_ppcTDecTop[0]->getBLReconFile();
       UInt uiWidth    = pBLPic->getPicYuvRec()->getWidth();
@@ -973,4 +1104,49 @@
 #endif
 
+#if NO_CLRAS_OUTPUT_FLAG
+    if (m_layerId == 0 &&
+        (m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
+      || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
+      || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP
+      || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL
+      || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP
+      || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA))
+    {
+      if (bFirstSliceInSeq)
+      {
+        setNoClrasOutputFlag(true);
+      }
+      else if (m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
+            || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
+            || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP)
+      {
+        setNoClrasOutputFlag(true);
+      }
+#if O0149_CROSS_LAYER_BLA_FLAG
+      else if ((m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP) &&
+               m_apcSlicePilot->getCrossLayerBLAFlag())
+      {
+        setNoClrasOutputFlag(true);
+      }
+#endif
+      else
+      {
+        setNoClrasOutputFlag(false);
+      }
+      if (getNoClrasOutputFlag())
+      {
+        for (UInt i = 0; i < m_apcSlicePilot->getVPS()->getMaxLayers(); i++)
+        {
+          m_ppcTDecTop[i]->setLayerInitializedFlag(false);
+          m_ppcTDecTop[i]->setFirstPicInLayerDecodedFlag(false);
+        }
+      }
+    }
+#endif
+
+#if NO_CLRAS_OUTPUT_FLAG
+    m_apcSlicePilot->decodingRefreshMarking(m_pocCRA, m_bRefreshPending, m_cListPic, getNoClrasOutputFlag());
+#endif
+
     // Buffer initialize for prediction.
     m_cPrediction.initTempBuff();
@@ -1143,9 +1319,5 @@
     if (m_layerId == 0)
 #endif
-#if FIX1071
     pcSlice->setRefPicList( m_cListPic, true );
-#else
-    pcSlice->setRefPicList( m_cListPic );
-#endif
 
 #if SVC_EXTENSION
@@ -1154,9 +1326,115 @@
     if( m_layerId > 0 && m_uiSliceIdx == 0 )
     {      
+#if M0040_ADAPTIVE_RESOLUTION_CHANGE
+      if( !pcSlice->getVPS()->getSingleLayerForNonIrapFlag() || ( pcSlice->getVPS()->getSingleLayerForNonIrapFlag() && pcSlice->isIRAP() ) )
+#endif
       for( i = 0; i < pcSlice->getNumILRRefIdx(); i++ )
       {
         UInt refLayerIdc = i;
 #if AVC_BASE
-        if( pcSlice->getVPS()->getRefLayerId( m_layerId, refLayerIdc ) == 0 && m_parameterSetManagerDecoder[0].getActiveVPS()->getAvcBaseLayerFlag() )
+        if( pcSlice->getVPS()->getRefLayerId( m_layerId, refLayerIdc ) == 0 && m_parameterSetManagerDecoder.getActiveVPS()->getAvcBaseLayerFlag() )
+        {          
+          TComPic* pic = *m_ppcTDecTop[0]->getListPic()->begin();
+
+          if( pic )
+          {
+            pcSlice->setBaseColPic ( refLayerIdc, pic );
+          }
+          else
+          {
+            continue;
+          }
+#if AVC_SYNTAX
+          TComPic* pBLPic = pcSlice->getBaseColPic(refLayerIdc);
+          if( pcSlice->getPOC() == 0 )
+          {
+            // initialize partition order.
+            UInt* piTmp = &g_auiZscanToRaster[0];
+            initZscanToRaster( pBLPic->getPicSym()->getMaxDepth() + 1, 1, 0, piTmp );
+            initRasterToZscan( pBLPic->getPicSym()->getMaxCUWidth(), pBLPic->getPicSym()->getMaxCUHeight(), pBLPic->getPicSym()->getMaxDepth() + 1 );
+          }      
+          pBLPic->getSlice( 0 )->initBaseLayerRPL( pcSlice );
+          pBLPic->readBLSyntax( m_ppcTDecTop[0]->getBLSyntaxFile(), SYNTAX_BYTES );
+#endif
+        }
+        else
+        {
+#if VPS_EXTN_DIRECT_REF_LAYERS
+          TDecTop *pcTDecTop = (TDecTop *)getRefLayerDec( refLayerIdc );
+#else
+          TDecTop *pcTDecTop = (TDecTop *)getLayerDec( m_layerId-1 );
+#endif
+          TComList<TComPic*> *cListPic = pcTDecTop->getListPic();
+          if( !pcSlice->setBaseColPic ( *cListPic, refLayerIdc ) )
+          {
+            continue;
+          }
+        }
+#else
+#if VPS_EXTN_DIRECT_REF_LAYERS
+        TDecTop *pcTDecTop = (TDecTop *)getRefLayerDec( refLayerIdc );
+#else
+        TDecTop *pcTDecTop = (TDecTop *)getLayerDec( m_layerId-1 );
+#endif
+        TComList<TComPic*> *cListPic = pcTDecTop->getListPic();
+        pcSlice->setBaseColPic ( *cListPic, refLayerIdc );
+#endif
+
+#if O0098_SCALED_REF_LAYER_ID
+        const Window &scalEL = pcSlice->getSPS()->getScaledRefLayerWindowForLayer(pcSlice->getVPS()->getRefLayerId(m_layerId, refLayerIdc));
+#else
+        const Window &scalEL = pcSlice->getSPS()->getScaledRefLayerWindow(refLayerIdc);
+#endif
+
+        Int widthBL   = pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec()->getWidth();
+        Int heightBL  = pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec()->getHeight();
+
+        Int widthEL   = pcPic->getPicYuvRec()->getWidth()  - scalEL.getWindowLeftOffset() - scalEL.getWindowRightOffset();
+        Int heightEL  = pcPic->getPicYuvRec()->getHeight() - scalEL.getWindowTopOffset()  - scalEL.getWindowBottomOffset();
+
+        g_mvScalingFactor[refLayerIdc][0] = widthEL  == widthBL  ? 4096 : Clip3(-4096, 4095, ((widthEL  << 8) + (widthBL  >> 1)) / widthBL);
+        g_mvScalingFactor[refLayerIdc][1] = heightEL == heightBL ? 4096 : Clip3(-4096, 4095, ((heightEL << 8) + (heightBL >> 1)) / heightBL);
+
+        g_posScalingFactor[refLayerIdc][0] = ((widthBL  << 16) + (widthEL  >> 1)) / widthEL;
+        g_posScalingFactor[refLayerIdc][1] = ((heightBL << 16) + (heightEL >> 1)) / heightEL;
+
+#if SVC_UPSAMPLING
+        if( pcPic->isSpatialEnhLayer(refLayerIdc) )
+        {    
+/*#if O0098_SCALED_REF_LAYER_ID
+          Window &scalEL = pcSlice->getSPS()->getScaledRefLayerWindowForLayer(pcSlice->getVPS()->getRefLayerId(m_layerId, refLayerIdc));
+#else
+          Window &scalEL = pcSlice->getSPS()->getScaledRefLayerWindow(refLayerIdc);
+#endif*/
+#if O0215_PHASE_ALIGNMENT
+#if O0194_JOINT_US_BITSHIFT
+          m_cPrediction.upsampleBasePic( pcSlice, refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(), pcPic->getPicYuvRec(), scalEL, pcSlice->getVPS()->getPhaseAlignFlag() );
+#else
+          m_cPrediction.upsampleBasePic( refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(), pcPic->getPicYuvRec(), scalEL, pcSlice->getVPS()->getPhaseAlignFlag() );
+#endif
+#else
+#if O0194_JOINT_US_BITSHIFT
+          m_cPrediction.upsampleBasePic( pcSlice, refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(), pcPic->getPicYuvRec(), scalEL );
+#else
+          m_cPrediction.upsampleBasePic( refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(), pcPic->getPicYuvRec(), scalEL );
+#endif
+#endif
+        }
+        else
+        {
+          pcPic->setFullPelBaseRec( refLayerIdc, pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec() );
+        }
+        pcSlice->setFullPelBaseRec ( refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc) );
+#endif
+      }
+    }
+
+    if( m_layerId > 0 && pcSlice->getActiveNumILRRefIdx() )
+    {
+      for( i = 0; i < pcSlice->getActiveNumILRRefIdx(); i++ )
+      {
+        UInt refLayerIdc = pcSlice->getInterLayerPredLayerIdc(i);
+#if AVC_BASE
+        if( pcSlice->getVPS()->getRefLayerId( m_layerId, refLayerIdc ) == 0 && m_parameterSetManagerDecoder.getActiveVPS()->getAvcBaseLayerFlag() )
         {
           pcSlice->setBaseColPic ( refLayerIdc, *m_ppcTDecTop[0]->getListPic()->begin() );
@@ -1194,86 +1472,4 @@
 #endif
 
-        const Window &scalEL = pcSlice->getSPS()->getScaledRefLayerWindow(refLayerIdc);
-
-        Int widthBL   = pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec()->getWidth();
-        Int heightBL  = pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec()->getHeight();
-
-        Int widthEL   = pcPic->getPicYuvRec()->getWidth()  - scalEL.getWindowLeftOffset() - scalEL.getWindowRightOffset();
-        Int heightEL  = pcPic->getPicYuvRec()->getHeight() - scalEL.getWindowTopOffset()  - scalEL.getWindowBottomOffset();
-
-        g_mvScalingFactor[refLayerIdc][0] = widthEL  == widthBL  ? 4096 : Clip3(-4096, 4095, ((widthEL  << 8) + (widthBL  >> 1)) / widthBL);
-        g_mvScalingFactor[refLayerIdc][1] = heightEL == heightBL ? 4096 : Clip3(-4096, 4095, ((heightEL << 8) + (heightBL >> 1)) / heightBL);
-
-        g_posScalingFactor[refLayerIdc][0] = ((widthBL  << 16) + (widthEL  >> 1)) / widthEL;
-        g_posScalingFactor[refLayerIdc][1] = ((heightBL << 16) + (heightEL >> 1)) / heightEL;
-
-#if SVC_UPSAMPLING
-        if( pcPic->isSpatialEnhLayer(refLayerIdc) )
-        {    
-#if O0215_PHASE_ALIGNMENT
-#if O0194_JOINT_US_BITSHIFT
-          m_cPrediction.upsampleBasePic( pcSlice, refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(), pcPic->getPicYuvRec(), pcSlice->getSPS()->getScaledRefLayerWindow(refLayerIdc), pcSlice->getVPS()->getPhaseAlignFlag() );
-#else
-          m_cPrediction.upsampleBasePic( refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(), pcPic->getPicYuvRec(), pcSlice->getSPS()->getScaledRefLayerWindow(refLayerIdc), pcSlice->getVPS()->getPhaseAlignFlag() );
-#endif
-#else
-#if O0194_JOINT_US_BITSHIFT
-          m_cPrediction.upsampleBasePic( pcSlice, refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(), pcPic->getPicYuvRec(), pcSlice->getSPS()->getScaledRefLayerWindow(refLayerIdc) );
-#else
-          m_cPrediction.upsampleBasePic( refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(), pcPic->getPicYuvRec(), pcSlice->getSPS()->getScaledRefLayerWindow(refLayerIdc) );
-#endif
-#endif
-        }
-        else
-        {
-          pcPic->setFullPelBaseRec( refLayerIdc, pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec() );
-        }
-        pcSlice->setFullPelBaseRec ( refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc) );
-#endif
-      }
-    }
-
-    if( m_layerId > 0 && pcSlice->getActiveNumILRRefIdx() )
-    {
-      for( i = 0; i < pcSlice->getActiveNumILRRefIdx(); i++ )
-      {
-        UInt refLayerIdc = pcSlice->getInterLayerPredLayerIdc(i);
-#if AVC_BASE
-        if( pcSlice->getVPS()->getRefLayerId( m_layerId, refLayerIdc ) == 0 && m_parameterSetManagerDecoder[0].getActiveVPS()->getAvcBaseLayerFlag() )
-        {
-          pcSlice->setBaseColPic ( refLayerIdc, *m_ppcTDecTop[0]->getListPic()->begin() );
-#if AVC_SYNTAX
-          TComPic* pBLPic = pcSlice->getBaseColPic(refLayerIdc);
-          if( pcSlice->getPOC() == 0 )
-          {
-            // initialize partition order.
-            UInt* piTmp = &g_auiZscanToRaster[0];
-            initZscanToRaster( pBLPic->getPicSym()->getMaxDepth() + 1, 1, 0, piTmp );
-            initRasterToZscan( pBLPic->getPicSym()->getMaxCUWidth(), pBLPic->getPicSym()->getMaxCUHeight(), pBLPic->getPicSym()->getMaxDepth() + 1 );
-          }      
-          pBLPic->getSlice( 0 )->initBaseLayerRPL( pcSlice );
-          pBLPic->readBLSyntax( m_ppcTDecTop[0]->getBLSyntaxFile(), SYNTAX_BYTES );
-#endif
-        }
-        else
-        {
-#if VPS_EXTN_DIRECT_REF_LAYERS
-          TDecTop *pcTDecTop = (TDecTop *)getRefLayerDec( refLayerIdc );
-#else
-          TDecTop *pcTDecTop = (TDecTop *)getLayerDec( m_layerId-1 );
-#endif
-          TComList<TComPic*> *cListPic = pcTDecTop->getListPic();
-          pcSlice->setBaseColPic ( *cListPic, refLayerIdc );
-        }
-#else
-#if VPS_EXTN_DIRECT_REF_LAYERS
-        TDecTop *pcTDecTop = (TDecTop *)getRefLayerDec( refLayerIdc );
-#else
-        TDecTop *pcTDecTop = (TDecTop *)getLayerDec( m_layerId-1 );
-#endif
-        TComList<TComPic*> *cListPic = pcTDecTop->getListPic();
-        pcSlice->setBaseColPic ( *cListPic, refLayerIdc );
-#endif
-
         pcSlice->setFullPelBaseRec ( refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc) );
       }
@@ -1315,6 +1511,9 @@
     
 #if N0147_IRAP_ALIGN_FLAG
-    if(  m_layerId > 0 && pcSlice->getVPS()->getCrossLayerIrapAlignFlag())
-    {
+    if( m_layerId > 0 && pcSlice->getVPS()->getCrossLayerIrapAlignFlag() )
+    {
+#if M0040_ADAPTIVE_RESOLUTION_CHANGE
+      if( !pcSlice->getVPS()->getSingleLayerForNonIrapFlag() || ( pcSlice->getVPS()->getSingleLayerForNonIrapFlag() && pcSlice->isIRAP() ) )
+#endif
       for(Int dependentLayerIdx = 0; dependentLayerIdx < pcSlice->getVPS()->getNumDirectRefLayers(m_layerId); dependentLayerIdx++)
       {
@@ -1376,25 +1575,15 @@
   if(pcSlice->getSPS()->getScalingListFlag())
   {
-#if IL_SL_SIGNALLING_N0371
-    pcSlice->getSPS()->getScalingList()->setLayerId( m_layerId );
-#endif
-
     pcSlice->setScalingList ( pcSlice->getSPS()->getScalingList()  );
-
     if(pcSlice->getPPS()->getScalingListPresentFlag())
     {
-#if IL_SL_SIGNALLING_N0371
-      pcSlice->getPPS()->getScalingList()->setLayerId( m_layerId );
-#endif
-
       pcSlice->setScalingList ( pcSlice->getPPS()->getScalingList()  );
     }
+#if SCALINGLIST_INFERRING
+    if( m_layerId == 0 || ( m_layerId > 0 && !pcSlice->getPPS()->getInferScalingListFlag() && !pcSlice->getSPS()->getInferScalingListFlag() ) )
+#endif
     if(!pcSlice->getPPS()->getScalingListPresentFlag() && !pcSlice->getSPS()->getScalingListPresentFlag())
     {
-#if IL_SL_SIGNALLING_N0371
-      pcSlice->setDefaultScalingList( m_layerId );
-#else
       pcSlice->setDefaultScalingList();
-#endif
     }
     m_cTrQuant.setScalingListDec(pcSlice->getScalingList());
@@ -1403,9 +1592,5 @@
   else
   {
-#if IL_SL_SIGNALLING_N0371
-    m_cTrQuant.setFlatScalingList( m_layerId );
-#else
     m_cTrQuant.setFlatScalingList();
-#endif
     m_cTrQuant.setUseScalingList(false);
   }
@@ -1425,9 +1610,5 @@
   
   m_cEntropyDecoder.decodeVPS( vps );
-#if SVC_EXTENSION
-  m_parameterSetManagerDecoder[0].storePrefetchedVPS(vps);
-#else
   m_parameterSetManagerDecoder.storePrefetchedVPS(vps);  
-#endif
 }
 
@@ -1437,6 +1618,6 @@
 #if SVC_EXTENSION
   sps->setLayerId(m_layerId);
-  m_cEntropyDecoder.decodeSPS( sps, &m_parameterSetManagerDecoder[0] );
-  m_parameterSetManagerDecoder[m_layerId].storePrefetchedSPS(sps);
+  m_cEntropyDecoder.decodeSPS( sps, &m_parameterSetManagerDecoder );
+  m_parameterSetManagerDecoder.storePrefetchedSPS(sps);
 #if !REPN_FORMAT_IN_VPS   // ILRP can only be initialized at activation  
   if(m_numLayer>0)
@@ -1455,14 +1636,10 @@
   TComPPS* pps = new TComPPS();
 
-#if IL_SL_SIGNALLING_N0371
-  pps->setLayerId(m_layerId);
+#if SCALINGLIST_INFERRING
+  pps->setLayerId( m_layerId );
 #endif
 
   m_cEntropyDecoder.decodePPS( pps );
-#if SVC_EXTENSION
-  m_parameterSetManagerDecoder[m_layerId].storePrefetchedPPS( pps );
-#else
   m_parameterSetManagerDecoder.storePrefetchedPPS( pps );
-#endif
 
   if( pps->getDependentSliceSegmentsEnabledFlag() )
@@ -1492,7 +1669,7 @@
 #endif
 #if M0043_LAYERS_PRESENT_SEI
-    m_seiReader.parseSEImessage( bs, m_pcPic->getSEIs(), nalUnitType, m_parameterSetManagerDecoder[m_layerId].getActiveVPS(), m_parameterSetManagerDecoder[m_layerId].getActiveSPS() );
-#else
-    m_seiReader.parseSEImessage( bs, m_pcPic->getSEIs(), nalUnitType, m_parameterSetManagerDecoder[m_layerId].getActiveSPS() );
+    m_seiReader.parseSEImessage( bs, m_pcPic->getSEIs(), nalUnitType, m_parameterSetManagerDecoder.getActiveVPS(), m_parameterSetManagerDecoder.getActiveSPS() );
+#else
+    m_seiReader.parseSEImessage( bs, m_pcPic->getSEIs(), nalUnitType, m_parameterSetManagerDecoder.getActiveSPS() );
 #endif
   }
@@ -1500,7 +1677,7 @@
   {
 #if M0043_LAYERS_PRESENT_SEI
-    m_seiReader.parseSEImessage( bs, m_SEIs, nalUnitType, m_parameterSetManagerDecoder[m_layerId].getActiveVPS(), m_parameterSetManagerDecoder[m_layerId].getActiveSPS() );
-#else
-    m_seiReader.parseSEImessage( bs, m_SEIs, nalUnitType, m_parameterSetManagerDecoder[m_layerId].getActiveSPS() );
+    m_seiReader.parseSEImessage( bs, m_SEIs, nalUnitType, m_parameterSetManagerDecoder.getActiveVPS(), m_parameterSetManagerDecoder.getActiveSPS() );
+#else
+    m_seiReader.parseSEImessage( bs, m_SEIs, nalUnitType, m_parameterSetManagerDecoder.getActiveSPS() );
 #endif
     SEIMessages activeParamSets = getSeisByType(m_SEIs, SEI::ACTIVE_PARAMETER_SETS);
@@ -1508,7 +1685,7 @@
     {
       SEIActiveParameterSets *seiAps = (SEIActiveParameterSets*)(*activeParamSets.begin());
-      m_parameterSetManagerDecoder[m_layerId].applyPrefetchedPS();
+      m_parameterSetManagerDecoder.applyPrefetchedPS();
       assert(seiAps->activeSeqParamSetId.size()>0);
-      if (! m_parameterSetManagerDecoder[m_layerId].activateSPSWithSEI(seiAps->activeSeqParamSetId[0] ))
+      if( !m_parameterSetManagerDecoder.activateSPSWithSEI( seiAps->activeSeqParamSetId[0] ) )
       {
         printf ("Warning SPS activation with Active parameter set SEI failed");
@@ -1565,5 +1742,5 @@
       xDecodeVPS();
 #if AVC_BASE
-      if( m_parameterSetManagerDecoder[0].getPrefetchedVPS(0)->getAvcBaseLayerFlag() )
+      if( m_parameterSetManagerDecoder.getPrefetchedVPS(0)->getAvcBaseLayerFlag() )
       {
         if( !m_ppcTDecTop[0]->getBLReconFile()->good() )
@@ -1591,5 +1768,5 @@
       xDecodeSPS();
 #if AVC_BASE
-      if( m_parameterSetManagerDecoder[0].getPrefetchedVPS(0)->getAvcBaseLayerFlag() )
+      if( m_parameterSetManagerDecoder.getPrefetchedVPS(0)->getAvcBaseLayerFlag() )
       {
         TComPic* pBLPic = (*m_ppcTDecTop[0]->getListPic()->begin());
@@ -1597,5 +1774,5 @@
         {
           // using EL SPS with spsId = 1
-          TComSPS* sps = m_parameterSetManagerDecoder[nalu.m_layerId].getPrefetchedSPS(1);
+          TComSPS* sps = m_parameterSetManagerDecoder.getPrefetchedSPS(1);
           Int  numReorderPics[MAX_TLAYER];
           Window &conformanceWindow = sps->getConformanceWindow();
@@ -1644,5 +1821,5 @@
     case NAL_UNIT_CODED_SLICE_TRAIL_R:
     case NAL_UNIT_CODED_SLICE_TRAIL_N:
-    case NAL_UNIT_CODED_SLICE_TLA_R:
+    case NAL_UNIT_CODED_SLICE_TSA_R:
     case NAL_UNIT_CODED_SLICE_TSA_N:
     case NAL_UNIT_CODED_SLICE_STSA_R:
@@ -1664,6 +1841,25 @@
 #endif
       break;
+      
+    case NAL_UNIT_EOS:
+      m_associatedIRAPType = NAL_UNIT_INVALID;
+      m_pocCRA = 0;
+      m_pocRandomAccess = MAX_INT;
+      m_prevPOC = MAX_INT;
+      m_bFirstSliceInPicture = true;
+      m_bFirstSliceInSequence = true;
+      m_prevSliceSkipped = false;
+      m_skippedPOC = 0;
+      return false;
+      
+    case NAL_UNIT_ACCESS_UNIT_DELIMITER:
+      // TODO: process AU delimiter
+      return false;
+      
+    case NAL_UNIT_EOB:
+      return false;
+      
     default:
-      assert (1);
+      assert (0);
   }
 
@@ -1746,5 +1942,5 @@
 TDecTop* TDecTop::getRefLayerDec( UInt refLayerIdc )
 {
-  TComVPS* vps = m_parameterSetManagerDecoder[0].getActiveVPS();
+  TComVPS* vps = m_parameterSetManagerDecoder.getActiveVPS();
   if( vps->getNumDirectRefLayers( m_layerId ) <= 0 )
   {
@@ -1838,4 +2034,100 @@
 }
 #endif
-
+#if OUTPUT_LAYER_SET_INDEX
+Void TDecTop::checkValueOfOutputLayerSetIdx(TComVPS *vps)
+{
+  CommonDecoderParams* params = this->getCommonDecoderParams();
+  if( params->getValueCheckedFlag() )
+  {
+    return; // Already checked
+  }
+  if( params->getOutputLayerSetIdx() == -1 )  // Output layer set index not specified
+  {
+    Bool layerSetMatchFound = false;
+    // Output layer set index not assigned.
+    // Based on the value of targetLayerId, check if any of the output layer matches
+    // Currently, the target layer ID in the encoder assumes that all the layers are decoded    
+    // Check if any of the output layer sets match this description
+    for(Int i = 0; i < vps->getNumOutputLayerSets(); i++)
+    {
+      Bool layerSetMatchFlag = true;
+      Int layerSetIdx = vps->getOutputLayerSetIdx( i );
+      if( vps->getNumLayersInIdList( layerSetIdx ) == params->getTargetLayerId() + 1 )
+      {
+        for(Int j = 0; j < vps->getNumLayersInIdList( layerSetIdx ); j++)
+        {
+          if( vps->getLayerSetLayerIdList( layerSetIdx, j ) != j )
+          {
+            layerSetMatchFlag = false;
+            break;
+          }
+        }
+      }
+      else
+      {
+        layerSetMatchFlag = false;
+      }
+      
+      if( layerSetMatchFlag ) // Potential output layer set candidate found
+      {
+        // If target dec layer ID list is also included - check if they match
+        if( params->getTargetDecLayerIdSet() )
+        {
+          if( params->getTargetDecLayerIdSet()->size() )  
+          {
+            for(Int j = 0; j < vps->getNumLayersInIdList( layerSetIdx ); j++)
+            {
+              if( *(params->getTargetDecLayerIdSet()->begin() + j) != vps->getLayerIdInNuh(vps->getLayerSetLayerIdList( layerSetIdx, j )))
+              {
+                layerSetMatchFlag = false;
+              }
+            }
+          }
+        }
+        if( layerSetMatchFlag ) // The target dec layer ID list also matches, if present
+        {
+          // Match found
+          layerSetMatchFound = true;
+          params->setOutputLayerSetIdx( i );
+          params->setValueCheckedFlag( true );
+          break;
+        }
+      }
+    }
+    assert( layerSetMatchFound ); // No output layer set matched the value of either targetLayerId or targetdeclayerIdlist
+  }   
+  else // Output layer set index is assigned - check if the values match
+  {
+    // Check if the target decoded layer is the highest layer in the list
+    Int layerSetIdx = vps->getOutputLayerSetIdx( params->getOutputLayerSetIdx() );  // Index to the layer set
+    assert( params->getTargetLayerId() == vps->getNumLayersInIdList( layerSetIdx ) - 1);
+
+    Bool layerSetMatchFlag = true;
+    for(Int j = 0; j < vps->getNumLayersInIdList( layerSetIdx ); j++)
+    {
+      if( vps->getLayerSetLayerIdList( layerSetIdx, j ) != j )
+      {
+        layerSetMatchFlag = false;
+        break;
+      }
+    }
+
+    assert(layerSetMatchFlag);    // Signaled output layer set index does not match targetOutputLayerId.
+    
+    // Check if the targetdeclayerIdlist matches the output layer set
+    if( params->getTargetDecLayerIdSet() )
+    {
+      if( params->getTargetDecLayerIdSet()->size() )  
+      {
+        for(Int i = 0; i < vps->getNumLayersInIdList( layerSetIdx ); i++)
+        {
+          assert( *(params->getTargetDecLayerIdSet()->begin() + i) == vps->getLayerIdInNuh(vps->getLayerSetLayerIdList( layerSetIdx, i )));
+        }
+      }
+    }
+    params->setValueCheckedFlag( true );
+
+  }
+}
+#endif
 //! \}
Index: trunk/source/Lib/TLibDecoder/TDecTop.h
===================================================================
--- trunk/source/Lib/TLibDecoder/TDecTop.h	(revision 499)
+++ trunk/source/Lib/TLibDecoder/TDecTop.h	(revision 540)
@@ -72,10 +72,5 @@
 
   TComList<TComPic*>      m_cListPic;         //  Dynamic buffer
-#if SVC_EXTENSION
-  ParameterSetManagerDecoder m_parameterSetManagerDecoder[MAX_LAYERS];  // storage for parameter sets 
-#else
   ParameterSetManagerDecoder m_parameterSetManagerDecoder;  // storage for parameter sets 
-#endif
-
   TComSlice*              m_apcSlicePilot;
 
@@ -134,6 +129,18 @@
   TComPic*                m_cIlpPic[MAX_NUM_REF];                    ///<  Inter layer Prediction picture =  upsampled picture
 #endif 
+#if OUTPUT_LAYER_SET_INDEX
+  CommonDecoderParams*    m_commonDecoderParams;
+#endif
 #if AVC_SYNTAX || SYNTAX_OUTPUT
   fstream*               m_pBLSyntaxFile;
+#endif
+
+#if NO_CLRAS_OUTPUT_FLAG
+  Bool                    m_noClrasOutputFlag;
+  Bool                    m_layerInitializedFlag;
+  Bool                    m_firstPicInLayerDecodedFlag;
+  Bool                    m_noOutputOfPriorPicsFlags;
+
+  Bool                   m_bRefreshPending;
 #endif
 
@@ -241,4 +248,23 @@
 #endif
 
+#if NO_CLRAS_OUTPUT_FLAG
+  Int  getNoClrasOutputFlag()                { return m_noClrasOutputFlag;}
+  Void setNoClrasOutputFlag(Bool x)          { m_noClrasOutputFlag = x;   }
+  Int  getLayerInitializedFlag()             { return m_layerInitializedFlag;}
+  Void setLayerInitializedFlag(Bool x)       { m_layerInitializedFlag = x;   }
+  Int  getFirstPicInLayerDecodedFlag()       { return m_firstPicInLayerDecodedFlag;}
+  Void setFirstPicInLayerDecodedFlag(Bool x) { m_firstPicInLayerDecodedFlag = x;   }
+  Int  getNoOutputOfPriorPicsFlags()         { return m_noOutputOfPriorPicsFlags;}
+  Void setNoOutputOfPriorPicsFlags(Bool x)   { m_noOutputOfPriorPicsFlags = x;   }
+#endif
+public:
+#if OUTPUT_LAYER_SET_INDEX
+  CommonDecoderParams*    getCommonDecoderParams() { return m_commonDecoderParams; }
+  Void                    setCommonDecoderParams(CommonDecoderParams* x) { m_commonDecoderParams = x; }
+  Void      checkValueOfOutputLayerSetIdx(TComVPS *vps);
+#endif
+#if SCALINGLIST_INFERRING
+  ParameterSetManagerDecoder* getParameterSetManager() { return &m_parameterSetManagerDecoder; }
+#endif
 };// END CLASS DEFINITION TDecTop
 
Index: trunk/source/Lib/TLibEncoder/TEncAnalyze.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncAnalyze.cpp	(revision 499)
+++ trunk/source/Lib/TLibEncoder/TEncAnalyze.cpp	(revision 540)
@@ -58,3 +58,4 @@
 
 TEncAnalyze             m_gcAnalyzeAll_in;
+
 //! \}
Index: trunk/source/Lib/TLibEncoder/TEncAnalyze.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncAnalyze.h	(revision 499)
+++ trunk/source/Lib/TLibEncoder/TEncAnalyze.h	(revision 540)
@@ -160,4 +160,5 @@
   }
   
+  
   Void    printSummary(Char ch)
   {
@@ -207,4 +208,5 @@
 
 extern TEncAnalyze             m_gcAnalyzeAll_in;
+
 //! \}
 
Index: trunk/source/Lib/TLibEncoder/TEncCavlc.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 499)
+++ trunk/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 540)
@@ -220,61 +220,32 @@
     }
   }
+
+#if SCALINGLIST_INFERRING
+  if( pcPPS->getLayerId() > 0 )
+  {
+    WRITE_FLAG( pcPPS->getInferScalingListFlag() ? 1 : 0, "pps_infer_scaling_list_flag" );
+  }
+
+  if( pcPPS->getInferScalingListFlag() )
+  {
+    // The value of pps_scaling_list_ref_layer_id shall be in the range of 0 to 62, inclusive
+    assert( pcPPS->getScalingListRefLayerId() <= 62 );
+
+    WRITE_UVLC( pcPPS->getScalingListRefLayerId(), "pps_scaling_list_ref_layer_id" );
+  }
+  else
+  {
+#endif
+
   WRITE_FLAG( pcPPS->getScalingListPresentFlag() ? 1 : 0,                          "pps_scaling_list_data_present_flag" ); 
-
-#if IL_SL_SIGNALLING_N0371
-  pcPPS->setPPS( pcPPS->getLayerId(), pcPPS );  
-#endif
-
   if( pcPPS->getScalingListPresentFlag() )
   {
-#if SCALING_LIST_OUTPUT_RESULT
-    printf("PPS\n");
-#endif
-
-#if IL_SL_SIGNALLING_N0371
-    m_pcSlice->getScalingList()->setLayerId( pcPPS->getLayerId() );
-
-    if( pcPPS->getLayerId() > 0 )
-    {
-      WRITE_FLAG( pcPPS->getPredScalingListFlag() ? 1 : 0,                          "pps_pred_scaling_list_flag" );
-      m_pcSlice->getScalingList()->setPredScalingListFlag( pcPPS->getPredScalingListFlag() );
-
-      if( pcPPS->getPredScalingListFlag() )
-      {
-        // The value of pps_scaling_list_ref_layer_id shall be in the range of 0 to 62, inclusive
-        assert( /*pcPPS->getScalingListRefLayerId() >= 0 &&*/ pcPPS->getScalingListRefLayerId() <= 62 );
-
-        // When avc_base_layer_flag is equal to 1, it is a requirement of bitstream conformance that the value of pps_scaling_list_ref_layer_id shall be greater than 0
-        if( pcPPS->getSPS()->getVPS()->getAvcBaseLayerFlag() )
-        {
-          assert( pcPPS->getScalingListRefLayerId() > 0 );
-        }
-
-        // It is a requirement of bitstream conformance that, when a PPS with nuh_layer_id equal to nuhLayerIdA is active for a layer with nuh_layer_id equal to nuhLayerIdB and 
-        // pps_infer_scaling_list_flag in the PPS is equal to 1, pps_infer_scaling_list_flag shall be equal to 0 for the PPS that is active for the layer with nuh_layer_id equal to pps_scaling_list_ref_layer_id
-        assert( pcPPS->getPPS( pcPPS->getScalingListRefLayerId() )->getPredScalingListFlag() == false );
-
-        // It is a requirement of bitstream conformance that, when a PPS with nuh_layer_id equal to nuhLayerIdA is active for a layer with nuh_layer_id equal to nuhLayerIdB, 
-        // the layer with nuh_layer_id equal to pps_scaling_list_ref_layer_id shall be a direct or indirect reference layer of the layer with nuh_layer_id equal to nuhLayerIdB
-        assert( pcPPS->getSPS()->getVPS()->getScalingListLayerDependency( pcPPS->getLayerId(), pcPPS->getScalingListRefLayerId() ) == true );
-        
-        WRITE_UVLC( pcPPS->getScalingListRefLayerId(),                            "scaling_list_pps_ref_layer_id" );
-        m_pcSlice->getScalingList()->setScalingListRefLayerId( pcPPS->getScalingListRefLayerId() );
-        codeScalingList( m_pcSlice->getScalingList() );
-      }
-      else
-      {
-        codeScalingList( m_pcSlice->getScalingList() );
-      }
-    }
-    else
-    {
-      codeScalingList( m_pcSlice->getScalingList() );
-    }
-#else
     codeScalingList( m_pcSlice->getScalingList() );
-#endif
-
-  }
+  }
+
+#if SCALINGLIST_INFERRING
+  }
+#endif
+
   WRITE_FLAG( pcPPS->getListsModificationPresentFlag(), "lists_modification_present_flag");
   WRITE_UVLC( pcPPS->getLog2ParallelMergeLevelMinus2(), "log2_parallel_merge_level_minus2");
@@ -471,5 +442,9 @@
     WRITE_FLAG( pcSPS->getUpdateRepFormatFlag(), "update_rep_format_flag" );
   }
+#if O0096_REP_FORMAT_INDEX
+  if( pcSPS->getLayerId() == 0 ) 
+#else
   if( pcSPS->getLayerId() == 0 || pcSPS->getUpdateRepFormatFlag() ) 
+#endif
   {
 #endif
@@ -486,4 +461,10 @@
 #if REPN_FORMAT_IN_VPS
   }
+#if O0096_REP_FORMAT_INDEX
+  else if (pcSPS->getUpdateRepFormatFlag())
+  {
+    WRITE_CODE( pcSPS->getUpdateRepFormatIndex(), 8,   "update_rep_format_index");
+  }
+#endif
 #endif
   Window conf = pcSPS->getConformanceWindow();
@@ -499,5 +480,9 @@
 
 #if REPN_FORMAT_IN_VPS
+#if O0096_REP_FORMAT_INDEX
+  if( pcSPS->getLayerId() == 0 ) 
+#else
   if( pcSPS->getLayerId() == 0 || pcSPS->getUpdateRepFormatFlag() ) 
+#endif  
   {
     assert( pcSPS->getBitDepthY() >= 8 );
@@ -532,64 +517,30 @@
   WRITE_UVLC( pcSPS->getQuadtreeTUMaxDepthIntra() - 1,                               "max_transform_hierarchy_depth_intra" );
   WRITE_FLAG( pcSPS->getScalingListFlag() ? 1 : 0,                                   "scaling_list_enabled_flag" ); 
-
-#if IL_SL_SIGNALLING_N0371
-  pcSPS->setSPS( pcSPS->getLayerId(), pcSPS );
-#endif
-
   if(pcSPS->getScalingListFlag())
   {
+#if SCALINGLIST_INFERRING
+    if( pcSPS->getLayerId() > 0 )
+    {
+      WRITE_FLAG( pcSPS->getInferScalingListFlag() ? 1 : 0, "sps_infer_scaling_list_flag" );
+    }
+
+    if( pcSPS->getInferScalingListFlag() )
+    {
+      // The value of pps_scaling_list_ref_layer_id shall be in the range of 0 to 62, inclusive
+      assert( pcSPS->getScalingListRefLayerId() <= 62 );
+
+      WRITE_UVLC( pcSPS->getScalingListRefLayerId(), "sps_scaling_list_ref_layer_id" );
+    }
+    else
+    {
+#endif
     WRITE_FLAG( pcSPS->getScalingListPresentFlag() ? 1 : 0,                          "sps_scaling_list_data_present_flag" ); 
     if(pcSPS->getScalingListPresentFlag())
     {
-#if SCALING_LIST_OUTPUT_RESULT
-    printf("SPS\n");
-#endif
-
-#if IL_SL_SIGNALLING_N0371
-    m_pcSlice->getScalingList()->setLayerId( pcSPS->getLayerId() );
-
-    if( pcSPS->getLayerId() > 0 )
-    {
-      WRITE_FLAG( pcSPS->getPredScalingListFlag() ? 1 : 0,                          "sps_pred_scaling_list_flag" );
-      m_pcSlice->getScalingList()->setPredScalingListFlag( pcSPS->getPredScalingListFlag() );
-
-      if( pcSPS->getPredScalingListFlag() )
-      {
-
-        // The value of sps_scaling_list_ref_layer_id shall be in the range of 0 to 62, inclusive
-        assert( /*pcSPS->getScalingListRefLayerId() >= 0 &&*/ pcSPS->getScalingListRefLayerId() <= 62 );
-        
-        // When avc_base_layer_flag is equal to 1, it is a requirement of bitstream conformance that the value of sps_scaling_list_ref_layer_id shall be greater than 0
-        if( pcSPS->getVPS()->getAvcBaseLayerFlag() )
-        {
-          assert( pcSPS->getScalingListRefLayerId() > 0 );
-        }
-
-        // It is a requirement of bitstream conformance that, when an SPS with nuh_layer_id equal to nuhLayerIdA is active for a layer with nuh_layer_id equal to nuhLayerIdB and 
-        // sps_infer_scaling_list_flag in the SPS is equal to 1, sps_infer_scaling_list_flag shall be equal to 0 for the SPS that is active for the layer with nuh_layer_id equal to sps_scaling_list_ref_layer_id
-        assert( pcSPS->getSPS( pcSPS->getScalingListRefLayerId() )->getPredScalingListFlag() == false );
-
-        // It is a requirement of bitstream conformance that, when an SPS with nuh_layer_id equal to nuhLayerIdA is active for a layer with nuh_layer_id equal to nuhLayerIdB, 
-        // the layer with nuh_layer_id equal to sps_scaling_list_ref_layer_id shall be a direct or indirect reference layer of the layer with nuh_layer_id equal to nuhLayerIdB
-        assert( pcSPS->getVPS()->getScalingListLayerDependency( pcSPS->getLayerId(), pcSPS->getScalingListRefLayerId() ) == true );
-
-        WRITE_UVLC( pcSPS->getScalingListRefLayerId(),                            "scaling_list_sps_ref_layer_id" );
-        m_pcSlice->getScalingList()->setScalingListRefLayerId( pcSPS->getScalingListRefLayerId() );
-        codeScalingList( m_pcSlice->getScalingList() );
-      }
-      else
-      {
-        codeScalingList( m_pcSlice->getScalingList() );
-      }
-    }
-    else
-    {
       codeScalingList( m_pcSlice->getScalingList() );
     }
-#else
-      codeScalingList( m_pcSlice->getScalingList() );
-#endif
-
-    }
+#if SCALINGLIST_INFERRING
+    }
+#endif
   }
   WRITE_FLAG( pcSPS->getUseAMP() ? 1 : 0,                                            "amp_enabled_flag" );
@@ -648,6 +599,18 @@
   if( 1 )   // if( sps_extension_flag )
   {
+#if O0142_CONDITIONAL_SPS_EXTENSION
+    UInt spsExtensionTypeFlag[8] = { 0, 1, 0, 0, 0, 0, 0, 0 };
+    for (UInt i = 0; i < 8; i++)
+    {
+      WRITE_FLAG( spsExtensionTypeFlag[i], "sps_extension_type_flag" );
+    }
+    if (spsExtensionTypeFlag[1])
+    {
+      codeSPSExtension( pcSPS );
+    }
+#else
     codeSPSExtension( pcSPS );
     WRITE_FLAG( 0, "sps_extension2_flag" );
+#endif
   }
 #else
@@ -670,4 +633,7 @@
     {
       Window scaledWindow = pcSPS->getScaledRefLayerWindow(i);
+#if O0098_SCALED_REF_LAYER_ID
+      WRITE_CODE( pcSPS->getScaledRefLayerId(i), 6,          "scaled_ref_layer_id" );
+#endif
       WRITE_SVLC( scaledWindow.getWindowLeftOffset()   >> 1, "scaled_ref_layer_left_offset" );
       WRITE_SVLC( scaledWindow.getWindowTopOffset()    >> 1, "scaled_ref_layer_top_offset" );
@@ -891,4 +857,14 @@
     }
   }
+#endif
+#if VPS_TSLAYERS
+    WRITE_FLAG( vps->getMaxTSLayersPresentFlag(), "vps_sub_layers_max_minus1_present_flag");
+    if (vps->getMaxTSLayersPresentFlag())
+    {
+        for( i = 0; i < vps->getMaxLayers() - 1; i++)
+        {
+            WRITE_CODE(vps->getMaxTSLayersMinus1(i), 3, "sub_layers_vps_max_minus1[i]" );
+        }
+    }
 #endif
 #if JCTVC_M0203_INTERLAYER_PRED_IDC
@@ -982,4 +958,11 @@
   }
 
+#if O0153_ALT_OUTPUT_LAYER_FLAG
+  if( vps->getMaxLayers() > 1 )
+  {
+    WRITE_FLAG( vps->getAltOuputLayerFlag(), "alt_output_layer_flag" );   
+  }
+#endif
+
 #if REPN_FORMAT_IN_VPS
   WRITE_FLAG( vps->getRepFormatIdxPresentFlag(), "rep_format_idx_present_flag"); 
@@ -987,5 +970,9 @@
   if( vps->getRepFormatIdxPresentFlag() )
   {
+#if O0096_REP_FORMAT_INDEX
+    WRITE_CODE( vps->getVpsNumRepFormats() - 1, 8, "vps_num_rep_formats_minus1" );
+#else
     WRITE_CODE( vps->getVpsNumRepFormats() - 1, 4, "vps_num_rep_formats_minus1" );
+#endif
   }
   for(i = 0; i < vps->getVpsNumRepFormats(); i++)
@@ -1001,5 +988,9 @@
       if( vps->getVpsNumRepFormats() > 1 )
       {
+#if O0096_REP_FORMAT_INDEX
+        WRITE_CODE( vps->getVpsRepFormatIdx(i), 8, "vps_rep_format_idx[i]" );
+#else
         WRITE_CODE( vps->getVpsRepFormatIdx(i), 4, "vps_rep_format_idx[i]" );
+#endif
       }
     }
@@ -1025,6 +1016,48 @@
   WRITE_FLAG(vps->getCrossLayerIrapAlignFlag(), "cross_layer_irap_aligned_flag");
 #endif 
+#if VPS_DPB_SIZE_TABLE
+  for(i = 1; i < vps->getNumOutputLayerSets(); i++)
+  {
+    WRITE_FLAG( vps->getSubLayerFlagInfoPresentFlag( i ), "sub_layer_flag_info_present_flag[i]");  
+    for(j = 0; j < vps->getMaxTLayers(); j++)
+    {
+      if( j > 0 && vps->getSubLayerFlagInfoPresentFlag(i) )
+      {
+        WRITE_FLAG( vps->getSubLayerDpbInfoPresentFlag( i, j), "sub_layer_dpb_info_present_flag[i]");  
+      }
+      if( vps->getSubLayerDpbInfoPresentFlag(i, j) )
+      {
+        for(Int k = 0; k < vps->getNumSubDpbs(i); k++)
+        {
+          WRITE_UVLC( vps->getMaxVpsDecPicBufferingMinus1( i, k, j), "max_vps_dec_pic_buffering_minus1[i][k][j]" ); 
+        }
+        WRITE_UVLC( vps->getMaxVpsNumReorderPics( i, j), "max_vps_num_reorder_pics[i][j]" );              
+        WRITE_UVLC( vps->getMaxVpsLatencyIncreasePlus1( i, j), "max_vps_latency_increase_plus1[i][j]" );        
+      }
+    }
+  }
+#endif
 #if VPS_EXTN_DIRECT_REF_LAYERS && M0457_PREDICTION_INDICATIONS
   WRITE_UVLC( vps->getDirectDepTypeLen()-2,                           "direct_dep_type_len_minus2");
+#if O0096_DEFAULT_DEPENDENCY_TYPE
+  WRITE_FLAG(vps->getDefaultDirectDependencyTypeFlag(), "default_direct_dependency_flag");
+  if (vps->getDefaultDirectDependencyTypeFlag())
+  {
+    WRITE_CODE( vps->getDefaultDirectDependencyType(), vps->getDirectDepTypeLen(), "default_direct_dependency_type" );
+  }
+  else
+  {
+    for(i = 1; i < vps->getMaxLayers(); i++)
+    {
+      for(j = 0; j < i; j++)
+      {
+        if (vps->getDirectDependencyFlag(i, j))
+        {
+          WRITE_CODE( vps->getDirectDependencyType(i, j), vps->getDirectDepTypeLen(), "direct_dependency_type[i][j]" );
+        }
+      }
+    }
+  }
+#else
   for(i = 1; i < vps->getMaxLayers(); i++)
   {
@@ -1037,19 +1070,12 @@
     }
   }
-
-#if IL_SL_SIGNALLING_N0371
-  for(i = 1; i < vps->getMaxLayers(); i++)
-  {
-    for(j = 0; j < i; j++)
-    {
-      vps->setScalingListLayerDependency( i, j, vps->checkLayerDependency( i,j ) );
-    }
-  }
-#endif
-
+#endif
 #endif
 #if M0040_ADAPTIVE_RESOLUTION_CHANGE
   WRITE_FLAG(vps->getSingleLayerForNonIrapFlag(), "single_layer_for_non_irap_flag" );
 #endif
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+  WRITE_FLAG(vps->getHigherLayerIrapSkipFlag(), "higher_layer_irap_skip_flag" );
+#endif
 
 #if !VPS_VUI
@@ -1071,4 +1097,25 @@
 Void  TEncCavlc::codeRepFormat      ( RepFormat *repFormat )
 {
+#if REPN_FORMAT_CONTROL_FLAG
+   WRITE_FLAG ( repFormat->getChromaAndBitDepthVpsPresentFlag(), "chroma_and_bit_depth_vps_presenet_flag"); 
+
+   WRITE_CODE ( repFormat->getPicWidthVpsInLumaSamples (), 16, "pic_width_in_luma_samples" );    
+   WRITE_CODE ( repFormat->getPicHeightVpsInLumaSamples(), 16, "pic_height_in_luma_samples" );  
+
+   if ( repFormat->getChromaAndBitDepthVpsPresentFlag() )
+   {
+     WRITE_CODE( repFormat->getChromaFormatVpsIdc(), 2, "chroma_format_idc" );   
+
+     if( repFormat->getChromaFormatVpsIdc() == 3 )
+     {
+       WRITE_FLAG( repFormat->getSeparateColourPlaneVpsFlag(), "separate_colour_plane_flag");      
+     }
+
+     assert( repFormat->getBitDepthVpsLuma() >= 8 );
+     assert( repFormat->getBitDepthVpsChroma() >= 8 );
+     WRITE_CODE( repFormat->getBitDepthVpsLuma() - 8,   4, "bit_depth_luma_minus8" );           
+     WRITE_CODE( repFormat->getBitDepthVpsChroma() - 8, 4, "bit_depth_chroma_minus8" );
+   }
+#else 
   WRITE_CODE( repFormat->getChromaFormatVpsIdc(), 2, "chroma_format_idc" );    
   
@@ -1084,5 +1131,6 @@
   assert( repFormat->getBitDepthVpsChroma() >= 8 );
   WRITE_CODE( repFormat->getBitDepthVpsLuma() - 8,   4, "bit_depth_luma_minus8" );           
-  WRITE_CODE( repFormat->getBitDepthVpsChroma() - 8, 4, "bit_depth_chroma_minus8" );         
+  WRITE_CODE( repFormat->getBitDepthVpsChroma() - 8, 4, "bit_depth_chroma_minus8" );
+#endif 
 
 }
@@ -1092,7 +1140,15 @@
 {
   Int i,j;
+#if O0223_PICTURE_TYPES_ALIGN_FLAG
+  WRITE_FLAG(vps->getCrossLayerPictureTypeAlignFlag(), "cross_layer_pic_type_aligned_flag");
+  if (!vps->getCrossLayerPictureTypeAlignFlag())
+  {
+#endif 
 #if IRAP_ALIGN_FLAG_IN_VPS_VUI
-      WRITE_FLAG(vps->getCrossLayerIrapAlignFlag(), "cross_layer_irap_aligned_flag");
+    WRITE_FLAG(vps->getCrossLayerIrapAlignFlag(), "cross_layer_irap_aligned_flag");
 #endif 
+#if O0223_PICTURE_TYPES_ALIGN_FLAG
+  }
+#endif
 #if VPS_VUI_BITRATE_PICRATE
   WRITE_FLAG( vps->getBitRatePresentVpsFlag(),        "bit_rate_present_vps_flag" );
@@ -1127,13 +1183,47 @@
   }
 #endif
+#if VPS_VUI_TILES_NOT_IN_USE__FLAG
+  UInt layerIdx;
+  WRITE_FLAG( vps->getTilesNotInUseFlag() ? 1 : 0 , "tiles_not_in_use_flag" );
+  if (!vps->getTilesNotInUseFlag())
+  {
+    for(i = 0; i < vps->getMaxLayers(); i++)
+    {
+      WRITE_FLAG( vps->getTilesInUseFlag(i) ? 1 : 0 , "tiles_in_use_flag[ i ]" );
+      if (vps->getTilesInUseFlag(i))
+      {
+        WRITE_FLAG( vps->getLoopFilterNotAcrossTilesFlag(i) ? 1 : 0 , "loop_filter_not_across_tiles_flag[ i ]" );
+      }
+    }
+#endif
 #if TILE_BOUNDARY_ALIGNED_FLAG
-  for(i = 1; i < vps->getMaxLayers(); i++)
-  {
-    for(j = 0; j < vps->getNumDirectRefLayers(vps->getLayerIdInNuh(i)); j++)
-    {
-      WRITE_FLAG( vps->getTileBoundariesAlignedFlag(i,j) ? 1 : 0 , "tile_boundaries_aligned_flag[i][j]" );
-    }
-  }  
-#endif 
+    for(i = 1; i < vps->getMaxLayers(); i++)
+    {
+      for(j = 0; j < vps->getNumDirectRefLayers(vps->getLayerIdInNuh(i)); j++)
+      {
+#if VPS_VUI_TILES_NOT_IN_USE__FLAG
+        layerIdx = vps->getLayerIdInVps(vps->getRefLayerId(vps->getLayerIdInNuh(i), j));
+        if (vps->getTilesInUseFlag(i) && vps->getTilesInUseFlag(layerIdx)) {
+          WRITE_FLAG( vps->getTileBoundariesAlignedFlag(i,j) ? 1 : 0 , "tile_boundaries_aligned_flag[i][j]" );
+        }
+#else
+        WRITE_FLAG( vps->getTileBoundariesAlignedFlag(i,j) ? 1 : 0 , "tile_boundaries_aligned_flag[i][j]" );
+#endif
+      }
+    }  
+#endif
+#if VPS_VUI_TILES_NOT_IN_USE__FLAG
+  }
+#endif
+#if VPS_VUI_WPP_NOT_IN_USE__FLAG
+  WRITE_FLAG( vps->getWppNotInUseFlag() ? 1 : 0 , "wpp_not_in_use_flag" );
+  if (!vps->getWppNotInUseFlag())
+  {
+    for(i = 0; i < vps->getMaxLayers(); i++)
+    {
+      WRITE_FLAG( vps->getWppInUseFlag(i) ? 1 : 0 , "wpp_in_use_flag[ i ]" );
+    }
+  }
+#endif
 #if N0160_VUI_EXT_ILP_REF
   WRITE_FLAG( vps->getNumIlpRestrictedRefLayers() ? 1 : 0 , "num_ilp_restricted_ref_layers" );    
@@ -1159,4 +1249,26 @@
   }
 #endif 
+#if VPS_VUI_VIDEO_SIGNAL
+    WRITE_FLAG( vps->getVideoSigPresentVpsFlag(), "video_signal_info_idx_present_flag" );
+    if (vps->getVideoSigPresentVpsFlag())
+    {
+        WRITE_CODE(vps->getNumVideoSignalInfo()-1, 4, "vps_num_video_signal_info_minus1" );
+    }
+    
+    for(i = 0; i < vps->getNumVideoSignalInfo(); i++)
+    {
+        WRITE_CODE(vps->getVideoVPSFormat(i), 3, "video_vps_format" );
+        WRITE_FLAG(vps->getVideoFullRangeVpsFlag(i), "video_full_range_vps_flag" );
+        WRITE_CODE(vps->getColorPrimaries(i), 8, "color_primaries_vps" );
+        WRITE_CODE(vps->getTransCharacter(i), 8, "transfer_characteristics_vps" );
+        WRITE_CODE(vps->getMaxtrixCoeff(i), 8, "matrix_coeffs_vps" );
+    }
+    
+    if (vps->getVideoSigPresentVpsFlag() && vps->getNumVideoSignalInfo() > 1 )
+    {
+        for (i=1; i < vps->getMaxLayers(); i++)
+            WRITE_CODE(vps->getVideoSignalInfoIdx(i), 4, "vps_video_signal_info_idx" );
+    }
+#endif
 }
 #endif
@@ -1221,4 +1333,12 @@
       iBits++;
     }
+#if O0149_CROSS_LAYER_BLA_FLAG
+    if( pcSlice->getPPS()->getNumExtraSliceHeaderBits() > iBits )
+    {
+      assert(!!"cross_layer_bla_flag");
+      WRITE_FLAG(pcSlice->getCrossLayerBLAFlag(), "cross_layer_bla_flag");
+      iBits++;
+    }
+#endif
     for ( ; iBits < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); iBits++)
     {
@@ -1299,5 +1419,4 @@
       TComReferencePictureSet* rps = pcSlice->getRPS();
       
-#if FIX1071
       // check for bitstream restriction stating that:
       // If the current picture is a BLA or CRA picture, the value of NumPocTotalCurr shall be equal to 0.
@@ -1313,5 +1432,4 @@
         }
       }
-#endif
 
       if(pcSlice->getRPSidx() < 0)
@@ -1467,18 +1585,22 @@
       if (pcSlice->getSPS()->getUseSAO())
       {
-         WRITE_FLAG( pcSlice->getSaoEnabledFlag(), "slice_sao_luma_flag" );
+         WRITE_FLAG( pcSlice->getSaoEnabledFlag(), "slice_sao_luma_flag" );         
+#if AUXILIARY_PICTURES
+         if (pcSlice->getChromaFormatIdc() != CHROMA_400)
          {
+#endif
+#if HM_CLEANUP_SAO
+         WRITE_FLAG( pcSlice->getSaoEnabledFlagChroma(), "slice_sao_chroma_flag" );
+#else
+         {
+           SAOParam *saoParam = pcSlice->getPic()->getPicSym()->getSaoParam();
+           WRITE_FLAG( saoParam->bSaoFlag[1], "slice_sao_chroma_flag" );
+         }
+#endif
 #if AUXILIARY_PICTURES
-           if (pcSlice->getChromaFormatIdc() != CHROMA_400)
-           {
-#endif
-           SAOParam *saoParam = pcSlice->getPic()->getPicSym()->getSaoParam();
-          WRITE_FLAG( saoParam->bSaoFlag[1], "slice_sao_chroma_flag" );
-#if AUXILIARY_PICTURES
-           }
-#endif
          }
-      }
-    }
+#endif
+      }
+    }   
 
     //check if numrefidxes match the defaults. If not, override
@@ -2026,11 +2148,4 @@
   Bool scalingListPredModeFlag;
 
-#if SCALING_LIST_OUTPUT_RESULT
-  Int startBit;
-  Int startTotalBit;
-  startBit = m_pcBitIf->getNumberOfWrittenBits();
-  startTotalBit = m_pcBitIf->getNumberOfWrittenBits();
-#endif
-
     //for each size
     for(sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
@@ -2038,36 +2153,4 @@
       for(listId = 0; listId < g_scalingListNum[sizeId]; listId++)
       {
-#if SCALING_LIST_OUTPUT_RESULT
-        startBit = m_pcBitIf->getNumberOfWrittenBits();
-#endif
-
-#if IL_SL_SIGNALLING_N0371
-        if( scalingList->getLayerId() > 0 && scalingList->getPredScalingListFlag() )
-        {
-          scalingListPredModeFlag = scalingList->checkPredMode( sizeId, listId );
-          WRITE_FLAG( scalingListPredModeFlag, "scaling_list_pred_mode_flag" );
-          if(!scalingListPredModeFlag)// Copy Mode
-          {
-            WRITE_UVLC( (Int)listId - (Int)scalingList->getRefMatrixId (sizeId,listId), "scaling_list_pred_matrix_id_delta");
-          }
-          else// DPCM Mode
-          {
-            xCodeScalingList(scalingList, sizeId, listId);
-          }
-        }
-        else
-        {
-          scalingListPredModeFlag = scalingList->checkPredMode( sizeId, listId );
-          WRITE_FLAG( scalingListPredModeFlag, "scaling_list_pred_mode_flag" );
-          if(!scalingListPredModeFlag)// Copy Mode
-          {
-            WRITE_UVLC( (Int)listId - (Int)scalingList->getRefMatrixId (sizeId,listId), "scaling_list_pred_matrix_id_delta");
-          }
-          else// DPCM Mode
-          {
-            xCodeScalingList(scalingList, sizeId, listId);
-          }
-        }
-#else
         scalingListPredModeFlag = scalingList->checkPredMode( sizeId, listId );
         WRITE_FLAG( scalingListPredModeFlag, "scaling_list_pred_mode_flag" );
@@ -2080,15 +2163,6 @@
           xCodeScalingList(scalingList, sizeId, listId);
         }
-#endif
-
-#if SCALING_LIST_OUTPUT_RESULT
-        printf("Matrix [%d][%d] Bit %d\n",sizeId,listId,m_pcBitIf->getNumberOfWrittenBits() - startBit);
-#endif
-
-      }
-    }
-#if SCALING_LIST_OUTPUT_RESULT
-  printf("Total Bit %d\n",m_pcBitIf->getNumberOfWrittenBits()-startTotalBit);
-#endif
+      }
+    }
   return;
 }
@@ -2105,63 +2179,24 @@
   Int data;
   Int *src = scalingList->getScalingListAddress(sizeId, listId);
-
-    if( sizeId > SCALING_LIST_8x8 )
-    {
-#if IL_SL_SIGNALLING_N0371
-      if( scalingList->getLayerId() > 0 && scalingList->getPredScalingListFlag() )
-      {
-        ref_scalingListDC[scalingList->getLayerId()][sizeId][listId] = scalingList->getScalingListDC(sizeId,listId);
-        scalingList->setScalingListDC(sizeId,listId,ref_scalingListDC[scalingList->getScalingListRefLayerId()][sizeId][listId]);
-      }
-      else
-      {
-        WRITE_SVLC( scalingList->getScalingListDC(sizeId,listId) - 8, "scaling_list_dc_coef_minus8");
-        nextCoef = scalingList->getScalingListDC(sizeId,listId);
-        ref_scalingListDC[scalingList->getLayerId()][sizeId][listId] = scalingList->getScalingListDC(sizeId,listId);
-      }
-#else
-      WRITE_SVLC( scalingList->getScalingListDC(sizeId,listId) - 8, "scaling_list_dc_coef_minus8");
-      nextCoef = scalingList->getScalingListDC(sizeId,listId);
-#endif
-    }
-    for(Int i=0;i<coefNum;i++)
-    {
-#if IL_SL_SIGNALLING_N0371
-      if( scalingList->getLayerId() > 0 && scalingList->getPredScalingListFlag() )
-      {
-        ref_scalingListCoef[scalingList->getLayerId()][sizeId][listId][i] = src[scan[i]];
-        src[scan[i]] = ref_scalingListCoef[scalingList->getScalingListRefLayerId()][sizeId][listId][i];
-      }
-      else
-      {
-        data = src[scan[i]] - nextCoef;
-        ref_scalingListCoef[scalingList->getLayerId()][sizeId][listId][i] = src[scan[i]];
-        nextCoef = src[scan[i]];
-        if(data > 127)
-        {
-          data = data - 256;
-        }
-        if(data < -128)
-        {
-          data = data + 256;
-        }
-
-        WRITE_SVLC( data,  "scaling_list_delta_coef");
-      }
-#else
-      data = src[scan[i]] - nextCoef;
-      nextCoef = src[scan[i]];
-      if(data > 127)
-      {
-        data = data - 256;
-      }
-      if(data < -128)
-      {
-        data = data + 256;
-      }
-
-      WRITE_SVLC( data,  "scaling_list_delta_coef");
-#endif
-    }
+  if( sizeId > SCALING_LIST_8x8 )
+  {
+    WRITE_SVLC( scalingList->getScalingListDC(sizeId,listId) - 8, "scaling_list_dc_coef_minus8");
+    nextCoef = scalingList->getScalingListDC(sizeId,listId);
+  }
+  for(Int i=0;i<coefNum;i++)
+  {
+    data = src[scan[i]] - nextCoef;
+    nextCoef = src[scan[i]];
+    if(data > 127)
+    {
+      data = data - 256;
+    }
+    if(data < -128)
+    {
+      data = data + 256;
+    }
+
+    WRITE_SVLC( data,  "scaling_list_delta_coef");
+  }
 }
 Bool TEncCavlc::findMatchingLTRP ( TComSlice* pcSlice, UInt *ltrpsIndex, Int ltrpPOC, Bool usedFlag )
Index: trunk/source/Lib/TLibEncoder/TEncCavlc.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncCavlc.h	(revision 499)
+++ trunk/source/Lib/TLibEncoder/TEncCavlc.h	(revision 540)
@@ -109,4 +109,7 @@
   
   Void codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList );
+#if HM_CLEANUP_SAO
+  Void codeSAOBlkParam(SAOBlkParam& saoBlkParam, Bool* sliceEnabled, Bool leftMergeAvail, Bool aboveMergeAvail, Bool onlyEstMergeInfo = false){printf("only supported in CABAC"); assert(0); exit(-1);}
+#else
   Void codeSAOSign       ( UInt code   ) { printf("Not supported\n"); assert (0); }
   Void codeSaoMaxUvlc    ( UInt   code, UInt maxSymbol ){printf("Not supported\n"); assert (0);}
@@ -114,5 +117,5 @@
   Void codeSaoTypeIdx    ( UInt uiCode ){printf("Not supported\n"); assert (0);}
   Void codeSaoUflc       ( UInt uiLength, UInt   uiCode ){ assert(uiCode < 32); printf("Not supported\n"); assert (0);}
-
+#endif
   Void codeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx );
   Void codeSkipFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
Index: trunk/source/Lib/TLibEncoder/TEncCfg.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncCfg.h	(revision 499)
+++ trunk/source/Lib/TLibEncoder/TEncCfg.h	(revision 540)
@@ -196,6 +196,7 @@
   Int       m_maxNumOffsetsPerPic;
   Bool      m_saoLcuBoundary;
+#if !HM_CLEANUP_SAO
   Bool      m_saoLcuBasedOptimization;
-
+#endif
   //====== Lossless ========
   Bool      m_useLossless;
@@ -328,21 +329,11 @@
   Int       m_TMVPModeId;
   Int       m_signHideFlag;
-#if RATE_CONTROL_LAMBDA_DOMAIN
   Bool      m_RCEnableRateControl;
   Int       m_RCTargetBitrate;
-#if M0036_RC_IMPROVEMENT
   Int       m_RCKeepHierarchicalBit;
-#else
-  Bool      m_RCKeepHierarchicalBit;
-#endif
   Bool      m_RCLCULevelRC;
   Bool      m_RCUseLCUSeparateModel;
   Int       m_RCInitialQP;
   Bool      m_RCForceIntraQP;
-#else
-  Bool      m_enableRateCtrl;                                ///< Flag for using rate control algorithm
-  Int       m_targetBitrate;                                 ///< target bitrate
-  Int       m_numLCUInUnit;                                  ///< Total number of LCUs in a frame should be divided by the NumLCUInUnit
-#endif
   Bool      m_TransquantBypassEnableFlag;                     ///< transquant_bypass_enable_flag setting in PPS.
   Bool      m_CUTransquantBypassFlagValue;                    ///< if transquant_bypass_enable_flag, the fixed value to use for the per-CU cu_transquant_bypass_flag.
@@ -393,4 +384,13 @@
   Int       m_adaptiveResolutionChange;
 #endif
+#if O0153_ALT_OUTPUT_LAYER_FLAG
+  Bool      m_altOutputLayerFlag;
+#endif
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+  Int       m_skipPictureAtArcSwitch;
+#endif
+#if O0149_CROSS_LAYER_BLA_FLAG
+  Bool      m_crossLayerBLAFlag;
+#endif
 #endif
 
@@ -629,6 +629,8 @@
   Void  setSaoLcuBoundary              (Bool val)      { m_saoLcuBoundary = val; }
   Bool  getSaoLcuBoundary              ()              { return m_saoLcuBoundary; }
+#if !HM_CLEANUP_SAO
   Void  setSaoLcuBasedOptimization               (Bool val)            { m_saoLcuBasedOptimization = val; }
   Bool  getSaoLcuBasedOptimization               ()                    { return m_saoLcuBasedOptimization; }
+#endif
   Void  setLFCrossTileBoundaryFlag               ( Bool   val  )       { m_loopFilterAcrossTilesEnabledFlag = val; }
   Bool  getLFCrossTileBoundaryFlag               ()                    { return m_loopFilterAcrossTilesEnabledFlag;   }
@@ -806,16 +808,10 @@
   Void      setSignHideFlag( Int signHideFlag ) { m_signHideFlag = signHideFlag; }
   Int       getSignHideFlag()                    { return m_signHideFlag; }
-#if RATE_CONTROL_LAMBDA_DOMAIN
   Bool      getUseRateCtrl         ()              { return m_RCEnableRateControl;   }
   Void      setUseRateCtrl         ( Bool b )      { m_RCEnableRateControl = b;      }
   Int       getTargetBitrate       ()              { return m_RCTargetBitrate;       }
   Void      setTargetBitrate       ( Int bitrate ) { m_RCTargetBitrate  = bitrate;   }
-#if M0036_RC_IMPROVEMENT
   Int       getKeepHierBit         ()              { return m_RCKeepHierarchicalBit; }
   Void      setKeepHierBit         ( Int i )       { m_RCKeepHierarchicalBit = i;    }
-#else
-  Bool      getKeepHierBit         ()              { return m_RCKeepHierarchicalBit; }
-  Void      setKeepHierBit         ( Bool b )      { m_RCKeepHierarchicalBit = b;    }
-#endif
   Bool      getLCULevelRC          ()              { return m_RCLCULevelRC; }
   Void      setLCULevelRC          ( Bool b )      { m_RCLCULevelRC = b; }
@@ -826,12 +822,4 @@
   Bool      getForceIntraQP        ()              { return m_RCForceIntraQP;        }
   Void      setForceIntraQP        ( Bool b )      { m_RCForceIntraQP = b;           }
-#else
-  Bool      getUseRateCtrl    ()                { return m_enableRateCtrl;    }
-  Void      setUseRateCtrl    (Bool flag)       { m_enableRateCtrl = flag;    }
-  Int       getTargetBitrate  ()                { return m_targetBitrate;     }
-  Void      setTargetBitrate  (Int target)      { m_targetBitrate  = target;  }
-  Int       getNumLCUInUnit   ()                { return m_numLCUInUnit;      }
-  Void      setNumLCUInUnit   (Int numLCUs)     { m_numLCUInUnit   = numLCUs; }
-#endif
   Bool      getTransquantBypassEnableFlag()           { return m_TransquantBypassEnableFlag; }
   Void      setTransquantBypassEnableFlag(Bool flag)  { m_TransquantBypassEnableFlag = flag; }
@@ -934,8 +922,20 @@
   Int       getAdaptiveResolutionChange()      { return m_adaptiveResolutionChange; }
 #endif
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+  Void      setSkipPictureAtArcSwitch(Int x) { m_skipPictureAtArcSwitch = x;    }
+  Int       getSkipPictureAtArcSwitch()      { return m_skipPictureAtArcSwitch; }
+#endif
 #if AUXILIARY_PICTURES
   Void         setChromaFormatIDC(ChromaFormat x) { m_chromaFormatIDC = x;    }
   ChromaFormat getChromaFormatIDC()               { return m_chromaFormatIDC; }
 #endif
+#if O0153_ALT_OUTPUT_LAYER_FLAG
+  Bool      getAltOuputLayerFlag() const { return m_altOutputLayerFlag; }
+  Void      setAltOuputLayerFlag(Bool b) { m_altOutputLayerFlag = b;    }
+#endif
+#if O0149_CROSS_LAYER_BLA_FLAG
+  Bool      getCrossLayerBLAFlag() const { return m_crossLayerBLAFlag; }
+  Void      setCrossLayerBLAFlag(Bool b) { m_crossLayerBLAFlag = b;    }
+#endif
 #endif
 };
Index: trunk/source/Lib/TLibEncoder/TEncCu.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncCu.cpp	(revision 499)
+++ trunk/source/Lib/TLibEncoder/TEncCu.cpp	(revision 540)
@@ -95,9 +95,4 @@
   
   m_bEncodeDQP = false;
-#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
-  m_LCUPredictionSAD = 0;
-  m_addSADDepth      = 0;
-  m_temporalSAD      = 0;
-#endif
 
   // initialize partition order.
@@ -243,10 +238,4 @@
   m_ppcBestCU[0]->initCU( rpcCU->getPic(), rpcCU->getAddr() );
   m_ppcTempCU[0]->initCU( rpcCU->getPic(), rpcCU->getAddr() );
-
-#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
-  m_addSADDepth      = 0;
-  m_LCUPredictionSAD = 0;
-  m_temporalSAD      = 0;
-#endif
 
 #if N0383_IL_CONSTRAINED_TILE_SETS_SEI
@@ -433,5 +422,4 @@
   }
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
   if ( m_pcEncCfg->getUseRateCtrl() )
   {
@@ -439,12 +427,4 @@
     iMaxQP = m_pcRateCtrl->getRCQP();
   }
-#else
-  if(m_pcEncCfg->getUseRateCtrl())
-  {
-    Int qp = m_pcRateCtrl->getUnitQP();
-    iMinQP  = Clip3( MIN_QP, MAX_QP, qp);
-    iMaxQP  = Clip3( MIN_QP, MAX_QP, qp);
-  }
-#endif
 
   // If slice start or slice end is within this cu...
@@ -460,4 +440,14 @@
   if(!bSliceEnd && !bSliceStart && bInsidePicture )
   {
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+    if (m_pcEncCfg->getSkipPictureAtArcSwitch() && m_pcEncCfg->getAdaptiveResolutionChange() > 0 && pcSlice->getLayerId() == 1 && pcSlice->getPOC() == m_pcEncCfg->getAdaptiveResolutionChange())
+    {
+      rpcTempCU->initEstData( uiDepth, iBaseQP );
+      
+      xCheckRDCostMerge2Nx2N( rpcBestCU, rpcTempCU, &earlyDetectionSkipMode, true );
+    }
+    else
+    {
+#endif
 #if (ENCODER_FAST_MODE)
     Bool testInter = true;
@@ -528,12 +518,4 @@
       }
     }
-
-#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
-    if ( uiDepth <= m_addSADDepth )
-    {
-      m_LCUPredictionSAD += m_temporalSAD;
-      m_addSADDepth = uiDepth;
-    }
-#endif
 
     if(!earlyDetectionSkipMode)
@@ -779,11 +761,11 @@
       bSubBranch = true;
     }
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+    }
+#endif
   }
   else if(!(bSliceEnd && bInsidePicture))
   {
     bBoundary = true;
-#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
-    m_addSADDepth++;
-#endif
   }
 
@@ -829,5 +811,4 @@
     iMaxQP = iStartQP;
   }
-#if RATE_CONTROL_LAMBDA_DOMAIN
   if ( m_pcEncCfg->getUseRateCtrl() )
   {
@@ -835,12 +816,4 @@
     iMaxQP = m_pcRateCtrl->getRCQP();
   }
-#else
-  if(m_pcEncCfg->getUseRateCtrl())
-  {
-    Int qp = m_pcRateCtrl->getUnitQP();
-    iMinQP  = Clip3( MIN_QP, MAX_QP, qp);
-    iMaxQP  = Clip3( MIN_QP, MAX_QP, qp);
-  }
-#endif
   for (Int iQP=iMinQP; iQP<=iMaxQP; iQP++)
   {
@@ -1143,4 +1116,10 @@
   
   TComSlice * pcSlice = pcCU->getPic()->getSlice(pcCU->getPic()->getCurrSliceIdx());
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+  if (m_pcEncCfg->getSkipPictureAtArcSwitch() && m_pcEncCfg->getAdaptiveResolutionChange() > 0 && pcSlice->getLayerId() == 1 && pcSlice->getPOC() == m_pcEncCfg->getAdaptiveResolutionChange())
+  {
+    pcCU->setSkipFlagSubParts(true, uiAbsPartIdx, uiDepth);
+  }
+#endif
   // If slice start is within this cu...
   Bool bSliceStart = pcSlice->getSliceSegmentCurStartCUAddr() > pcPic->getPicSym()->getInverseCUOrderMap(pcCU->getAddr())*pcCU->getPic()->getNumPartInCU()+uiAbsPartIdx && 
@@ -1231,5 +1210,4 @@
 }
 
-#if RATE_CONTROL_INTRA
 Int xCalcHADs8x8_ISlice(Pel *piOrg, Int iStrideOrg) 
 {
@@ -1346,5 +1324,4 @@
   return(iSumHad);
 }
-#endif
 
 /** check RD costs for a CU block encoded with merge
@@ -1353,5 +1330,9 @@
  * \returns Void
  */
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+Void TEncCu::xCheckRDCostMerge2Nx2N( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, Bool *earlyDetectionSkipMode, Bool bUseSkip )
+#else
 Void TEncCu::xCheckRDCostMerge2Nx2N( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, Bool *earlyDetectionSkipMode )
+#endif
 {
   assert( rpcTempCU->getSlice()->getSliceType() != I_SLICE );
@@ -1387,5 +1368,9 @@
   }
 
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+  for( UInt uiNoResidual = bUseSkip?1:0; uiNoResidual < iteration; ++uiNoResidual )
+#else
   for( UInt uiNoResidual = 0; uiNoResidual < iteration; ++uiNoResidual )
+#endif
   {
     for( UInt uiMergeCand = 0; uiMergeCand < numValidMergeCand; ++uiMergeCand )
@@ -1515,14 +1500,4 @@
 #endif
 
-#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
-  if ( m_pcEncCfg->getUseRateCtrl() && m_pcEncCfg->getLCULevelRC() && ePartSize == SIZE_2Nx2N && uhDepth <= m_addSADDepth )
-  {
-    UInt SAD = m_pcRdCost->getSADPart( g_bitDepthY, m_ppcPredYuvTemp[uhDepth]->getLumaAddr(), m_ppcPredYuvTemp[uhDepth]->getStride(),
-      m_ppcOrigYuv[uhDepth]->getLumaAddr(), m_ppcOrigYuv[uhDepth]->getStride(),
-      rpcTempCU->getWidth(0), rpcTempCU->getHeight(0) );
-    m_temporalSAD = (Int)SAD;
-  }
-#endif
-
   m_pcPredSearch->encodeResAndCalcRdInterCU( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcResiYuvBest[uhDepth], m_ppcRecoYuvTemp[uhDepth], false );
   rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
@@ -1555,5 +1530,4 @@
   
   m_pcEntropyCoder->resetBits();
-
   if ( rpcTempCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
   {
@@ -1609,5 +1583,4 @@
 
   m_pcEntropyCoder->resetBits();
-
   if ( rpcTempCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
   {
Index: trunk/source/Lib/TLibEncoder/TEncCu.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncCu.h	(revision 499)
+++ trunk/source/Lib/TLibEncoder/TEncCu.h	(revision 540)
@@ -103,9 +103,5 @@
   Bool                    m_bUseSBACRD;
   TEncRateCtrl*           m_pcRateCtrl;
-#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
-  UInt                    m_LCUPredictionSAD;
-  Int                     m_addSADDepth;
-  Int                     m_temporalSAD;
-#endif
+
 #if N0383_IL_CONSTRAINED_TILE_SETS_SEI
   Bool                    m_disableILP;
@@ -128,11 +124,5 @@
   
   Void setBitCounter        ( TComBitCounter* pcBitCounter ) { m_pcBitCounter = pcBitCounter; }
-#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
-  UInt getLCUPredictionSAD() { return m_LCUPredictionSAD; }
-#endif
-#if RATE_CONTROL_INTRA
   Int   updateLCUDataISlice ( TComDataCU* pcCU, Int LCUIdx, Int width, Int height );
-#endif
-
 protected:
   Void  finishCU            ( TComDataCU*  pcCU, UInt uiAbsPartIdx,           UInt uiDepth        );
@@ -146,6 +136,9 @@
   Int   xComputeQP          ( TComDataCU* pcCU, UInt uiDepth );
   Void  xCheckBestMode      ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UInt uiDepth        );
-  
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+  Void  xCheckRDCostMerge2Nx2N( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, Bool *earlyDetectionSkipMode, Bool bUseSkip=false);
+#else  
   Void  xCheckRDCostMerge2Nx2N( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, Bool *earlyDetectionSkipMode);
+#endif
 
 #if AMP_MRG
Index: trunk/source/Lib/TLibEncoder/TEncEntropy.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncEntropy.cpp	(revision 499)
+++ trunk/source/Lib/TLibEncoder/TEncEntropy.cpp	(revision 540)
@@ -51,4 +51,5 @@
 Void TEncEntropy::encodeSliceHeader ( TComSlice* pcSlice )
 {
+#if !HM_CLEANUP_SAO
   if (pcSlice->getSPS()->getUseSAO())
   {
@@ -59,5 +60,5 @@
     }
   }
-
+#endif
   m_pcEntropyCoderIf->codeSliceHeader( pcSlice );
   return;
@@ -638,4 +639,5 @@
 }
 
+#if !HM_CLEANUP_SAO
 /** Encode SAO Offset
  * \param  saoLcuParam SAO LCU paramters
@@ -731,4 +733,6 @@
 }
 
+#endif
+
 Int TEncEntropy::countNonZeroCoeffs( TCoeff* pcCoef, UInt uiSize )
 {
Index: trunk/source/Lib/TLibEncoder/TEncEntropy.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncEntropy.h	(revision 499)
+++ trunk/source/Lib/TLibEncoder/TEncEntropy.h	(revision 540)
@@ -105,4 +105,7 @@
   virtual Void codeCoeffNxN      ( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType ) = 0;
   virtual Void codeTransformSkipFlags ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, TextType eTType ) = 0;
+#if HM_CLEANUP_SAO
+  virtual Void codeSAOBlkParam(SAOBlkParam& saoBlkParam, Bool* sliceEnabled, Bool leftMergeAvail, Bool aboveMergeAvail, Bool onlyEstMergeInfo = false)    =0;
+#else
   virtual Void codeSAOSign          ( UInt code   ) = 0;
   virtual Void codeSaoMaxUvlc       ( UInt code, UInt maxSymbol ) = 0;
@@ -110,4 +113,5 @@
   virtual Void codeSaoTypeIdx      ( UInt   uiCode) = 0;
   virtual Void codeSaoUflc         ( UInt uiLength, UInt   uiCode ) = 0;
+#endif
   virtual Void estBit               (estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType) = 0;
   
@@ -188,6 +192,10 @@
   
   Void estimateBit             ( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType);
+#if HM_CLEANUP_SAO
+  Void encodeSAOBlkParam(SAOBlkParam& saoBlkParam, Bool* sliceEnabled, Bool leftMergeAvail, Bool aboveMergeAvail){m_pcEntropyCoderIf->codeSAOBlkParam(saoBlkParam, sliceEnabled, leftMergeAvail, aboveMergeAvail, false);}
+#else
   Void    encodeSaoOffset(SaoLcuParam* saoLcuParam, UInt compIdx);
   Void    encodeSaoUnitInterleaving(Int compIdx, Bool saoFlag, Int rx, Int ry, SaoLcuParam* saoLcuParam, Int cuAddrInSlice, Int cuAddrUpInSlice, Int allowMergeLeft, Int allowMergeUp);
+#endif
   static Int countNonZeroCoeffs( TCoeff* pcCoef, UInt uiSize );
 
Index: trunk/source/Lib/TLibEncoder/TEncGOP.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 499)
+++ trunk/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 540)
@@ -635,4 +635,54 @@
     }
 #endif
+#if O0149_CROSS_LAYER_BLA_FLAG
+    if( m_layerId == 0 && (getNalUnitType(pocCurr, m_iLastIDR) == NAL_UNIT_CODED_SLICE_IDR_W_RADL || getNalUnitType(pocCurr, m_iLastIDR) == NAL_UNIT_CODED_SLICE_IDR_N_LP) )
+    {
+      pcSlice->setCrossLayerBLAFlag(m_pcEncTop->getCrossLayerBLAFlag());
+    }
+    else
+    {
+      pcSlice->setCrossLayerBLAFlag(false);
+    }
+#endif
+#if NO_CLRAS_OUTPUT_FLAG
+    if (m_layerId == 0 &&
+        (pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA))
+    {
+      if (m_bFirst)
+      {
+        m_pcEncTop->setNoClrasOutputFlag(true);
+      }
+      else if (pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
+            || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
+            || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP)
+      {
+        m_pcEncTop->setNoClrasOutputFlag(true);
+      }
+#if O0149_CROSS_LAYER_BLA_FLAG
+      else if ((pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP) &&
+               pcSlice->getCrossLayerBLAFlag())
+      {
+        m_pcEncTop->setNoClrasOutputFlag(true);
+      }
+#endif
+      else
+      {
+        m_pcEncTop->setNoClrasOutputFlag(false);
+      }
+      if (m_pcEncTop->getNoClrasOutputFlag())
+      {
+        for (UInt i = 0; i < m_pcCfg->getNumLayer(); i++)
+        {
+          m_ppcTEncTop[i]->setLayerInitializedFlag(false);
+          m_ppcTEncTop[i]->setFirstPicInLayerDecodedFlag(false);
+        }
+      }
+    }
+#endif
 #if M0040_ADAPTIVE_RESOLUTION_CHANGE
     if (m_pcEncTop->getAdaptiveResolutionChange() > 0 && m_layerId == 1 && pocCurr > m_pcEncTop->getAdaptiveResolutionChange())
@@ -661,8 +711,4 @@
 #endif
 
-#if IL_SL_SIGNALLING_N0371
-    m_pcEncTop->getScalingList()->setLayerId( m_layerId );
-#endif
-
     pcSlice->setLastIDR(m_iLastIDR);
     pcSlice->setSliceIdx(0);
@@ -672,9 +718,5 @@
     if(m_pcEncTop->getUseScalingListId() == SCALING_LIST_OFF)
     {
-#if IL_SL_SIGNALLING_N0371
-      m_pcEncTop->getTrQuant()->setFlatScalingList( m_layerId );
-#else
       m_pcEncTop->getTrQuant()->setFlatScalingList();
-#endif
       m_pcEncTop->getTrQuant()->setUseScalingList(false);
       m_pcEncTop->getSPS()->setScalingListPresentFlag(false);
@@ -683,16 +725,29 @@
     else if(m_pcEncTop->getUseScalingListId() == SCALING_LIST_DEFAULT)
     {
-#if IL_SL_SIGNALLING_N0371
-      pcSlice->getScalingList()->setLayerId( m_layerId );
-#endif
-
-#if IL_SL_SIGNALLING_N0371
-      pcSlice->setDefaultScalingList ( m_layerId );
-#else
+#if SCALINGLIST_INFERRING
+      // inferring of the scaling list can be moved to the config file
+      UInt refLayerId = 0;
+      if( m_layerId > 0 && !m_pcEncTop->getVPS()->getAvcBaseLayerFlag() && m_pcEncTop->getVPS()->getRecursiveRefLayerFlag( m_layerId, refLayerId ) )
+      {
+        m_pcEncTop->getSPS()->setInferScalingListFlag( true );
+        m_pcEncTop->getSPS()->setScalingListRefLayerId( refLayerId );
+        m_pcEncTop->getSPS()->setScalingListPresentFlag( false );
+        m_pcEncTop->getPPS()->setInferScalingListFlag( false );
+        m_pcEncTop->getPPS()->setScalingListPresentFlag( false );
+
+        // infer the scaling list from the reference layer
+        pcSlice->setScalingList ( m_ppcTEncTop[refLayerId]->getScalingList() );
+      }
+      else
+      {
+#endif
       pcSlice->setDefaultScalingList ();
-#endif
-
       m_pcEncTop->getSPS()->setScalingListPresentFlag(false);
       m_pcEncTop->getPPS()->setScalingListPresentFlag(false);
+
+#if SCALINGLIST_INFERRING
+      }
+#endif
+
       m_pcEncTop->getTrQuant()->setScalingList(pcSlice->getScalingList());
       m_pcEncTop->getTrQuant()->setUseScalingList(true);
@@ -700,39 +755,33 @@
     else if(m_pcEncTop->getUseScalingListId() == SCALING_LIST_FILE_READ)
     {
-#if IL_SL_SIGNALLING_N0371
-      pcSlice->getScalingList()->setLayerId( m_layerId );
+#if SCALINGLIST_INFERRING
+      // inferring of the scaling list can be moved to the config file
+      UInt refLayerId = 0;
+      if( m_layerId > 0 && !m_pcEncTop->getVPS()->getAvcBaseLayerFlag() && m_pcEncTop->getVPS()->getRecursiveRefLayerFlag( m_layerId, refLayerId ) )
+      {
+        m_pcEncTop->getSPS()->setInferScalingListFlag( true );
+        m_pcEncTop->getSPS()->setScalingListRefLayerId( refLayerId );
+        m_pcEncTop->getSPS()->setScalingListPresentFlag( false );
+        m_pcEncTop->getPPS()->setInferScalingListFlag( false );
+        m_pcEncTop->getPPS()->setScalingListPresentFlag( false );
+
+        // infer the scaling list from the reference layer
+        pcSlice->setScalingList ( m_ppcTEncTop[refLayerId]->getScalingList() );
+      }
+      else
+      {
 #endif
 
       if(pcSlice->getScalingList()->xParseScalingList(m_pcCfg->getScalingListFile()))
       {
-#if IL_SL_SIGNALLING_N0371
-        pcSlice->setDefaultScalingList ( m_layerId );
-#else
         pcSlice->setDefaultScalingList ();
-#endif
-      }
-#if IL_SL_SIGNALLING_N0371
-      pcSlice->getScalingList()->checkDcOfMatrix( m_layerId );
-#else
+      }
+
       pcSlice->getScalingList()->checkDcOfMatrix();
-#endif
       m_pcEncTop->getSPS()->setScalingListPresentFlag(pcSlice->checkDefaultScalingList());
-
-#if IL_SL_SIGNALLING_N0371
-      if( m_layerId > 0 )
-      {
-        m_pcEncTop->getSPS()->setPredScalingListFlag  (true); 
-        m_pcEncTop->getSPS()->setScalingListRefLayerId( 0 ); 
-      }
-#endif
-
       m_pcEncTop->getPPS()->setScalingListPresentFlag(false);
 
-#if IL_SL_SIGNALLING_N0371
-      if( m_layerId > 0 )
-      {
-        m_pcEncTop->getPPS()->setPredScalingListFlag  (false); 
-        m_pcEncTop->getPPS()->setScalingListRefLayerId( 0   ); 
-      }
+#if SCALINGLIST_INFERRING
+    }
 #endif
 
@@ -783,5 +832,9 @@
         }
 
+#if O0098_SCALED_REF_LAYER_ID
+        const Window &scalEL = m_pcEncTop->getScaledRefLayerWindowForLayer(pcSlice->getVPS()->getRefLayerId(m_layerId, refLayerIdc));
+#else
         const Window &scalEL = m_pcEncTop->getScaledRefLayerWindow(refLayerIdc);
+#endif
 
         Int widthBL   = pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec()->getWidth();
@@ -800,15 +853,20 @@
         if( pcPic->isSpatialEnhLayer(refLayerIdc))
         {
+/*#if O0098_SCALED_REF_LAYER_ID
+          Window scalEL = pcSlice->getSPS()->getScaledRefLayerWindowForLayer(pcSlice->getVPS()->getRefLayerId(m_layerId, refLayerIdc));
+#else
+          Window scalEL = pcSlice->getSPS()->getScaledRefLayerWindow(refLayerIdc);
+#endif*/
 #if O0215_PHASE_ALIGNMENT
 #if O0194_JOINT_US_BITSHIFT
-          m_pcPredSearch->upsampleBasePic( pcSlice, refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(), pcPic->getPicYuvRec(), pcSlice->getSPS()->getScaledRefLayerWindow(refLayerIdc), pcSlice->getVPS()->getPhaseAlignFlag() );
-#else
-          m_pcPredSearch->upsampleBasePic( refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(), pcPic->getPicYuvRec(), pcSlice->getSPS()->getScaledRefLayerWindow(refLayerIdc), pcSlice->getVPS()->getPhaseAlignFlag() );
+          m_pcPredSearch->upsampleBasePic( pcSlice, refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(), pcPic->getPicYuvRec(), scalEL, pcSlice->getVPS()->getPhaseAlignFlag() );
+#else
+          m_pcPredSearch->upsampleBasePic( refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(), pcPic->getPicYuvRec(), scalEL, pcSlice->getVPS()->getPhaseAlignFlag() );
 #endif
 #else
 #if O0194_JOINT_US_BITSHIFT
-          m_pcPredSearch->upsampleBasePic( pcSlice, refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(), pcPic->getPicYuvRec(), pcSlice->getSPS()->getScaledRefLayerWindow(refLayerIdc) );
-#else
-          m_pcPredSearch->upsampleBasePic( refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(), pcPic->getPicYuvRec(), pcSlice->getSPS()->getScaledRefLayerWindow(refLayerIdc) );
+          m_pcPredSearch->upsampleBasePic( pcSlice, refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(), pcPic->getPicYuvRec(), scalEL );
+#else
+          m_pcPredSearch->upsampleBasePic( refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(), pcPic->getPicYuvRec(), scalEL );
 #endif
 #endif
@@ -827,5 +885,8 @@
         pcSlice->setInterLayerPredLayerIdc( interLayerPredLayerIdcTmp[i], i );
       }
+
+#if !O0225_TID_BASED_IL_RPS_DERIV
       pcSlice->setActiveNumILRRefIdx( activeNumILRRefIdxTmp );
+#endif 
       if ( pcSlice->getActiveNumILRRefIdx() == 0 )
       {
@@ -902,19 +963,16 @@
 
     // Do decoding refresh marking if any 
+#if NO_CLRAS_OUTPUT_FLAG
+    pcSlice->decodingRefreshMarking(m_pocCRA, m_bRefreshPending, rcListPic, m_pcEncTop->getNoClrasOutputFlag());
+#else
     pcSlice->decodingRefreshMarking(m_pocCRA, m_bRefreshPending, rcListPic);
+#endif
     m_pcEncTop->selectReferencePictureSet(pcSlice, pocCurr, iGOPid);
     pcSlice->getRPS()->setNumberOfLongtermPictures(0);
 
-#if FIX1071
     if ((pcSlice->checkThatAllRefPicsAreAvailable(rcListPic, pcSlice->getRPS(), false) != 0) || (pcSlice->isIRAP()))
     {
       pcSlice->createExplicitReferencePictureSetFromReference(rcListPic, pcSlice->getRPS(), pcSlice->isIRAP());
     }
-#else
-    if(pcSlice->checkThatAllRefPicsAreAvailable(rcListPic, pcSlice->getRPS(), false) != 0)
-    {
-      pcSlice->createExplicitReferencePictureSetFromReference(rcListPic, pcSlice->getRPS());
-    }
-#endif
     pcSlice->applyReferencePictureSet(rcListPic, pcSlice->getRPS());
 
@@ -934,5 +992,5 @@
             {
               if( ( lowerLayerPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_N ) ||
-                  ( lowerLayerPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_TLA_R ) 
+                  ( lowerLayerPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_R ) 
                 )
               {
@@ -943,5 +1001,5 @@
                 else
                 {
-                  pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TLA_R );
+                  pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TSA_R );
                 }
                 oneRefLayerTSA = true;
@@ -975,5 +1033,5 @@
             else
             {
-              pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TLA_R );
+              pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TSA_R );
             }
           }
@@ -986,5 +1044,5 @@
         else
         {
-          pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TLA_R);
+          pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TSA_R);
         }
 #endif
@@ -1356,5 +1414,4 @@
     pcPic->getSlice(pcSlice->getSliceIdx())->setMvdL1ZeroFlag(pcSlice->getMvdL1ZeroFlag());
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
     Double lambda            = 0.0;
     Int actualHeadBits       = 0;
@@ -1389,15 +1446,9 @@
       else if ( frameLevel == 0 )   // intra case, but use the model
       {
-#if RATE_CONTROL_INTRA
         m_pcSliceEncoder->calCostSliceI(pcPic);
-#endif
         if ( m_pcCfg->getIntraPeriod() != 1 )   // do not refine allocated bits for all intra case
         {
           Int bits = m_pcRateCtrl->getRCSeq()->getLeftAverageBits();
-#if RATE_CONTROL_INTRA
           bits = m_pcRateCtrl->getRCPic()->getRefineBitsForIntra( bits );
-#else
-          bits = m_pcRateCtrl->getRCSeq()->getRefineBitsForIntra( bits );
-#endif
           if ( bits < 200 )
           {
@@ -1408,10 +1459,6 @@
 
         list<TEncRCPic*> listPreviousPicture = m_pcRateCtrl->getPicList();
-#if RATE_CONTROL_INTRA
         m_pcRateCtrl->getRCPic()->getLCUInitTargetBits();
         lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambda( listPreviousPicture, pcSlice->getSliceType());
-#else
-        lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambda( listPreviousPicture );
-#endif
         sliceQP = m_pcRateCtrl->getRCPic()->estimatePicQP( lambda, listPreviousPicture );
       }
@@ -1419,9 +1466,5 @@
       {
         list<TEncRCPic*> listPreviousPicture = m_pcRateCtrl->getPicList();
-#if RATE_CONTROL_INTRA
         lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambda( listPreviousPicture, pcSlice->getSliceType());
-#else
-        lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambda( listPreviousPicture );
-#endif
         sliceQP = m_pcRateCtrl->getRCPic()->estimatePicQP( lambda, listPreviousPicture );
       }
@@ -1436,5 +1479,4 @@
       m_pcSliceEncoder->resetQP( pcPic, sliceQP, lambda );
     }
-#endif
 
     UInt uiNumSlices = 1;
@@ -1647,4 +1689,10 @@
 
     // SAO parameter estimation using non-deblocked pixels for LCU bottom and right boundary areas
+#if HM_CLEANUP_SAO
+    if( pcSlice->getSPS()->getUseSAO() && m_pcCfg->getSaoLcuBoundary() )
+    {
+      m_pcSAO->getPreDBFStatistics(pcPic);
+    }
+#else
     if( m_pcCfg->getSaoLcuBasedOptimization() && m_pcCfg->getSaoLcuBoundary() )
     {
@@ -1652,5 +1700,5 @@
       m_pcSAO->calcSaoStatsCu_BeforeDblk( pcPic );
     }
-
+#endif    
     //-- Loop filter
     Bool bLFCrossTileBoundary = pcSlice->getPPS()->getLoopFilterAcrossTilesEnabledFlag();
@@ -1662,4 +1710,5 @@
     m_pcLoopFilter->loopFilterPic( pcPic );
 
+#if !HM_CLEANUP_SAO    
     pcSlice = pcPic->getSlice(0);
     if(pcSlice->getSPS()->getUseSAO())
@@ -1681,5 +1730,5 @@
       m_pcSAO->createPicSaoInfo(pcPic);
     }
-
+#endif
     /////////////////////////////////////////////////////////////////////////////////////////////////// File writing
     // Set entropy coder
@@ -1713,7 +1762,5 @@
       writeRBSPTrailingBits(nalu.m_Bitstream);
       accessUnit.push_back(new NALUnitEBSP(nalu));
-#if RATE_CONTROL_LAMBDA_DOMAIN
       actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
-#endif
 #if SVC_EXTENSION
       }
@@ -1722,7 +1769,4 @@
 #if SVC_EXTENSION
       nalu = NALUnit(NAL_UNIT_SPS, 0, m_layerId);
-#if IL_SL_SIGNALLING_N0371
-      pcSlice->getSPS()->setVPS( pcSlice->getVPS() );
-#endif
 #else
       nalu = NALUnit(NAL_UNIT_SPS);
@@ -1753,10 +1797,11 @@
         pcSlice->getSPS()->getVuiParameters()->setHrdParametersPresentFlag( true );
       }
+#if O0092_0094_DEPENDENCY_CONSTRAINT
+      assert( pcSlice->getSPS()->getLayerId() == 0 || pcSlice->getSPS()->getLayerId() == m_layerId || m_pcEncTop->getVPS()->getRecursiveRefLayerFlag(m_layerId, pcSlice->getSPS()->getLayerId()) );
+#endif
       m_pcEntropyCoder->encodeSPS(pcSlice->getSPS());
       writeRBSPTrailingBits(nalu.m_Bitstream);
       accessUnit.push_back(new NALUnitEBSP(nalu));
-#if RATE_CONTROL_LAMBDA_DOMAIN
       actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
-#endif
 
 #if SVC_EXTENSION
@@ -1766,10 +1811,11 @@
 #endif
       m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+#if O0092_0094_DEPENDENCY_CONSTRAINT
+      assert( pcSlice->getPPS()->getPPSId() == 0 || pcSlice->getPPS()->getPPSId() == m_layerId || m_pcEncTop->getVPS()->getRecursiveRefLayerFlag(m_layerId, pcSlice->getPPS()->getPPSId()) );
+#endif
       m_pcEntropyCoder->encodePPS(pcSlice->getPPS());
       writeRBSPTrailingBits(nalu.m_Bitstream);
       accessUnit.push_back(new NALUnitEBSP(nalu));
-#if RATE_CONTROL_LAMBDA_DOMAIN
       actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
-#endif
 
       xCreateLeadingSEIMessages(accessUnit, pcSlice->getSPS());
@@ -2091,13 +2137,7 @@
           }
           m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
-#if RATE_CONTROL_LAMBDA_DOMAIN
           tmpBitsBeforeWriting = m_pcEntropyCoder->getNumberOfWrittenBits();
-#endif
-
           m_pcEntropyCoder->encodeSliceHeader(pcSlice);
-
-#if RATE_CONTROL_LAMBDA_DOMAIN
           actualHeadBits += ( m_pcEntropyCoder->getNumberOfWrittenBits() - tmpBitsBeforeWriting );
-#endif
 
           // is it needed?
@@ -2220,7 +2260,5 @@
           xAttachSliceDataToNalUnit(nalu, pcBitstreamRedirect);
           accessUnit.push_back(new NALUnitEBSP(nalu));
-#if RATE_CONTROL_LAMBDA_DOMAIN
           actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
-#endif
           bNALUAlignedWrittenToList = true; 
           uiOneBitstreamPerSliceLength += nalu.m_Bitstream.getNumberOfWrittenBits(); // length of bitstream after byte-alignment
@@ -2262,28 +2300,58 @@
             // set entropy coder for RD
             m_pcEntropyCoder->setEntropyCoder ( m_pcSbacCoder, pcSlice );
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+            if ( pcSlice->getSPS()->getUseSAO() && !( m_pcEncTop->getSkipPictureAtArcSwitch() && m_pcEncTop->getAdaptiveResolutionChange() > 0 && pcSlice->getLayerId() == 1 && pcSlice->getPOC() == m_pcEncTop->getAdaptiveResolutionChange()) )
+#else
             if ( pcSlice->getSPS()->getUseSAO() )
+#endif
             {
               m_pcEntropyCoder->resetEntropy();
               m_pcEntropyCoder->setBitstream( m_pcBitCounter );
+#if HM_CLEANUP_SAO
+              Bool sliceEnabled[NUM_SAO_COMPONENTS];
+              m_pcSAO->initRDOCabacCoder(m_pcEncTop->getRDGoOnSbacCoder(), pcSlice);
+              m_pcSAO->SAOProcess(pcPic
+                , sliceEnabled
+                , pcPic->getSlice(0)->getLambdas()
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                , m_pcCfg->getSaoLcuBoundary()
+#endif
+              );
+              m_pcSAO->PCMLFDisableProcess(pcPic);   
+
+              //assign SAO slice header
+              for(Int s=0; s< uiNumSlices; s++)
+              {
+                pcPic->getSlice(s)->setSaoEnabledFlag(sliceEnabled[SAO_Y]);
+                assert(sliceEnabled[SAO_Cb] == sliceEnabled[SAO_Cr]);
+                pcPic->getSlice(s)->setSaoEnabledFlagChroma(sliceEnabled[SAO_Cb]);
+              }
+#else
               m_pcSAO->startSaoEnc(pcPic, m_pcEntropyCoder, m_pcEncTop->getRDSbacCoder(), m_pcEncTop->getRDGoOnSbacCoder());
               SAOParam& cSaoParam = *pcSlice->getPic()->getPicSym()->getSaoParam();
 
-#if SAO_CHROMA_LAMBDA
 #if SAO_ENCODING_CHOICE
-              m_pcSAO->SAOProcess(&cSaoParam, pcPic->getSlice(0)->getLambdaLuma(), pcPic->getSlice(0)->getLambdaChroma(), pcPic->getSlice(0)->getDepth());
+              m_pcSAO->SAOProcess(&cSaoParam, pcPic->getSlice(0)->getLambdas()[TEXT_LUMA], pcPic->getSlice(0)->getLambdas()[TEXT_CHROMA], pcPic->getSlice(0)->getDepth());
 #else
               m_pcSAO->SAOProcess(&cSaoParam, pcPic->getSlice(0)->getLambdaLuma(), pcPic->getSlice(0)->getLambdaChroma());
-#endif
-#else
-              m_pcSAO->SAOProcess(&cSaoParam, pcPic->getSlice(0)->getLambda());
 #endif
               m_pcSAO->endSaoEnc();
               m_pcSAO->PCMLFDisableProcess(pcPic);
+#endif
             }
+#if !HM_CLEANUP_SAO          
 #if SAO_RDO
             m_pcEntropyCoder->setEntropyCoder ( m_pcCavlcCoder, pcSlice );
 #endif
+#endif
             processingState = ENCODE_SLICE;
-
+#if !HM_CLEANUP_SAO
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+            if ( ( m_pcEncTop->getSkipPictureAtArcSwitch() && m_pcEncTop->getAdaptiveResolutionChange() > 0 && pcSlice->getLayerId() == 1 && pcSlice->getPOC() == m_pcEncTop->getAdaptiveResolutionChange()) )
+            {
+              pcSlice->getPic()->getPicSym()->getSaoParam()->bSaoFlag[0]=0;
+              pcSlice->getPic()->getPicSym()->getSaoParam()->bSaoFlag[1]=0;
+            }
+#endif
             for(Int s=0; s< uiNumSlices; s++)
             {
@@ -2293,4 +2361,5 @@
               }
             }
+#endif
           }
           break;
@@ -2303,5 +2372,5 @@
         }
       } // end iteration over slices
-
+#if !HM_CLEANUP_SAO    
       if(pcSlice->getSPS()->getUseSAO())
       {
@@ -2312,5 +2381,5 @@
         pcPic->destroyNonDBFilterInfo();
       }
-
+#endif
       pcPic->compressMotion(); 
       
@@ -2412,10 +2481,6 @@
         }
       }
-#if RATE_CONTROL_LAMBDA_DOMAIN
       if ( m_pcCfg->getUseRateCtrl() )
       {
-#if !M0036_RC_IMPROVEMENT
-        Double effectivePercentage = m_pcRateCtrl->getRCPic()->getEffectivePercentage();
-#endif
         Double avgQP     = m_pcRateCtrl->getRCPic()->calAverageQP();
         Double avgLambda = m_pcRateCtrl->getRCPic()->calAverageLambda();
@@ -2424,13 +2489,5 @@
           avgLambda = lambda;
         }
-#if M0036_RC_IMPROVEMENT
-#if RATE_CONTROL_INTRA
         m_pcRateCtrl->getRCPic()->updateAfterPicture( actualHeadBits, actualTotalBits, avgQP, avgLambda, pcSlice->getSliceType());
-#else
-        m_pcRateCtrl->getRCPic()->updateAfterPicture( actualHeadBits, actualTotalBits, avgQP, avgLambda );
-#endif
-#else
-        m_pcRateCtrl->getRCPic()->updateAfterPicture( actualHeadBits, actualTotalBits, avgQP, avgLambda, effectivePercentage );
-#endif
         m_pcRateCtrl->getRCPic()->addToPictureLsit( m_pcRateCtrl->getPicList() );
 
@@ -2445,11 +2502,4 @@
         }
       }
-#else
-      if(m_pcCfg->getUseRateCtrl())
-      {
-        UInt  frameBits = m_vRVM_RP[m_vRVM_RP.size()-1];
-        m_pcRateCtrl->updataRCFrameStatus((Int)frameBits, pcSlice->getSliceType());
-      }
-#endif
 
       if( ( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() ) &&
@@ -2636,10 +2686,4 @@
       delete[] pcSubstreamsOut;
   }
-#if !RATE_CONTROL_LAMBDA_DOMAIN
-  if(m_pcCfg->getUseRateCtrl())
-  {
-    m_pcRateCtrl->updateRCGOPStatus();
-  }
-#endif
   delete pcBitstreamRedirect;
 
@@ -2724,4 +2768,5 @@
   m_pcEntropyCoder->resetEntropy    ();
   m_pcEntropyCoder->setBitstream    ( m_pcBitCounter );
+#if !HM_CLEANUP_SAO
   pcSlice = pcPic->getSlice(0);
   if(pcSlice->getSPS()->getUseSAO())
@@ -2738,5 +2783,5 @@
     pcPic->destroyNonDBFilterInfo();
   }
-  
+#endif
   m_pcEntropyCoder->resetEntropy    ();
   ruiBits += m_pcEntropyCoder->getNumberOfWrittenBits();
@@ -2810,4 +2855,5 @@
       iterPicYuvRec--;
     }
+    
   }
   
@@ -2905,5 +2951,5 @@
     case NAL_UNIT_CODED_SLICE_TRAIL_R:    return "TRAIL_R";
     case NAL_UNIT_CODED_SLICE_TRAIL_N:    return "TRAIL_N";
-    case NAL_UNIT_CODED_SLICE_TLA_R:      return "TLA_R";
+    case NAL_UNIT_CODED_SLICE_TSA_R:      return "TSA_R";
     case NAL_UNIT_CODED_SLICE_TSA_N:      return "TSA_N";
     case NAL_UNIT_CODED_SLICE_STSA_R:     return "STSA_R";
@@ -3140,6 +3186,6 @@
     for (Int x = 0; x < width; x++)
     {
-      dst[x] = isTff ? (UChar) top[x] : (UChar) bottom[x];
-      dst[stride+x] = isTff ? (UChar) bottom[x] : (UChar) top[x];
+      dst[x] = isTff ? top[x] : bottom[x];
+      dst[stride+x] = isTff ? bottom[x] : top[x];
     }
     top += stride;
@@ -3298,4 +3344,6 @@
   delete pcRecInterlaced;
 }
+
+
 
 /** Function for deciding the nal_unit_type.
Index: trunk/source/Lib/TLibEncoder/TEncRateCtrl.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncRateCtrl.cpp	(revision 499)
+++ trunk/source/Lib/TLibEncoder/TEncRateCtrl.cpp	(revision 540)
@@ -42,6 +42,4 @@
 using namespace std;
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
-
 //sequence level
 TEncRCSeq::TEncRCSeq()
@@ -67,8 +65,6 @@
   m_bitsLeft            = 0;
   m_useLCUSeparateModel = false;
-#if M0036_RC_IMPROVEMENT
   m_adaptiveBit         = 0;
   m_lastLambda          = 0.0;
-#endif
 }
 
@@ -78,9 +74,5 @@
 }
 
-#if M0036_RC_IMPROVEMENT
 Void TEncRCSeq::create( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Int numberOfLevel, Bool useLCUSeparateModel, Int adaptiveBit )
-#else
-Void TEncRCSeq::create( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Int numberOfLevel, Bool useLCUSeparateModel )
-#endif
 {
   destroy();
@@ -109,5 +101,4 @@
     m_betaUpdate  = 0.025;
   }
-#if M0036_RC_IMPROVEMENT
   else if ( m_seqTargetBpp < 0.2 )
   {
@@ -125,11 +116,4 @@
     m_betaUpdate  = 0.2;
   }
-#else
-  else
-  {
-    m_alphaUpdate = 0.1;
-    m_betaUpdate  = 0.05;
-  }
-#endif
   m_averageBits     = (Int)(m_targetBits / totalFrames);
   Int picWidthInBU  = ( m_picWidth  % m_LCUWidth  ) == 0 ? m_picWidth  / m_LCUWidth  : m_picWidth  / m_LCUWidth  + 1;
@@ -172,8 +156,6 @@
   m_framesLeft = m_totalFrames;
   m_bitsLeft   = m_targetBits;
-#if M0036_RC_IMPROVEMENT
   m_adaptiveBit = adaptiveBit;
   m_lastLambda = 0.0;
-#endif
 }
 
@@ -233,5 +215,4 @@
     for ( Int i=0; i<m_numberOfLevel; i++ )
     {
-#if RATE_CONTROL_INTRA
       if (i>0)
       {
@@ -244,8 +225,4 @@
         m_picPara[i].m_beta  = BETA2;
       }
-#else
-      m_picPara[i].m_alpha = 3.2003;
-      m_picPara[i].m_beta  = -1.367;
-#endif
     }
   }
@@ -271,11 +248,6 @@
       for ( Int j=0; j<m_numberOfLCU; j++)
       {
-#if RATE_CONTROL_INTRA
         m_LCUPara[i][j].m_alpha = m_picPara[i].m_alpha;
         m_LCUPara[i][j].m_beta  = m_picPara[i].m_beta;
-#else
-        m_LCUPara[i][j].m_alpha = 3.2003;
-        m_LCUPara[i][j].m_beta  = -1.367;
-#endif
       }
     }
@@ -299,21 +271,4 @@
 }
 
-#if !RATE_CONTROL_INTRA
-Int TEncRCSeq::getRefineBitsForIntra( Int orgBits )
-{
-  Double bpp = ( (Double)orgBits ) / m_picHeight / m_picHeight;
-  if ( bpp > 0.2 )
-  {
-    return orgBits * 5;
-  }
-  if ( bpp > 0.1 )
-  {
-    return orgBits * 7;
-  }
-  return orgBits * 10;
-}
-#endif
-
-#if M0036_RC_IMPROVEMENT
 Void TEncRCSeq::setAllBitRatio( Double basicLambda, Double* equaCoeffA, Double* equaCoeffB )
 {
@@ -326,5 +281,4 @@
   delete[] bitsRatio;
 }
-#endif
 
 //GOP level
@@ -349,5 +303,4 @@
   Int targetBits = xEstGOPTargetBits( encRCSeq, numPic );
 
-#if M0036_RC_IMPROVEMENT
   if ( encRCSeq->getAdaptiveBits() > 0 && encRCSeq->getLastLambda() > 0.1 )
   {
@@ -409,5 +362,4 @@
     delete []equaCoeffB;
   }
-#endif
 
   m_picTargetBitInGOP = new Int[numPic];
@@ -422,9 +374,5 @@
   {
     currPicRatio = encRCSeq->getBitRatio( i );
-#if M0036_RC_IMPROVEMENT
     m_picTargetBitInGOP[i] = (Int)( ((Double)targetBits) * currPicRatio / totalPicRatio );
-#else
-    m_picTargetBitInGOP[i] = targetBits * currPicRatio / totalPicRatio;
-#endif
   }
 
@@ -436,5 +384,4 @@
 }
 
-#if M0036_RC_IMPROVEMENT
 Void TEncRCGOP::xCalEquaCoeff( TEncRCSeq* encRCSeq, Double* lambdaRatio, Double* equaCoeffA, Double* equaCoeffB, Int GOPSize )
 {
@@ -482,5 +429,4 @@
   return solution;
 }
-#endif
 
 Void TEncRCGOP::destroy()
@@ -534,11 +480,5 @@
 
   m_LCUs         = NULL;
-#if !M0036_RC_IMPROVEMENT
-  m_lastPicture  = NULL;
-#endif
   m_picActualHeaderBits = 0;
-#if !M0036_RC_IMPROVEMENT
-  m_totalMAD            = 0.0;
-#endif
   m_picActualBits       = 0;
   m_picQP               = 0;
@@ -565,9 +505,5 @@
   }
 
-#if M0036_RC_IMPROVEMENT
   targetBits  = Int( ((Double)GOPbitsLeft) * currPicRatio / totalPicRatio );
-#else
-  targetBits  = Int( GOPbitsLeft * currPicRatio / totalPicRatio );
-#endif
 
   if ( targetBits < 100 )
@@ -665,9 +601,5 @@
       m_LCUs[LCUIdx].m_lambda     = 0.0;
       m_LCUs[LCUIdx].m_targetBits = 0;
-#if M0036_RC_IMPROVEMENT
       m_LCUs[LCUIdx].m_bitWeight  = 1.0;
-#else
-      m_LCUs[LCUIdx].m_MAD        = 0.0;
-#endif
       Int currWidth  = ( (i == picWidthInLCU -1) ? picWidth  - LCUWidth *(picWidthInLCU -1) : LCUWidth  );
       Int currHeight = ( (j == picHeightInLCU-1) ? picHeight - LCUHeight*(picHeightInLCU-1) : LCUHeight );
@@ -676,23 +608,7 @@
   }
   m_picActualHeaderBits = 0;
-#if !M0036_RC_IMPROVEMENT
-  m_totalMAD            = 0.0;
-#endif
   m_picActualBits       = 0;
   m_picQP               = 0;
   m_picLambda           = 0.0;
-
-#if !M0036_RC_IMPROVEMENT
-  m_lastPicture = NULL;
-  list<TEncRCPic*>::reverse_iterator it;
-  for ( it = listPreviousPictures.rbegin(); it != listPreviousPictures.rend(); it++ )
-  {
-    if ( (*it)->getFrameLevel() == m_frameLevel )
-    {
-      m_lastPicture = (*it);
-      break;
-    }
-  }
-#endif
 }
 
@@ -709,14 +625,9 @@
 
 
-#if RATE_CONTROL_INTRA
 Double TEncRCPic::estimatePicLambda( list<TEncRCPic*>& listPreviousPictures, SliceType eSliceType)
-#else
-Double TEncRCPic::estimatePicLambda( list<TEncRCPic*>& listPreviousPictures )
-#endif
 {
   Double alpha         = m_encRCSeq->getPicPara( m_frameLevel ).m_alpha;
   Double beta          = m_encRCSeq->getPicPara( m_frameLevel ).m_beta;
   Double bpp       = (Double)m_targetBits/(Double)m_numberOfPixel;
-#if RATE_CONTROL_INTRA
   Double estLambda;
   if (eSliceType == I_SLICE)
@@ -728,7 +639,4 @@
     estLambda = alpha * pow( bpp, beta );
   }
-#else
-  Double estLambda = alpha * pow( bpp, beta );
-#endif  
   
   Double lastLevelLambda = -1.0;
@@ -778,10 +686,8 @@
   m_estPicLambda = estLambda;
 
-#if M0036_RC_IMPROVEMENT
   Double totalWeight = 0.0;
   // initial BU bit allocation weight
   for ( Int i=0; i<m_numberOfLCU; i++ )
   {
-#if RC_FIX
     Double alphaLCU, betaLCU;
     if ( m_encRCSeq->getUseLCUSeparateModel() )
@@ -795,8 +701,4 @@
       betaLCU  = m_encRCSeq->getPicPara( m_frameLevel ).m_beta;
     }
-#else
-    Double alphaLCU = m_encRCSeq->getLCUPara( m_frameLevel, i ).m_alpha;
-    Double betaLCU  = m_encRCSeq->getLCUPara( m_frameLevel, i ).m_beta;
-#endif
 
     m_LCUs[i].m_bitWeight =  m_LCUs[i].m_numberOfPixel * pow( estLambda/alphaLCU, 1.0/betaLCU );
@@ -813,5 +715,4 @@
     m_LCUs[i].m_bitWeight = BUTargetBits;
   }
-#endif
 
   return estLambda;
@@ -856,20 +757,12 @@
 }
 
-#if RATE_CONTROL_INTRA
 Double TEncRCPic::getLCUTargetBpp(SliceType eSliceType)  
-#else 
-Double TEncRCPic::getLCUTargetBpp()
-#endif
 {
   Int   LCUIdx    = getLCUCoded();
   Double bpp      = -1.0;
   Int avgBits     = 0;
-#if !M0036_RC_IMPROVEMENT
-  Double totalMAD = -1.0;
-  Double MAD      = -1.0;
-#endif
-
-#if RATE_CONTROL_INTRA
-  if (eSliceType == I_SLICE){
+
+  if (eSliceType == I_SLICE)
+  {
     Int noOfLCUsLeft = m_numberOfLCU - LCUIdx + 1;
     Int bitrateWindow = min(4,noOfLCUsLeft);
@@ -889,6 +782,4 @@
   else
   {
-#endif
-#if M0036_RC_IMPROVEMENT
   Double totalWeight = 0;
   for ( Int i=LCUIdx; i<m_numberOfLCU; i++ )
@@ -898,31 +789,5 @@
   Int realInfluenceLCU = min( g_RCLCUSmoothWindowSize, getLCULeft() );
   avgBits = (Int)( m_LCUs[LCUIdx].m_bitWeight - ( totalWeight - m_bitsLeft ) / realInfluenceLCU + 0.5 );
-#else
-  if ( m_lastPicture == NULL )
-  {
-    avgBits = Int( m_bitsLeft / m_LCULeft );
-  }
-  else
-  {
-    MAD = m_lastPicture->getLCU(LCUIdx).m_MAD;
-    totalMAD = m_lastPicture->getTotalMAD();
-    for ( Int i=0; i<LCUIdx; i++ )
-    {
-      totalMAD -= m_lastPicture->getLCU(i).m_MAD;
-    }
-
-    if ( totalMAD > 0.1 )
-    {
-      avgBits = Int( m_bitsLeft * MAD / totalMAD );
-    }
-    else
-    {
-      avgBits = Int( m_bitsLeft / m_LCULeft );
-    }
-  }
-#endif
-#if RATE_CONTROL_INTRA
-  }
-#endif
+    }
 
   if ( avgBits < 1 )
@@ -1050,11 +915,6 @@
     beta  *= ( 1.0 - m_encRCSeq->getBetaUpdate() / 2.0 );
 
-#if M0036_RC_IMPROVEMENT
     alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha );
     beta  = Clip3( g_RCBetaMinValue,  g_RCBetaMaxValue,  beta  );
-#else
-    alpha = Clip3( 0.05, 20.0, alpha );
-    beta  = Clip3( -3.0, -0.1, beta  );
-#endif
 
     TRCParameter rcPara;
@@ -1069,18 +929,9 @@
   alpha += m_encRCSeq->getAlphaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * alpha;
   double lnbpp = log( bpp );
-#if M0036_RC_IMPROVEMENT
   lnbpp = Clip3( -5.0, -0.1, lnbpp );
-#else
-  lnbpp = Clip3( -5.0, 1.0, lnbpp );
-#endif
   beta  += m_encRCSeq->getBetaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * lnbpp;
 
-#if M0036_RC_IMPROVEMENT
   alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha );
   beta  = Clip3( g_RCBetaMinValue,  g_RCBetaMaxValue,  beta  );
-#else
-  alpha = Clip3( 0.05, 20.0, alpha );
-  beta  = Clip3( -3.0, -0.1, beta  );
-#endif
   TRCParameter rcPara;
   rcPara.m_alpha = alpha;
@@ -1090,24 +941,4 @@
 }
 
-#if !M0036_RC_IMPROVEMENT
-Double TEncRCPic::getEffectivePercentage()
-{
-  Int effectivePiexels = 0;
-  Int totalPixels = 0;
-
-  for ( Int i=0; i<m_numberOfLCU; i++ )
-  {
-    totalPixels += m_LCUs[i].m_numberOfPixel;
-    if ( m_LCUs[i].m_QP > 0 )
-    {
-      effectivePiexels += m_LCUs[i].m_numberOfPixel;
-    }
-  }
-
-  Double effectivePixelPercentage = (Double)effectivePiexels/(Double)totalPixels;
-  return effectivePixelPercentage;
-}
-#endif
-
 Double TEncRCPic::calAverageQP()
 {
@@ -1164,13 +995,5 @@
 }
 
-#if M0036_RC_IMPROVEMENT
-#if RATE_CONTROL_INTRA
 Void TEncRCPic::updateAfterPicture( Int actualHeaderBits, Int actualTotalBits, Double averageQP, Double averageLambda, SliceType eSliceType)
-#else
-Void TEncRCPic::updateAfterPicture( Int actualHeaderBits, Int actualTotalBits, Double averageQP, Double averageLambda )
-#endif
-#else
-Void TEncRCPic::updateAfterPicture( Int actualHeaderBits, Int actualTotalBits, Double averageQP, Double averageLambda, Double effectivePercentage )
-#endif
 {
   m_picActualHeaderBits = actualHeaderBits;
@@ -1185,14 +1008,7 @@
   }
   m_picLambda           = averageLambda;
-#if !M0036_RC_IMPROVEMENT
-  for ( Int i=0; i<m_numberOfLCU; i++ )
-  {
-    m_totalMAD += m_LCUs[i].m_MAD;
-  }
-#endif
 
   Double alpha = m_encRCSeq->getPicPara( m_frameLevel ).m_alpha;
   Double beta  = m_encRCSeq->getPicPara( m_frameLevel ).m_beta;
-#if RATE_CONTROL_INTRA
   if (eSliceType == I_SLICE)
   {
@@ -1201,5 +1017,4 @@
   else
   {
-#endif
   // update parameters
   Double picActualBits = ( Double )m_picActualBits;
@@ -1208,20 +1023,11 @@
   Double inputLambda   = m_picLambda;
 
-#if M0036_RC_IMPROVEMENT
   if ( inputLambda < 0.01 || calLambda < 0.01 || picActualBpp < 0.0001 )
-#else
-  if ( inputLambda < 0.01 || calLambda < 0.01 || picActualBpp < 0.0001 || effectivePercentage < 0.05 )
-#endif
   {
     alpha *= ( 1.0 - m_encRCSeq->getAlphaUpdate() / 2.0 );
     beta  *= ( 1.0 - m_encRCSeq->getBetaUpdate() / 2.0 );
 
-#if M0036_RC_IMPROVEMENT
     alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha );
     beta  = Clip3( g_RCBetaMinValue,  g_RCBetaMaxValue,  beta  );
-#else
-    alpha = Clip3( 0.05, 20.0, alpha );
-    beta  = Clip3( -3.0, -0.1, beta  );
-#endif
     TRCParameter rcPara;
     rcPara.m_alpha = alpha;
@@ -1235,21 +1041,10 @@
   alpha += m_encRCSeq->getAlphaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * alpha;
   double lnbpp = log( picActualBpp );
-#if M0036_RC_IMPROVEMENT
   lnbpp = Clip3( -5.0, -0.1, lnbpp );
-#else
-  lnbpp = Clip3( -5.0, 1.0, lnbpp );
-#endif
   beta  += m_encRCSeq->getBetaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * lnbpp;
 
-#if M0036_RC_IMPROVEMENT
   alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha );
   beta  = Clip3( g_RCBetaMinValue,  g_RCBetaMaxValue,  beta  );
-#else
-  alpha = Clip3( 0.05, 20.0, alpha );
-  beta  = Clip3( -3.0, -0.1, beta  );
-#endif
-#if RATE_CONTROL_INTRA
-  }
-#endif
+  }
 
   TRCParameter rcPara;
@@ -1259,5 +1054,4 @@
   m_encRCSeq->setPicPara( m_frameLevel, rcPara );
 
-#if M0036_RC_IMPROVEMENT
   if ( m_frameLevel == 1 )
   {
@@ -1266,8 +1060,6 @@
     m_encRCSeq->setLastLambda( updateLastLambda );
   }
-#endif
-}
-
-#if RATE_CONTROL_INTRA
+}
+
 Int TEncRCPic::getRefineBitsForIntra( Int orgBits )
 {
@@ -1358,5 +1150,4 @@
   return estLambda;
 }
-#endif
 
 TEncRateCtrl::TEncRateCtrl()
@@ -1392,9 +1183,5 @@
 }
 
-#if M0036_RC_IMPROVEMENT
 Void TEncRateCtrl::init( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Int keepHierBits, Bool useLCUSeparateModel, GOPEntry  GOPList[MAX_GOP] )
-#else
-Void TEncRateCtrl::init( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Bool keepHierBits, Bool useLCUSeparateModel, GOPEntry  GOPList[MAX_GOP] )
-#endif
 {
   destroy();
@@ -1411,10 +1198,6 @@
 
   Int numberOfLevel = 1;
-#if M0036_RC_IMPROVEMENT
   Int adaptiveBit = 0;
   if ( keepHierBits > 0 )
-#else
-  if ( keepHierBits )
-#endif
   {
     numberOfLevel = Int( log((Double)GOPSize)/log(2.0) + 0.5 ) + 1;
@@ -1439,9 +1222,5 @@
   }
 
-#if M0036_RC_IMPROVEMENT
   if ( keepHierBits > 0 )
-#else
-  if ( keepHierBits )
-#endif
   {
     Double bpp = (Double)( targetBitrate / (Double)( frameRate*picWidth*picHeight ) );
@@ -1476,10 +1255,8 @@
         bitsRatio[3] = 14;
       }
-#if M0036_RC_IMPROVEMENT
       if ( keepHierBits == 2 )
       {
         adaptiveBit = 1;
       }
-#endif
     }
     else if ( GOPSize == 8 && !isLowdelay )
@@ -1529,18 +1306,12 @@
         bitsRatio[7] = 1;
       }
-#if M0036_RC_IMPROVEMENT
       if ( keepHierBits == 2 )
       {
         adaptiveBit = 2;
       }
-#endif
     }
     else
     {
-#if M0036_RC_IMPROVEMENT
       printf( "\n hierarchical bit allocation is not support for the specified coding structure currently.\n" );
-#else
-      printf( "\n hierarchical bit allocation is not support for the specified coding structure currently." );
-#endif
     }
   }
@@ -1555,9 +1326,5 @@
     }
   }
-#if M0036_RC_IMPROVEMENT
   if ( keepHierBits > 0 )
-#else
-  if ( keepHierBits )
-#endif
   {
     if ( GOPSize == 4 && isLowdelay )
@@ -1594,9 +1361,5 @@
 
   m_encRCSeq = new TEncRCSeq;
-#if M0036_RC_IMPROVEMENT
   m_encRCSeq->create( totalFrames, targetBitrate, frameRate, GOPSize, picWidth, picHeight, LCUWidth, LCUHeight, numberOfLevel, useLCUSeparateModel, adaptiveBit );
-#else
-  m_encRCSeq->create( totalFrames, targetBitrate, frameRate, GOPSize, picWidth, picHeight, LCUWidth, LCUHeight, numberOfLevel, useLCUSeparateModel );
-#endif
   m_encRCSeq->initBitsRatio( bitsRatio );
   m_encRCSeq->initGOPID2Level( GOPID2Level );
@@ -1629,596 +1392,2 @@
 }
 
-#else
-
-#define ADJUSTMENT_FACTOR       0.60
-#define HIGH_QSTEP_THRESHOLD    9.5238
-#define HIGH_QSTEP_ALPHA        4.9371
-#define HIGH_QSTEP_BETA         0.0922
-#define LOW_QSTEP_ALPHA         16.7429
-#define LOW_QSTEP_BETA          -1.1494
-
-#define MAD_PRED_Y1             1.0
-#define MAD_PRED_Y2             0.0
-
-enum MAD_HISOTRY {
-  MAD_PPPrevious = 0,
-  MAD_PPrevious  = 1,
-  MAD_Previous   = 2
-};
-
-Void    MADLinearModel::initMADLinearModel()
-{
-  m_activeOn = false;
-  m_paramY1  = 1.0;
-  m_paramY2  = 0.0;
-  m_costMADs[0] = m_costMADs[1] = m_costMADs[2] = 0.0;
-}
-
-Double  MADLinearModel::getMAD()
-{
-  Double costPredMAD = m_paramY1 * m_costMADs[MAD_Previous] + m_paramY2;
-
-  if(costPredMAD < 0)
-  {
-    costPredMAD = m_costMADs[MAD_Previous];
-    m_paramY1   = MAD_PRED_Y1;
-    m_paramY2   = MAD_PRED_Y2;
-  } 
-  return costPredMAD;
-}
-
-Void    MADLinearModel::updateMADLiearModel()
-{
-  Double dNewY1 = ((m_costMADs[MAD_Previous] - m_costMADs[MAD_PPrevious]) / (m_costMADs[MAD_PPrevious] - m_costMADs[MAD_PPPrevious]));
-  Double dNewY2 =  (m_costMADs[MAD_Previous] - (dNewY1*m_costMADs[MAD_PPrevious]));
-  
-  m_paramY1 = 0.70+0.20*m_paramY1+ 0.10*dNewY1;
-  m_paramY2 =      0.20*m_paramY2+ 0.10*dNewY2;
-}
-
-Void    MADLinearModel::updateMADHistory(Double dMAD)
-{
-  m_costMADs[MAD_PPPrevious] = m_costMADs[MAD_PPrevious];
-  m_costMADs[MAD_PPrevious ] = m_costMADs[MAD_Previous ];
-  m_costMADs[MAD_Previous  ] = dMAD;
-  m_activeOn = (m_costMADs[MAD_Previous  ] && m_costMADs[MAD_PPrevious ] && m_costMADs[MAD_PPPrevious]);
-}
-
-
-Void    PixelBaseURQQuadraticModel::initPixelBaseQuadraticModel()
-{
-  m_paramHighX1 = HIGH_QSTEP_ALPHA;
-  m_paramHighX2 = HIGH_QSTEP_BETA;
-  m_paramLowX1  = LOW_QSTEP_ALPHA;
-  m_paramLowX2  = LOW_QSTEP_BETA;
-}
-
-Int     PixelBaseURQQuadraticModel::getQP(Int qp, Int targetBits, Int numberOfPixels, Double costPredMAD)
-{
-  Double qStep;
-  Double bppPerMAD = (Double)(targetBits/(numberOfPixels*costPredMAD));
-  
-  if(xConvertQP2QStep(qp) >= HIGH_QSTEP_THRESHOLD)
-  {
-    qStep = 1/( sqrt((bppPerMAD/m_paramHighX1)+((m_paramHighX2*m_paramHighX2)/(4*m_paramHighX1*m_paramHighX1))) - (m_paramHighX2/(2*m_paramHighX1)));
-  }
-  else
-  {
-    qStep = 1/( sqrt((bppPerMAD/m_paramLowX1)+((m_paramLowX2*m_paramLowX2)/(4*m_paramLowX1*m_paramLowX1))) - (m_paramLowX2/(2*m_paramLowX1)));
-  }
-  
-  return xConvertQStep2QP(qStep);
-}
-
-Void    PixelBaseURQQuadraticModel::updatePixelBasedURQQuadraticModel (Int qp, Int bits, Int numberOfPixels, Double costMAD)
-{
-  Double qStep     = xConvertQP2QStep(qp);
-  Double invqStep = (1/qStep);
-  Double paramNewX1, paramNewX2;
-  
-  if(qStep >= HIGH_QSTEP_THRESHOLD)
-  {
-    paramNewX2    = (((bits/(numberOfPixels*costMAD))-(23.3772*invqStep*invqStep))/((1-200*invqStep)*invqStep));
-    paramNewX1    = (23.3772-200*paramNewX2);
-    m_paramHighX1 = 0.70*HIGH_QSTEP_ALPHA + 0.20 * m_paramHighX1 + 0.10 * paramNewX1;
-    m_paramHighX2 = 0.70*HIGH_QSTEP_BETA  + 0.20 * m_paramHighX2 + 0.10 * paramNewX2;
-  }
-  else
-  {
-    paramNewX2   = (((bits/(numberOfPixels*costMAD))-(5.8091*invqStep*invqStep))/((1-9.5455*invqStep)*invqStep));
-    paramNewX1   = (5.8091-9.5455*paramNewX2);
-    m_paramLowX1 = 0.90*LOW_QSTEP_ALPHA + 0.09 * m_paramLowX1 + 0.01 * paramNewX1;
-    m_paramLowX2 = 0.90*LOW_QSTEP_BETA  + 0.09 * m_paramLowX2 + 0.01 * paramNewX2;
-  }
-}
-
-Bool    PixelBaseURQQuadraticModel::checkUpdateAvailable(Int qpReference )
-{ 
-  Double qStep = xConvertQP2QStep(qpReference);
-
-  if (qStep > xConvertQP2QStep(MAX_QP) 
-    ||qStep < xConvertQP2QStep(MIN_QP) )
-  {
-    return false;
-  }
-
-  return true;
-}
-
-Double  PixelBaseURQQuadraticModel::xConvertQP2QStep(Int qp )
-{
-  Int i;
-  Double qStep;
-  static const Double mapQP2QSTEP[6] = { 0.625, 0.703, 0.797, 0.891, 1.000, 1.125 };
-
-  qStep = mapQP2QSTEP[qp % 6];
-  for( i=0; i<(qp/6); i++)
-  {
-    qStep *= 2;
-  }
-
-  return qStep;
-}
-
-Int     PixelBaseURQQuadraticModel::xConvertQStep2QP(Double qStep )
-{
-  Int per = 0, rem = 0;
-
-  if( qStep < xConvertQP2QStep(MIN_QP))
-  {
-    return MIN_QP;
-  }
-  else if (qStep > xConvertQP2QStep(MAX_QP) )
-  {
-    return MAX_QP;
-  }
-
-  while( qStep > xConvertQP2QStep(5) )
-  {
-    qStep /= 2.0;
-    per++;
-  }
-
-  if (qStep <= 0.625)
-  {
-    rem = 0;
-  }
-  else if (qStep <= 0.703)
-  {
-    rem = 1;
-  }
-  else if (qStep <= 0.797)
-  {
-    rem = 2;
-  }
-  else if (qStep <= 0.891)
-  {
-    rem = 3;
-  }
-  else if (qStep <= 1.000)
-  {
-    rem = 4;
-  }
-  else
-  {
-    rem = 5;
-  }
-  return (per * 6 + rem);
-}
-
-
-Void  TEncRateCtrl::create(Int sizeIntraPeriod, Int sizeGOP, Int frameRate, Int targetKbps, Int qp, Int numLCUInBasicUnit, Int sourceWidth, Int sourceHeight, Int maxCUWidth, Int maxCUHeight)
-{
-  Int leftInHeight, leftInWidth;
-
-  m_sourceWidthInLCU         = (sourceWidth  / maxCUWidth  ) + (( sourceWidth  %  maxCUWidth ) ? 1 : 0);
-  m_sourceHeightInLCU        = (sourceHeight / maxCUHeight) + (( sourceHeight %  maxCUHeight) ? 1 : 0);  
-  m_isLowdelay               = (sizeIntraPeriod == -1) ? true : false;
-  m_prevBitrate              = ( targetKbps << 10 );  // in units of 1,024 bps
-  m_currBitrate              = ( targetKbps << 10 );
-  m_frameRate                = frameRate;
-  m_refFrameNum              = m_isLowdelay ? (sizeGOP) : (sizeGOP>>1);
-  m_nonRefFrameNum           = sizeGOP-m_refFrameNum;
-  m_sizeGOP                  = sizeGOP;
-  m_numOfPixels              = ((sourceWidth*sourceHeight*3)>>1);
-  m_indexGOP                 = 0;
-  m_indexFrame               = 0;
-  m_indexLCU                 = 0;
-  m_indexUnit                = 0;
-  m_indexRefFrame            = 0;
-  m_indexNonRefFrame         = 0;
-  m_occupancyVB              = 0;
-  m_initialOVB               = 0;
-  m_targetBufLevel           = 0;
-  m_initialTBL               = 0;
-  m_occupancyVBInFrame       = 0;
-  m_remainingBitsInGOP       = (m_currBitrate*sizeGOP/m_frameRate);
-  m_remainingBitsInFrame     = 0;
-  m_numUnitInFrame           = m_sourceWidthInLCU*m_sourceHeightInLCU;
-  m_cMADLinearModel.        initMADLinearModel();
-  m_cPixelURQQuadraticModel.initPixelBaseQuadraticModel();
-
-  m_costRefAvgWeighting      = 0.0;
-  m_costNonRefAvgWeighting   = 0.0;
-  m_costAvgbpp               = 0.0;  
-  m_activeUnitLevelOn        = false;
-
-  m_pcFrameData              = new FrameData   [sizeGOP+1];         initFrameData(qp);
-  m_pcLCUData                = new LCUData     [m_numUnitInFrame];  initUnitData (qp);
-
-  for(Int i = 0, addressUnit = 0; i < m_sourceHeightInLCU*maxCUHeight; i += maxCUHeight)  
-  {
-    leftInHeight = sourceHeight - i;
-    leftInHeight = min(leftInHeight, maxCUHeight);
-    for(Int j = 0; j < m_sourceWidthInLCU*maxCUWidth; j += maxCUWidth, addressUnit++)
-    {
-      leftInWidth = sourceWidth - j;
-      leftInWidth = min(leftInWidth, maxCUWidth);
-      m_pcLCUData[addressUnit].m_widthInPixel = leftInWidth;
-      m_pcLCUData[addressUnit].m_heightInPixel= leftInHeight;
-      m_pcLCUData[addressUnit].m_pixels       = ((leftInHeight*leftInWidth*3)>>1);
-    }
-  }
-}
-
-Void  TEncRateCtrl::destroy()
-{
-  if(m_pcFrameData)
-  {
-    delete [] m_pcFrameData;
-    m_pcFrameData = NULL;
-  }
-  if(m_pcLCUData)
-  {
-    delete [] m_pcLCUData;
-    m_pcLCUData = NULL;
-  }
-}
-
-Void  TEncRateCtrl::initFrameData   (Int qp)
-{
-  for(Int i = 0 ; i <= m_sizeGOP; i++)
-  {
-    m_pcFrameData[i].m_isReferenced = false;
-    m_pcFrameData[i].m_costMAD      = 0.0;
-    m_pcFrameData[i].m_bits         = 0;
-    m_pcFrameData[i].m_qp           = qp;
-  }
-}
-
-Void  TEncRateCtrl::initUnitData    (Int qp)
-{
-  for(Int i = 1 ; i < m_numUnitInFrame; i++)
-  {
-    m_pcLCUData[i].m_qp            = qp;
-    m_pcLCUData[i].m_bits          = 0;
-    m_pcLCUData[i].m_pixels        = 0;
-    m_pcLCUData[i].m_widthInPixel  = 0;
-    m_pcLCUData[i].m_heightInPixel = 0;
-    m_pcLCUData[i].m_costMAD       = 0.0;
-  }
-}
-
-Int  TEncRateCtrl::getFrameQP(Bool isReferenced, Int POC)
-{
-  Int numofReferenced = 0;
-  Int finalQP = 0;
-  FrameData* pcFrameData;
-
-  m_indexPOCInGOP = (POC%m_sizeGOP) == 0 ? m_sizeGOP : (POC%m_sizeGOP);
-  pcFrameData     = &m_pcFrameData[m_indexPOCInGOP];
-    
-  if(m_indexFrame != 0)
-  {
-    if(isReferenced)
-    {
-      Double gamma = m_isLowdelay ? 0.5 : 0.25;
-      Double beta  = m_isLowdelay ? 0.9 : 0.6;
-      Int    numRemainingRefFrames  = m_refFrameNum    - m_indexRefFrame;
-      Int    numRemainingNRefFrames = m_nonRefFrameNum - m_indexNonRefFrame;
-      
-      Double targetBitsOccupancy  = (m_currBitrate/(Double)m_frameRate) + gamma*(m_targetBufLevel-m_occupancyVB - (m_initialOVB/(Double)m_frameRate));
-      Double targetBitsLeftBudget = ((m_costRefAvgWeighting*m_remainingBitsInGOP)/((m_costRefAvgWeighting*numRemainingRefFrames)+(m_costNonRefAvgWeighting*numRemainingNRefFrames)));
-
-      m_targetBits = (Int)(beta * targetBitsLeftBudget + (1-beta) * targetBitsOccupancy);
-  
-      if(m_targetBits <= 0 || m_remainingBitsInGOP <= 0)
-      {
-        finalQP = m_pcFrameData[m_indexPrevPOCInGOP].m_qp + 2;
-      }
-      else
-      {
-        Double costPredMAD   = m_cMADLinearModel.getMAD();
-        Int    qpLowerBound = m_pcFrameData[m_indexPrevPOCInGOP].m_qp-2;
-        Int    qpUpperBound = m_pcFrameData[m_indexPrevPOCInGOP].m_qp+2;
-        finalQP = m_cPixelURQQuadraticModel.getQP(m_pcFrameData[m_indexPrevPOCInGOP].m_qp, m_targetBits, m_numOfPixels, costPredMAD);
-        finalQP = max(qpLowerBound, min(qpUpperBound, finalQP));
-        m_activeUnitLevelOn    = true;
-        m_remainingBitsInFrame = m_targetBits;
-        m_costAvgbpp           = (m_targetBits/(Double)m_numOfPixels);
-      }
-
-      m_indexRefFrame++;
-    }
-    else
-    {
-      Int bwdQP = m_pcFrameData[m_indexPOCInGOP-1].m_qp;
-      Int fwdQP = m_pcFrameData[m_indexPOCInGOP+1].m_qp;
-       
-      if( (fwdQP+bwdQP) == m_pcFrameData[m_indexPOCInGOP-1].m_qp
-        ||(fwdQP+bwdQP) == m_pcFrameData[m_indexPOCInGOP+1].m_qp)
-      {
-        finalQP = (fwdQP+bwdQP);
-      }
-      else if(bwdQP != fwdQP)
-      {
-        finalQP = ((bwdQP+fwdQP+2)>>1);
-      }
-      else
-      {
-        finalQP = bwdQP+2;
-      }
-      m_indexNonRefFrame++;
-    }
-  }
-  else
-  {
-    Int lastQPminus2 = m_pcFrameData[0].m_qp - 2;
-    Int lastQPplus2  = m_pcFrameData[0].m_qp + 2;
-
-    for(Int idx = 1; idx <= m_sizeGOP; idx++)
-    {
-      if(m_pcFrameData[idx].m_isReferenced)
-      {
-        finalQP += m_pcFrameData[idx].m_qp;
-        numofReferenced++;
-      }
-    }
-    
-    finalQP = (numofReferenced == 0) ? m_pcFrameData[0].m_qp : ((finalQP + (1<<(numofReferenced>>1)))/numofReferenced);
-    finalQP = max( lastQPminus2, min( lastQPplus2, finalQP));
-
-    Double costAvgFrameBits = m_remainingBitsInGOP/(Double)m_sizeGOP;
-    Int    bufLevel  = m_occupancyVB + m_initialOVB;
-
-    if(abs(bufLevel) > costAvgFrameBits)
-    {
-      if(bufLevel < 0)
-      {
-        finalQP -= 2;
-      }
-      else
-      {
-        finalQP += 2;
-      }
-    }
-    m_indexRefFrame++;
-  }
-  finalQP = max(MIN_QP, min(MAX_QP, finalQP));
-
-  for(Int indexLCU = 0 ; indexLCU < m_numUnitInFrame; indexLCU++)
-  {
-    m_pcLCUData[indexLCU].m_qp = finalQP;
-  }
-
-  pcFrameData->m_isReferenced = isReferenced;
-  pcFrameData->m_qp           = finalQP;
-
-  return finalQP;
-}
-
-Bool  TEncRateCtrl::calculateUnitQP ()
-{
-  if(!m_activeUnitLevelOn || m_indexLCU == 0)
-  {
-    return false;
-  }
-  Int upperQPBound, lowerQPBound, finalQP;
-  Int    colQP        = m_pcLCUData[m_indexLCU].m_qp;
-  Double colMAD       = m_pcLCUData[m_indexLCU].m_costMAD;
-  Double budgetInUnit = m_pcLCUData[m_indexLCU].m_pixels*m_costAvgbpp;
-
-
-  Int targetBitsOccupancy = (Int)(budgetInUnit - (m_occupancyVBInFrame/(m_numUnitInFrame-m_indexUnit)));
-  Int targetBitsLeftBudget= (Int)((m_remainingBitsInFrame*m_pcLCUData[m_indexLCU].m_pixels)/(Double)(m_numOfPixels-m_codedPixels));
-  Int targetBits = (targetBitsLeftBudget>>1) + (targetBitsOccupancy>>1);
-  
-
-  if( m_indexLCU >= m_sourceWidthInLCU)
-  {
-    upperQPBound = ( (m_pcLCUData[m_indexLCU-1].m_qp + m_pcLCUData[m_indexLCU - m_sourceWidthInLCU].m_qp)>>1) + MAX_DELTA_QP;
-    lowerQPBound = ( (m_pcLCUData[m_indexLCU-1].m_qp + m_pcLCUData[m_indexLCU - m_sourceWidthInLCU].m_qp)>>1) - MAX_DELTA_QP;
-  }
-  else
-  {
-    upperQPBound = m_pcLCUData[m_indexLCU-1].m_qp + MAX_DELTA_QP;
-    lowerQPBound = m_pcLCUData[m_indexLCU-1].m_qp - MAX_DELTA_QP;
-  }
-
-  if(targetBits < 0)
-  {
-    finalQP = m_pcLCUData[m_indexLCU-1].m_qp + 1;
-  }
-  else
-  {
-    finalQP = m_cPixelURQQuadraticModel.getQP(colQP, targetBits, m_pcLCUData[m_indexLCU].m_pixels, colMAD);
-  }
-  
-  finalQP = max(lowerQPBound, min(upperQPBound, finalQP));
-  m_pcLCUData[m_indexLCU].m_qp = max(MIN_QP, min(MAX_QP, finalQP));
-  
-  return true;
-}
-
-Void  TEncRateCtrl::updateRCGOPStatus()
-{
-  m_remainingBitsInGOP = ((m_currBitrate/m_frameRate)*m_sizeGOP) - m_occupancyVB;
-  
-  FrameData cFrameData = m_pcFrameData[m_sizeGOP];
-  initFrameData();
-
-  m_pcFrameData[0]   = cFrameData;
-  m_indexGOP++;
-  m_indexFrame       = 0;
-  m_indexRefFrame    = 0;
-  m_indexNonRefFrame = 0;
-}
-
-Void  TEncRateCtrl::updataRCFrameStatus(Int frameBits, SliceType eSliceType)
-{
-  FrameData* pcFrameData = &m_pcFrameData[m_indexPOCInGOP];
-  Int occupancyBits;
-  Double adjustmentBits;
-
-  m_remainingBitsInGOP = m_remainingBitsInGOP + ( ((m_currBitrate-m_prevBitrate)/m_frameRate)*(m_sizeGOP-m_indexFrame) ) - frameBits;
-  occupancyBits        = (Int)((Double)frameBits - (m_currBitrate/(Double)m_frameRate));
-  
-  if( (occupancyBits < 0) && (m_initialOVB > 0) )
-  {
-    adjustmentBits = xAdjustmentBits(occupancyBits, m_initialOVB );
-
-    if(m_initialOVB < 0)
-    {
-      adjustmentBits = m_initialOVB;
-      occupancyBits += (Int)adjustmentBits;
-      m_initialOVB   =  0;
-    }
-  }
-  else if( (occupancyBits > 0) && (m_initialOVB < 0) )
-  {
-    adjustmentBits = xAdjustmentBits(m_initialOVB, occupancyBits );
-    
-    if(occupancyBits < 0)
-    {
-      adjustmentBits = occupancyBits;
-      m_initialOVB  += (Int)adjustmentBits;
-      occupancyBits  =  0;
-    }
-  }
-
-  if(m_indexGOP == 0)
-  {
-    m_initialOVB = occupancyBits;
-  }
-  else
-  {
-    m_occupancyVB= m_occupancyVB + occupancyBits;
-  }
-
-  if(pcFrameData->m_isReferenced)
-  {
-    m_costRefAvgWeighting  = ((pcFrameData->m_bits*pcFrameData->m_qp)/8.0) + (7.0*(m_costRefAvgWeighting)/8.0);
-
-    if(m_indexFrame == 0)
-    {
-      m_initialTBL = m_targetBufLevel  = (frameBits - (m_currBitrate/m_frameRate));
-    }
-    else
-    {
-      Int distance = (m_costNonRefAvgWeighting == 0) ? 0 : 1;
-      m_targetBufLevel =  m_targetBufLevel 
-                            - (m_initialTBL/(m_refFrameNum-1)) 
-                            + (Int)((m_costRefAvgWeighting*(distance+1)*m_currBitrate)/(m_frameRate*(m_costRefAvgWeighting+(m_costNonRefAvgWeighting*distance)))) 
-                            - (m_currBitrate/m_frameRate);
-    }
-
-    if(m_cMADLinearModel.IsUpdateAvailable())
-    {
-      m_cMADLinearModel.updateMADLiearModel();
-    }
-
-    if(eSliceType != I_SLICE &&
-       m_cPixelURQQuadraticModel.checkUpdateAvailable(pcFrameData->m_qp))
-    {
-      m_cPixelURQQuadraticModel.updatePixelBasedURQQuadraticModel(pcFrameData->m_qp, pcFrameData->m_bits, m_numOfPixels, pcFrameData->m_costMAD);
-    }
-  }
-  else
-  {
-    m_costNonRefAvgWeighting = ((pcFrameData->m_bits*pcFrameData->m_qp)/8.0) + (7.0*(m_costNonRefAvgWeighting)/8.0);
-  }
-
-  m_indexFrame++;
-  m_indexLCU             = 0;
-  m_indexUnit            = 0;
-  m_occupancyVBInFrame   = 0;
-  m_remainingBitsInFrame = 0;
-  m_codedPixels          = 0;
-  m_activeUnitLevelOn    = false;
-  m_costAvgbpp           = 0.0;
-}
-Void  TEncRateCtrl::updataRCUnitStatus ()
-{
-  if(!m_activeUnitLevelOn || m_indexLCU == 0)
-  {
-    return;
-  }
-
-  m_codedPixels  += m_pcLCUData[m_indexLCU-1].m_pixels;
-  m_remainingBitsInFrame = m_remainingBitsInFrame - m_pcLCUData[m_indexLCU-1].m_bits;
-  m_occupancyVBInFrame   = (Int)(m_occupancyVBInFrame + m_pcLCUData[m_indexLCU-1].m_bits - m_pcLCUData[m_indexLCU-1].m_pixels*m_costAvgbpp);
-
-  if( m_cPixelURQQuadraticModel.checkUpdateAvailable(m_pcLCUData[m_indexLCU-1].m_qp) )
-  {
-    m_cPixelURQQuadraticModel.updatePixelBasedURQQuadraticModel(m_pcLCUData[m_indexLCU-1].m_qp, m_pcLCUData[m_indexLCU-1].m_bits, m_pcLCUData[m_indexLCU-1].m_pixels, m_pcLCUData[m_indexLCU-1].m_costMAD);
-  }
-
-  m_indexUnit++;
-}
-
-Void  TEncRateCtrl::updateFrameData(UInt64 actualFrameBits)
-{
-  Double costMAD = 0.0;
-  
-  for(Int i = 0; i < m_numUnitInFrame; i++)
-  {
-    costMAD    += m_pcLCUData[i].m_costMAD;
-  }
-  
-  m_pcFrameData[m_indexPOCInGOP].m_costMAD = (costMAD/(Double)m_numUnitInFrame);
-  m_pcFrameData[m_indexPOCInGOP].m_bits    = (Int)actualFrameBits;
-  
-  if(m_pcFrameData[m_indexPOCInGOP].m_isReferenced)
-  {
-    m_indexPrevPOCInGOP = m_indexPOCInGOP;
-    m_cMADLinearModel.updateMADHistory(m_pcFrameData[m_indexPOCInGOP].m_costMAD);
-  }
-}
-
-Void  TEncRateCtrl::updateLCUData(TComDataCU* pcCU, UInt64 actualLCUBits, Int qp)
-{
-  Int     x, y;
-  Double  costMAD = 0.0;
-
-  Pel*  pOrg   = pcCU->getPic()->getPicYuvOrg()->getLumaAddr(pcCU->getAddr(), 0);
-  Pel*  pRec   = pcCU->getPic()->getPicYuvRec()->getLumaAddr(pcCU->getAddr(), 0);
-  Int   stride = pcCU->getPic()->getStride();
-
-  Int   width  = m_pcLCUData[m_indexLCU].m_widthInPixel;
-  Int   height = m_pcLCUData[m_indexLCU].m_heightInPixel;
-
-  for( y = 0; y < height; y++ )
-  {
-    for( x = 0; x < width; x++ )
-    {
-      costMAD += abs( pOrg[x] - pRec[x] );
-    }
-    pOrg += stride;
-    pRec += stride;
-  }
-  m_pcLCUData[m_indexLCU  ].m_qp      = qp;
-  m_pcLCUData[m_indexLCU  ].m_costMAD = (costMAD /(Double)(width*height));
-  m_pcLCUData[m_indexLCU++].m_bits    = (Int)actualLCUBits;
-}
-
-Double TEncRateCtrl::xAdjustmentBits(Int& reductionBits, Int& compensationBits)
-{
-  Double adjustment  = ADJUSTMENT_FACTOR*reductionBits;
-  reductionBits     -= (Int)adjustment;
-  compensationBits  += (Int)adjustment;
-
-  return adjustment;
-}
-
-#endif
-
Index: trunk/source/Lib/TLibEncoder/TEncRateCtrl.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncRateCtrl.h	(revision 499)
+++ trunk/source/Lib/TLibEncoder/TEncRateCtrl.h	(revision 540)
@@ -55,5 +55,4 @@
 //! \{
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
 #include "../TLibEncoder/TEncCfg.h"
 #include <list>
@@ -65,5 +64,4 @@
 const Double g_RCWeightPicTargetBitInGOP    = 0.9;
 const Double g_RCWeightPicRargetBitInBuffer = 1.0 - g_RCWeightPicTargetBitInGOP;
-#if M0036_RC_IMPROVEMENT
 const Int g_RCIterationNum = 20;
 const Double g_RCWeightHistoryLambda = 0.5;
@@ -74,11 +72,8 @@
 const Double g_RCBetaMinValue  = -3.0;
 const Double g_RCBetaMaxValue  = -0.1;
-#endif
-
-#if RATE_CONTROL_INTRA
+
 #define ALPHA     6.7542;
 #define BETA1     1.2517
 #define BETA2     1.7860
-#endif
 
 struct TRCLCU
@@ -88,14 +83,8 @@
   Int m_targetBits;
   Double m_lambda;
-#if M0036_RC_IMPROVEMENT
   Double m_bitWeight;
-#else
-  Double m_MAD;
-#endif
   Int m_numberOfPixel;
-#if RATE_CONTROL_INTRA
   Double m_costIntra;
   Int m_targetBitsLeft;
-#endif
 };
 
@@ -113,9 +102,5 @@
 
 public:
-#if M0036_RC_IMPROVEMENT
   Void create( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Int numberOfLevel, Bool useLCUSeparateModel, Int adaptiveBit );
-#else
-  Void create( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Int numberOfLevel, Bool useLCUSeparateModel );
-#endif
   Void destroy();
   Void initBitsRatio( Int bitsRatio[] );
@@ -124,10 +109,5 @@
   Void initLCUPara( TRCParameter** LCUPara = NULL );    // NULL to initial with default value
   Void updateAfterPic ( Int bits );
-#if !RATE_CONTROL_INTRA
-  Int  getRefineBitsForIntra( Int orgBits );
-#endif
-#if M0036_RC_IMPROVEMENT
   Void setAllBitRatio( Double basicLambda, Double* equaCoeffA, Double* equaCoeffB );
-#endif
 
 public:
@@ -167,9 +147,7 @@
   Double getBetaUpdate()                { return m_betaUpdate; }
 
-#if M0036_RC_IMPROVEMENT
   Int    getAdaptiveBits()              { return m_adaptiveBit;  }
   Double getLastLambda()                { return m_lastLambda;   }
   Void   setLastLambda( Double lamdba ) { m_lastLambda = lamdba; }
-#endif
 
 private:
@@ -200,8 +178,6 @@
   Bool m_useLCUSeparateModel;
 
-#if M0036_RC_IMPROVEMENT
   Int m_adaptiveBit;
   Double m_lastLambda;
-#endif
 };
 
@@ -219,8 +195,6 @@
 private:
   Int  xEstGOPTargetBits( TEncRCSeq* encRCSeq, Int GOPSize );
-#if M0036_RC_IMPROVEMENT
   Void   xCalEquaCoeff( TEncRCSeq* encRCSeq, Double* lambdaRatio, Double* equaCoeffA, Double* equaCoeffB, Int GOPSize );
   Double xSolveEqua( Double targetBpp, Double* equaCoeffA, Double* equaCoeffB, Int GOPSize );
-#endif
 
 public:
@@ -251,9 +225,5 @@
   Void destroy();
 
-#if !RATE_CONTROL_INTRA
-  Double estimatePicLambda( list<TEncRCPic*>& listPreviousPictures );
-#endif
   Int    estimatePicQP    ( Double lambda, list<TEncRCPic*>& listPreviousPictures );
-#if RATE_CONTROL_INTRA
   Int    getRefineBitsForIntra(Int orgBits);
   Double calculateLambdaIntra(double alpha, double beta, double MADPerPixel, double bitsPerPixel);
@@ -264,25 +234,11 @@
   Double getLCUTargetBpp(SliceType eSliceType);
   Double getLCUEstLambdaAndQP(Double bpp, Int clipPicQP, Int *estQP);
-#else
-  Double getLCUTargetBpp();
-#endif
   Double getLCUEstLambda( Double bpp );
   Int    getLCUEstQP( Double lambda, Int clipPicQP );
 
   Void updateAfterLCU( Int LCUIdx, Int bits, Int QP, Double lambda, Bool updateLCUParameter = true );
-#if M0036_RC_IMPROVEMENT
-#if RATE_CONTROL_INTRA
   Void updateAfterPicture( Int actualHeaderBits, Int actualTotalBits, Double averageQP, Double averageLambda, SliceType eSliceType);
-#else
-  Void updateAfterPicture( Int actualHeaderBits, Int actualTotalBits, Double averageQP, Double averageLambda );
-#endif
-#else
-  Void updateAfterPicture( Int actualHeaderBits, Int actualTotalBits, Double averageQP, Double averageLambda, Double effectivePercentage );
-#endif
 
   Void addToPictureLsit( list<TEncRCPic*>& listPreviousPictures );
-#if !M0036_RC_IMPROVEMENT
-  Double getEffectivePercentage();
-#endif
   Double calAverageQP();
   Double calAverageLambda();
@@ -300,7 +256,4 @@
   Int  getNumberOfLCU()                                   { return m_numberOfLCU; }
   Int  getTargetBits()                                    { return m_targetBits; }
-#if !RATE_CONTROL_INTRA 
-  Void setTargetBits( Int bits )                          { m_targetBits = bits; }
-#endif
   Int  getEstHeaderBits()                                 { return m_estHeaderBits; }
   Int  getLCULeft()                                       { return m_LCULeft; }
@@ -312,13 +265,7 @@
   TRCLCU& getLCU( Int LCUIdx )                            { return m_LCUs[LCUIdx]; }
   Int  getPicActualHeaderBits()                           { return m_picActualHeaderBits; }
-#if !M0036_RC_IMPROVEMENT
-  Double getTotalMAD()                                    { return m_totalMAD; }
-  Void   setTotalMAD( Double MAD )                        { m_totalMAD = MAD; }
-#endif
-#if RATE_CONTROL_INTRA
   Void setTargetBits( Int bits )                          { m_targetBits = bits; m_bitsLeft = bits;}
   Void setTotalIntraCost(Double cost)                     { m_totalCostIntra = cost; }
   Void getLCUInitTargetBits();
-#endif
 
   Int  getPicActualBits()                                 { return m_picActualBits; }
@@ -348,17 +295,9 @@
   TRCLCU* m_LCUs;
   Int m_picActualHeaderBits;    // only SH and potential APS
-#if !M0036_RC_IMPROVEMENT
-  Double m_totalMAD;
-#endif
-#if RATE_CONTROL_INTRA
   Double m_totalCostIntra; 
   Double m_remainingCostIntra;
-#endif
   Int m_picActualBits;          // the whole picture, including header
   Int m_picQP;                  // in integer form
   Double m_picLambda;
-#if !M0036_RC_IMPROVEMENT
-  TEncRCPic* m_lastPicture;
-#endif
 };
 
@@ -370,9 +309,5 @@
 
 public:
-#if M0036_RC_IMPROVEMENT
   Void init( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Int keepHierBits, Bool useLCUSeparateModel, GOPEntry GOPList[MAX_GOP] );
-#else
-  Void init( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Bool keepHierBits, Bool useLCUSeparateModel, GOPEntry GOPList[MAX_GOP] );
-#endif
   Void destroy();
   Void initRCPic( Int frameLevel );
@@ -396,133 +331,5 @@
 };
 
-#else
-
-// ====================================================================================================================
-// Class definition
-// ====================================================================================================================
-#define MAX_DELTA_QP    2
-#define MAX_CUDQP_DEPTH 0 
-
-typedef struct FrameData
-{
-  Bool       m_isReferenced;
-  Int        m_qp;
-  Int        m_bits;
-  Double     m_costMAD;
-}FrameData;
-
-typedef struct LCUData
-{
-  Int     m_qp;                ///<  coded QP
-  Int     m_bits;              ///<  actually generated bits
-  Int     m_pixels;            ///<  number of pixels for a unit
-  Int     m_widthInPixel;      ///<  number of pixels for width
-  Int     m_heightInPixel;     ///<  number of pixels for height
-  Double  m_costMAD;           ///<  texture complexity for a unit
-}LCUData;
-
-class MADLinearModel
-{
-private:
-  Bool   m_activeOn;
-  Double m_paramY1;
-  Double m_paramY2;
-  Double m_costMADs[3];
-
-public:
-  MADLinearModel ()   {};
-  ~MADLinearModel()   {};
-  
-  Void    initMADLinearModel      ();
-  Double  getMAD                  ();
-  Void    updateMADLiearModel     ();
-  Void    updateMADHistory        (Double costMAD);
-  Bool    IsUpdateAvailable       ()              { return m_activeOn; }
-};
-
-class PixelBaseURQQuadraticModel
-{
-private:
-  Double m_paramHighX1;
-  Double m_paramHighX2;
-  Double m_paramLowX1;
-  Double m_paramLowX2;
-public:
-  PixelBaseURQQuadraticModel () {};
-  ~PixelBaseURQQuadraticModel() {};
-
-  Void    initPixelBaseQuadraticModel       ();
-  Int     getQP                             (Int qp, Int targetBits, Int numberOfPixels, Double costPredMAD);
-  Void    updatePixelBasedURQQuadraticModel (Int qp, Int bits, Int numberOfPixels, Double costMAD);
-  Bool    checkUpdateAvailable              (Int qpReference );
-  Double  xConvertQP2QStep                  (Int qp );
-  Int     xConvertQStep2QP                  (Double qStep );
-};
-
-class TEncRateCtrl
-{
-private:
-  Bool            m_isLowdelay;
-  Int             m_prevBitrate;
-  Int             m_currBitrate;
-  Int             m_frameRate;
-  Int             m_refFrameNum;
-  Int             m_nonRefFrameNum;
-  Int             m_numOfPixels;
-  Int             m_sourceWidthInLCU;
-  Int             m_sourceHeightInLCU;      
-  Int             m_sizeGOP;
-  Int             m_indexGOP;
-  Int             m_indexFrame;
-  Int             m_indexLCU;
-  Int             m_indexUnit;
-  Int             m_indexRefFrame;
-  Int             m_indexNonRefFrame;
-  Int             m_indexPOCInGOP;
-  Int             m_indexPrevPOCInGOP;
-  Int             m_occupancyVB;
-  Int             m_initialOVB;
-  Int             m_targetBufLevel;
-  Int             m_initialTBL;
-  Int             m_remainingBitsInGOP;
-  Int             m_remainingBitsInFrame;
-  Int             m_occupancyVBInFrame;
-  Int             m_targetBits;
-  Int             m_numUnitInFrame;
-  Int             m_codedPixels;
-  Bool            m_activeUnitLevelOn;
-  Double          m_costNonRefAvgWeighting;
-  Double          m_costRefAvgWeighting;
-  Double          m_costAvgbpp;         
-  
-  FrameData*      m_pcFrameData;
-  LCUData*        m_pcLCUData;
-
-  MADLinearModel              m_cMADLinearModel;
-  PixelBaseURQQuadraticModel  m_cPixelURQQuadraticModel;
-  
-public:
-  TEncRateCtrl         () {};
-  virtual ~TEncRateCtrl() {};
-
-  Void          create                (Int sizeIntraPeriod, Int sizeGOP, Int frameRate, Int targetKbps, Int qp, Int numLCUInBasicUnit, Int sourceWidth, Int sourceHeight, Int maxCUWidth, Int maxCUHeight);
-  Void          destroy               ();
-
-  Void          initFrameData         (Int qp = 0);
-  Void          initUnitData          (Int qp = 0);
-  Int           getFrameQP            (Bool isReferenced, Int POC);
-  Bool          calculateUnitQP       ();
-  Int           getUnitQP             ()                                          { return m_pcLCUData[m_indexLCU].m_qp;  }
-  Void          updateRCGOPStatus     ();
-  Void          updataRCFrameStatus   (Int frameBits, SliceType eSliceType);
-  Void          updataRCUnitStatus    ();
-  Void          updateLCUData         (TComDataCU* pcCU, UInt64 actualLCUBits, Int qp);
-  Void          updateFrameData       (UInt64 actualFrameBits);
-  Double        xAdjustmentBits       (Int& reductionBits, Int& compensationBits);
-  Int           getGOPId              ()                                          { return m_indexFrame; }
-};
 #endif
 
-#endif
-
-
+
Index: trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp	(revision 499)
+++ trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp	(revision 540)
@@ -45,4 +45,1267 @@
 //! \{
 
+
+#if HM_CLEANUP_SAO
+
+/** rounding with IBDI
+ * \param  x
+ */
+inline Double xRoundIbdi2(Int bitDepth, Double x)
+{
+  return ((x)>0) ? (Int)(((Int)(x)+(1<<(bitDepth-8-1)))/(1<<(bitDepth-8))) : ((Int)(((Int)(x)-(1<<(bitDepth-8-1)))/(1<<(bitDepth-8))));
+}
+
+inline Double xRoundIbdi(Int bitDepth, Double x)
+{
+  return (bitDepth > 8 ? xRoundIbdi2(bitDepth, (x)) : ((x)>=0 ? ((Int)((x)+0.5)) : ((Int)((x)-0.5)))) ;
+}
+
+
+TEncSampleAdaptiveOffset::TEncSampleAdaptiveOffset()
+{
+  m_pppcRDSbacCoder = NULL;           
+  m_pcRDGoOnSbacCoder = NULL;
+  m_pppcBinCoderCABAC = NULL;    
+  m_statData = NULL;
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  m_preDBFstatData = NULL;
+#endif
+}
+
+TEncSampleAdaptiveOffset::~TEncSampleAdaptiveOffset()
+{
+  destroyEncData();
+}
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+Void TEncSampleAdaptiveOffset::createEncData(Bool isPreDBFSamplesUsed)
+#else
+Void TEncSampleAdaptiveOffset::createEncData()
+#endif
+{
+
+  //cabac coder for RDO
+  m_pppcRDSbacCoder = new TEncSbac* [NUM_SAO_CABACSTATE_LABELS];
+  m_pppcBinCoderCABAC = new TEncBinCABACCounter* [NUM_SAO_CABACSTATE_LABELS];
+
+  for(Int cs=0; cs < NUM_SAO_CABACSTATE_LABELS; cs++)
+  {
+    m_pppcRDSbacCoder[cs] = new TEncSbac;
+    m_pppcBinCoderCABAC[cs] = new TEncBinCABACCounter;
+    m_pppcRDSbacCoder   [cs]->init( m_pppcBinCoderCABAC [cs] );
+  }
+
+
+  //statistics
+  m_statData = new SAOStatData**[m_numCTUsPic];
+  for(Int i=0; i< m_numCTUsPic; i++)
+  {
+    m_statData[i] = new SAOStatData*[NUM_SAO_COMPONENTS];
+    for(Int compIdx=0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
+    {
+      m_statData[i][compIdx] = new SAOStatData[NUM_SAO_NEW_TYPES];
+    }
+  }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  if(isPreDBFSamplesUsed)
+  {
+    m_preDBFstatData = new SAOStatData**[m_numCTUsPic];
+    for(Int i=0; i< m_numCTUsPic; i++)
+    {
+      m_preDBFstatData[i] = new SAOStatData*[NUM_SAO_COMPONENTS];
+      for(Int compIdx=0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
+      {
+        m_preDBFstatData[i][compIdx] = new SAOStatData[NUM_SAO_NEW_TYPES];
+      }
+    }
+
+  }
+#endif
+
+#if SAO_ENCODING_CHOICE
+  ::memset(m_saoDisabledRate, 0, sizeof(m_saoDisabledRate));
+#endif
+
+  for(Int typeIdc=0; typeIdc < NUM_SAO_NEW_TYPES; typeIdc++)
+  {
+    m_skipLinesR[SAO_Y ][typeIdc]= 5;
+    m_skipLinesR[SAO_Cb][typeIdc]= m_skipLinesR[SAO_Cr][typeIdc]= 3;
+
+    m_skipLinesB[SAO_Y ][typeIdc]= 4;
+    m_skipLinesB[SAO_Cb][typeIdc]= m_skipLinesB[SAO_Cr][typeIdc]= 2;
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+    if(isPreDBFSamplesUsed)
+    {
+      switch(typeIdc)
+      {
+      case SAO_TYPE_EO_0:
+        {
+          m_skipLinesR[SAO_Y ][typeIdc]= 5;
+          m_skipLinesR[SAO_Cb][typeIdc]= m_skipLinesR[SAO_Cr][typeIdc]= 3;
+
+          m_skipLinesB[SAO_Y ][typeIdc]= 3;
+          m_skipLinesB[SAO_Cb][typeIdc]= m_skipLinesB[SAO_Cr][typeIdc]= 1;
+        }
+        break;
+      case SAO_TYPE_EO_90:
+        {
+          m_skipLinesR[SAO_Y ][typeIdc]= 4;
+          m_skipLinesR[SAO_Cb][typeIdc]= m_skipLinesR[SAO_Cr][typeIdc]= 2;
+
+          m_skipLinesB[SAO_Y ][typeIdc]= 4;
+          m_skipLinesB[SAO_Cb][typeIdc]= m_skipLinesB[SAO_Cr][typeIdc]= 2;
+        }
+        break;
+      case SAO_TYPE_EO_135:
+      case SAO_TYPE_EO_45:
+        {
+          m_skipLinesR[SAO_Y ][typeIdc]= 5;
+          m_skipLinesR[SAO_Cb][typeIdc]= m_skipLinesR[SAO_Cr][typeIdc]= 3;
+
+          m_skipLinesB[SAO_Y ][typeIdc]= 4;
+          m_skipLinesB[SAO_Cb][typeIdc]= m_skipLinesB[SAO_Cr][typeIdc]= 2;
+        }
+        break;
+      case SAO_TYPE_BO:
+        {
+          m_skipLinesR[SAO_Y ][typeIdc]= 4;
+          m_skipLinesR[SAO_Cb][typeIdc]= m_skipLinesR[SAO_Cr][typeIdc]= 2;
+
+          m_skipLinesB[SAO_Y ][typeIdc]= 3;
+          m_skipLinesB[SAO_Cb][typeIdc]= m_skipLinesB[SAO_Cr][typeIdc]= 1;
+        }
+        break;
+      default:
+        {
+          printf("Not a supported type");
+          assert(0);
+          exit(-1);
+        }
+      }
+    }
+#endif    
+  }
+
+}
+
+Void TEncSampleAdaptiveOffset::destroyEncData()
+{
+  if(m_pppcRDSbacCoder != NULL)
+  {
+    for (Int cs = 0; cs < NUM_SAO_CABACSTATE_LABELS; cs ++ )
+    {
+      delete m_pppcRDSbacCoder[cs];
+    }
+    delete[] m_pppcRDSbacCoder; m_pppcRDSbacCoder = NULL;
+  }
+
+  if(m_pppcBinCoderCABAC != NULL)
+  {
+    for (Int cs = 0; cs < NUM_SAO_CABACSTATE_LABELS; cs ++ )
+    {
+      delete m_pppcBinCoderCABAC[cs];
+    }
+    delete[] m_pppcBinCoderCABAC; m_pppcBinCoderCABAC = NULL;
+  }
+
+  if(m_statData != NULL)
+  {
+    for(Int i=0; i< m_numCTUsPic; i++)
+    {
+      for(Int compIdx=0; compIdx< NUM_SAO_COMPONENTS; compIdx++)
+      {
+        delete[] m_statData[i][compIdx];
+      }
+      delete[] m_statData[i];
+    }
+    delete[] m_statData; m_statData = NULL;
+  }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  if(m_preDBFstatData != NULL)
+  {
+    for(Int i=0; i< m_numCTUsPic; i++)
+    {
+      for(Int compIdx=0; compIdx< NUM_SAO_COMPONENTS; compIdx++)
+      {
+        delete[] m_preDBFstatData[i][compIdx];
+      }
+      delete[] m_preDBFstatData[i];
+    }
+    delete[] m_preDBFstatData; m_preDBFstatData = NULL;
+  }
+
+#endif
+}
+
+Void TEncSampleAdaptiveOffset::initRDOCabacCoder(TEncSbac* pcRDGoOnSbacCoder, TComSlice* pcSlice) 
+{
+  m_pcRDGoOnSbacCoder = pcRDGoOnSbacCoder;
+  m_pcRDGoOnSbacCoder->setSlice(pcSlice);
+  m_pcRDGoOnSbacCoder->resetEntropy();
+  m_pcRDGoOnSbacCoder->resetBits();
+
+  m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[SAO_CABACSTATE_PIC_INIT]);
+}
+
+
+
+Void TEncSampleAdaptiveOffset::SAOProcess(TComPic* pPic, Bool* sliceEnabled, const Double *lambdas
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                                         , Bool isPreDBFSamplesUsed
+#endif
+                                          )
+{
+  TComPicYuv* orgYuv= pPic->getPicYuvOrg();
+  TComPicYuv* resYuv= pPic->getPicYuvRec();
+  m_labmda[SAO_Y]= lambdas[0]; m_labmda[SAO_Cb]= lambdas[1]; m_labmda[SAO_Cr]= lambdas[2];
+  TComPicYuv* srcYuv = m_tempPicYuv;
+  resYuv->copyToPic(srcYuv);
+  srcYuv->setBorderExtension(false);
+  srcYuv->extendPicBorder();
+
+  //collect statistics
+  getStatistics(m_statData, orgYuv, srcYuv, pPic);
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  if(isPreDBFSamplesUsed)
+  {
+    addPreDBFStatistics(m_statData);
+  }
+#endif
+  //slice on/off 
+  decidePicParams(sliceEnabled, pPic->getSlice(0)->getDepth()); 
+
+  //block on/off 
+  SAOBlkParam* reconParams = new SAOBlkParam[m_numCTUsPic]; //temporary parameter buffer for storing reconstructed SAO parameters
+  decideBlkParams(pPic, sliceEnabled, m_statData, srcYuv, resYuv, reconParams, pPic->getPicSym()->getSAOBlkParam());
+  delete[] reconParams;
+
+}
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+Void TEncSampleAdaptiveOffset::getPreDBFStatistics(TComPic* pPic)
+{
+  getStatistics(m_preDBFstatData, pPic->getPicYuvOrg(), pPic->getPicYuvRec(), pPic, true);
+}
+
+Void TEncSampleAdaptiveOffset::addPreDBFStatistics(SAOStatData*** blkStats)
+{
+  for(Int n=0; n< m_numCTUsPic; n++)
+  {
+    for(Int compIdx=0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
+    {
+      for(Int typeIdc=0; typeIdc < NUM_SAO_NEW_TYPES; typeIdc++)
+      {
+        blkStats[n][compIdx][typeIdc] += m_preDBFstatData[n][compIdx][typeIdc];
+      }
+    }
+  }
+}
+
+#endif
+
+Void TEncSampleAdaptiveOffset::getStatistics(SAOStatData*** blkStats, TComPicYuv* orgYuv, TComPicYuv* srcYuv, TComPic* pPic
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                          , Bool isCalculatePreDeblockSamples
+#endif
+                          )
+{
+  Bool isLeftAvail,isRightAvail,isAboveAvail,isBelowAvail,isAboveLeftAvail,isAboveRightAvail,isBelowLeftAvail,isBelowRightAvail;
+
+  for(Int ctu= 0; ctu < m_numCTUsPic; ctu++)
+  {
+    Int yPos   = (ctu / m_numCTUInWidth)*m_maxCUHeight;
+    Int xPos   = (ctu % m_numCTUInWidth)*m_maxCUWidth;
+    Int height = (yPos + m_maxCUHeight > m_picHeight)?(m_picHeight- yPos):m_maxCUHeight;
+    Int width  = (xPos + m_maxCUWidth  > m_picWidth )?(m_picWidth - xPos):m_maxCUWidth;
+
+    pPic->getPicSym()->deriveLoopFilterBoundaryAvailibility(ctu, isLeftAvail,isRightAvail,isAboveAvail,isBelowAvail,isAboveLeftAvail,isAboveRightAvail,isBelowLeftAvail,isBelowRightAvail);
+
+    //NOTE: The number of skipped lines during gathering CTU statistics depends on the slice boundary availabilities.
+    //For simplicity, here only picture boundaries are considered.
+
+    isRightAvail      = (xPos + m_maxCUWidth  < m_picWidth );
+    isBelowAvail      = (yPos + m_maxCUHeight < m_picHeight);
+    isBelowRightAvail = (isRightAvail && isBelowAvail);
+    isBelowLeftAvail  = ((xPos > 0) && (isBelowAvail));
+    isAboveRightAvail = ((yPos > 0) && (isRightAvail));
+
+    for(Int compIdx=0; compIdx< NUM_SAO_COMPONENTS; compIdx++)
+    {
+      Bool isLuma     = (compIdx == SAO_Y);
+      Int  formatShift= isLuma?0:1;
+
+      Int  srcStride = isLuma?srcYuv->getStride():srcYuv->getCStride();
+      Pel* srcBlk    = getPicBuf(srcYuv, compIdx)+ (yPos >> formatShift)*srcStride+ (xPos >> formatShift);
+
+      Int  orgStride  = isLuma?orgYuv->getStride():orgYuv->getCStride();
+      Pel* orgBlk     = getPicBuf(orgYuv, compIdx)+ (yPos >> formatShift)*orgStride+ (xPos >> formatShift);
+
+      getBlkStats(compIdx, blkStats[ctu][compIdx]  
+                , srcBlk, orgBlk, srcStride, orgStride, (width  >> formatShift), (height >> formatShift)
+                , isLeftAvail,  isRightAvail, isAboveAvail, isBelowAvail, isAboveLeftAvail, isAboveRightAvail, isBelowLeftAvail, isBelowRightAvail
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                , isCalculatePreDeblockSamples
+#endif
+                );
+
+    }
+  }
+}
+
+Void TEncSampleAdaptiveOffset::decidePicParams(Bool* sliceEnabled, Int picTempLayer)
+{
+  //decide sliceEnabled[compIdx]
+  for (Int compIdx=0; compIdx<NUM_SAO_COMPONENTS; compIdx++)
+  {
+    // reset flags & counters
+    sliceEnabled[compIdx] = true;
+
+#if SAO_ENCODING_CHOICE
+#if SAO_ENCODING_CHOICE_CHROMA
+    // decide slice-level on/off based on previous results
+    if( (picTempLayer > 0) 
+      && (m_saoDisabledRate[compIdx][picTempLayer-1] > ((compIdx==SAO_Y) ? SAO_ENCODING_RATE : SAO_ENCODING_RATE_CHROMA)) )
+    {
+      sliceEnabled[compIdx] = false;
+    }
+#else
+    // decide slice-level on/off based on previous results
+    if( (picTempLayer > 0) 
+      && (m_saoDisabledRate[SAO_Y][0] > SAO_ENCODING_RATE) )
+    {
+      sliceEnabled[compIdx] = false;
+    }
+#endif
+#endif
+  }
+}
+
+Int64 TEncSampleAdaptiveOffset::getDistortion(Int ctu, Int compIdx, Int typeIdc, Int typeAuxInfo, Int* invQuantOffset, SAOStatData& statData)
+{
+  Int64 dist=0;
+  Int inputBitDepth    = (compIdx == SAO_Y) ? g_bitDepthY : g_bitDepthC ;
+  Int shift = 2 * DISTORTION_PRECISION_ADJUSTMENT(inputBitDepth-8);
+
+  switch(typeIdc)
+  {
+    case SAO_TYPE_EO_0:
+    case SAO_TYPE_EO_90:
+    case SAO_TYPE_EO_135:
+    case SAO_TYPE_EO_45:
+      {
+        for (Int offsetIdx=0; offsetIdx<NUM_SAO_EO_CLASSES; offsetIdx++)
+        {
+          dist += estSaoDist( statData.count[offsetIdx], invQuantOffset[offsetIdx], statData.diff[offsetIdx], shift);
+        }        
+      }
+      break;
+    case SAO_TYPE_BO:
+      {
+        for (Int offsetIdx=typeAuxInfo; offsetIdx<typeAuxInfo+4; offsetIdx++)
+        {
+          Int bandIdx = offsetIdx % NUM_SAO_BO_CLASSES ; 
+          dist += estSaoDist( statData.count[bandIdx], invQuantOffset[bandIdx], statData.diff[bandIdx], shift);
+        }
+      }
+      break;
+    default:
+      {
+        printf("Not a supported type");
+        assert(0);
+        exit(-1);
+      }
+  }
+
+  return dist;
+}
+
+inline Int64 TEncSampleAdaptiveOffset::estSaoDist(Int64 count, Int64 offset, Int64 diffSum, Int shift)
+{
+  return (( count*offset*offset-diffSum*offset*2 ) >> shift);
+}
+
+
+inline Int TEncSampleAdaptiveOffset::estIterOffset(Int typeIdx, Int classIdx, Double lambda, Int offsetInput, Int64 count, Int64 diffSum, Int shift, Int bitIncrease, Int64& bestDist, Double& bestCost, Int offsetTh )
+{
+  Int iterOffset, tempOffset;
+  Int64 tempDist, tempRate;
+  Double tempCost, tempMinCost;
+  Int offsetOutput = 0;
+  iterOffset = offsetInput;
+  // Assuming sending quantized value 0 results in zero offset and sending the value zero needs 1 bit. entropy coder can be used to measure the exact rate here. 
+  tempMinCost = lambda; 
+  while (iterOffset != 0)
+  {
+    // Calculate the bits required for signaling the offset
+    tempRate = (typeIdx == SAO_TYPE_BO) ? (abs((Int)iterOffset)+2) : (abs((Int)iterOffset)+1); 
+    if (abs((Int)iterOffset)==offsetTh) //inclusive 
+    {  
+      tempRate --;
+    }
+    // Do the dequantization before distortion calculation
+    tempOffset  = iterOffset << bitIncrease;
+    tempDist    = estSaoDist( count, tempOffset, diffSum, shift);
+    tempCost    = ((Double)tempDist + lambda * (Double) tempRate);
+    if(tempCost < tempMinCost)
+    {
+      tempMinCost = tempCost;
+      offsetOutput = iterOffset;
+      bestDist = tempDist;
+      bestCost = tempCost;
+    }
+    iterOffset = (iterOffset > 0) ? (iterOffset-1):(iterOffset+1);
+  }
+  return offsetOutput;
+}
+
+
+Void TEncSampleAdaptiveOffset::deriveOffsets(Int ctu, Int compIdx, Int typeIdc, SAOStatData& statData, Int* quantOffsets, Int& typeAuxInfo)
+{
+  Int bitDepth = (compIdx== SAO_Y) ? g_bitDepthY : g_bitDepthC;
+  Int shift = 2 * DISTORTION_PRECISION_ADJUSTMENT(bitDepth-8);
+  Int offsetTh = g_saoMaxOffsetQVal[compIdx];  //inclusive
+
+  ::memset(quantOffsets, 0, sizeof(Int)*MAX_NUM_SAO_CLASSES);
+
+  //derive initial offsets 
+  Int numClasses = (typeIdc == SAO_TYPE_BO)?((Int)NUM_SAO_BO_CLASSES):((Int)NUM_SAO_EO_CLASSES);
+  for(Int classIdx=0; classIdx< numClasses; classIdx++)
+  {
+    if( (typeIdc != SAO_TYPE_BO) && (classIdx==SAO_CLASS_EO_PLAIN)  ) 
+    {
+      continue; //offset will be zero
+    }
+
+    if(statData.count[classIdx] == 0)
+    {
+      continue; //offset will be zero
+    }
+
+    quantOffsets[classIdx] = (Int) xRoundIbdi(bitDepth, (Double)( statData.diff[classIdx]<<(bitDepth-8)) 
+                                                                  / 
+                                                          (Double)( statData.count[classIdx]<< m_offsetStepLog2[compIdx])
+                                               );
+    quantOffsets[classIdx] = Clip3(-offsetTh, offsetTh, quantOffsets[classIdx]);
+  }
+
+  // adjust offsets
+  switch(typeIdc)
+  {
+    case SAO_TYPE_EO_0:
+    case SAO_TYPE_EO_90:
+    case SAO_TYPE_EO_135:
+    case SAO_TYPE_EO_45:
+      {
+        Int64 classDist;
+        Double classCost;
+        for(Int classIdx=0; classIdx<NUM_SAO_EO_CLASSES; classIdx++)  
+        {         
+          if(classIdx==SAO_CLASS_EO_FULL_VALLEY && quantOffsets[classIdx] < 0) quantOffsets[classIdx] =0;
+          if(classIdx==SAO_CLASS_EO_HALF_VALLEY && quantOffsets[classIdx] < 0) quantOffsets[classIdx] =0;
+          if(classIdx==SAO_CLASS_EO_HALF_PEAK   && quantOffsets[classIdx] > 0) quantOffsets[classIdx] =0;
+          if(classIdx==SAO_CLASS_EO_FULL_PEAK   && quantOffsets[classIdx] > 0) quantOffsets[classIdx] =0;
+
+          if( quantOffsets[classIdx] != 0 ) //iterative adjustment only when derived offset is not zero
+          {
+            quantOffsets[classIdx] = estIterOffset( typeIdc, classIdx, m_labmda[compIdx], quantOffsets[classIdx], statData.count[classIdx], statData.diff[classIdx], shift, m_offsetStepLog2[compIdx], classDist , classCost , offsetTh );
+          }
+        }
+      
+        typeAuxInfo =0;
+      }
+      break;
+    case SAO_TYPE_BO:
+      {
+        Int64  distBOClasses[NUM_SAO_BO_CLASSES];
+        Double costBOClasses[NUM_SAO_BO_CLASSES];
+        ::memset(distBOClasses, 0, sizeof(Int64)*NUM_SAO_BO_CLASSES);
+        for(Int classIdx=0; classIdx< NUM_SAO_BO_CLASSES; classIdx++)
+        {         
+          costBOClasses[classIdx]= m_labmda[compIdx];
+          if( quantOffsets[classIdx] != 0 ) //iterative adjustment only when derived offset is not zero
+          {
+            quantOffsets[classIdx] = estIterOffset( typeIdc, classIdx, m_labmda[compIdx], quantOffsets[classIdx], statData.count[classIdx], statData.diff[classIdx], shift, m_offsetStepLog2[compIdx], distBOClasses[classIdx], costBOClasses[classIdx], offsetTh );
+          }
+        }
+
+        //decide the starting band index
+        Double minCost = MAX_DOUBLE, cost;
+        for(Int band=0; band< NUM_SAO_BO_CLASSES- 4+ 1; band++) 
+        {
+          cost  = costBOClasses[band  ];
+          cost += costBOClasses[band+1];
+          cost += costBOClasses[band+2];
+          cost += costBOClasses[band+3];
+
+          if(cost < minCost)
+          {
+            minCost = cost;
+            typeAuxInfo = band;
+          }
+        }
+        //clear those unused classes
+        Int clearQuantOffset[NUM_SAO_BO_CLASSES];
+        ::memset(clearQuantOffset, 0, sizeof(Int)*NUM_SAO_BO_CLASSES);
+        for(Int i=0; i< 4; i++) 
+        {
+          Int band = (typeAuxInfo+i)%NUM_SAO_BO_CLASSES;
+          clearQuantOffset[band] = quantOffsets[band];
+        }
+        ::memcpy(quantOffsets, clearQuantOffset, sizeof(Int)*NUM_SAO_BO_CLASSES);        
+      }
+      break;
+    default:
+      {
+        printf("Not a supported type");
+        assert(0);
+        exit(-1);
+      }
+
+  }
+
+
+}
+
+
+Void TEncSampleAdaptiveOffset::deriveModeNewRDO(Int ctu, std::vector<SAOBlkParam*>& mergeList, Bool* sliceEnabled, SAOStatData*** blkStats, SAOBlkParam& modeParam, Double& modeNormCost, TEncSbac** cabacCoderRDO, Int inCabacLabel)
+{
+  Double minCost, cost;
+  Int rate, minRate;
+  Int64 dist[NUM_SAO_COMPONENTS], modeDist[NUM_SAO_COMPONENTS];
+  SAOOffset testOffset[NUM_SAO_COMPONENTS];
+  Int compIdx;
+  Int invQuantOffset[MAX_NUM_SAO_CLASSES];
+
+  modeDist[SAO_Y]= modeDist[SAO_Cb] = modeDist[SAO_Cr] = 0;
+
+  //pre-encode merge flags
+  modeParam[SAO_Y ].modeIdc = SAO_MODE_OFF;
+  m_pcRDGoOnSbacCoder->load(cabacCoderRDO[inCabacLabel]);
+  m_pcRDGoOnSbacCoder->codeSAOBlkParam(modeParam, sliceEnabled, (mergeList[SAO_MERGE_LEFT]!= NULL), (mergeList[SAO_MERGE_ABOVE]!= NULL), true);
+  m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
+
+  //------ luma --------//
+  compIdx = SAO_Y;
+  //"off" case as initial cost
+  modeParam[compIdx].modeIdc = SAO_MODE_OFF;
+  m_pcRDGoOnSbacCoder->resetBits();
+  m_pcRDGoOnSbacCoder->codeSAOOffsetParam(compIdx, modeParam[compIdx], sliceEnabled[compIdx]);
+  minRate= m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
+  modeDist[compIdx] = 0;
+  minCost= m_labmda[compIdx]*((Double)minRate);
+  m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
+  if(sliceEnabled[compIdx])
+  {
+    for(Int typeIdc=0; typeIdc< NUM_SAO_NEW_TYPES; typeIdc++)
+    {
+      testOffset[compIdx].modeIdc = SAO_MODE_NEW;
+      testOffset[compIdx].typeIdc = typeIdc;
+
+      //derive coded offset
+      deriveOffsets(ctu, compIdx, typeIdc, blkStats[ctu][compIdx][typeIdc], testOffset[compIdx].offset, testOffset[compIdx].typeAuxInfo);
+
+      //inversed quantized offsets
+      invertQuantOffsets(compIdx, typeIdc, testOffset[compIdx].typeAuxInfo, invQuantOffset, testOffset[compIdx].offset);
+
+      //get distortion
+      dist[compIdx] = getDistortion(ctu, compIdx, testOffset[compIdx].typeIdc, testOffset[compIdx].typeAuxInfo, invQuantOffset, blkStats[ctu][compIdx][typeIdc]);
+
+      //get rate
+      m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
+      m_pcRDGoOnSbacCoder->resetBits();
+      m_pcRDGoOnSbacCoder->codeSAOOffsetParam(compIdx, testOffset[compIdx], sliceEnabled[compIdx]);
+      rate = m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
+      cost = (Double)dist[compIdx] + m_labmda[compIdx]*((Double)rate);
+      if(cost < minCost)
+      {
+        minCost = cost;
+        minRate = rate;
+        modeDist[compIdx] = dist[compIdx];
+        modeParam[compIdx]= testOffset[compIdx];
+        m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
+      }
+    }
+  }
+  m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
+  m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
+
+  //------ chroma --------//
+  assert(m_labmda[SAO_Cb] == m_labmda[SAO_Cr]);
+  Double chromaLambda = m_labmda[SAO_Cb];
+  //"off" case as initial cost
+  m_pcRDGoOnSbacCoder->resetBits();
+  modeParam[SAO_Cb].modeIdc = SAO_MODE_OFF; 
+  m_pcRDGoOnSbacCoder->codeSAOOffsetParam(SAO_Cb, modeParam[SAO_Cb], sliceEnabled[SAO_Cb]);
+  modeParam[SAO_Cr].modeIdc = SAO_MODE_OFF; 
+  m_pcRDGoOnSbacCoder->codeSAOOffsetParam(SAO_Cr, modeParam[SAO_Cr], sliceEnabled[SAO_Cr]);
+  minRate= m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
+  modeDist[SAO_Cb] = modeDist[SAO_Cr]= 0;
+  minCost= chromaLambda*((Double)minRate); 
+
+  //doesn't need to store cabac status here since the whole CTU parameters will be re-encoded at the end of this function
+
+  for(Int typeIdc=0; typeIdc< NUM_SAO_NEW_TYPES; typeIdc++)
+  {
+    for(compIdx= SAO_Cb; compIdx< NUM_SAO_COMPONENTS; compIdx++)
+    {
+      if(!sliceEnabled[compIdx])
+      {
+        testOffset[compIdx].modeIdc = SAO_MODE_OFF;
+        dist[compIdx]= 0;
+        continue;
+      }
+      testOffset[compIdx].modeIdc = SAO_MODE_NEW;
+      testOffset[compIdx].typeIdc = typeIdc;
+
+      //derive offset & get distortion
+      deriveOffsets(ctu, compIdx, typeIdc, blkStats[ctu][compIdx][typeIdc], testOffset[compIdx].offset, testOffset[compIdx].typeAuxInfo);
+      invertQuantOffsets(compIdx, typeIdc, testOffset[compIdx].typeAuxInfo, invQuantOffset, testOffset[compIdx].offset);
+      dist[compIdx]= getDistortion(ctu, compIdx, typeIdc, testOffset[compIdx].typeAuxInfo, invQuantOffset, blkStats[ctu][compIdx][typeIdc]);
+    }
+
+    //get rate
+    m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
+    m_pcRDGoOnSbacCoder->resetBits();
+    m_pcRDGoOnSbacCoder->codeSAOOffsetParam(SAO_Cb, testOffset[SAO_Cb], sliceEnabled[SAO_Cb]);
+    m_pcRDGoOnSbacCoder->codeSAOOffsetParam(SAO_Cr, testOffset[SAO_Cr], sliceEnabled[SAO_Cr]);
+    rate = m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
+
+    cost = (Double)(dist[SAO_Cb]+ dist[SAO_Cr]) + chromaLambda*((Double)rate);
+    if(cost < minCost)
+    {
+      minCost = cost;
+      minRate = rate;
+      modeDist[SAO_Cb] = dist[SAO_Cb];
+      modeDist[SAO_Cr] = dist[SAO_Cr];
+      modeParam[SAO_Cb]= testOffset[SAO_Cb];
+      modeParam[SAO_Cr]= testOffset[SAO_Cr];
+    }
+  }
+
+
+  //----- re-gen rate & normalized cost----//
+  modeNormCost  = (Double)modeDist[SAO_Y]/m_labmda[SAO_Y];
+  modeNormCost += (Double)(modeDist[SAO_Cb]+ modeDist[SAO_Cr])/chromaLambda; 
+  m_pcRDGoOnSbacCoder->load(cabacCoderRDO[inCabacLabel]);
+  m_pcRDGoOnSbacCoder->resetBits();
+  m_pcRDGoOnSbacCoder->codeSAOBlkParam(modeParam, sliceEnabled, (mergeList[SAO_MERGE_LEFT]!= NULL), (mergeList[SAO_MERGE_ABOVE]!= NULL), false);
+  modeNormCost += (Double)m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
+
+}
+
+Void TEncSampleAdaptiveOffset::deriveModeMergeRDO(Int ctu, std::vector<SAOBlkParam*>& mergeList, Bool* sliceEnabled, SAOStatData*** blkStats, SAOBlkParam& modeParam, Double& modeNormCost, TEncSbac** cabacCoderRDO, Int inCabacLabel)
+{
+  Int mergeListSize = (Int)mergeList.size();
+  modeNormCost = MAX_DOUBLE;
+
+  Double cost;
+  SAOBlkParam testBlkParam;
+
+  for(Int mergeType=0; mergeType< mergeListSize; mergeType++)
+  {
+    if(mergeList[mergeType] == NULL)
+    {
+      continue;
+    }
+
+    testBlkParam = *(mergeList[mergeType]);
+    //normalized distortion
+    Double normDist=0;
+    for(Int compIdx=0; compIdx< NUM_SAO_COMPONENTS; compIdx++)
+    {
+      testBlkParam[compIdx].modeIdc = SAO_MODE_MERGE;
+      testBlkParam[compIdx].typeIdc = mergeType;
+
+      SAOOffset& mergedOffsetParam = (*(mergeList[mergeType]))[compIdx];
+
+      if( mergedOffsetParam.modeIdc != SAO_MODE_OFF)
+      {
+        //offsets have been reconstructed. Don't call inversed quantization function.
+        normDist += (((Double)getDistortion(ctu, compIdx, mergedOffsetParam.typeIdc, mergedOffsetParam.typeAuxInfo, mergedOffsetParam.offset, blkStats[ctu][compIdx][mergedOffsetParam.typeIdc]))
+                       /m_labmda[compIdx]
+                    );
+      }
+
+    }
+
+    //rate
+    m_pcRDGoOnSbacCoder->load(cabacCoderRDO[inCabacLabel]);
+    m_pcRDGoOnSbacCoder->resetBits();
+    m_pcRDGoOnSbacCoder->codeSAOBlkParam(testBlkParam, sliceEnabled, (mergeList[SAO_MERGE_LEFT]!= NULL), (mergeList[SAO_MERGE_ABOVE]!= NULL), false);
+    Int rate = m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
+
+    cost = normDist+(Double)rate;
+
+    if(cost < modeNormCost)
+    {
+      modeNormCost = cost;
+      modeParam    = testBlkParam;
+      m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
+    }
+  }
+
+  m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
+
+
+}
+
+Void TEncSampleAdaptiveOffset::decideBlkParams(TComPic* pic, Bool* sliceEnabled, SAOStatData*** blkStats, TComPicYuv* srcYuv, TComPicYuv* resYuv, SAOBlkParam* reconParams, SAOBlkParam* codedParams)
+{
+  Bool isAllBlksDisabled = false;
+  if(!sliceEnabled[SAO_Y] && !sliceEnabled[SAO_Cb] && !sliceEnabled[SAO_Cr])
+  {
+    isAllBlksDisabled = true;
+  }
+
+  m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[ SAO_CABACSTATE_PIC_INIT ]);
+
+  SAOBlkParam modeParam;
+  Double minCost, modeCost;
+
+  for(Int ctu=0; ctu< m_numCTUsPic; ctu++)
+  {
+    if(isAllBlksDisabled)
+    {
+      codedParams[ctu].reset();
+      continue;
+    }
+
+    m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[ SAO_CABACSTATE_BLK_CUR ]);
+
+    //get merge list
+    std::vector<SAOBlkParam*> mergeList;
+    getMergeList(pic, ctu, reconParams, mergeList);
+
+    minCost = MAX_DOUBLE;
+    for(Int mode=0; mode < NUM_SAO_MODES; mode++)
+    {
+      switch(mode)
+      {
+      case SAO_MODE_OFF:
+        {
+          continue; //not necessary, since all-off case will be tested in SAO_MODE_NEW case.
+        }
+        break;
+      case SAO_MODE_NEW:
+        {
+          deriveModeNewRDO(ctu, mergeList, sliceEnabled, blkStats, modeParam, modeCost, m_pppcRDSbacCoder, SAO_CABACSTATE_BLK_CUR);
+
+        }
+        break;
+      case SAO_MODE_MERGE:
+        {
+          deriveModeMergeRDO(ctu, mergeList, sliceEnabled, blkStats , modeParam, modeCost, m_pppcRDSbacCoder, SAO_CABACSTATE_BLK_CUR);
+        }
+        break;
+      default:
+        {
+          printf("Not a supported SAO mode\n");
+          assert(0);
+          exit(-1);
+        }
+      }
+
+      if(modeCost < minCost)
+      {
+        minCost = modeCost;
+        codedParams[ctu] = modeParam;
+        m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[ SAO_CABACSTATE_BLK_NEXT ]);
+
+      }
+    } //mode
+    m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[ SAO_CABACSTATE_BLK_NEXT ]);
+
+    //apply reconstructed offsets
+    reconParams[ctu] = codedParams[ctu];
+    reconstructBlkSAOParam(reconParams[ctu], mergeList);
+    offsetCTU(ctu, srcYuv, resYuv, reconParams[ctu], pic);
+  } //ctu
+
+#if SAO_ENCODING_CHOICE 
+  Int picTempLayer = pic->getSlice(0)->getDepth();
+  Int numLcusForSAOOff[NUM_SAO_COMPONENTS];
+  numLcusForSAOOff[SAO_Y ] = numLcusForSAOOff[SAO_Cb]= numLcusForSAOOff[SAO_Cr]= 0;
+
+  for (Int compIdx=0; compIdx<NUM_SAO_COMPONENTS; compIdx++)
+  {
+    for(Int ctu=0; ctu< m_numCTUsPic; ctu++)
+    {
+      if( reconParams[ctu][compIdx].modeIdc == SAO_MODE_OFF)
+      {
+        numLcusForSAOOff[compIdx]++;
+      }
+    }
+  }
+#if SAO_ENCODING_CHOICE_CHROMA
+  for (Int compIdx=0; compIdx<NUM_SAO_COMPONENTS; compIdx++)
+  {
+    m_saoDisabledRate[compIdx][picTempLayer] = (Double)numLcusForSAOOff[compIdx]/(Double)m_numCTUsPic;
+  }
+#else
+  if (picTempLayer == 0)
+  {
+    m_saoDisabledRate[SAO_Y][0] = (Double)(numLcusForSAOOff[SAO_Y]+numLcusForSAOOff[SAO_Cb]+numLcusForSAOOff[SAO_Cr])/(Double)(m_numCTUsPic*3);
+  }
+#endif                                              
+#endif
+}
+
+
+Void TEncSampleAdaptiveOffset::getBlkStats(Int compIdx, SAOStatData* statsDataTypes  
+                        , Pel* srcBlk, Pel* orgBlk, Int srcStride, Int orgStride, Int width, Int height
+                        , Bool isLeftAvail,  Bool isRightAvail, Bool isAboveAvail, Bool isBelowAvail, Bool isAboveLeftAvail, Bool isAboveRightAvail, Bool isBelowLeftAvail, Bool isBelowRightAvail
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                        , Bool isCalculatePreDeblockSamples
+#endif
+                        )
+{
+  if(m_lineBufWidth != m_maxCUWidth)
+  {
+    m_lineBufWidth = m_maxCUWidth;
+
+    if (m_signLineBuf1) delete[] m_signLineBuf1; m_signLineBuf1 = NULL;
+    m_signLineBuf1 = new Char[m_lineBufWidth+1]; 
+
+    if (m_signLineBuf2) delete[] m_signLineBuf2; m_signLineBuf2 = NULL;
+    m_signLineBuf2 = new Char[m_lineBufWidth+1];
+  }
+
+  Int x,y, startX, startY, endX, endY, edgeType, firstLineStartX, firstLineEndX;
+  Char signLeft, signRight, signDown;
+  Int64 *diff, *count;
+  Pel *srcLine, *orgLine;
+  Int* skipLinesR = m_skipLinesR[compIdx];
+  Int* skipLinesB = m_skipLinesB[compIdx];
+
+  for(Int typeIdx=0; typeIdx< NUM_SAO_NEW_TYPES; typeIdx++)
+  {
+    SAOStatData& statsData= statsDataTypes[typeIdx];
+    statsData.reset();
+
+    srcLine = srcBlk;
+    orgLine = orgBlk;
+    diff    = statsData.diff;
+    count   = statsData.count;
+    switch(typeIdx)
+    {
+    case SAO_TYPE_EO_0:
+      {
+        diff +=2;
+        count+=2;
+        endY   = (isBelowAvail) ? (height - skipLinesB[typeIdx]) : height;
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        startX = (!isCalculatePreDeblockSamples) ? (isLeftAvail  ? 0 : 1)
+                                                 : (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
+                                                 ;
+#else
+        startX = isLeftAvail ? 0 : 1;
+#endif
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        endX   = (!isCalculatePreDeblockSamples) ? (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
+                                                 : (isRightAvail ? width : (width - 1))
+                                                 ;
+#else
+        endX   = isRightAvail ? (width - skipLinesR[typeIdx]): (width - 1);
+#endif
+        for (y=0; y<endY; y++)
+        {
+          signLeft = (Char)m_sign[srcLine[startX] - srcLine[startX-1]];
+          for (x=startX; x<endX; x++)
+          {
+            signRight =  (Char)m_sign[srcLine[x] - srcLine[x+1]]; 
+            edgeType  =  signRight + signLeft;
+            signLeft  = -signRight;
+
+            diff [edgeType] += (orgLine[x] - srcLine[x]);
+            count[edgeType] ++;
+          }
+          srcLine  += srcStride;
+          orgLine  += orgStride;
+        }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        if(isCalculatePreDeblockSamples)
+        {
+          if(isBelowAvail)
+          {
+            startX = isLeftAvail  ? 0 : 1;
+            endX   = isRightAvail ? width : (width -1);
+
+            for(y=0; y<skipLinesB[typeIdx]; y++)
+            {
+              signLeft = (Char)m_sign[srcLine[startX] - srcLine[startX-1]];
+              for (x=startX; x<endX; x++)
+              {
+                signRight =  (Char)m_sign[srcLine[x] - srcLine[x+1]]; 
+                edgeType  =  signRight + signLeft;
+                signLeft  = -signRight;
+
+                diff [edgeType] += (orgLine[x] - srcLine[x]);
+                count[edgeType] ++;
+              }
+              srcLine  += srcStride;
+              orgLine  += orgStride;
+            }
+          }
+        }
+#endif
+      }
+      break;
+    case SAO_TYPE_EO_90:
+      {
+        diff +=2;
+        count+=2;
+        Char *signUpLine = m_signLineBuf1;
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        startX = (!isCalculatePreDeblockSamples) ? 0
+                                                 : (isRightAvail ? (width - skipLinesR[typeIdx]) : width)
+                                                 ;
+#endif
+        startY = isAboveAvail ? 0 : 1;
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        endX   = (!isCalculatePreDeblockSamples) ? (isRightAvail ? (width - skipLinesR[typeIdx]) : width) 
+                                                 : width
+                                                 ;
+#else
+        endX   = isRightAvail ? (width - skipLinesR[typeIdx]) : width ;
+#endif
+        endY   = isBelowAvail ? (height - skipLinesB[typeIdx]) : (height - 1);
+        if (!isAboveAvail)
+        {
+          srcLine += srcStride;
+          orgLine += orgStride;
+        }
+
+        Pel* srcLineAbove = srcLine - srcStride;
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        for (x=startX; x<endX; x++) 
+#else
+        for (x=0; x< endX; x++) 
+#endif
+        {
+          signUpLine[x] = (Char)m_sign[srcLine[x] - srcLineAbove[x]];
+        }
+
+        Pel* srcLineBelow;
+        for (y=startY; y<endY; y++)
+        {
+          srcLineBelow = srcLine + srcStride;
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+          for (x=startX; x<endX; x++)
+#else
+          for (x=0; x<endX; x++)
+#endif
+          {
+            signDown  = (Char)m_sign[srcLine[x] - srcLineBelow[x]]; 
+            edgeType  = signDown + signUpLine[x];
+            signUpLine[x]= -signDown;
+
+            diff [edgeType] += (orgLine[x] - srcLine[x]);
+            count[edgeType] ++;
+          }
+          srcLine += srcStride;
+          orgLine += orgStride;
+        }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        if(isCalculatePreDeblockSamples)
+        {
+          if(isBelowAvail)
+          {
+            startX = 0;
+            endX   = width;
+
+            for(y=0; y<skipLinesB[typeIdx]; y++)
+            {
+              srcLineBelow = srcLine + srcStride;
+              srcLineAbove = srcLine - srcStride;
+
+              for (x=startX; x<endX; x++)
+              {
+                edgeType = m_sign[srcLine[x] - srcLineBelow[x]] + m_sign[srcLine[x] - srcLineAbove[x]];
+                diff [edgeType] += (orgLine[x] - srcLine[x]);
+                count[edgeType] ++;
+              }
+              srcLine  += srcStride;
+              orgLine  += orgStride;
+            }
+          }
+        }
+#endif
+
+      }
+      break;
+    case SAO_TYPE_EO_135:
+      {
+        diff +=2;
+        count+=2;
+        Char *signUpLine, *signDownLine, *signTmpLine;
+
+        signUpLine  = m_signLineBuf1;
+        signDownLine= m_signLineBuf2;
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        startX = (!isCalculatePreDeblockSamples) ? (isLeftAvail  ? 0 : 1)
+                                                 : (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
+                                                 ;
+#else
+        startX = isLeftAvail ? 0 : 1 ;
+#endif
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        endX   = (!isCalculatePreDeblockSamples) ? (isRightAvail ? (width - skipLinesR[typeIdx]): (width - 1))
+                                                 : (isRightAvail ? width : (width - 1))
+                                                 ;
+#else
+        endX   = isRightAvail ? (width - skipLinesR[typeIdx]): (width - 1);
+#endif
+        endY   = isBelowAvail ? (height - skipLinesB[typeIdx]) : (height - 1);
+
+        //prepare 2nd line's upper sign
+        Pel* srcLineBelow = srcLine + srcStride;
+        for (x=startX; x<endX+1; x++)
+        {
+          signUpLine[x] = (Char)m_sign[srcLineBelow[x] - srcLine[x-1]];
+        }
+
+        //1st line
+        Pel* srcLineAbove = srcLine - srcStride;
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        firstLineStartX = (!isCalculatePreDeblockSamples) ? (isAboveLeftAvail ? 0    : 1) : startX;
+        firstLineEndX   = (!isCalculatePreDeblockSamples) ? (isAboveAvail     ? endX : 1) : endX;
+#else
+        firstLineStartX = isAboveLeftAvail ? 0    : 1;
+        firstLineEndX   = isAboveAvail     ? endX : 1;
+#endif
+        for(x=firstLineStartX; x<firstLineEndX; x++)
+        {
+          edgeType = m_sign[srcLine[x] - srcLineAbove[x-1]] - signUpLine[x+1];
+          diff [edgeType] += (orgLine[x] - srcLine[x]);
+          count[edgeType] ++;
+        }
+        srcLine  += srcStride;
+        orgLine  += orgStride;
+
+
+        //middle lines
+        for (y=1; y<endY; y++)
+        {
+          srcLineBelow = srcLine + srcStride;
+
+          for (x=startX; x<endX; x++)
+          {
+            signDown = (Char)m_sign[srcLine[x] - srcLineBelow[x+1]] ;
+            edgeType = signDown + signUpLine[x];
+            diff [edgeType] += (orgLine[x] - srcLine[x]);
+            count[edgeType] ++;
+
+            signDownLine[x+1] = -signDown; 
+          }
+          signDownLine[startX] = (Char)m_sign[srcLineBelow[startX] - srcLine[startX-1]];
+
+          signTmpLine  = signUpLine;
+          signUpLine   = signDownLine;
+          signDownLine = signTmpLine;
+
+          srcLine += srcStride;
+          orgLine += orgStride;
+        }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        if(isCalculatePreDeblockSamples)
+        {
+          if(isBelowAvail)
+          {
+            startX = isLeftAvail  ? 0     : 1 ;
+            endX   = isRightAvail ? width : (width -1);
+
+            for(y=0; y<skipLinesB[typeIdx]; y++)
+            {
+              srcLineBelow = srcLine + srcStride;
+              srcLineAbove = srcLine - srcStride;
+
+              for (x=startX; x< endX; x++)
+              {
+                edgeType = m_sign[srcLine[x] - srcLineBelow[x+1]] + m_sign[srcLine[x] - srcLineAbove[x-1]];
+                diff [edgeType] += (orgLine[x] - srcLine[x]);
+                count[edgeType] ++;
+              }
+              srcLine  += srcStride;
+              orgLine  += orgStride;
+            }
+          }
+        }
+#endif
+      }
+      break;
+    case SAO_TYPE_EO_45:
+      {
+        diff +=2;
+        count+=2;
+        Char *signUpLine = m_signLineBuf1+1;
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        startX = (!isCalculatePreDeblockSamples) ? (isLeftAvail  ? 0 : 1)
+                                                 : (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
+                                                 ;
+#else
+        startX = isLeftAvail ? 0 : 1;
+#endif
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        endX   = (!isCalculatePreDeblockSamples) ? (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
+                                                 : (isRightAvail ? width : (width - 1))
+                                                 ;
+#else
+        endX   = isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1);
+#endif
+        endY   = isBelowAvail ? (height - skipLinesB[typeIdx]) : (height - 1);
+
+        //prepare 2nd line upper sign
+        Pel* srcLineBelow = srcLine + srcStride;
+        for (x=startX-1; x<endX; x++)
+        {
+          signUpLine[x] = (Char)m_sign[srcLineBelow[x] - srcLine[x+1]];
+        }
+
+
+        //first line
+        Pel* srcLineAbove = srcLine - srcStride;
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        firstLineStartX = (!isCalculatePreDeblockSamples) ? (isAboveAvail ? startX : endX)
+                                                          : startX
+                                                          ;
+        firstLineEndX   = (!isCalculatePreDeblockSamples) ? ((!isRightAvail && isAboveRightAvail) ? width : endX)
+                                                          : endX
+                                                          ;
+#else
+        firstLineStartX = isAboveAvail ? startX : endX;
+        firstLineEndX   = (!isRightAvail && isAboveRightAvail) ? width : endX;
+#endif
+        for(x=firstLineStartX; x<firstLineEndX; x++)
+        {
+          edgeType = m_sign[srcLine[x] - srcLineAbove[x+1]] - signUpLine[x-1];
+          diff [edgeType] += (orgLine[x] - srcLine[x]);
+          count[edgeType] ++;
+        }
+
+        srcLine += srcStride;
+        orgLine += orgStride;
+
+        //middle lines
+        for (y=1; y<endY; y++)
+        {
+          srcLineBelow = srcLine + srcStride;
+
+          for(x=startX; x<endX; x++)
+          {
+            signDown = (Char)m_sign[srcLine[x] - srcLineBelow[x-1]] ;
+            edgeType = signDown + signUpLine[x];
+
+            diff [edgeType] += (orgLine[x] - srcLine[x]);
+            count[edgeType] ++;
+
+            signUpLine[x-1] = -signDown; 
+          }
+          signUpLine[endX-1] = (Char)m_sign[srcLineBelow[endX-1] - srcLine[endX]];
+          srcLine  += srcStride;
+          orgLine  += orgStride;
+        }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        if(isCalculatePreDeblockSamples)
+        {
+          if(isBelowAvail)
+          {
+            startX = isLeftAvail  ? 0     : 1 ;
+            endX   = isRightAvail ? width : (width -1);
+
+            for(y=0; y<skipLinesB[typeIdx]; y++)
+            {
+              srcLineBelow = srcLine + srcStride;
+              srcLineAbove = srcLine - srcStride;
+
+              for (x=startX; x<endX; x++)
+              {
+                edgeType = m_sign[srcLine[x] - srcLineBelow[x-1]] + m_sign[srcLine[x] - srcLineAbove[x+1]];
+                diff [edgeType] += (orgLine[x] - srcLine[x]);
+                count[edgeType] ++;
+              }
+              srcLine  += srcStride;
+              orgLine  += orgStride;
+            }
+          }
+        }
+#endif
+      }
+      break;
+    case SAO_TYPE_BO:
+      {
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        startX = (!isCalculatePreDeblockSamples)?0
+                                                :( isRightAvail?(width- skipLinesR[typeIdx]):width)
+                                                ;
+        endX   = (!isCalculatePreDeblockSamples)?(isRightAvail ? (width - skipLinesR[typeIdx]) : width )
+                                                :width
+                                                ;
+#else
+        endX = isRightAvail ? (width- skipLinesR[typeIdx]) : width;
+#endif
+        endY = isBelowAvail ? (height- skipLinesB[typeIdx]) : height;
+        Int shiftBits = ((compIdx == SAO_Y)?g_bitDepthY:g_bitDepthC)- NUM_SAO_BO_CLASSES_LOG2;
+        for (y=0; y< endY; y++)
+        {
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+          for (x=startX; x< endX; x++)
+#else
+          for (x=0; x< endX; x++)
+#endif
+          {
+
+            Int bandIdx= srcLine[x] >> shiftBits; 
+            diff [bandIdx] += (orgLine[x] - srcLine[x]);
+            count[bandIdx] ++;
+          }
+          srcLine += srcStride;
+          orgLine += orgStride;
+        }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        if(isCalculatePreDeblockSamples)
+        {
+          if(isBelowAvail)
+          {
+            startX = 0;
+            endX   = width;
+
+            for(y= 0; y< skipLinesB[typeIdx]; y++)
+            {
+              for (x=startX; x< endX; x++)
+              {
+                Int bandIdx= srcLine[x] >> shiftBits; 
+                diff [bandIdx] += (orgLine[x] - srcLine[x]);
+                count[bandIdx] ++;
+              }
+              srcLine  += srcStride;
+              orgLine  += orgStride;
+
+            }
+
+          }
+        }
+#endif
+      }
+      break;
+    default:
+      {
+        printf("Not a supported SAO types\n");
+        assert(0);
+        exit(-1);
+      }
+    }
+  }
+}
+
+#else
+
+
+
 TEncSampleAdaptiveOffset::TEncSampleAdaptiveOffset()
 {
@@ -1661,5 +2924,4 @@
 }
 
-#if SAO_CHROMA_LAMBDA 
 /** Sample adaptive offset process
  * \param pcSaoParam
@@ -1671,10 +2933,4 @@
 #else
 Void TEncSampleAdaptiveOffset::SAOProcess(SAOParam *pcSaoParam, Double dLambdaLuma, Double dLambdaChroma)
-#endif
-#else
-/** Sample adaptive offset process
- * \param dLambda
- */
-Void TEncSampleAdaptiveOffset::SAOProcess(SAOParam *pcSaoParam, Double dLambda)
 #endif
 {
@@ -2501,3 +3757,5 @@
 }
 
+#endif
+
 //! \}
Index: trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h	(revision 499)
+++ trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h	(revision 540)
@@ -53,4 +53,112 @@
 // Class definition
 // ====================================================================================================================
+
+#if HM_CLEANUP_SAO
+enum SAOCabacStateLablesRDO //CABAC state labels
+{
+  SAO_CABACSTATE_PIC_INIT =0,
+  SAO_CABACSTATE_BLK_CUR,
+  SAO_CABACSTATE_BLK_NEXT,
+  SAO_CABACSTATE_BLK_MID,
+  SAO_CABACSTATE_BLK_TEMP,
+  NUM_SAO_CABACSTATE_LABELS
+};
+
+struct SAOStatData //data structure for SAO statistics
+{
+  Int64 diff[MAX_NUM_SAO_CLASSES];
+  Int64 count[MAX_NUM_SAO_CLASSES];
+
+  SAOStatData(){}
+  ~SAOStatData(){}
+  Void reset()
+  {
+    ::memset(diff, 0, sizeof(Int64)*MAX_NUM_SAO_CLASSES);
+    ::memset(count, 0, sizeof(Int64)*MAX_NUM_SAO_CLASSES);
+  }
+  const SAOStatData& operator=(const SAOStatData& src)
+  {
+    ::memcpy(diff, src.diff, sizeof(Int64)*MAX_NUM_SAO_CLASSES);
+    ::memcpy(count, src.count, sizeof(Int64)*MAX_NUM_SAO_CLASSES);
+    return *this;
+  }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  const SAOStatData& operator+= (const SAOStatData& src)
+  {
+    for(Int i=0; i< MAX_NUM_SAO_CLASSES; i++)
+    {
+      diff[i] += src.diff[i];
+      count[i] += src.count[i];
+    }
+    return *this;
+  }
+#endif
+};
+
+class TEncSampleAdaptiveOffset : public TComSampleAdaptiveOffset
+{
+public:
+  TEncSampleAdaptiveOffset();
+  virtual ~TEncSampleAdaptiveOffset();
+
+  //interface
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  Void createEncData(Bool isPreDBFSamplesUsed);
+#else
+  Void createEncData();
+#endif
+  Void destroyEncData();
+  Void initRDOCabacCoder(TEncSbac* pcRDGoOnSbacCoder, TComSlice* pcSlice) ;
+  Void SAOProcess(TComPic* pPic, Bool* sliceEnabled, const Double *lambdas
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                , Bool isPreDBFSamplesUsed
+#endif
+                ); 
+public: //methods
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  Void getPreDBFStatistics(TComPic* pPic); 
+#endif
+private: //methods
+  Void getStatistics(SAOStatData*** blkStats, TComPicYuv* orgYuv, TComPicYuv* srcYuv,TComPic* pPic
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                   , Bool isCalculatePreDeblockSamples = false
+#endif
+                   );
+  Void decidePicParams(Bool* sliceEnabled, Int picTempLayer);
+  Void decideBlkParams(TComPic* pic, Bool* sliceEnabled, SAOStatData*** blkStats, TComPicYuv* srcYuv, TComPicYuv* resYuv, SAOBlkParam* reconParams, SAOBlkParam* codedParams);
+  Void getBlkStats(Int compIdx, SAOStatData* statsDataTypes, Pel* srcBlk, Pel* orgBlk, Int srcStride, Int orgStride, Int width, Int height, Bool isLeftAvail,  Bool isRightAvail, Bool isAboveAvail, Bool isBelowAvail, Bool isAboveLeftAvail, Bool isAboveRightAvail, Bool isBelowLeftAvail, Bool isBelowRightAvail
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                  , Bool isCalculatePreDeblockSamples
+#endif
+                  );
+  Void deriveModeNewRDO(Int ctu, std::vector<SAOBlkParam*>& mergeList, Bool* sliceEnabled, SAOStatData*** blkStats, SAOBlkParam& modeParam, Double& modeNormCost, TEncSbac** cabacCoderRDO, Int inCabacLabel);
+  Void deriveModeMergeRDO(Int ctu, std::vector<SAOBlkParam*>& mergeList, Bool* sliceEnabled, SAOStatData*** blkStats, SAOBlkParam& modeParam, Double& modeNormCost, TEncSbac** cabacCoderRDO, Int inCabacLabel);
+  Int64 getDistortion(Int ctu, Int compIdx, Int typeIdc, Int typeAuxInfo, Int* offsetVal, SAOStatData& statData);
+  Void deriveOffsets(Int ctu, Int compIdx, Int typeIdc, SAOStatData& statData, Int* quantOffsets, Int& typeAuxInfo);
+  inline Int64 estSaoDist(Int64 count, Int64 offset, Int64 diffSum, Int shift);
+  inline Int estIterOffset(Int typeIdx, Int classIdx, Double lambda, Int offsetInput, Int64 count, Int64 diffSum, Int shift, Int bitIncrease, Int64& bestDist, Double& bestCost, Int offsetTh );
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  Void addPreDBFStatistics(SAOStatData*** blkStats);
+#endif
+private: //members
+  //for RDO
+  TEncSbac**             m_pppcRDSbacCoder;           
+  TEncSbac*              m_pcRDGoOnSbacCoder;
+  TEncBinCABACCounter**  m_pppcBinCoderCABAC;    
+  Double                 m_labmda[NUM_SAO_COMPONENTS];
+
+  //statistics
+  SAOStatData***         m_statData; //[ctu][comp][classes]
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  SAOStatData***         m_preDBFstatData;
+#endif
+#if SAO_ENCODING_CHOICE
+  Double                 m_saoDisabledRate[NUM_SAO_COMPONENTS][MAX_TLAYER];
+#endif
+  Int                    m_skipLinesR[NUM_SAO_COMPONENTS][NUM_SAO_NEW_TYPES];
+  Int                    m_skipLinesB[NUM_SAO_COMPONENTS][NUM_SAO_NEW_TYPES];
+};
+#else
+
 
 class TEncSampleAdaptiveOffset : public TComSampleAdaptiveOffset
@@ -95,12 +203,8 @@
   Void endSaoEnc();
   Void resetStats();
-#if SAO_CHROMA_LAMBDA
 #if SAO_ENCODING_CHOICE
   Void SAOProcess(SAOParam *pcSaoParam, Double dLambda, Double dLambdaChroma, Int depth);
 #else
   Void SAOProcess(SAOParam *pcSaoParam, Double dLambda, Double dLambdaChroma);
-#endif
-#else
-  Void SAOProcess(SAOParam *pcSaoParam, Double dLambda);
 #endif
 
@@ -131,5 +235,5 @@
   Int  getMaxNumOffsetsPerPic() {return m_maxNumOffsetsPerPic; }
 };
-
+#endif
 //! \}
 
Index: trunk/source/Lib/TLibEncoder/TEncSbac.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSbac.cpp	(revision 499)
+++ trunk/source/Lib/TLibEncoder/TEncSbac.cpp	(revision 540)
@@ -416,5 +416,4 @@
 {
   PartSize eSize         = pcCU->getPartitionSize( uiAbsPartIdx );
-
   if ( pcCU->isIntra( uiAbsPartIdx ) )
   {
@@ -1394,5 +1393,9 @@
   {
     m_pcBinIf->encodeBin( 1, m_cSaoTypeIdxSCModel.get( 0, 0, 0 ) );
+#if HM_CLEANUP_SAO
+    m_pcBinIf->encodeBinEP( uiCode == 1 ? 0 : 1 );
+#else
     m_pcBinIf->encodeBinEP( uiCode <= 4 ? 1 : 0 );
+#endif
   }
 }
@@ -1597,3 +1600,118 @@
 }
 
+#if HM_CLEANUP_SAO
+Void TEncSbac::codeSAOOffsetParam(Int compIdx, SAOOffset& ctbParam, Bool sliceEnabled)
+{
+  UInt uiSymbol;
+  if(!sliceEnabled)
+  {
+    assert(ctbParam.modeIdc == SAO_MODE_OFF);
+    return;
+  }
+
+  //type
+  if(compIdx == SAO_Y || compIdx == SAO_Cb)
+  {
+    //sao_type_idx_luma or sao_type_idx_chroma
+    if(ctbParam.modeIdc == SAO_MODE_OFF)
+    {
+      uiSymbol =0;
+    }
+    else if(ctbParam.typeIdc == SAO_TYPE_BO) //BO
+    {
+      uiSymbol = 1;
+    }
+    else
+    {
+      assert(ctbParam.typeIdc < SAO_TYPE_START_BO); //EO
+      uiSymbol = 2;
+    }
+    codeSaoTypeIdx(uiSymbol); 
+  }
+
+  if(ctbParam.modeIdc == SAO_MODE_NEW)
+  {
+    Int numClasses = (ctbParam.typeIdc == SAO_TYPE_BO)?4:NUM_SAO_EO_CLASSES; 
+    Int offset[4];
+    Int k=0;
+    for(Int i=0; i< numClasses; i++)
+    {
+      if(ctbParam.typeIdc != SAO_TYPE_BO && i == SAO_CLASS_EO_PLAIN)
+      {
+        continue;
+      }
+      Int classIdx = (ctbParam.typeIdc == SAO_TYPE_BO)?(  (ctbParam.typeAuxInfo+i)% NUM_SAO_BO_CLASSES   ):i;
+      offset[k] = ctbParam.offset[classIdx];
+      k++;
+    }
+
+    for(Int i=0; i< 4; i++)
+    {
+      codeSaoMaxUvlc((offset[i]<0)?(-offset[i]):(offset[i]),  g_saoMaxOffsetQVal[compIdx] ); //sao_offset_abs
+    }
+
+
+    if(ctbParam.typeIdc == SAO_TYPE_BO)
+    {
+      for(Int i=0; i< 4; i++)
+      {
+        if(offset[i] != 0)
+        {
+          codeSAOSign((offset[i]< 0)?1:0);
+        }
+      }
+
+      codeSaoUflc(NUM_SAO_BO_CLASSES_LOG2, ctbParam.typeAuxInfo ); //sao_band_position
+    }
+    else //EO
+    {
+      if(compIdx == SAO_Y || compIdx == SAO_Cb)
+      {
+        assert(ctbParam.typeIdc - SAO_TYPE_START_EO >=0);
+        codeSaoUflc(NUM_SAO_EO_TYPES_LOG2, ctbParam.typeIdc - SAO_TYPE_START_EO ); //sao_eo_class_luma or sao_eo_class_chroma
+      }
+    }
+
+  }
+}
+
+
+Void TEncSbac::codeSAOBlkParam(SAOBlkParam& saoBlkParam
+                              , Bool* sliceEnabled
+                              , Bool leftMergeAvail
+                              , Bool aboveMergeAvail
+                              , Bool onlyEstMergeInfo // = false
+                              )
+{
+
+  Bool isLeftMerge = false;
+  Bool isAboveMerge= false;
+
+  if(leftMergeAvail)
+  {
+    isLeftMerge = ((saoBlkParam[SAO_Y].modeIdc == SAO_MODE_MERGE) && (saoBlkParam[SAO_Y].typeIdc == SAO_MERGE_LEFT));
+    codeSaoMerge( isLeftMerge?1:0  ); //sao_merge_left_flag
+  }
+
+  if( aboveMergeAvail && !isLeftMerge)
+  {
+    isAboveMerge = ((saoBlkParam[SAO_Y].modeIdc == SAO_MODE_MERGE) && (saoBlkParam[SAO_Y].typeIdc == SAO_MERGE_ABOVE)); 
+    codeSaoMerge( isAboveMerge?1:0  ); //sao_merge_left_flag
+  }
+
+  if(onlyEstMergeInfo)
+  {
+    return; //only for RDO
+  }
+
+  if(!isLeftMerge && !isAboveMerge) //not merge mode
+  {
+    for(Int compIdx=0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
+    {
+      codeSAOOffsetParam(compIdx, saoBlkParam[compIdx], sliceEnabled[compIdx]);
+    }
+  }
+}
+#endif
+
 //! \}
Index: trunk/source/Lib/TLibEncoder/TEncSbac.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSbac.h	(revision 499)
+++ trunk/source/Lib/TLibEncoder/TEncSbac.h	(revision 540)
@@ -103,4 +103,14 @@
   Void  codeSAOSign       ( UInt  uiCode);  //<! code SAO offset sign
   Void  codeScalingList      ( TComScalingList* /*scalingList*/     ){ assert (0);  return;};
+
+#if HM_CLEANUP_SAO
+  Void codeSAOOffsetParam(Int compIdx, SAOOffset& ctbParam, Bool sliceEnabled);
+  Void codeSAOBlkParam(SAOBlkParam& saoBlkParam
+                    , Bool* sliceEnabled
+                    , Bool leftMergeAvail
+                    , Bool aboveMergeAvail
+                    , Bool onlyEstMergeInfo = false
+                    );
+#endif
 
 private:
Index: trunk/source/Lib/TLibEncoder/TEncSearch.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSearch.cpp	(revision 499)
+++ trunk/source/Lib/TLibEncoder/TEncSearch.cpp	(revision 540)
@@ -720,9 +720,5 @@
   Pel*  piRefPos;
   Int iRefStride = m_filteredBlock[0][0].getStride();
-#if NS_HAD
-  m_pcRdCost->setDistParam( pcPatternKey, m_filteredBlock[0][0].getLumaAddr(), iRefStride, 1, m_cDistParam, m_pcEncCfg->getUseHADME(), m_pcEncCfg->getUseNSQT() );
-#else
   m_pcRdCost->setDistParam( pcPatternKey, m_filteredBlock[0][0].getLumaAddr(), iRefStride, 1, m_cDistParam, m_pcEncCfg->getUseHADME() );
-#endif
   
   const TComMv* pcMvRefine = (iFrac == 2 ? s_acMvRefineH : s_acMvRefineQ);
@@ -737,7 +733,11 @@
     piRefPos = m_filteredBlock[ verVal & 3 ][ horVal & 3 ].getLumaAddr();
     if ( horVal == 2 && ( verVal & 1 ) == 0 )
+    {
       piRefPos += 1;
+    }
     if ( ( horVal & 1 ) == 0 && verVal == 2 )
+    {
       piRefPos += iRefStride;
+    }
     cMvTest = pcMvRefine[i];
     cMvTest += rcMvFrac;
@@ -774,28 +774,26 @@
   UInt  uiLog2TrafoSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth()] + 2 - uiFullDepth;
 
-  {
-    if( pcCU->getPredictionMode(0) == MODE_INTRA && pcCU->getPartitionSize(0) == SIZE_NxN && uiTrDepth == 0 )
-    {
-      assert( uiSubdiv );
-    }
-    else if( uiLog2TrafoSize > pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() )
-    {
-      assert( uiSubdiv );
-    }
-    else if( uiLog2TrafoSize == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
-    {
-      assert( !uiSubdiv );
-    }
-    else if( uiLog2TrafoSize == pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
-    {
-      assert( !uiSubdiv );
-    }
-    else
-    {
-      assert( uiLog2TrafoSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) );
-      if( bLuma )
-      {
-        m_pcEntropyCoder->encodeTransformSubdivFlag( uiSubdiv, 5 - uiLog2TrafoSize );
-      }
+  if( pcCU->getPredictionMode(0) == MODE_INTRA && pcCU->getPartitionSize(0) == SIZE_NxN && uiTrDepth == 0 )
+  {
+    assert( uiSubdiv );
+  }
+  else if( uiLog2TrafoSize > pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() )
+  {
+    assert( uiSubdiv );
+  }
+  else if( uiLog2TrafoSize == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+  {
+    assert( !uiSubdiv );
+  }
+  else if( uiLog2TrafoSize == pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
+  {
+    assert( !uiSubdiv );
+  }
+  else
+  {
+    assert( uiLog2TrafoSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) );
+    if( bLuma )
+    {
+      m_pcEntropyCoder->encodeTransformSubdivFlag( uiSubdiv, 5 - uiLog2TrafoSize );
     }
   }
@@ -806,7 +804,11 @@
     {
       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 );
+      }
     }
   }
@@ -822,10 +824,8 @@
   }
   
-  {
-    //===== Cbfs =====
-    if( bLuma )
-    {
-      m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
-    }
+  //===== Cbfs =====
+  if( bLuma )
+  {
+    m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
   }
 }
@@ -944,5 +944,4 @@
     }
   }
-
   if( bChroma )
   {
@@ -1306,5 +1305,5 @@
 
 #if RDOQ_CHROMA_LAMBDA 
-    m_pcTrQuant->selectLambda      (TEXT_CHROMA);  
+    m_pcTrQuant->selectLambda(eText);
 #endif
     m_pcTrQuant->transformNxN      ( pcCU, piResi, uiStride, pcCoeff, 
@@ -1358,9 +1357,5 @@
   
   //===== update distortion =====
-#if WEIGHTED_CHROMA_DISTORTION
   ruiDist += m_pcRdCost->getDistPart(g_bitDepthC, piReco, uiStride, piOrg, uiStride, uiWidth, uiHeight, eText );
-#else
-  ruiDist += m_pcRdCost->getDistPart(g_bitDepthC, piReco, uiStride, piOrg, uiStride, uiWidth, uiHeight );
-#endif
 }
 
@@ -2539,5 +2534,4 @@
       
       for( Int j=0; j < numCand; j++)
-
       {
         Bool mostProbableModeIncluded = false;
@@ -3039,9 +3033,5 @@
                             pcYuvOrg->getLumaAddr( uiAbsPartIdx ), pcYuvOrg->getStride(), 
                             m_tmpYuvPred .getLumaAddr( uiAbsPartIdx ), m_tmpYuvPred .getStride(), 
-#if NS_HAD
-                            iWidth, iHeight, m_pcEncCfg->getUseHADME(), m_pcEncCfg->getUseNSQT() );
-#else
                             iWidth, iHeight, m_pcEncCfg->getUseHADME() );
-#endif
   ruiErr = cDistParam.DistFunc( &cDistParam );
 }
@@ -3246,5 +3236,8 @@
 
     UInt          uiCostTempL0[MAX_NUM_REF];
-    for (Int iNumRef=0; iNumRef < MAX_NUM_REF; iNumRef++) uiCostTempL0[iNumRef] = MAX_UINT;
+    for (Int iNumRef=0; iNumRef < MAX_NUM_REF; iNumRef++)
+    {
+      uiCostTempL0[iNumRef] = MAX_UINT;
+    }
     UInt          uiBitsTempL0[MAX_NUM_REF];
 
@@ -3716,18 +3709,14 @@
     {
       uiLastMode = 2;
-      {
-            pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMv( cMvBi[0], ePartSize, uiPartAddr, 0, iPartIdx );
-            pcCU->getCUMvField(REF_PIC_LIST_0)->setAllRefIdx( iRefIdxBi[0], ePartSize, uiPartAddr, 0, iPartIdx );
-            pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMv( cMvBi[1], ePartSize, uiPartAddr, 0, iPartIdx );
-            pcCU->getCUMvField(REF_PIC_LIST_1)->setAllRefIdx( iRefIdxBi[1], ePartSize, uiPartAddr, 0, iPartIdx );
-      }
-      {
-        TempMv = cMvBi[0] - cMvPredBi[0][iRefIdxBi[0]];
-            pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
-      }
-      {
-        TempMv = cMvBi[1] - cMvPredBi[1][iRefIdxBi[1]];
-            pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
-      }
+      pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMv( cMvBi[0], ePartSize, uiPartAddr, 0, iPartIdx );
+      pcCU->getCUMvField(REF_PIC_LIST_0)->setAllRefIdx( iRefIdxBi[0], ePartSize, uiPartAddr, 0, iPartIdx );
+      pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMv( cMvBi[1], ePartSize, uiPartAddr, 0, iPartIdx );
+      pcCU->getCUMvField(REF_PIC_LIST_1)->setAllRefIdx( iRefIdxBi[1], ePartSize, uiPartAddr, 0, iPartIdx );
+      
+      TempMv = cMvBi[0] - cMvPredBi[0][iRefIdxBi[0]];
+      pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
+      
+      TempMv = cMvBi[1] - cMvPredBi[1][iRefIdxBi[1]];
+      pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
       
       pcCU->setInterDirSubParts( 3, uiPartAddr, iPartIdx, pcCU->getDepth(0) );
@@ -3743,10 +3732,8 @@
     {
       uiLastMode = 0;
-          pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMv( cMv[0], ePartSize, uiPartAddr, 0, iPartIdx );
-          pcCU->getCUMvField(REF_PIC_LIST_0)->setAllRefIdx( iRefIdx[0], ePartSize, uiPartAddr, 0, iPartIdx );
-      {
-        TempMv = cMv[0] - cMvPred[0][iRefIdx[0]];
-            pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
-      }
+      pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMv( cMv[0], ePartSize, uiPartAddr, 0, iPartIdx );
+      pcCU->getCUMvField(REF_PIC_LIST_0)->setAllRefIdx( iRefIdx[0], ePartSize, uiPartAddr, 0, iPartIdx );
+      TempMv = cMv[0] - cMvPred[0][iRefIdx[0]];
+      pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
       pcCU->setInterDirSubParts( 1, uiPartAddr, iPartIdx, pcCU->getDepth(0) );
       
@@ -3759,10 +3746,8 @@
     {
       uiLastMode = 1;
-          pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMv( cMv[1], ePartSize, uiPartAddr, 0, iPartIdx );
-          pcCU->getCUMvField(REF_PIC_LIST_1)->setAllRefIdx( iRefIdx[1], ePartSize, uiPartAddr, 0, iPartIdx );
-      {
-        TempMv = cMv[1] - cMvPred[1][iRefIdx[1]];
-            pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
-      }
+      pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMv( cMv[1], ePartSize, uiPartAddr, 0, iPartIdx );
+      pcCU->getCUMvField(REF_PIC_LIST_1)->setAllRefIdx( iRefIdx[1], ePartSize, uiPartAddr, 0, iPartIdx );
+      TempMv = cMv[1] - cMvPred[1][iRefIdx[1]];
+      pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
       pcCU->setInterDirSubParts( 2, uiPartAddr, iPartIdx, pcCU->getDepth(0) );
       
@@ -3816,8 +3801,6 @@
         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], ePartSize, uiPartAddr, 0, iPartIdx );
-          pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMRGMvField[1], ePartSize, uiPartAddr, 0, iPartIdx );
-        }
+        pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( cMRGMvField[0], ePartSize, uiPartAddr, 0, iPartIdx );
+        pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMRGMvField[1], ePartSize, uiPartAddr, 0, iPartIdx );
 
         pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvd    ( cMvZero,            ePartSize, uiPartAddr, 0, iPartIdx );
@@ -3834,8 +3817,6 @@
         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], ePartSize, uiPartAddr, 0, iPartIdx );
-          pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMEMvField[1], ePartSize, uiPartAddr, 0, iPartIdx );
-        }
+        pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( cMEMvField[0], ePartSize, uiPartAddr, 0, iPartIdx );
+        pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMEMvField[1], ePartSize, uiPartAddr, 0, iPartIdx );
       }
     }
@@ -3944,5 +3925,7 @@
   
   if (iNum == 1)
+  {
     return 0;
+  }
   
   UInt uiLength = 1;
@@ -4123,17 +4106,9 @@
                             pcOrgYuv->getLumaAddr(uiPartAddr), pcOrgYuv->getStride(), 
                             pcTemplateCand->getLumaAddr(uiPartAddr), pcTemplateCand->getStride(), 
-#if NS_HAD
-                            iSizeX, iSizeY, m_pcEncCfg->getUseHADME(), m_pcEncCfg->getUseNSQT() );
-#else
                             iSizeX, iSizeY, m_pcEncCfg->getUseHADME() );
-#endif
   ruiDist = cDistParam.DistFunc( &cDistParam );
   uiCost = ruiDist + m_pcRdCost->getCost( m_auiMVPIdxCost[iMVPIdx][iMVPNum] );
 #else
-#if WEIGHTED_CHROMA_DISTORTION
   uiCost = m_pcRdCost->getDistPart(g_bitDepthY, pcTemplateCand->getLumaAddr(uiPartAddr), pcTemplateCand->getStride(), pcOrgYuv->getLumaAddr(uiPartAddr), pcOrgYuv->getStride(), iSizeX, iSizeY, TEXT_LUMA, DF_SAD );
-#else
-  uiCost = m_pcRdCost->getDistPart(g_bitDepthY, pcTemplateCand->getLumaAddr(uiPartAddr), pcTemplateCand->getStride(), pcOrgYuv->getLumaAddr(uiPartAddr), pcOrgYuv->getStride(), iSizeX, iSizeY, DF_SAD );
-#endif
   uiCost = (UInt) m_pcRdCost->calcRdCost( m_auiMVPIdxCost[iMVPIdx][iMVPNum], uiCost, false, DF_SAD );
 #endif
@@ -4228,24 +4203,18 @@
   m_pcRdCost->getMotionCost( 1, 0 );
   m_pcRdCost->setCostScale ( 1 );
-  
-  {
+
 #if REF_IDX_ME_ZEROMV
-    if( pcCU->getSlice()->getRefPic( eRefPicList, iRefIdxPred )->isILR(pcCU->getLayerId()))  //ILR reference pic
-    {
-      xPatternSearchFracDIFMv0( pcCU, pcPatternKey, piRefY, iRefStride, &rcMv, cMvHalf, cMvQter, ruiCost, bBi );
-    }
-    else    //non ILR reference pic
-    {
-      xPatternSearchFracDIF( pcCU, pcPatternKey, piRefY, iRefStride, &rcMv, cMvHalf, cMvQter, ruiCost, bBi );
-    }
+  if( pcCU->getSlice()->getRefPic( eRefPicList, iRefIdxPred )->isILR(pcCU->getLayerId()))  //ILR reference pic
+  {
+    xPatternSearchFracDIFMv0( pcCU, pcPatternKey, piRefY, iRefStride, &rcMv, cMvHalf, cMvQter, ruiCost, bBi );
+  }
+  else    //non ILR reference pic
+  {
+    xPatternSearchFracDIF( pcCU, pcPatternKey, piRefY, iRefStride, &rcMv, cMvHalf, cMvQter, ruiCost, bBi );
+  }
 #else
-    xPatternSearchFracDIF( pcCU, pcPatternKey, piRefY, iRefStride, &rcMv, cMvHalf, cMvQter, ruiCost
-                          ,bBi
-                          );
-#endif
-  }
-  
-  
-  
+  xPatternSearchFracDIF( pcCU, pcPatternKey, piRefY, iRefStride, &rcMv, cMvHalf, cMvQter, ruiCost,bBi );
+#endif
+
   m_pcRdCost->setCostScale( 0 );
   rcMv <<= 2;
@@ -4601,16 +4570,12 @@
     pcYuvPred->copyToPartYuv( rpcYuvRec, 0 );
     
-#if WEIGHTED_CHROMA_DISTORTION
     uiDistortion = m_pcRdCost->getDistPart(g_bitDepthY, rpcYuvRec->getLumaAddr(), rpcYuvRec->getStride(),  pcYuvOrg->getLumaAddr(), pcYuvOrg->getStride(),  uiWidth,      uiHeight      )
     + m_pcRdCost->getDistPart(g_bitDepthC, rpcYuvRec->getCbAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCbAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1, TEXT_CHROMA_U )
     + m_pcRdCost->getDistPart(g_bitDepthC, rpcYuvRec->getCrAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCrAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1, TEXT_CHROMA_V );
-#else
-    uiDistortion = m_pcRdCost->getDistPart(g_bitDepthY, rpcYuvRec->getLumaAddr(), rpcYuvRec->getStride(),  pcYuvOrg->getLumaAddr(), pcYuvOrg->getStride(),  uiWidth,      uiHeight      )
-    + m_pcRdCost->getDistPart(g_bitDepthC, rpcYuvRec->getCbAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCbAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1 )
-    + m_pcRdCost->getDistPart(g_bitDepthC, rpcYuvRec->getCrAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCrAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1 );
-#endif
 
     if( m_bUseSBACRD )
+    {
       m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_CURR_BEST]);
+    }
     
     m_pcEntropyCoder->resetBits();
@@ -4628,5 +4593,7 @@
     
     if( m_bUseSBACRD )
+    {
       m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_TEMP_BEST]);
+    }
     
     pcCU->setCbfSubParts( 0, 0, 0, 0, pcCU->getDepth( 0 ) );
@@ -4799,13 +4766,7 @@
   
   // update with clipped distortion and cost (qp estimation loop uses unclipped values)
-#if WEIGHTED_CHROMA_DISTORTION
     uiDistortionBest = m_pcRdCost->getDistPart(g_bitDepthY, rpcYuvRec->getLumaAddr(), rpcYuvRec->getStride(),  pcYuvOrg->getLumaAddr(), pcYuvOrg->getStride(),  uiWidth,      uiHeight      )
     + m_pcRdCost->getDistPart(g_bitDepthC, rpcYuvRec->getCbAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCbAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1, TEXT_CHROMA_U )
     + m_pcRdCost->getDistPart(g_bitDepthC, rpcYuvRec->getCrAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCrAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1, TEXT_CHROMA_V );
-#else
-  uiDistortionBest = m_pcRdCost->getDistPart(g_bitDepthY, rpcYuvRec->getLumaAddr(), rpcYuvRec->getStride(),  pcYuvOrg->getLumaAddr(), pcYuvOrg->getStride(),  uiWidth,      uiHeight      )
-  + m_pcRdCost->getDistPart(g_bitDepthC, rpcYuvRec->getCbAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCbAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1 )
-  + m_pcRdCost->getDistPart(g_bitDepthC, rpcYuvRec->getCrAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCrAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1 );
-#endif
   dCostBest = m_pcRdCost->calcRdCost( uiBitsBest, uiDistortionBest );
   
@@ -4832,7 +4793,11 @@
   Bool bCheckFull;
   if ( SplitFlag && uiDepth == pcCU->getDepth(uiAbsPartIdx) && ( uiLog2TrSize >  pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) ) )
+  {
      bCheckFull = false;
+  }
   else
+  {
      bCheckFull =  ( uiLog2TrSize <= pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() );
+  }
 
   const Bool bCheckSplit  = ( uiLog2TrSize >  pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) );
@@ -4932,5 +4897,5 @@
 
 #if RDOQ_CHROMA_LAMBDA 
-      m_pcTrQuant->selectLambda(TEXT_CHROMA); 
+      m_pcTrQuant->selectLambda(TEXT_CHROMA_U);
 #endif
 
@@ -4943,4 +4908,9 @@
       curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCrQpOffset() + pcCU->getSlice()->getSliceQpDeltaCr();
       m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
+      
+#if RDOQ_CHROMA_LAMBDA
+      m_pcTrQuant->selectLambda(TEXT_CHROMA_V);
+#endif
+
       m_pcTrQuant->transformNxN( pcCU, pcResi->getCrAddr(absTUPartIdxC), pcResi->getCStride(), pcCoeffCurrV, 
 #if ADAPTIVE_QP_SELECTION
@@ -4955,8 +4925,6 @@
     m_pcEntropyCoder->resetBits();
     
-    {
-      m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
-    }
-    
+    m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
+
     m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrY, uiAbsPartIdx,  trWidth,  trHeight,    uiDepth, TEXT_LUMA );
     const UInt uiSingleBitsY = m_pcEntropyCoder->getNumberOfWrittenBits();
@@ -4966,13 +4934,9 @@
     if( bCodeChroma )
     {
-      {
-        m_pcEntropyCoder->encodeQtCbf   ( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrMode );
-      }
+      m_pcEntropyCoder->encodeQtCbf   ( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrMode );
       m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrU, uiAbsPartIdx, trWidthC, trHeightC, uiDepth, TEXT_CHROMA_U );
       uiSingleBitsU = m_pcEntropyCoder->getNumberOfWrittenBits() - uiSingleBitsY;
       
-      {
-        m_pcEntropyCoder->encodeQtCbf   ( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrMode );
-      }
+      m_pcEntropyCoder->encodeQtCbf   ( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrMode );
       m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrV, uiAbsPartIdx, trWidthC, trHeightC, uiDepth, TEXT_CHROMA_V );
       uiSingleBitsV = m_pcEntropyCoder->getNumberOfWrittenBits() - ( uiSingleBitsY + uiSingleBitsU );
@@ -5003,4 +4967,5 @@
       assert(scalingListType < 6);     
       m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_LUMA,REG_DCT, pcResiCurrY, m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(),  pcCoeffCurrY, trWidth, trHeight, scalingListType );//this is for inter mode only
+      
       const UInt uiNonzeroDistY = m_pcRdCost->getDistPart(g_bitDepthY, m_pcQTTempTComYuv[uiQTTempAccessLayer].getLumaAddr( absTUPartIdx ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(),
       pcResi->getLumaAddr( absTUPartIdx ), pcResi->getStride(), trWidth,trHeight );
@@ -5059,7 +5024,5 @@
     {
       uiDistU = m_pcRdCost->getDistPart(g_bitDepthC, m_pTempPel, trWidthC, pcResi->getCbAddr( absTUPartIdxC ), pcResi->getCStride(), trWidthC, trHeightC
-#if WEIGHTED_CHROMA_DISTORTION
                                         , TEXT_CHROMA_U
-#endif
                                         ); // initialized with zero residual destortion
       if ( puiZeroDist )
@@ -5080,7 +5043,5 @@
         const UInt uiNonzeroDistU = m_pcRdCost->getDistPart(g_bitDepthC, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCbAddr( absTUPartIdxC), m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(),
                                                             pcResi->getCbAddr( absTUPartIdxC), pcResi->getCStride(), trWidthC, trHeightC
-#if WEIGHTED_CHROMA_DISTORTION
                                                             , TEXT_CHROMA_U
-#endif
                                                             );
 
@@ -5118,5 +5079,5 @@
       {
         m_pcEntropyCoder->resetBits();
-        m_pcEntropyCoder->encodeQtCbfZero( pcCU, TEXT_CHROMA_U, uiTrModeC );
+        m_pcEntropyCoder->encodeQtCbfZero( pcCU, TEXT_CHROMA_U, uiTrMode );
         const UInt uiNullBitsU = m_pcEntropyCoder->getNumberOfWrittenBits();
         minCostU = m_pcRdCost->calcRdCost( uiNullBitsU, uiDistU );
@@ -5134,7 +5095,5 @@
       
       uiDistV = m_pcRdCost->getDistPart(g_bitDepthC, m_pTempPel, trWidthC, pcResi->getCrAddr( absTUPartIdxC), pcResi->getCStride(), trWidthC, trHeightC
-#if WEIGHTED_CHROMA_DISTORTION
                                         , TEXT_CHROMA_V
-#endif
                                         ); // initialized with zero residual destortion
       if ( puiZeroDist )
@@ -5154,7 +5113,5 @@
         const UInt uiNonzeroDistV = m_pcRdCost->getDistPart(g_bitDepthC, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCrAddr( absTUPartIdxC ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(),
                                                             pcResi->getCrAddr( absTUPartIdxC ), pcResi->getCStride(), trWidthC, trHeightC
-#if WEIGHTED_CHROMA_DISTORTION
                                                             , TEXT_CHROMA_V
-#endif
                                                             );
         if (pcCU->isLosslessCoded(0)) 
@@ -5191,5 +5148,5 @@
       {
         m_pcEntropyCoder->resetBits();
-        m_pcEntropyCoder->encodeQtCbfZero( pcCU, TEXT_CHROMA_V, uiTrModeC );
+        m_pcEntropyCoder->encodeQtCbfZero( pcCU, TEXT_CHROMA_V, uiTrMode );
         const UInt uiNullBitsV = m_pcEntropyCoder->getNumberOfWrittenBits();
         minCostV = m_pcRdCost->calcRdCost( uiNullBitsV, uiDistV );
@@ -5352,5 +5309,5 @@
 
 #if RDOQ_CHROMA_LAMBDA 
-      m_pcTrQuant->selectLambda(TEXT_CHROMA); 
+      m_pcTrQuant->selectLambda(TEXT_CHROMA_U);
 #endif
 
@@ -5362,4 +5319,7 @@
       curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCrQpOffset() + pcCU->getSlice()->getSliceQpDeltaCr();
       m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
+#if RDOQ_CHROMA_LAMBDA
+      m_pcTrQuant->selectLambda(TEXT_CHROMA_V);
+#endif
       m_pcTrQuant->transformNxN( pcCU, pcResi->getCrAddr(absTUPartIdxC), pcResi->getCStride(), pcCoeffCurrV, 
 #if ADAPTIVE_QP_SELECTION
@@ -5391,7 +5351,5 @@
         uiNonzeroDistU = m_pcRdCost->getDistPart(g_bitDepthC, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCbAddr( absTUPartIdxC), m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(),
                                                  pcResi->getCbAddr( absTUPartIdxC), pcResi->getCStride(), trWidthC, trHeightC
-#if WEIGHTED_CHROMA_DISTORTION
                                                  , TEXT_CHROMA_U
-#endif
                                                  );
 
@@ -5435,7 +5393,5 @@
         uiNonzeroDistV = m_pcRdCost->getDistPart(g_bitDepthC, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCrAddr( absTUPartIdxC ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(),
                                                  pcResi->getCrAddr( absTUPartIdxC ), pcResi->getCStride(), trWidthC, trHeightC
-#if WEIGHTED_CHROMA_DISTORTION
                                                  , TEXT_CHROMA_V
-#endif
                                                  );
 
@@ -5474,20 +5430,16 @@
     m_pcEntropyCoder->resetBits();
 
-    {
-      if( uiLog2TrSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
-      {
-        m_pcEntropyCoder->encodeTransformSubdivFlag( 0, 5 - uiLog2TrSize );
-      }
-    }
-
-    {
-      if( bCodeChroma )
-      {
-        m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrMode );
-        m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrMode );
-      }
-
-      m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
-    }
+    if( uiLog2TrSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
+    {
+      m_pcEntropyCoder->encodeTransformSubdivFlag( 0, 5 - uiLog2TrSize );
+    }
+
+    if( bCodeChroma )
+    {
+      m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrMode );
+      m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrMode );
+    }
+
+    m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
 
     m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrY, uiAbsPartIdx, trWidth, trHeight,    uiDepth, TEXT_LUMA );
@@ -5546,11 +5498,9 @@
     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 );
-    }
-    
+    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();
     dSubdivCost  = m_pcRdCost->calcRdCost( uiSubdivBits, uiSubdivDist );
@@ -5602,13 +5552,10 @@
   const UInt uiLog2TrSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiDepth]+2;
 
-  {
-    if( bSubdivAndCbf && uiLog2TrSize <= pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() && uiLog2TrSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
-    {
-      m_pcEntropyCoder->encodeTransformSubdivFlag( bSubdiv, 5 - uiLog2TrSize );
-    }
-  }
-
-  {
-    assert( pcCU->getPredictionMode(uiAbsPartIdx) != MODE_INTRA );
+  if( bSubdivAndCbf && uiLog2TrSize <= pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() && uiLog2TrSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
+  {
+    m_pcEntropyCoder->encodeTransformSubdivFlag( bSubdiv, 5 - uiLog2TrSize );
+  }
+
+  assert( pcCU->getPredictionMode(uiAbsPartIdx) != MODE_INTRA );
     if( bSubdivAndCbf )
     {
@@ -5631,5 +5578,4 @@
       }
     }
-  }
   
   if( !bSubdiv )
@@ -5655,7 +5601,5 @@
     if( bSubdivAndCbf )
     {
-      {
-        m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
-      }
+      m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
     }
     else
@@ -5725,7 +5669,5 @@
       if( bCodeChroma )
       {
-        {
-          m_pcQTTempTComYuv[uiQTTempAccessLayer].copyPartToPartChroma( pcResi, uiAbsPartIdx, 1 << uiLog2TrSizeC, 1 << uiLog2TrSizeC );
-        }
+        m_pcQTTempTComYuv[uiQTTempAccessLayer].copyPartToPartChroma( pcResi, uiAbsPartIdx, 1 << uiLog2TrSizeC, 1 << uiLog2TrSizeC );
       }
     }
@@ -5847,5 +5789,4 @@
     m_pcEntropyCoder->encodePartSize( pcCU, 0, pcCU->getDepth(0), true );
     m_pcEntropyCoder->encodePredInfo( pcCU, 0, true );
-
     Bool bDummy = false;
     m_pcEntropyCoder->encodeCoeff   ( pcCU, 0, pcCU->getDepth(0), pcCU->getWidth(0), pcCU->getHeight(0), bDummy );
Index: trunk/source/Lib/TLibEncoder/TEncSearch.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSearch.h	(revision 499)
+++ trunk/source/Lib/TLibEncoder/TEncSearch.h	(revision 540)
@@ -194,4 +194,5 @@
                                   UInt        uiPreCalcDistC );
   
+  
   /// encoder estimation - inter prediction (non-skip)
   Void predInterSearch          ( TComDataCU* pcCU,
Index: trunk/source/Lib/TLibEncoder/TEncSlice.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 499)
+++ trunk/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 540)
@@ -295,10 +295,4 @@
     dQP += pdQPs[ rpcSlice->getPOC() ];
   }
-#if !RATE_CONTROL_LAMBDA_DOMAIN
-  if ( m_pcCfg->getUseRateCtrl())
-  {
-    dQP = m_pcRateCtrl->getFrameQP(rpcSlice->isReferenced(), rpcSlice->getPOC());
-  }
-#endif
   // ------------------------------------------------------------------------------------------------------------------
   // Lambda computation
@@ -386,8 +380,7 @@
   // store lambda
   m_pcRdCost ->setLambda( dLambda );
-#if WEIGHTED_CHROMA_DISTORTION
 // for RDO
   // in RdCost there is only one lambda because the luma and chroma bits are not separated, instead we weight the distortion of chroma.
-  Double weight = 1.0;
+  Double weight[2] = { 1.0, 1.0 };
   Int qpc;
   Int chromaQPOffset;
@@ -395,33 +388,36 @@
   chromaQPOffset = rpcSlice->getPPS()->getChromaCbQpOffset() + rpcSlice->getSliceQpDeltaCb();
   qpc = Clip3( 0, 57, iQP + chromaQPOffset);
-  weight = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
-  m_pcRdCost->setCbDistortionWeight(weight);
+  weight[0] = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+  m_pcRdCost->setCbDistortionWeight(weight[0]);
 
   chromaQPOffset = rpcSlice->getPPS()->getChromaCrQpOffset() + rpcSlice->getSliceQpDeltaCr();
   qpc = Clip3( 0, 57, iQP + chromaQPOffset);
-  weight = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+  weight[1] = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+  m_pcRdCost->setCrDistortionWeight(weight[1]);
+
 #if JCTVC_M0259_LAMBDAREFINEMENT
   if( rpcSlice->getLayerId() > 0 && m_ppcTEncTop[layerId]->getNumActiveRefLayers() && m_pcCfg->getGOPSize() >= 8 && rpcSlice->isIntra() == false && depth == 0 )
   {
     dLambda *= 1.1;
-    weight *= 1.15;
-  }
-#endif
-  m_pcRdCost->setCrDistortionWeight(weight);
-#endif
-
+    weight[1] *= 1.15;
+    weight[0] *= 1.15;
+
+    m_pcRdCost ->setLambda( dLambda );
+    m_pcRdCost->setCbDistortionWeight(weight[0]);
+    m_pcRdCost->setCrDistortionWeight(weight[1]);
+  }
+#endif
+
+  const Double lambdaArray[3] = {dLambda, (dLambda / weight[0]), (dLambda / weight[1])};
+ 
 #if RDOQ_CHROMA_LAMBDA
 // for RDOQ
-  m_pcTrQuant->setLambda( dLambda, dLambda / weight );
+  m_pcTrQuant->setLambdas( lambdaArray );
 #else
   m_pcTrQuant->setLambda( dLambda );
 #endif
 
-#if SAO_CHROMA_LAMBDA
 // For SAO
-  rpcSlice   ->setLambda( dLambda, dLambda / weight );
-#else
-  rpcSlice   ->setLambda( dLambda );
-#endif
+  rpcSlice->setLambdas( lambdaArray );
 
 #if HB_LAMBDA_FOR_LDC
@@ -430,5 +426,5 @@
 
 #if SVC_EXTENSION
-  if(m_pcCfg->getLayerId() > 0)
+  if( m_pcCfg->getLayerId() > 0 && m_pcCfg->getNumActiveRefLayers() > 0 )
   {
     eSliceType=B_SLICE;
@@ -500,5 +496,4 @@
 
   pcPic->setTLayer( m_pcCfg->getGOPEntry(iGOPid).m_temporalId );
-
   if(eSliceType==I_SLICE)
   {
@@ -517,4 +512,10 @@
   rpcSlice->setSliceSegmentArgument ( m_pcCfg->getSliceSegmentArgument() );
   rpcSlice->setMaxNumMergeCand        ( m_pcCfg->getMaxNumMergeCand()        );
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+  if (m_pcCfg->getSkipPictureAtArcSwitch() && m_pcCfg->getAdaptiveResolutionChange() > 0 && rpcSlice->getLayerId() == 1 && rpcSlice->getPOC() == m_pcCfg->getAdaptiveResolutionChange())
+  {
+    rpcSlice->setMaxNumMergeCand        ( 1 );
+  }
+#endif
   xStoreWPparam( pPPS->getUseWP(), pPPS->getWPBiPred() );
 
@@ -546,5 +547,4 @@
 }
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
 Void TEncSlice::resetQP( TComPic* pic, Int sliceQP, Double lambda )
 {
@@ -555,8 +555,7 @@
   slice->setSliceQpBase ( sliceQP );
   m_pcRdCost ->setLambda( lambda );
-#if WEIGHTED_CHROMA_DISTORTION
   // for RDO
   // in RdCost there is only one lambda because the luma and chroma bits are not separated, instead we weight the distortion of chroma.
-  Double weight;
+  Double weight[2] = { 1.0, 1.0 };
   Int qpc;
   Int chromaQPOffset;
@@ -564,136 +563,24 @@
   chromaQPOffset = slice->getPPS()->getChromaCbQpOffset() + slice->getSliceQpDeltaCb();
   qpc = Clip3( 0, 57, sliceQP + chromaQPOffset);
-  weight = pow( 2.0, (sliceQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
-  m_pcRdCost->setCbDistortionWeight(weight);
+  weight[0] = pow( 2.0, (sliceQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+  m_pcRdCost->setCbDistortionWeight(weight[0]);
 
   chromaQPOffset = slice->getPPS()->getChromaCrQpOffset() + slice->getSliceQpDeltaCr();
   qpc = Clip3( 0, 57, sliceQP + chromaQPOffset);
-  weight = pow( 2.0, (sliceQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
-  m_pcRdCost->setCrDistortionWeight(weight);
-#endif
+  weight[1] = pow( 2.0, (sliceQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+  m_pcRdCost->setCrDistortionWeight(weight[1]);
+
+  const Double lambdaArray[3] = {lambda, (lambda / weight[0]), (lambda / weight[1])};
 
 #if RDOQ_CHROMA_LAMBDA
   // for RDOQ
-  m_pcTrQuant->setLambda( lambda, lambda / weight );
+  m_pcTrQuant->setLambdas( lambdaArray );
 #else
   m_pcTrQuant->setLambda( lambda );
 #endif
 
-#if SAO_CHROMA_LAMBDA
   // For SAO
-  slice   ->setLambda( lambda, lambda / weight );
-#else
-  slice   ->setLambda( lambda );
-#endif
+  slice->setLambdas( lambdaArray );
 }
-#else
-/**
- - lambda re-computation based on rate control QP
- */
-Void TEncSlice::xLamdaRecalculation(Int changeQP, Int idGOP, Int depth, SliceType eSliceType, TComSPS* pcSPS, TComSlice* pcSlice)
-{
-  Int qp;
-  Double recalQP= (Double)changeQP;
-  Double origQP = (Double)recalQP;
-  Double lambda;
-
-  // pre-compute lambda and QP values for all possible QP candidates
-  for ( Int deltqQpIdx = 0; deltqQpIdx < 2 * m_pcCfg->getDeltaQpRD() + 1; deltqQpIdx++ )
-  {
-    // compute QP value
-    recalQP = origQP + ((deltqQpIdx+1)>>1)*(deltqQpIdx%2 ? -1 : 1);
-
-    // compute lambda value
-    Int    NumberBFrames = ( m_pcCfg->getGOPSize() - 1 );
-    Int    SHIFT_QP = 12;
-    Double dLambda_scale = 1.0 - Clip3( 0.0, 0.5, 0.05*(Double)NumberBFrames );
-#if FULL_NBIT
-    Int    bitdepth_luma_qp_scale = 6 * (g_bitDepth - 8);
-#else
-    Int    bitdepth_luma_qp_scale = 0;
-#endif
-    Double qp_temp = (Double) recalQP + bitdepth_luma_qp_scale - SHIFT_QP;
-#if FULL_NBIT
-    Double qp_temp_orig = (Double) recalQP - SHIFT_QP;
-#endif
-    // Case #1: I or P-slices (key-frame)
-    Double dQPFactor = m_pcCfg->getGOPEntry(idGOP).m_QPFactor;
-    if ( eSliceType==I_SLICE )
-    {
-      dQPFactor=0.57*dLambda_scale;
-    }
-    lambda = dQPFactor*pow( 2.0, qp_temp/3.0 );
-
-    if ( depth>0 )
-    {
-#if FULL_NBIT
-      lambda *= Clip3( 2.00, 4.00, (qp_temp_orig / 6.0) ); // (j == B_SLICE && p_cur_frm->layer != 0 )
-#else
-      lambda *= Clip3( 2.00, 4.00, (qp_temp / 6.0) ); // (j == B_SLICE && p_cur_frm->layer != 0 )
-#endif
-    }
-
-    // if hadamard is used in ME process
-    if ( !m_pcCfg->getUseHADME() )
-    {
-      lambda *= 0.95;
-    }
-
-#if REPN_FORMAT_IN_VPS
-    qp = max( -pcSlice->getQpBDOffsetY(), min( MAX_QP, (Int) floor( recalQP + 0.5 ) ) );
-#else
-    qp = max( -pcSPS->getQpBDOffsetY(), min( MAX_QP, (Int) floor( recalQP + 0.5 ) ) );
-#endif
-
-    m_pdRdPicLambda[deltqQpIdx] = lambda;
-    m_pdRdPicQp    [deltqQpIdx] = recalQP;
-    m_piRdPicQp    [deltqQpIdx] = qp;
-  }
-
-  // obtain dQP = 0 case
-  lambda  = m_pdRdPicLambda[0];
-  recalQP = m_pdRdPicQp    [0];
-  qp      = m_piRdPicQp    [0];
-
-  if( pcSlice->getSliceType( ) != I_SLICE )
-  {
-    lambda *= m_pcCfg->getLambdaModifier( depth );
-  }
-
-  // store lambda
-  m_pcRdCost ->setLambda( lambda );
-#if WEIGHTED_CHROMA_DISTORTION
-  // for RDO
-  // in RdCost there is only one lambda because the luma and chroma bits are not separated, instead we weight the distortion of chroma.
-  Double weight = 1.0;
-  Int qpc;
-  Int chromaQPOffset;
-
-  chromaQPOffset = pcSlice->getPPS()->getChromaCbQpOffset() + pcSlice->getSliceQpDeltaCb();
-  qpc = Clip3( 0, 57, qp + chromaQPOffset);
-  weight = pow( 2.0, (qp-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
-  m_pcRdCost->setCbDistortionWeight(weight);
-
-  chromaQPOffset = pcSlice->getPPS()->getChromaCrQpOffset() + pcSlice->getSliceQpDeltaCr();
-  qpc = Clip3( 0, 57, qp + chromaQPOffset);
-  weight = pow( 2.0, (qp-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
-  m_pcRdCost->setCrDistortionWeight(weight);
-#endif
-
-#if RDOQ_CHROMA_LAMBDA
-  // for RDOQ
-  m_pcTrQuant->setLambda( lambda, lambda / weight );
-#else
-  m_pcTrQuant->setLambda( lambda );
-#endif
-
-#if SAO_CHROMA_LAMBDA
-  // For SAO
-  pcSlice   ->setLambda( lambda, lambda / weight );
-#else
-  pcSlice   ->setLambda( lambda );
-#endif
-}
-#endif
 // ====================================================================================================================
 // Public member functions
@@ -735,5 +622,4 @@
   }
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
   if ( m_pcCfg->getUseRateCtrl() )
   {
@@ -741,5 +627,4 @@
     assert(0);
   }
-#endif
 
   TComSlice* pcSlice        = rpcPic->getSlice(getSliceIdx());
@@ -773,9 +658,8 @@
 #endif
     m_pcRdCost    ->setLambda              ( m_pdRdPicLambda[uiQpIdx] );
-#if WEIGHTED_CHROMA_DISTORTION
     // for RDO
     // in RdCost there is only one lambda because the luma and chroma bits are not separated, instead we weight the distortion of chroma.
     Int iQP = m_piRdPicQp    [uiQpIdx];
-    Double weight = 1.0;
+    Double weight[2] = { 1.0, 1.0 };
     Int qpc;
     Int chromaQPOffset;
@@ -783,25 +667,21 @@
     chromaQPOffset = pcSlice->getPPS()->getChromaCbQpOffset() + pcSlice->getSliceQpDeltaCb();
     qpc = Clip3( 0, 57, iQP + chromaQPOffset);
-    weight = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
-    m_pcRdCost->setCbDistortionWeight(weight);
+    weight[0] = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+    m_pcRdCost->setCbDistortionWeight(weight[0]);
 
     chromaQPOffset = pcSlice->getPPS()->getChromaCrQpOffset() + pcSlice->getSliceQpDeltaCr();
     qpc = Clip3( 0, 57, iQP + chromaQPOffset);
-    weight = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
-    m_pcRdCost->setCrDistortionWeight(weight);
-#endif
-
+    weight[1] = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+    m_pcRdCost->setCrDistortionWeight(weight[1]);
+
+    const Double lambdaArray[3] = {m_pdRdPicLambda[uiQpIdx], (m_pdRdPicLambda[uiQpIdx] / weight[0]), (m_pdRdPicLambda[uiQpIdx] / weight[1])};
 #if RDOQ_CHROMA_LAMBDA
     // for RDOQ
-    m_pcTrQuant   ->setLambda( m_pdRdPicLambda[uiQpIdx], m_pdRdPicLambda[uiQpIdx] / weight );
+    m_pcTrQuant->setLambdas( lambdaArray );
 #else
     m_pcTrQuant   ->setLambda              ( m_pdRdPicLambda[uiQpIdx] );
 #endif
-#if SAO_CHROMA_LAMBDA
     // For SAO
-    pcSlice       ->setLambda              ( m_pdRdPicLambda[uiQpIdx], m_pdRdPicLambda[uiQpIdx] / weight );
-#else
-    pcSlice       ->setLambda              ( m_pdRdPicLambda[uiQpIdx] );
-#endif
+    pcSlice->setLambdas( lambdaArray );
 
     // try compress
@@ -830,8 +710,7 @@
 #endif
   m_pcRdCost    ->setLambda              ( m_pdRdPicLambda[uiQpIdxBest] );
-#if WEIGHTED_CHROMA_DISTORTION
   // in RdCost there is only one lambda because the luma and chroma bits are not separated, instead we weight the distortion of chroma.
   Int iQP = m_piRdPicQp    [uiQpIdxBest];
-  Double weight = 1.0;
+  Double weight[2] = { 1.0, 1.0 };
   Int qpc;
   Int chromaQPOffset;
@@ -839,30 +718,25 @@
   chromaQPOffset = pcSlice->getPPS()->getChromaCbQpOffset() + pcSlice->getSliceQpDeltaCb();
   qpc = Clip3( 0, 57, iQP + chromaQPOffset);
-  weight = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
-  m_pcRdCost->setCbDistortionWeight(weight);
+  weight[0] = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+  m_pcRdCost->setCbDistortionWeight(weight[0]);
 
   chromaQPOffset = pcSlice->getPPS()->getChromaCrQpOffset() + pcSlice->getSliceQpDeltaCr();
   qpc = Clip3( 0, 57, iQP + chromaQPOffset);
-  weight = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
-  m_pcRdCost->setCrDistortionWeight(weight);
-#endif
-
+  weight[1] = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+  m_pcRdCost->setCrDistortionWeight(weight[1]);
+
+  const Double lambdaArray[3] = {m_pdRdPicLambda[uiQpIdxBest], (m_pdRdPicLambda[uiQpIdxBest] / weight[0]), (m_pdRdPicLambda[uiQpIdxBest] / weight[1])};
 #if RDOQ_CHROMA_LAMBDA
   // for RDOQ
-  m_pcTrQuant   ->setLambda( m_pdRdPicLambda[uiQpIdxBest], m_pdRdPicLambda[uiQpIdxBest] / weight );
+  m_pcTrQuant->setLambdas( lambdaArray );
 #else
   m_pcTrQuant   ->setLambda              ( m_pdRdPicLambda[uiQpIdxBest] );
 #endif
-#if SAO_CHROMA_LAMBDA
   // For SAO
-  pcSlice       ->setLambda              ( m_pdRdPicLambda[uiQpIdxBest], m_pdRdPicLambda[uiQpIdxBest] / weight );
-#else
-  pcSlice       ->setLambda              ( m_pdRdPicLambda[uiQpIdxBest] );
-#endif
+  pcSlice->setLambdas( lambdaArray );
 }
 
 /** \param rpcPic   picture class
  */
-#if RATE_CONTROL_INTRA
 Void TEncSlice::calCostSliceI(TComPic*& rpcPic)
 {
@@ -903,5 +777,4 @@
   m_pcRateCtrl->getRCPic()->setTotalIntraCost(iSumHadSlice);
 }
-#endif
 
 Void TEncSlice::compressSlice( TComPic*& rpcPic )
@@ -1031,5 +904,4 @@
   UInt uiTileStartLCU = 0;
   UInt uiTileLCUX     = 0;
-
   Bool depSliceSegmentsEnabled = pcSlice->getPPS()->getDependentSliceSegmentsEnabledFlag();
   uiCUAddr = rpcPic->getPicSym()->getCUOrderMap( uiStartCUAddr /rpcPic->getNumPartInCU());
@@ -1080,13 +952,4 @@
     pcCU->initCU( rpcPic, uiCUAddr );
 
-#if !RATE_CONTROL_LAMBDA_DOMAIN
-    if(m_pcCfg->getUseRateCtrl())
-    {
-      if(m_pcRateCtrl->calculateUnitQP())
-      {
-        xLamdaRecalculation(m_pcRateCtrl->getUnitQP(), m_pcRateCtrl->getGOPId(), pcSlice->getDepth(), pcSlice->getSliceType(), pcSlice->getSPS(), pcSlice );
-      }
-    }
-#endif
     // inherit from TR if necessary, select substream to use.
     if( m_pcCfg->getUseSBACRD() )
@@ -1163,5 +1026,4 @@
       ((TEncBinCABAC*)m_pcRDGoOnSbacCoder->getEncBinIf())->setBinCountingEnableFlag(true);
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
       Double oldLambda = m_pcRdCost->getLambda();
       if ( m_pcCfg->getUseRateCtrl() )
@@ -1171,9 +1033,5 @@
         Double bpp       = -1.0;
 
-#if M0036_RC_IMPROVEMENT
         if ( ( rpcPic->getSlice( 0 )->getSliceType() == I_SLICE && m_pcCfg->getForceIntraQP() ) || !m_pcCfg->getLCULevelRC() )
-#else
-        if ( rpcPic->getSlice( 0 )->getSliceType() == I_SLICE || !m_pcCfg->getLCULevelRC() )
-#endif
         {
           estQP = pcSlice->getSliceQp();
@@ -1181,5 +1039,4 @@
         else
         {
-#if RATE_CONTROL_INTRA
           bpp = m_pcRateCtrl->getRCPic()->getLCUTargetBpp(pcSlice->getSliceType());
           if ( rpcPic->getSlice( 0 )->getSliceType() == I_SLICE)
@@ -1192,9 +1049,4 @@
             estQP     = m_pcRateCtrl->getRCPic()->getLCUEstQP    ( estLambda, pcSlice->getSliceQp() );
           }
-#else
-          bpp       = m_pcRateCtrl->getRCPic()->getLCUTargetBpp();
-          estLambda = m_pcRateCtrl->getRCPic()->getLCUEstLambda( bpp );
-          estQP     = m_pcRateCtrl->getRCPic()->getLCUEstQP    ( estLambda, pcSlice->getSliceQp() );
-#endif
 
 #if REPN_FORMAT_IN_VPS
@@ -1205,12 +1057,11 @@
 
           m_pcRdCost->setLambda(estLambda);
-#if M0036_RC_IMPROVEMENT
 #if RDOQ_CHROMA_LAMBDA
           // set lambda for RDOQ
           Double weight=m_pcRdCost->getChromaWeight();
-          m_pcTrQuant->setLambda( estLambda, estLambda / weight );
+          const Double lambdaArray[3] = { estLambda, (estLambda / weight), (estLambda / weight) };
+          m_pcTrQuant->setLambdas( lambdaArray );
 #else
           m_pcTrQuant->setLambda( estLambda );
-#endif
 #endif
         }
@@ -1219,58 +1070,7 @@
         pcCU->getSlice()->setSliceQpBase( estQP );
       }
-#endif
 
       // run CU encoder
       m_pcCuEncoder->compressCU( pcCU );
-
-#if !TICKET_1090_FIX
-#if RATE_CONTROL_LAMBDA_DOMAIN
-      if ( m_pcCfg->getUseRateCtrl() )
-      {
-#if !M0036_RC_IMPROVEMENT
-        UInt SAD    = m_pcCuEncoder->getLCUPredictionSAD();
-#if REPN_FORMAT_IN_VPS
-        Int height  = min( pcSlice->getSPS()->getMaxCUHeight(),pcSlice->getPicHeightInLumaSamples() - uiCUAddr / rpcPic->getFrameWidthInCU() * pcSlice->getSPS()->getMaxCUHeight() );
-        Int width   = min( pcSlice->getSPS()->getMaxCUWidth(),pcSlice->>getPicWidthInLumaSamples() - uiCUAddr % rpcPic->getFrameWidthInCU() * pcSlice->getSPS()->getMaxCUWidth() );
-#else
-        Int height  = min( pcSlice->getSPS()->getMaxCUHeight(),pcSlice->getSPS()->getPicHeightInLumaSamples() - uiCUAddr / rpcPic->getFrameWidthInCU() * pcSlice->getSPS()->getMaxCUHeight() );
-        Int width   = min( pcSlice->getSPS()->getMaxCUWidth(),pcSlice->getSPS()->getPicWidthInLumaSamples() - uiCUAddr % rpcPic->getFrameWidthInCU() * pcSlice->getSPS()->getMaxCUWidth() );
-#endif
-        Double MAD = (Double)SAD / (Double)(height * width);
-        MAD = MAD * MAD;
-        ( m_pcRateCtrl->getRCPic()->getLCU(uiCUAddr) ).m_MAD = MAD;
-#endif
-
-        Int actualQP        = g_RCInvalidQPValue;
-        Double actualLambda = m_pcRdCost->getLambda();
-        Int actualBits      = pcCU->getTotalBits();
-        Int numberOfEffectivePixels    = 0;
-        for ( Int idx = 0; idx < rpcPic->getNumPartInCU(); idx++ )
-        {
-          if ( pcCU->getPredictionMode( idx ) != MODE_NONE && ( !pcCU->isSkipped( idx ) ) )
-          {
-            numberOfEffectivePixels = numberOfEffectivePixels + 16;
-            break;
-          }
-        }
-
-        if ( numberOfEffectivePixels == 0 )
-        {
-          actualQP = g_RCInvalidQPValue;
-        }
-        else
-        {
-          actualQP = pcCU->getQP( 0 );
-        }
-        m_pcRdCost->setLambda(oldLambda);
-#if RATE_CONTROL_INTRA
-        m_pcRateCtrl->getRCPic()->updateAfterLCU( m_pcRateCtrl->getRCPic()->getLCUCoded(), actualBits, actualQP, actualLambda,
-          pcCU->getSlice()->getSliceType() == I_SLICE ? 0 : m_pcCfg->getLCULevelRC() );
-#else
-        m_pcRateCtrl->getRCPic()->updateAfterLCU( m_pcRateCtrl->getRCPic()->getLCUCoded(), actualBits, actualQP, actualLambda, m_pcCfg->getLCULevelRC() );
-#endif
-      }
-#endif
-#endif
 
       // restore entropy coder to an initial stage
@@ -1306,21 +1106,6 @@
       }
 
-#if TICKET_1090_FIX
-#if RATE_CONTROL_LAMBDA_DOMAIN
       if ( m_pcCfg->getUseRateCtrl() )
       {
-#if !M0036_RC_IMPROVEMENT
-        UInt SAD    = m_pcCuEncoder->getLCUPredictionSAD();
-#if REPN_FORMAT_IN_VPS
-        Int height  = min( pcSlice->getSPS()->getMaxCUHeight(),pcSlice->getPicHeightInLumaSamples() - uiCUAddr / rpcPic->getFrameWidthInCU() * pcSlice->getSPS()->getMaxCUHeight() );
-        Int width   = min( pcSlice->getSPS()->getMaxCUWidth(),pcSlice->getPicWidthInLumaSamples() - uiCUAddr % rpcPic->getFrameWidthInCU() * pcSlice->getSPS()->getMaxCUWidth() );
-#else
-        Int height  = min( pcSlice->getSPS()->getMaxCUHeight(),pcSlice->getSPS()->getPicHeightInLumaSamples() - uiCUAddr / rpcPic->getFrameWidthInCU() * pcSlice->getSPS()->getMaxCUHeight() );
-        Int width   = min( pcSlice->getSPS()->getMaxCUWidth(),pcSlice->getSPS()->getPicWidthInLumaSamples() - uiCUAddr % rpcPic->getFrameWidthInCU() * pcSlice->getSPS()->getMaxCUWidth() );
-#endif
-        Double MAD = (Double)SAD / (Double)(height * width);
-        MAD = MAD * MAD;
-        ( m_pcRateCtrl->getRCPic()->getLCU(uiCUAddr) ).m_MAD = MAD;
-#endif
 
         Int actualQP        = g_RCInvalidQPValue;
@@ -1347,13 +1132,7 @@
         m_pcRdCost->setLambda(oldLambda);
 
-#if RATE_CONTROL_INTRA
         m_pcRateCtrl->getRCPic()->updateAfterLCU( m_pcRateCtrl->getRCPic()->getLCUCoded(), actualBits, actualQP, actualLambda,
           pcCU->getSlice()->getSliceType() == I_SLICE ? 0 : m_pcCfg->getLCULevelRC() );
-#else
-        m_pcRateCtrl->getRCPic()->updateAfterLCU( m_pcRateCtrl->getRCPic()->getLCUCoded(), actualBits, actualQP, actualLambda, m_pcCfg->getLCULevelRC() );
-#endif
-      }
-#endif
-#endif
+      }
     }
     // other case: encodeCU is not called
@@ -1377,11 +1156,4 @@
     m_dPicRdCost     += pcCU->getTotalCost();
     m_uiPicDist      += pcCU->getTotalDistortion();
-#if !RATE_CONTROL_LAMBDA_DOMAIN
-    if(m_pcCfg->getUseRateCtrl())
-    {
-      m_pcRateCtrl->updateLCUData(pcCU, pcCU->getTotalBits(), pcCU->getQP(0));
-      m_pcRateCtrl->updataRCUnitStatus();
-    }
-#endif
   }
   if ((pcSlice->getPPS()->getNumSubstreams() > 1) && !depSliceSegmentsEnabled)
@@ -1398,10 +1170,4 @@
   }
   xRestoreWPparam( pcSlice );
-#if !RATE_CONTROL_LAMBDA_DOMAIN
-  if(m_pcCfg->getUseRateCtrl())
-  {
-    m_pcRateCtrl->updateFrameData(m_uiPicTotalBits);
-  }
-#endif
 }
 
@@ -1603,4 +1369,34 @@
 
     TComDataCU*& pcCU = rpcPic->getCU( uiCUAddr );
+#if HM_CLEANUP_SAO
+    if ( pcSlice->getSPS()->getUseSAO() )
+    {
+      if (pcSlice->getSaoEnabledFlag()||pcSlice->getSaoEnabledFlagChroma())
+      {
+        SAOBlkParam& saoblkParam = (rpcPic->getPicSym()->getSAOBlkParam())[uiCUAddr];
+        Bool sliceEnabled[NUM_SAO_COMPONENTS];
+        sliceEnabled[SAO_Y] = pcSlice->getSaoEnabledFlag();
+        sliceEnabled[SAO_Cb]= sliceEnabled[SAO_Cr]= pcSlice->getSaoEnabledFlagChroma();
+
+        Bool leftMergeAvail = false;
+        Bool aboveMergeAvail= false;
+        //merge left condition
+        Int rx = (uiCUAddr % uiWidthInLCUs);
+        if(rx > 0)
+        {
+          leftMergeAvail = rpcPic->getSAOMergeAvailability(uiCUAddr, uiCUAddr-1);
+        }
+
+        //merge up condition
+        Int ry = (uiCUAddr / uiWidthInLCUs);
+        if(ry > 0)
+        {
+          aboveMergeAvail = rpcPic->getSAOMergeAvailability(uiCUAddr, uiCUAddr-uiWidthInLCUs);
+        }
+
+        m_pcEntropyCoder->encodeSAOBlkParam(saoblkParam,sliceEnabled, leftMergeAvail, aboveMergeAvail);
+      }
+    }
+#else
     if ( pcSlice->getSPS()->getUseSAO() && (pcSlice->getSaoEnabledFlag()||pcSlice->getSaoEnabledFlagChroma()) )
     {
@@ -1685,4 +1481,6 @@
       }
     }
+#endif
+
 #if ENC_DEC_TRACE
     g_bJustDoIt = g_bEncDecTraceEnable;
Index: trunk/source/Lib/TLibEncoder/TEncSlice.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSlice.h	(revision 499)
+++ trunk/source/Lib/TLibEncoder/TEncSlice.h	(revision 540)
@@ -131,15 +131,9 @@
 #endif
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
   Void    resetQP             ( TComPic* pic, Int sliceQP, Double lambda );
-#else
-  Void    xLamdaRecalculation ( Int changeQP, Int idGOP, Int depth, SliceType eSliceType, TComSPS* pcSPS, TComSlice* pcSlice);
-#endif
   // compress and encode slice
   Void    precompressSlice    ( TComPic*& rpcPic                                );      ///< precompress slice for multi-loop opt.
   Void    compressSlice       ( TComPic*& rpcPic                                );      ///< analysis stage of slice
-#if RATE_CONTROL_INTRA
   Void    calCostSliceI       ( TComPic*& rpcPic );
-#endif
   Void    encodeSlice         ( TComPic*& rpcPic, TComOutputBitstream* pcSubstreams  );
   
Index: trunk/source/Lib/TLibEncoder/TEncTop.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncTop.cpp	(revision 499)
+++ trunk/source/Lib/TLibEncoder/TEncTop.cpp	(revision 540)
@@ -92,4 +92,10 @@
   m_pocAdjustmentValue     = 0;
 #endif
+#if NO_CLRAS_OUTPUT_FLAG
+  m_noClrasOutputFlag          = false;
+  m_layerInitializedFlag       = false;
+  m_firstPicInLayerDecodedFlag = false;
+  m_noOutputOfPriorPicsFlags   = false;
+#endif
 #endif //SVC_EXTENSION
 }
@@ -123,4 +129,16 @@
   if (m_bUseSAO)
   {
+#if HM_CLEANUP_SAO
+#if AUXILIARY_PICTURES
+    m_cEncSAO.create( getSourceWidth(), getSourceHeight(), m_chromaFormatIDC, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+#else
+    m_cEncSAO.create( getSourceWidth(), getSourceHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+#endif
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+    m_cEncSAO.createEncData(getSaoLcuBoundary());
+#else
+    m_cEncSAO.createEncData();
+#endif
+#else
     m_cEncSAO.setSaoLcuBoundary(getSaoLcuBoundary());
     m_cEncSAO.setSaoLcuBasedOptimization(getSaoLcuBasedOptimization());
@@ -128,4 +146,5 @@
     m_cEncSAO.create( getSourceWidth(), getSourceHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight );
     m_cEncSAO.createEncBuffer();
+#endif
   }
 #if ADAPTIVE_QP_SELECTION
@@ -137,5 +156,4 @@
   m_cLoopFilter.        create( g_uiMaxCUDepth );
   
-#if RATE_CONTROL_LAMBDA_DOMAIN
   if ( m_RCEnableRateControl )
   {
@@ -143,7 +161,4 @@
                       g_uiMaxCUWidth, g_uiMaxCUHeight, m_RCKeepHierarchicalBit, m_RCUseLCUSeparateModel, m_GOPList );
   }
-#else
-  m_cRateCtrl.create(getIntraPeriod(), getGOPSize(), getFrameRate(), getTargetBitrate(), getQP(), getNumLCUInUnit(), getSourceWidth(), getSourceHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight);
-#endif
   // if SBAC-based RD optimization is used
   if( m_bUseSBACRD )
@@ -244,6 +259,11 @@
   if (m_cSPS.getUseSAO())
   {
+#if HM_CLEANUP_SAO
+    m_cEncSAO.destroyEncData();
+    m_cEncSAO.destroy();
+#else
     m_cEncSAO.destroy();
     m_cEncSAO.destroyEncBuffer();
+#endif
   }
   m_cLoopFilter.        destroy();
@@ -395,5 +415,4 @@
 {
   // compress GOP
-#if RATE_CONTROL_LAMBDA_DOMAIN
 #if !RC_SHVC_HARMONIZATION
   if ( m_RCEnableRateControl )
@@ -402,10 +421,8 @@
   }
 #endif
-#endif
 
   // compress GOP
   m_cGOPEncoder.compressGOP(iPicIdInGOP, m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, false, false);
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
 #if !RC_SHVC_HARMONIZATION
   if ( m_RCEnableRateControl )
@@ -413,5 +430,4 @@
     m_cRateCtrl.destroyRCGOP();
   }
-#endif
 #endif
   
@@ -457,10 +473,8 @@
   }
   
-#if RATE_CONTROL_LAMBDA_DOMAIN
   if ( m_RCEnableRateControl )
   {
     m_cRateCtrl.initRCGOP( m_iNumPicRcvd );
   }
-#endif
 
   // compress GOP
@@ -468,10 +482,8 @@
   m_cGOPEncoder.compressGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, false, false);
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
   if ( m_RCEnableRateControl )
   {
     m_cRateCtrl.destroyRCGOP();
   }
-#endif
   
   iNumEncoded         = m_iNumPicRcvd;
@@ -513,5 +525,7 @@
     TComPic *pcTopField;
     xGetNewPicBuffer( pcTopField );
+#if !HM_CLEANUP_SAO
     pcTopField->getPicSym()->allocSaoParam(&m_cEncSAO);
+#endif
     pcTopField->setReconMark (false);
     
@@ -534,11 +548,11 @@
     Pel * pcTopFieldU =  pcTopField->getPicYuvOrg()->getCbAddr();
     Pel * pcTopFieldV =  pcTopField->getPicYuvOrg()->getCrAddr();
-    
+
     // compute image characteristics
     if ( getUseAdaptiveQP() )
     {
       m_cPreanalyzer.xPreanalyze( dynamic_cast<TEncPic*>( pcTopField ) );
-    }
-    
+    }    
+
     /* -- Defield -- */
     
@@ -554,5 +568,7 @@
     TComPic* pcBottomField;
     xGetNewPicBuffer( pcBottomField );
+#if !HM_CLEANUP_SAO
     pcBottomField->getPicSym()->allocSaoParam(&m_cEncSAO);
+#endif
     pcBottomField->setReconMark (false);
    
@@ -575,11 +591,11 @@
     Pel * pcBottomFieldU =  pcBottomField->getPicYuvOrg()->getCbAddr();
     Pel * pcBottomFieldV =  pcBottomField->getPicYuvOrg()->getCrAddr();
-    
-    // Compute image characteristics
+
+    // compute image characteristics
     if ( getUseAdaptiveQP() )
     {
       m_cPreanalyzer.xPreanalyze( dynamic_cast<TEncPic*>( pcBottomField ) );
-    }
-    
+    }       
+
     /* -- Defield -- */
     
@@ -636,5 +652,7 @@
     TComPic *pcTopField;
     xGetNewPicBuffer( pcTopField );
+#if !HM_CLEANUP_SAO
     pcTopField->getPicSym()->allocSaoParam(&m_cEncSAO);
+#endif
     pcTopField->setReconMark (false);
     
@@ -688,8 +706,10 @@
     TComPic* pcBottomField;
     xGetNewPicBuffer( pcBottomField );
+#if !HM_CLEANUP_SAO
     pcBottomField->getPicSym()->allocSaoParam(&m_cEncSAO);
+#endif
     pcBottomField->setReconMark (false);
     
-    TComPicYuv* rpcPicYuvRec = new TComPicYuv;
+    TComPicYuv* rpcPicYuvRec;
     if ( rcListPicYuvRecOut.size() == (UInt)m_iGOPSize )
     {
@@ -698,4 +718,5 @@
     else
     {
+      rpcPicYuvRec = new TComPicYuv;
       rpcPicYuvRec->create( m_iSourceWidth, m_iSourceHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
     }
@@ -791,5 +812,9 @@
         for(UInt i = 0; i < m_cVPS.getNumDirectRefLayers( m_layerId ); i++ )
         {
+#if O0098_SCALED_REF_LAYER_ID
+          const Window scalEL = getSPS()->getScaledRefLayerWindowForLayer(m_cVPS.getRefLayerId(m_layerId, i));
+#else
           const Window scalEL = getSPS()->getScaledRefLayerWindow(i);
+#endif
           Bool zeroOffsets = ( scalEL.getWindowLeftOffset() == 0 && scalEL.getWindowRightOffset() == 0 && scalEL.getWindowTopOffset() == 0 && scalEL.getWindowBottomOffset() == 0 );
 
@@ -842,5 +867,9 @@
         for(UInt i = 0; i < m_cVPS.getNumDirectRefLayers( m_layerId ); i++ )
         {
+#if O0098_SCALED_REF_LAYER_ID
+          const Window scalEL = getSPS()->getScaledRefLayerWindowForLayer(m_cVPS.getRefLayerId(m_layerId, i));
+#else
           const Window scalEL = getSPS()->getScaledRefLayerWindow(i);
+#endif
           Bool zeroOffsets = ( scalEL.getWindowLeftOffset() == 0 && scalEL.getWindowRightOffset() == 0 && scalEL.getWindowTopOffset() == 0 && scalEL.getWindowBottomOffset() == 0 );
 
@@ -883,9 +912,10 @@
 #endif
     }
-
+#if !HM_CLEANUP_SAO
     if (getUseSAO())
     {
       rpcPic->getPicSym()->allocSaoParam(&m_cEncSAO);
     }
+#endif
     m_cListPic.pushBack( rpcPic );
   }
@@ -912,4 +942,7 @@
   for(Int i = 0; i < m_cSPS.getNumScaledRefLayerOffsets(); i++)
   {
+#if O0098_SCALED_REF_LAYER_ID
+    m_cSPS.setScaledRefLayerId(i, m_scaledRefLayerId[i]);
+#endif
     m_cSPS.getScaledRefLayerWindow(i) = m_scaledRefLayerWindow[i];
   }
@@ -1063,6 +1096,6 @@
 Void TEncTop::xInitPPS()
 {
-#if IL_SL_SIGNALLING_N0371
-  m_cPPS.setLayerId(m_layerId);
+#if SCALINGLIST_INFERRING
+  m_cPPS.setLayerId( m_layerId );
 #endif
 
@@ -1072,4 +1105,14 @@
 #if REPN_FORMAT_IN_VPS
   Int lowestQP;
+#if O0096_REP_FORMAT_INDEX
+  if( m_layerId == 0 )
+  {
+    lowestQP = - m_cSPS.getQpBDOffsetY();
+  }
+  else
+  {
+    lowestQP = - (m_cVPS.getVpsRepFormat( m_cVPS.getVpsRepFormatIdx( m_cSPS.getUpdateRepFormatFlag() ? m_cSPS.getUpdateRepFormatIndex() : m_layerId ) )->getBitDepthVpsLuma() - 8) * 6;
+  }
+#else
   if( m_layerId == 0 || m_cSPS.getUpdateRepFormatFlag() )
   {
@@ -1080,4 +1123,5 @@
     lowestQP = - (m_cVPS.getVpsRepFormat( m_cVPS.getVpsRepFormatIdx( m_layerId ) )->getBitDepthVpsLuma() - 8) * 6;
   }
+#endif
 #else
   Int lowestQP = - m_cSPS.getQpBDOffsetY();
@@ -1119,5 +1163,4 @@
   }
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
   if ( m_RCEnableRateControl )
   {
@@ -1126,5 +1169,4 @@
     m_cPPS.setMinCuDQPSize( m_cPPS.getSPS()->getMaxCUWidth() >> ( m_cPPS.getMaxCuDQPDepth()) );
   } 
-#endif
 
   m_cPPS.setChromaCbQpOffset( m_chromaCbQpOffset );
@@ -1209,4 +1251,10 @@
 #if POC_RESET_FLAG
   m_cPPS.setNumExtraSliceHeaderBits( 2 );
+#endif
+#if O0149_CROSS_LAYER_BLA_FLAG
+  if (m_crossLayerBLAFlag)
+  {
+    m_cPPS.setNumExtraSliceHeaderBits( 3 );
+  }
 #endif
 }
@@ -1607,7 +1655,17 @@
 Void TEncTop::xInitILRP()
 {
+#if O0096_REP_FORMAT_INDEX
+  RepFormat *repFormat = m_cVPS.getVpsRepFormat( m_cVPS.getVpsRepFormatIdx( m_cSPS.getUpdateRepFormatFlag() ? m_cSPS.getUpdateRepFormatIndex() : m_layerId ) );
+#else
   RepFormat *repFormat = m_cVPS.getVpsRepFormat( m_cVPS.getVpsRepFormatIdx( m_layerId ) );
+#endif
   Int bitDepthY,bitDepthC,picWidth,picHeight;
 
+#if O0096_REP_FORMAT_INDEX
+  bitDepthY   = repFormat->getBitDepthVpsLuma();
+  bitDepthC   = repFormat->getBitDepthVpsChroma();
+  picWidth    = repFormat->getPicWidthVpsInLumaSamples();
+  picHeight   = repFormat->getPicHeightVpsInLumaSamples();
+#else
   if( m_cSPS.getUpdateRepFormatFlag() )
   {
@@ -1624,4 +1682,5 @@
     picHeight   = repFormat->getPicHeightVpsInLumaSamples();
   }
+#endif
   
   if(m_layerId > 0)
@@ -1661,4 +1720,23 @@
 }
 #endif
+
+#if O0098_SCALED_REF_LAYER_ID
+Window& TEncTop::getScaledRefLayerWindowForLayer(Int layerId)
+{
+  static Window win;
+
+  for (Int i = 0; i < m_numScaledRefLayerOffsets; i++)
+  {
+    if (layerId == m_scaledRefLayerId[i])
+    {
+      return m_scaledRefLayerWindow[i];
+    }
+  }
+
+  win.resetWindow();  // scaled reference layer offsets are inferred to be zero when not present
+  return win;
+}
+#endif
+
 #endif //SVC_EXTENSION
 //! \}
Index: trunk/source/Lib/TLibEncoder/TEncTop.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncTop.h	(revision 499)
+++ trunk/source/Lib/TLibEncoder/TEncTop.h	(revision 540)
@@ -83,5 +83,5 @@
   // encoder search
   TEncSearch              m_cSearch;                      ///< encoder search class
-  TEncEntropy*            m_pcEntropyCoder;                     ///< entropy encoder 
+  //TEncEntropy*            m_pcEntropyCoder;                     ///< entropy encoder
   TEncCavlc*              m_pcCavlcCoder;                       ///< CAVLC encoder  
   // coding tool
@@ -141,7 +141,16 @@
 #endif
   UInt                    m_numScaledRefLayerOffsets;
+#if O0098_SCALED_REF_LAYER_ID
+  UInt                    m_scaledRefLayerId[MAX_LAYERS];
+#endif
   Window                  m_scaledRefLayerWindow[MAX_LAYERS];
 #if POC_RESET_FLAG
   Int                     m_pocAdjustmentValue;
+#endif
+#if NO_CLRAS_OUTPUT_FLAG
+  Bool                    m_noClrasOutputFlag;
+  Bool                    m_layerInitializedFlag;
+  Bool                    m_firstPicInLayerDecodedFlag;
+  Bool                    m_noOutputOfPriorPicsFlags;
 #endif
 #endif //SVC_EXTENSION
@@ -209,4 +218,9 @@
   Void                    setNumScaledRefLayerOffsets(Int x) { m_numScaledRefLayerOffsets = x; }
   UInt                    getNumScaledRefLayerOffsets() { return m_numScaledRefLayerOffsets; }
+#if O0098_SCALED_REF_LAYER_ID
+  Void                    setScaledRefLayerId(Int x, UInt id) { m_scaledRefLayerId[x] = id;   }
+  UInt                    getScaledRefLayerId(Int x)          { return m_scaledRefLayerId[x]; }
+  Window&  getScaledRefLayerWindowForLayer(Int layerId);
+#endif
   Window&  getScaledRefLayerWindow(Int x)            { return m_scaledRefLayerWindow[x]; }
 #endif //SVC_EXTENSION
@@ -242,4 +256,14 @@
   Void setPocAdjustmentValue(Int x) { m_pocAdjustmentValue = x;   }
 #endif
+#if NO_CLRAS_OUTPUT_FLAG
+  Int  getNoClrasOutputFlag()                { return m_noClrasOutputFlag;}
+  Void setNoClrasOutputFlag(Bool x)          { m_noClrasOutputFlag = x;   }
+  Int  getLayerInitializedFlag()             { return m_layerInitializedFlag;}
+  Void setLayerInitializedFlag(Bool x)       { m_layerInitializedFlag = x;   }
+  Int  getFirstPicInLayerDecodedFlag()       { return m_firstPicInLayerDecodedFlag;}
+  Void setFirstPicInLayerDecodedFlag(Bool x) { m_firstPicInLayerDecodedFlag = x;   }
+  Int  getNoOutputOfPriorPicsFlags()         { return m_noOutputOfPriorPicsFlags;}
+  Void setNoOutputOfPriorPicsFlags(Bool x)   { m_noOutputOfPriorPicsFlags = x;   }
+#endif
 #else //SVC_EXTENSION
   Void encode( Bool bEos, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut,
