Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/AnnexBwrite.h
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/AnnexBwrite.h	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/AnnexBwrite.h	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/NALwrite.cpp
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/NALwrite.cpp	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/NALwrite.cpp	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/NALwrite.h
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/NALwrite.h	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/NALwrite.h	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/SEIwrite.cpp
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/SEIwrite.cpp	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/SEIwrite.cpp	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -307,13 +307,13 @@
   if( !hrd->getSubPicCpbParamsPresentFlag() )
   {
-    WRITE_FLAG( sei.m_rapCpbParamsPresentFlag, "rap_cpb_params_present_flag" );
+    WRITE_FLAG( sei.m_rapCpbParamsPresentFlag, "irap_cpb_params_present_flag" );
+  }
+  if( sei.m_rapCpbParamsPresentFlag )
+  {
+    WRITE_CODE( sei.m_cpbDelayOffset, hrd->getCpbRemovalDelayLengthMinus1() + 1, "cpb_delay_offset" );
+    WRITE_CODE( sei.m_dpbDelayOffset, hrd->getDpbOutputDelayLengthMinus1()  + 1, "dpb_delay_offset" );
   }
   WRITE_FLAG( sei.m_concatenationFlag, "concatenation_flag");
   WRITE_CODE( sei.m_auCpbRemovalDelayDelta - 1, ( hrd->getCpbRemovalDelayLengthMinus1() + 1 ), "au_cpb_removal_delay_delta_minus1" );
-  if( sei.m_rapCpbParamsPresentFlag )
-  {
-    WRITE_CODE( sei.m_cpbDelayOffset, hrd->getCpbRemovalDelayLengthMinus1() + 1, "cpb_delay_offset" );
-    WRITE_CODE( sei.m_dpbDelayOffset, hrd->getDpbOutputDelayLengthMinus1()  + 1, "dpb_delay_offset" );
-  }
   for( nalOrVcl = 0; nalOrVcl < 2; nalOrVcl ++ )
   {
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/SEIwrite.h
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/SEIwrite.h	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/SEIwrite.h	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/SyntaxElementWriter.cpp
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/SyntaxElementWriter.cpp	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/SyntaxElementWriter.cpp	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/SyntaxElementWriter.h
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/SyntaxElementWriter.h	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/SyntaxElementWriter.h	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncAnalyze.cpp
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncAnalyze.cpp	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncAnalyze.cpp	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncAnalyze.h
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncAnalyze.h	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncAnalyze.h	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncBinCoder.h
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncBinCoder.h	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncBinCoder.h	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncBinCoderCABAC.cpp
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncBinCoderCABAC.cpp	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncBinCoderCABAC.cpp	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncBinCoderCABAC.h
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncBinCoderCABAC.h	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncBinCoderCABAC.h	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.cpp
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.cpp	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.cpp	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.h
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.h	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.h	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncCavlc.cpp
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -256,7 +256,4 @@
   if( pcPPS->getScalingListPresentFlag() )
   {
-#if SCALING_LIST_OUTPUT_RESULT
-    printf("PPS\n");
-#endif
     codeScalingList( m_pcSlice->getScalingList() );
   }
@@ -742,7 +739,4 @@
     if(pcSPS->getScalingListPresentFlag())
     {
-#if SCALING_LIST_OUTPUT_RESULT
-    printf("SPS\n");
-#endif
       codeScalingList( m_pcSlice->getScalingList() );
     }
@@ -1688,5 +1682,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.
@@ -1699,5 +1692,4 @@
           }
         }
-#endif
 
       if(pcSlice->getRPSidx() < 0)
@@ -1833,8 +1825,5 @@
       {
          WRITE_FLAG( pcSlice->getSaoEnabledFlag(), "slice_sao_luma_flag" );
-         {
-           SAOParam *saoParam = pcSlice->getPic()->getPicSym()->getSaoParam();
-          WRITE_FLAG( saoParam->bSaoFlag[1], "slice_sao_chroma_flag" );
-         }
+         WRITE_FLAG( pcSlice->getSaoEnabledFlagChroma(), "slice_sao_chroma_flag" );
       }
     }
@@ -2429,11 +2418,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++)
@@ -2441,7 +2423,4 @@
       for(listId = 0; listId < g_scalingListNum[sizeId]; listId++)
       {
-#if SCALING_LIST_OUTPUT_RESULT
-        startBit = m_pcBitIf->getNumberOfWrittenBits();
-#endif
         scalingListPredModeFlag = scalingList->checkPredMode( sizeId, listId );
         WRITE_FLAG( scalingListPredModeFlag, "scaling_list_pred_mode_flag" );
@@ -2454,12 +2433,6 @@
           xCodeScalingList(scalingList, sizeId, listId);
         }
-#if SCALING_LIST_OUTPUT_RESULT
-        printf("Matrix [%d][%d] Bit %d\n",sizeId,listId,m_pcBitIf->getNumberOfWrittenBits() - startBit);
-#endif
-      }
-    }
-#if SCALING_LIST_OUTPUT_RESULT
-  printf("Total Bit %d\n",m_pcBitIf->getNumberOfWrittenBits()-startTotalBit);
-#endif
+      }
+    }
   return;
 }
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncCavlc.h
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncCavlc.h	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncCavlc.h	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -120,10 +120,4 @@
   
   Void codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList );
-  Void codeSAOSign       ( UInt code   ) { printf("Not supported\n"); assert (0); }
-  Void codeSaoMaxUvlc    ( UInt   code, UInt maxSymbol ){printf("Not supported\n"); assert (0);}
-  Void codeSaoMerge  ( UInt uiCode ){printf("Not supported\n"); assert (0);}
-  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);}
-
   Void codeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx );
   Void codeSkipFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncCfg.h
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncCfg.h	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncCfg.h	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -177,8 +177,4 @@
   Int       m_maxNumOffsetsPerPic;
   Bool      m_saoLcuBoundary;
-  Bool      m_saoLcuBasedOptimization;
-
-  //====== Lossless ========
-  Bool      m_useLossless;
   //====== Motion search ========
   Int       m_iFastSearch;                      //  0:Full search  1:Diamond  2:PMVFAST
@@ -201,5 +197,4 @@
   
   //====== Tool list ========
-  Bool      m_bUseSBACRD;
   Bool      m_bUseASR;
   Bool      m_bUseHADME;
@@ -292,12 +287,7 @@
   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;
@@ -324,5 +314,5 @@
 #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.
+  Bool      m_CUTransquantBypassFlagForce;                    ///< if transquant_bypass_enable_flag, then, if true, all CU transquant bypass flags will be set to true.
 #if H_MV
   TComVPS*  m_cVPS;                                           ///< pointer to VPS, same for all layers
@@ -573,6 +563,4 @@
   Void      setQPAdaptationRange            ( Int   i )      { m_iQPAdaptationRange = i; }
   
-  //====== Lossless ========
-  Void      setUseLossless                  (Bool    b  )        { m_useLossless = b;  }
   //====== Sequence ========
   Int       getFrameRate                    ()      { return  m_iFrameRate; }
@@ -617,9 +605,6 @@
   Bool      getUseAdaptiveQP                ()      { return  m_bUseAdaptiveQP; }
   Int       getQPAdaptationRange            ()      { return  m_iQPAdaptationRange; }
-  //====== Lossless ========
-  Bool      getUseLossless                  ()      { return  m_useLossless;  }
   
   //==== Tool list ========
-  Void      setUseSBACRD                    ( Bool  b )     { m_bUseSBACRD  = b; }
   Void      setUseASR                       ( Bool  b )     { m_bUseASR     = b; }
   Void      setUseHADME                     ( Bool  b )     { m_bUseHADME   = b; }
@@ -640,5 +625,4 @@
   Void      setdQPs                         ( Int*  p )     { m_aidQP       = p; }
   Void      setDeltaQpRD                    ( UInt  u )     {m_uiDeltaQpRD  = u; }
-  Bool      getUseSBACRD                    ()      { return m_bUseSBACRD;  }
   Bool      getUseASR                       ()      { return m_bUseASR;     }
   Bool      getUseHADME                     ()      { return m_bUseHADME;   }
@@ -684,6 +668,4 @@
   Void  setSaoLcuBoundary              (Bool val)      { m_saoLcuBoundary = val; }
   Bool  getSaoLcuBoundary              ()              { return m_saoLcuBoundary; }
-  Void  setSaoLcuBasedOptimization               (Bool val)            { m_saoLcuBasedOptimization = val; }
-  Bool  getSaoLcuBasedOptimization               ()                    { return m_saoLcuBasedOptimization; }
   Void  setLFCrossTileBoundaryFlag               ( Bool   val  )       { m_loopFilterAcrossTilesEnabledFlag = val; }
   Bool  getLFCrossTileBoundaryFlag               ()                    { return m_loopFilterAcrossTilesEnabledFlag;   }
@@ -825,16 +807,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; }
@@ -873,6 +849,6 @@
   Bool      getTransquantBypassEnableFlag()           { return m_TransquantBypassEnableFlag; }
   Void      setTransquantBypassEnableFlag(Bool flag)  { m_TransquantBypassEnableFlag = flag; }
-  Bool      getCUTransquantBypassFlagValue()          { return m_CUTransquantBypassFlagValue; }
-  Void      setCUTransquantBypassFlagValue(Bool flag) { m_CUTransquantBypassFlagValue = flag; }
+  Bool      getCUTransquantBypassFlagForceValue()          { return m_CUTransquantBypassFlagForce; }
+  Void      setCUTransquantBypassFlagForceValue(Bool flag) { m_CUTransquantBypassFlagForce = flag; }
 #if H_MV
   Void      setVPS           ( TComVPS *p ) { m_cVPS = p;    }
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncCu.cpp
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncCu.cpp	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncCu.cpp	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -109,18 +109,5 @@
   
   m_bEncodeDQP = false;
-#if RATE_CONTROL_LAMBDA_DOMAIN
-#if !M0036_RC_IMPROVEMENT
-  m_LCUPredictionSAD = 0;
-  m_addSADDepth      = 0;
-  m_temporalSAD      = 0;
-#endif
-#if M0036_RC_IMPROVEMENT && KWU_RC_MADPRED_E0227
-  m_LCUPredictionSAD = 0;
-  m_addSADDepth      = 0;
-  m_temporalSAD      = 0;
-  m_spatialSAD       = 0;
-#endif
-#endif
-#if !RATE_CONTROL_LAMBDA_DOMAIN && KWU_RC_MADPRED_E0227
+#if KWU_RC_MADPRED_E0227
   m_LCUPredictionSAD = 0;
   m_addSADDepth      = 0;
@@ -273,5 +260,4 @@
   m_pcRDGoOnSbacCoder = pcEncTop->getRDGoOnSbacCoder();
   
-  m_bUseSBACRD        = pcEncTop->getUseSBACRD();
   m_pcRateCtrl        = pcEncTop->getRateCtrl();
 }
@@ -289,17 +275,4 @@
   m_ppcTempCU[0]->initCU( rpcCU->getPic(), rpcCU->getAddr() );
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
-#if !M0036_RC_IMPROVEMENT
-  m_addSADDepth      = 0;
-  m_LCUPredictionSAD = 0;
-  m_temporalSAD      = 0;
-#endif
-#if M0036_RC_IMPROVEMENT && KWU_RC_MADPRED_E0227
-  m_LCUPredictionSAD = 0;
-  m_addSADDepth      = 0;
-  m_temporalSAD      = 0;
-  m_spatialSAD       = 0;
-#endif
-#endif
 #if KWU_RC_MADPRED_E0227
   m_LCUPredictionSAD = 0;
@@ -482,5 +455,4 @@
   Int iMaxQP;
   Bool isAddLowestQP = false;
-  Int lowestQP = -rpcTempCU->getSlice()->getSPS()->getQpBDOffsetY();
 
   if( (g_uiMaxCUWidth>>uiDepth) >= rpcTempCU->getSlice()->getPPS()->getMinCuDQPSize() )
@@ -489,9 +461,4 @@
     iMinQP = Clip3( -rpcTempCU->getSlice()->getSPS()->getQpBDOffsetY(), MAX_QP, iBaseQP-idQP );
     iMaxQP = Clip3( -rpcTempCU->getSlice()->getSPS()->getQpBDOffsetY(), MAX_QP, iBaseQP+idQP );
-    if ( (rpcTempCU->getSlice()->getSPS()->getUseLossless()) && (lowestQP < iMinQP) && rpcTempCU->getSlice()->getPPS()->getUseDQP() )
-    {
-      isAddLowestQP = true; 
-      iMinQP = iMinQP - 1;
-    }
   }
   else
@@ -501,5 +468,4 @@
   }
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
   if ( m_pcEncCfg->getUseRateCtrl() )
   {
@@ -507,12 +473,18 @@
     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
+  // transquant-bypass (TQB) processing loop variable initialisation ---
+
+  const Int lowestQP = iMinQP; // For TQB, use this QP which is the lowest non TQB QP tested (rather than QP'=0) - that way delta QPs are smaller, and TQB can be tested at all CU levels.
+
+  if ( (rpcTempCU->getSlice()->getPPS()->getTransquantBypassEnableFlag()) )
+  {
+    isAddLowestQP = true; // mark that the first iteration is to cost TQB mode.
+    iMinQP = iMinQP - 1;  // increase loop variable range by 1, to allow testing of TQB mode along with other QPs
+    if ( m_pcEncCfg->getCUTransquantBypassFlagForceValue() )
+    {
+      iMaxQP = iMinQP;
+    }
+  }
+
 #if H_3D_IC
   Bool bICEnabled = rpcTempCU->getSlice()->getViewIndex() && ( rpcTempCU->getSlice()->getSliceType() == P_SLICE || rpcTempCU->getSlice()->getSliceType() == B_SLICE ) && !rpcTempCU->getSlice()->getIsDepth();
@@ -534,14 +506,16 @@
     for (Int iQP=iMinQP; iQP<=iMaxQP; iQP++)
     {
-      if (isAddLowestQP && (iQP == iMinQP))
+      const Bool bIsLosslessMode = isAddLowestQP && (iQP == iMinQP);
+
+      if (bIsLosslessMode)
       {
         iQP = lowestQP;
       }
-      // variables for fast encoder decision
+
 #if H_3D_QTLPC
       bTrySplit    = true;
 #endif
 
-      rpcTempCU->initEstData( uiDepth, iQP );
+      rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 #if H_3D_QTLPC
       //logic for setting bTrySplit using the partition information that is stored of the texture colocated CU
@@ -647,7 +621,7 @@
 #endif
 #if  H_3D_FAST_TEXTURE_ENCODING
-          xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N, bFMD );  rpcTempCU->initEstData( uiDepth, iQP );//by Competition for inter_2Nx2N
-#else
-          xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N );  rpcTempCU->initEstData( uiDepth, iQP );//by Competition for inter_2Nx2N
+          xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N, bFMD );  rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode  );//by Competition for inter_2Nx2N
+#else
+          xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N, bIsLosslessMode  );  rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode  );//by Competition for inter_2Nx2N
 #endif
 #if H_3D_VSP
@@ -663,5 +637,5 @@
         bFMD = bIVFMerge && rpcBestCU->isSkipped(0);
 #endif
-        rpcTempCU->initEstData( uiDepth, iQP );
+        rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 #if H_3D_VSP
         rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
@@ -675,7 +649,7 @@
 #endif
 #if  H_3D_FAST_TEXTURE_ENCODING
-            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N, bFMD );  rpcTempCU->initEstData( uiDepth, iQP );
-#else
-            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N );  rpcTempCU->initEstData( uiDepth, iQP );
+            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N, bFMD );  rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+#else
+            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N );  rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 #endif
 #if H_3D_VSP
@@ -687,5 +661,5 @@
           {
             xCheckRDCostInterDBBP( rpcBestCU, rpcTempCU, false );
-            rpcTempCU->initEstData( uiDepth, iQP );
+            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode  );
 #if H_3D_VSP
             rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
@@ -710,5 +684,5 @@
       }
 #endif
-      if (isAddLowestQP && (iQP == lowestQP))
+      if ( bIsLosslessMode )
       {
         iQP = iMinQP;
@@ -716,5 +690,5 @@
     }
 
-#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
+#if KWU_RC_MADPRED_E0227
     if ( uiDepth <= m_addSADDepth )
     {
@@ -723,27 +697,4 @@
     }
 #endif
-#if RATE_CONTROL_LAMBDA_DOMAIN && M0036_RC_IMPROVEMENT && KWU_RC_MADPRED_E0227
-    if ( uiDepth <= m_addSADDepth )
-    {
-      m_LCUPredictionSAD += m_temporalSAD;
-      m_addSADDepth = uiDepth;
-    }
-#endif
-#if !RATE_CONTROL_LAMBDA_DOMAIN && KWU_RC_MADPRED_E0227
-if ( uiDepth <= m_addSADDepth )
-{
-  m_LCUPredictionSAD += m_temporalSAD;
-  m_addSADDepth = uiDepth;
-}
-#endif
-#if !RATE_CONTROL_LAMBDA_DOMAIN && KWU_FIX_URQ
-    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 H_3D_DIM_ENC
     if( rpcBestCU->getSlice()->getIsDepth() && rpcBestCU->getSlice()->isIRAP() )
@@ -757,9 +708,11 @@
       for (Int iQP=iMinQP; iQP<=iMaxQP; iQP++)
       {
-        if (isAddLowestQP && (iQP == iMinQP))
+        const Bool bIsLosslessMode = isAddLowestQP && (iQP == iMinQP);
+
+        if (bIsLosslessMode)
         {
           iQP = lowestQP;
         }
-        rpcTempCU->initEstData( uiDepth, iQP );
+        rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 
         // do inter modes, NxN, 2NxN, and Nx2N
@@ -780,5 +733,5 @@
                 xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_NxN   );
 #endif
-                rpcTempCU->initEstData( uiDepth, iQP );
+                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 #if H_3D_VSP
                 rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
@@ -799,5 +752,5 @@
             xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_Nx2N  );
 #endif
-            rpcTempCU->initEstData( uiDepth, iQP );
+            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 #if H_3D_VSP
             rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
@@ -819,5 +772,5 @@
             xCheckRDCostInter      ( rpcBestCU, rpcTempCU, SIZE_2NxN  );
 #endif
-            rpcTempCU->initEstData( uiDepth, iQP );
+            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 #if H_3D_VSP
             rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
@@ -858,5 +811,5 @@
                 xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU );
 #endif
-                rpcTempCU->initEstData( uiDepth, iQP );
+                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 #if H_3D_VSP
                 rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
@@ -878,5 +831,5 @@
                 xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD );
 #endif
-                rpcTempCU->initEstData( uiDepth, iQP );
+                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 #if H_3D_VSP
                 rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
@@ -902,5 +855,5 @@
                 xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU, true );
 #endif
-                rpcTempCU->initEstData( uiDepth, iQP );
+                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 #if H_3D_VSP
                 rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
@@ -922,5 +875,5 @@
                 xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD, true );
 #endif
-                rpcTempCU->initEstData( uiDepth, iQP );
+                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 #if H_3D_VSP
                 rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
@@ -948,5 +901,5 @@
                 xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N );
 #endif
-                rpcTempCU->initEstData( uiDepth, iQP );
+                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 #if H_3D_VSP
                 rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
@@ -968,5 +921,5 @@
                 xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N );
 #endif
-                rpcTempCU->initEstData( uiDepth, iQP );
+                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 #if H_3D_VSP
                 rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
@@ -988,5 +941,5 @@
                 xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N, true );
 #endif
-                rpcTempCU->initEstData( uiDepth, iQP );
+                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 #if H_3D_VSP
                 rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
@@ -1008,5 +961,5 @@
                 xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N, true );
 #endif
-                rpcTempCU->initEstData( uiDepth, iQP );
+                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 #if H_3D_VSP
                 rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
@@ -1022,10 +975,10 @@
 #endif
               xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU );
-              rpcTempCU->initEstData( uiDepth, iQP );
+              rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 #if H_3D_VSP
               rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
 #endif
               xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD );
-              rpcTempCU->initEstData( uiDepth, iQP );
+              rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 #if H_3D_VSP
               rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
@@ -1037,10 +990,10 @@
 #endif
               xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N );
-              rpcTempCU->initEstData( uiDepth, iQP );
+              rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 #if H_3D_VSP
               rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
 #endif
               xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N );
-              rpcTempCU->initEstData( uiDepth, iQP );
+              rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 #if H_3D_VSP
               rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
@@ -1072,5 +1025,5 @@
             xCheckRDCostIntra( rpcBestCU, rpcTempCU, SIZE_2Nx2N );
 
-#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT && KWU_RC_MADPRED_E0227
+#if KWU_RC_MADPRED_E0227
             if ( uiDepth <= m_addSADDepth )
             {
@@ -1079,20 +1032,6 @@
             }
 #endif
-#if RATE_CONTROL_LAMBDA_DOMAIN && M0036_RC_IMPROVEMENT && KWU_RC_MADPRED_E0227
-            if ( uiDepth <= m_addSADDepth )
-            {
-              m_LCUPredictionSAD += m_spatialSAD;
-              m_addSADDepth = uiDepth;
-            }
-#endif
-
-#if !RATE_CONTROL_LAMBDA_DOMAIN && KWU_RC_MADPRED_E0227
-            if ( uiDepth <= m_addSADDepth )
-            {
-              m_LCUPredictionSAD += m_spatialSAD;
-              m_addSADDepth = uiDepth;
-            }
-#endif
-            rpcTempCU->initEstData( uiDepth, iQP );
+
+            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
             if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
             {
@@ -1104,5 +1043,5 @@
                 {
                   xCheckRDCostIntra( rpcBestCU, rpcTempCU, SIZE_NxN   );
-                  rpcTempCU->initEstData( uiDepth, iQP );
+                  rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
                 }
 #if H_3D_QTLPC
@@ -1126,5 +1065,5 @@
           {
             xCheckIntraPCM (rpcBestCU, rpcTempCU);
-            rpcTempCU->initEstData( uiDepth, iQP );
+            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
           }
         }
@@ -1132,5 +1071,5 @@
         }
 #endif
-        if (isAddLowestQP && (iQP == lowestQP))
+        if (bIsLosslessMode)
         {
           iQP = iMinQP;
@@ -1142,14 +1081,5 @@
     m_pcEntropyCoder->encodeSplitFlag( rpcBestCU, 0, uiDepth, true );
     rpcBestCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // split bits
-    if(m_pcEncCfg->getUseSBACRD())
-    {
       rpcBestCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
-    }
-
-#if H_3D_VSO // M8
-    if ( m_pcRdCost->getUseVSO() )    
-      rpcBestCU->getTotalCost()  = m_pcRdCost->calcRdCostVSO( rpcBestCU->getTotalBits(), rpcBestCU->getTotalDistortion() );    
-    else
-#endif
     rpcBestCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcBestCU->getTotalBits(), rpcBestCU->getTotalDistortion() );
 
@@ -1173,7 +1103,4 @@
   {
     bBoundary = true;
-#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
-    m_addSADDepth++;
-#endif
   }
 
@@ -1188,9 +1115,4 @@
     iMinQP = Clip3( -rpcTempCU->getSlice()->getSPS()->getQpBDOffsetY(), MAX_QP, iBaseQP-idQP );
     iMaxQP = Clip3( -rpcTempCU->getSlice()->getSPS()->getQpBDOffsetY(), MAX_QP, iBaseQP+idQP );
-    if ( (rpcTempCU->getSlice()->getSPS()->getUseLossless()) && (lowestQP < iMinQP) && rpcTempCU->getSlice()->getPPS()->getUseDQP() )
-    {
-      isAddLowestQP = true;
-      iMinQP = iMinQP - 1;      
-    }
   }
   else if( (g_uiMaxCUWidth>>uiDepth) > rpcTempCU->getSlice()->getPPS()->getMinCuDQPSize() )
@@ -1214,5 +1136,4 @@
     iMaxQP = iStartQP;
   }
-#if RATE_CONTROL_LAMBDA_DOMAIN
   if ( m_pcEncCfg->getUseRateCtrl() )
   {
@@ -1220,19 +1141,13 @@
     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 ( m_pcEncCfg->getCUTransquantBypassFlagForceValue() )
+  {
+    iMaxQP = iMinQP; // If all blocks are forced into using transquant bypass, do not loop here.
+  }
   for (Int iQP=iMinQP; iQP<=iMaxQP; iQP++)
   {
-    if (isAddLowestQP && (iQP == iMinQP))
-    {
-      iQP = lowestQP;
-    }
-    rpcTempCU->initEstData( uiDepth, iQP );
+    const Bool bIsLosslessMode = false; // False at this level. Next level down may set it to true.
+    rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 
     // further split
@@ -1267,6 +1182,4 @@
         if(bInSlice && ( pcSubBestPartCU->getCUPelX() < pcSlice->getSPS()->getPicWidthInLumaSamples() ) && ( pcSubBestPartCU->getCUPelY() < pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
         {
-          if( m_bUseSBACRD )
-          {
             if ( 0 == uiPartUnitIdx) //initialize RD with previous depth buffer
             {
@@ -1277,5 +1190,4 @@
               m_pppcRDSbacCoder[uhNextDepth][CI_CURR_BEST]->load(m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]);
             }
-          }
 
 #if AMP_ENC_SPEEDUP
@@ -1308,10 +1220,6 @@
 
         rpcTempCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // split bits
-        if(m_pcEncCfg->getUseSBACRD())
-        {
           rpcTempCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
         }
-      }
-
 #if H_3D_VSO // M10
       if ( m_pcRdCost->getUseVSO() )
@@ -1349,8 +1257,5 @@
           m_pcEntropyCoder->encodeQP( rpcTempCU, uiTargetPartIdx, false );
           rpcTempCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // dQP bits
-          if(m_pcEncCfg->getUseSBACRD())
-          {
             rpcTempCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
-          }
 #if H_3D_VSO // M11
           if ( m_pcRdCost->getUseLambdaScaleVSO())          
@@ -1371,8 +1276,5 @@
       }
 
-      if( m_bUseSBACRD )
-      {
         m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
-      }
       Bool isEndOfSlice        = rpcBestCU->getSlice()->getSliceMode()==FIXED_NUMBER_OF_BYTES
                                  && (rpcBestCU->getTotalBits()>rpcBestCU->getSlice()->getSliceArgument()<<3);
@@ -1385,10 +1287,5 @@
       xCheckBestMode( rpcBestCU, rpcTempCU, uiDepth);                                  // RD compare current larger prediction
     }                                                                                  // with sub partitioned prediction.
-    if (isAddLowestQP && (iQP == lowestQP))
-    {
-      iQP = iMinQP;
-    }
-  }
-
+    }
 
 #if H_3D_VSO // M12 
@@ -1402,5 +1299,4 @@
   }
 #endif
-
   rpcBestCU->copyToPic(uiDepth);                                                     // Copy Best data to Picture for next partition prediction.
 
@@ -1683,5 +1579,4 @@
 }
 
-#if RATE_CONTROL_INTRA
 Int xCalcHADs8x8_ISlice(Pel *piOrg, Int iStrideOrg) 
 {
@@ -1798,5 +1693,4 @@
   return(iSumHad);
 }
-#endif
 
 /** check RD costs for a CU block encoded with merge
@@ -1816,4 +1710,5 @@
 #endif
   Int numValidMergeCand = 0;
+  const Bool bTransquantBypassFlag = rpcTempCU->getCUTransquantBypass(0);
 
   for( UInt ui = 0; ui < rpcTempCU->getSlice()->getMaxNumMergeCand(); ++ui )
@@ -1840,5 +1735,4 @@
 #else
   rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uhDepth ); // interprets depth relative to LCU level
-  rpcTempCU->setCUTransquantBypassSubParts( m_pcEncCfg->getCUTransquantBypassFlagValue(), 0, uhDepth );
 #endif
 
@@ -1968,5 +1862,5 @@
           // set MC parameters
           rpcTempCU->setPredModeSubParts( MODE_INTER, 0, uhDepth ); // interprets depth relative to LCU level
-          rpcTempCU->setCUTransquantBypassSubParts( m_pcEncCfg->getCUTransquantBypassFlagValue(),     0, uhDepth );
+          rpcTempCU->setCUTransquantBypassSubParts( bTransquantBypassFlag,     0, uhDepth );
           rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uhDepth ); // interprets depth relative to LCU level
 #if H_3D_IC
@@ -2160,5 +2054,5 @@
           }
 #endif
-          rpcTempCU->initEstData( uhDepth, orgQP );
+          rpcTempCU->initEstData( uhDepth, orgQP, bTransquantBypassFlag );
 
       if( m_pcEncCfg->getUseFastDecisionForMerge() && !bestIsSkip )
@@ -2274,6 +2168,4 @@
   rpcTempCU->setPartSizeSubParts  ( ePartSize,  0, uhDepth );
   rpcTempCU->setPredModeSubParts  ( MODE_INTER, 0, uhDepth );
-  rpcTempCU->setCUTransquantBypassSubParts  ( m_pcEncCfg->getCUTransquantBypassFlagValue(),      0, uhDepth );
-  
 #if MTK_DDD_G0063
   rpcTempCU->setUseDDD( false, 0, uhDepth );
@@ -2328,5 +2220,5 @@
 #endif
 
-#if RATE_CONTROL_LAMBDA_DOMAIN  && (!M0036_RC_IMPROVEMENT || KWU_RC_MADPRED_E0227)
+#if KWU_RC_MADPRED_E0227
   if ( m_pcEncCfg->getUseRateCtrl() && m_pcEncCfg->getLCULevelRC() && ePartSize == SIZE_2Nx2N && uhDepth <= m_addSADDepth )
   {
@@ -2337,16 +2229,5 @@
   }
 #endif
-#if !RATE_CONTROL_LAMBDA_DOMAIN  && KWU_RC_MADPRED_E0227
-  if ( m_pcEncCfg->getUseRateCtrl() && 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 );
-  
 #if NTT_STORE_SPDV_VSP_G0148 // possible bug fix
   if( rpcTempCU->getQtRootCbf(0)==0 )
@@ -2657,5 +2538,4 @@
   rpcTempCU->setPartSizeSubParts( eSize, 0, uiDepth );
   rpcTempCU->setPredModeSubParts( MODE_INTRA, 0, uiDepth );
-  rpcTempCU->setCUTransquantBypassSubParts( m_pcEncCfg->getCUTransquantBypassFlagValue(), 0, uiDepth );
   
   Bool bSeparateLumaChroma = true; // choose estimation mode
@@ -2693,12 +2573,8 @@
   setdQPFlag( bCodeDQP );
   
-  if( m_bUseSBACRD ) m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
+  m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
   
   rpcTempCU->getTotalBits() = m_pcEntropyCoder->getNumberOfWrittenBits();
-  if(m_pcEncCfg->getUseSBACRD())
-  {
     rpcTempCU->getTotalBins() = ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
-  }
-
 #if H_3D_VSO // M6
   if( m_pcRdCost->getUseLambdaScaleVSO())  
@@ -2708,34 +2584,4 @@
   rpcTempCU->getTotalCost() = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
   
-#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT && KWU_RC_MADPRED_E0227
-  UChar uhDepth = rpcTempCU->getDepth( 0 );
-  if ( m_pcEncCfg->getUseRateCtrl() && m_pcEncCfg->getLCULevelRC() && eSize == 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_spatialSAD = (Int)SAD;
-  }
-#endif
-#if RATE_CONTROL_LAMBDA_DOMAIN && M0036_RC_IMPROVEMENT && KWU_RC_MADPRED_E0227
-  UChar uhDepth = rpcTempCU->getDepth( 0 );
-  if ( m_pcEncCfg->getUseRateCtrl() && m_pcEncCfg->getLCULevelRC() && eSize == 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_spatialSAD = (Int)SAD;
-  }
-#endif
-#if !RATE_CONTROL_LAMBDA_DOMAIN && KWU_RC_MADPRED_E0227
-  UChar uhDepth = rpcTempCU->getDepth( 0 );
-  if ( m_pcEncCfg->getUseRateCtrl() && eSize == 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_spatialSAD = (Int)SAD;
-  }
-#endif
   xCheckDQP( rpcTempCU );
   xCheckBestMode(rpcBestCU, rpcTempCU, uiDepth);
@@ -2760,9 +2606,8 @@
   rpcTempCU->setPredModeSubParts( MODE_INTRA, 0, uiDepth );
   rpcTempCU->setTrIdxSubParts ( 0, 0, uiDepth );
-  rpcTempCU->setCUTransquantBypassSubParts( m_pcEncCfg->getCUTransquantBypassFlagValue(), 0, uiDepth );
 
   m_pcPredSearch->IPCMSearch( rpcTempCU, m_ppcOrigYuv[uiDepth], m_ppcPredYuvTemp[uiDepth], m_ppcResiYuvTemp[uiDepth], m_ppcRecoYuvTemp[uiDepth]);
 
-  if( m_bUseSBACRD ) m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
+  m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
 
   m_pcEntropyCoder->resetBits();
@@ -2779,11 +2624,8 @@
   m_pcEntropyCoder->encodeIPCMInfo ( rpcTempCU, 0, true );
 
-  if( m_bUseSBACRD ) m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
+  m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
 
   rpcTempCU->getTotalBits() = m_pcEntropyCoder->getNumberOfWrittenBits();
-  if(m_pcEncCfg->getUseSBACRD())
-  {
     rpcTempCU->getTotalBins() = ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
-  }
 #if H_3D_VSO // M44
   if ( m_pcRdCost->getUseVSO() )
@@ -2825,5 +2667,5 @@
     pcCU  = NULL;
 
-    if( m_bUseSBACRD )  // store temp best CI for next CU coding
+    // store temp best CI for next CU coding
       m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]->store(m_pppcRDSbacCoder[uiDepth][CI_NEXT_BEST]);
   }
@@ -2842,8 +2684,5 @@
       m_pcEntropyCoder->encodeQP( pcCU, 0, false );
       pcCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // dQP bits
-      if(m_pcEncCfg->getUseSBACRD())
-      {
         pcCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
-      }
 #if H_3D_VSO // M45
       if ( m_pcRdCost->getUseVSO() )      
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncCu.h
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncCu.h	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncCu.h	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -104,13 +104,6 @@
   TEncSbac***             m_pppcRDSbacCoder;
   TEncSbac*               m_pcRDGoOnSbacCoder;
-  Bool                    m_bUseSBACRD;
   TEncRateCtrl*           m_pcRateCtrl;
-#if RATE_CONTROL_LAMBDA_DOMAIN
-#if !M0036_RC_IMPROVEMENT
-  UInt                    m_LCUPredictionSAD;
-  Int                     m_addSADDepth;
-  Int                     m_temporalSAD;
-#endif
-#if M0036_RC_IMPROVEMENT && KWU_RC_MADPRED_E0227
+#if KWU_RC_MADPRED_E0227
   UInt                    m_LCUPredictionSAD;
   Int                     m_addSADDepth;
@@ -118,12 +111,4 @@
   Int                     m_spatialSAD;
 #endif
-#endif
-#if !RATE_CONTROL_LAMBDA_DOMAIN && KWU_RC_MADPRED_E0227
-  UInt                    m_LCUPredictionSAD;
-  Int                     m_addSADDepth;
-  Int                     m_temporalSAD;
-  Int                     m_spatialSAD;
-#endif
-
 public:
   /// copy parameters from encoder class
@@ -143,10 +128,8 @@
   
   Void setBitCounter        ( TComBitCounter* pcBitCounter ) { m_pcBitCounter = pcBitCounter; }
-#if (RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT) || KWU_RC_MADPRED_E0227
+#if KWU_RC_MADPRED_E0227
   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        );
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncEntropy.cpp
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncEntropy.cpp	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncEntropy.cpp	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -51,13 +51,4 @@
 Void TEncEntropy::encodeSliceHeader ( TComSlice* pcSlice )
 {
-  if (pcSlice->getSPS()->getUseSAO())
-  {
-    SAOParam *saoParam = pcSlice->getPic()->getPicSym()->getSaoParam();
-    pcSlice->setSaoEnabledFlag     (saoParam->bSaoFlag[0]);
-    {
-      pcSlice->setSaoEnabledFlagChroma   (saoParam->bSaoFlag[1]);
-    }
-  }
-
   m_pcEntropyCoderIf->codeSliceHeader( pcSlice );
   return;
@@ -787,97 +778,4 @@
 }
 
-/** Encode SAO Offset
- * \param  saoLcuParam SAO LCU paramters
- */
-Void TEncEntropy::encodeSaoOffset(SaoLcuParam* saoLcuParam, UInt compIdx)
-{
-  UInt uiSymbol;
-  Int i;
-
-  uiSymbol = saoLcuParam->typeIdx + 1;
-  if (compIdx!=2)
-  {
-    m_pcEntropyCoderIf->codeSaoTypeIdx(uiSymbol);
-  }
-  if (uiSymbol)
-  {
-    if (saoLcuParam->typeIdx < 4 && compIdx != 2)
-    {
-      saoLcuParam->subTypeIdx = saoLcuParam->typeIdx;
-    }
-    Int bitDepth = compIdx ? g_bitDepthC : g_bitDepthY;
-    Int offsetTh = 1 << min(bitDepth - 5,5);
-    if( saoLcuParam->typeIdx == SAO_BO )
-    {
-      for( i=0; i< saoLcuParam->length; i++)
-      {
-        UInt absOffset = ( (saoLcuParam->offset[i] < 0) ? -saoLcuParam->offset[i] : saoLcuParam->offset[i]);
-        m_pcEntropyCoderIf->codeSaoMaxUvlc(absOffset, offsetTh-1);
-      }  
-      for( i=0; i< saoLcuParam->length; i++)
-      {
-        if (saoLcuParam->offset[i] != 0)
-        {
-          UInt sign = (saoLcuParam->offset[i] < 0) ? 1 : 0 ;
-          m_pcEntropyCoderIf->codeSAOSign(sign);
-        }
-      }
-      uiSymbol = (UInt) (saoLcuParam->subTypeIdx);
-      m_pcEntropyCoderIf->codeSaoUflc(5, uiSymbol);
-    }
-    else if( saoLcuParam->typeIdx < 4 )
-    {
-      m_pcEntropyCoderIf->codeSaoMaxUvlc( saoLcuParam->offset[0], offsetTh-1);
-      m_pcEntropyCoderIf->codeSaoMaxUvlc( saoLcuParam->offset[1], offsetTh-1);
-      m_pcEntropyCoderIf->codeSaoMaxUvlc(-saoLcuParam->offset[2], offsetTh-1);
-      m_pcEntropyCoderIf->codeSaoMaxUvlc(-saoLcuParam->offset[3], offsetTh-1);
-      if (compIdx!=2)
-      {
-        uiSymbol = (UInt) (saoLcuParam->subTypeIdx);
-        m_pcEntropyCoderIf->codeSaoUflc(2, uiSymbol);
-      }
-    }
-  }
-}
-
-/** Encode SAO unit interleaving
-* \param  rx
-* \param  ry
-* \param  pSaoParam
-* \param  pcCU
-* \param  iCUAddrInSlice
-* \param  iCUAddrUpInSlice
-* \param  bLFCrossSliceBoundaryFlag
- */
-Void TEncEntropy::encodeSaoUnitInterleaving(Int compIdx, Bool saoFlag, Int rx, Int ry, SaoLcuParam* saoLcuParam, Int cuAddrInSlice, Int cuAddrUpInSlice, Int allowMergeLeft, Int allowMergeUp)
-{
-  if (saoFlag)
-  {
-    if (rx>0 && cuAddrInSlice!=0 && allowMergeLeft)
-    {
-      m_pcEntropyCoderIf->codeSaoMerge(saoLcuParam->mergeLeftFlag);
-    }
-    else
-    {
-      saoLcuParam->mergeLeftFlag = 0;
-    }
-    if (saoLcuParam->mergeLeftFlag == 0)
-    {
-      if ( (ry > 0) && (cuAddrUpInSlice>=0) && allowMergeUp )
-      {
-        m_pcEntropyCoderIf->codeSaoMerge(saoLcuParam->mergeUpFlag);
-      }
-      else
-      {
-        saoLcuParam->mergeUpFlag = 0;
-      }
-      if (!saoLcuParam->mergeUpFlag)
-      {
-        encodeSaoOffset(saoLcuParam, compIdx);
-      }
-    }
-  }
-}
-
 Int TEncEntropy::countNonZeroCoeffs( TCoeff* pcCoef, UInt uiSize )
 {
@@ -900,100 +798,3 @@
 }
 
-#if H_3D_INTER_SDC
-#if QC_SDC_UNIFY_G0130
-Void TEncEntropy::encodeDeltaDC  ( TComDataCU* pcCU, UInt absPartIdx )
-{
-  m_pcEntropyCoderIf->codeDeltaDC( pcCU, absPartIdx );
-}
-
-Void TEncEntropy::encodeSDCFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
-{
-  if( ( !pcCU->isIntra( uiAbsPartIdx ) && !pcCU->getSlice()->getVPS()->getInterSDCFlag( pcCU->getSlice()->getLayerIdInVps() ) ) || 
-    ( pcCU->isIntra( uiAbsPartIdx ) && !pcCU->getSlice()->getVPS()->getVpsDepthModesFlag( pcCU->getSlice()->getLayerIdInVps() ) ) )
-  {
-    return;
-  }
-
-#if SEC_INTER_SDC_G0101
-  if( !pcCU->getSlice()->getIsDepth() || pcCU->getPartitionSize( uiAbsPartIdx ) != SIZE_2Nx2N || pcCU->isSkipped( uiAbsPartIdx ) )
-#else
-  if( !pcCU->getSlice()->getIsDepth() || ( pcCU->isIntra( uiAbsPartIdx ) && pcCU->getPartitionSize( uiAbsPartIdx ) != SIZE_2Nx2N ) || pcCU->isSkipped( uiAbsPartIdx ) )
-#endif
-  {
-    return;
-  }
-
-#if SEC_INTER_SDC_G0101
-  assert( pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_2Nx2N || ( !pcCU->isIntra( uiAbsPartIdx ) && !pcCU->isSkipped( uiAbsPartIdx ) ) );
-#else
-  assert( ( pcCU->isIntra( uiAbsPartIdx ) && pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_2Nx2N ) || ( !pcCU->isIntra( uiAbsPartIdx ) && !pcCU->isSkipped( uiAbsPartIdx ) ) );
-#endif
-
-  if( bRD )
-  {
-    uiAbsPartIdx = 0;
-  }
-
-  m_pcEntropyCoderIf->codeSDCFlag( pcCU, uiAbsPartIdx );
-}
-#else
-Void TEncEntropy::encodeInterSDCFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
-{
-  if( !pcCU->getSlice()->getVPS()->getInterSDCFlag( pcCU->getSlice()->getLayerIdInVps() ) )
-  {
-    return;
-  }
-
-  if( !pcCU->getSlice()->getIsDepth() || pcCU->isIntra( uiAbsPartIdx ) || pcCU->isSkipped( uiAbsPartIdx ) )
-  {
-    return;
-  }
-
-  if( bRD )
-  {
-    uiAbsPartIdx = 0;
-  }
-
-  m_pcEntropyCoderIf->codeInterSDCFlag( pcCU, uiAbsPartIdx );
-}
-
-Void TEncEntropy::encodeInterSDCResidualData( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
-{
-  if( !pcCU->getSlice()->getVPS()->getInterSDCFlag( pcCU->getSlice()->getLayerIdInVps() ) )
-  {
-    return;
-  }
-
-  if( !pcCU->getSlice()->getIsDepth() || pcCU->isIntra( uiAbsPartIdx ) || !pcCU->getInterSDCFlag( uiAbsPartIdx ) )
-  {
-    return;
-  }
-
-  if( bRD )
-  {
-    uiAbsPartIdx = 0;
-  }
-
-  // number of segments depends on prediction mode for INTRA
-  UInt uiNumSegments = ( pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_2Nx2N ) ? 1 : ( pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_NxN ? 4 : 2 );
-
-  // encode residual data for each segment
-  for( UInt uiSeg = 0; uiSeg < uiNumSegments; uiSeg++ )
-  {
-    m_pcEntropyCoderIf->codeInterSDCResidualData( pcCU, uiAbsPartIdx, uiSeg );
-  }
-}
-#endif
-#endif
-#if H_3D_DBBP
-Void TEncEntropy::encodeDBBPFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
-{
-  if( bRD )
-  {
-    uiAbsPartIdx = 0;
-  }
-  m_pcEntropyCoderIf->codeDBBPFlag( pcCU, uiAbsPartIdx );
-}
-#endif
-
 //! \}
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncEntropy.h
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncEntropy.h	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncEntropy.h	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -127,9 +127,4 @@
   virtual Void codeCoeffNxN      ( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType ) = 0;
   virtual Void codeTransformSkipFlags ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, TextType eTType ) = 0;
-  virtual Void codeSAOSign          ( UInt code   ) = 0;
-  virtual Void codeSaoMaxUvlc       ( UInt code, UInt maxSymbol ) = 0;
-  virtual Void codeSaoMerge    ( UInt   uiCode  ) = 0;
-  virtual Void codeSaoTypeIdx      ( UInt   uiCode) = 0;
-  virtual Void codeSaoUflc         ( UInt uiLength, UInt   uiCode ) = 0;
   virtual Void estBit               (estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType) = 0;
   
@@ -232,6 +227,4 @@
   
   Void estimateBit             ( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType);
-  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);
   static Int countNonZeroCoeffs( TCoeff* pcCoef, UInt uiSize );
 
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncGOP.cpp
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -105,4 +105,8 @@
 #endif
 #endif
+#if FIX1172
+  m_associatedIRAPType = NAL_UNIT_CODED_SLICE_IDR_N_LP;
+  m_associatedIRAPPOC  = 0;
+#endif
   return;
 }
@@ -472,5 +476,5 @@
     }
 
-    if( getNalUnitType(pocCurr, m_iLastIDR) == NAL_UNIT_CODED_SLICE_IDR_W_RADL || getNalUnitType(pocCurr, m_iLastIDR) == NAL_UNIT_CODED_SLICE_IDR_N_LP )
+    if( getNalUnitType(pocCurr, m_iLastIDR, isField) == NAL_UNIT_CODED_SLICE_IDR_W_RADL || getNalUnitType(pocCurr, m_iLastIDR, isField) == NAL_UNIT_CODED_SLICE_IDR_N_LP )
     {
       m_iLastIDR = pocCurr;
@@ -551,5 +555,5 @@
 #if H_MV
     // Set the nal unit type
-    pcSlice->setNalUnitType(getNalUnitType(pocCurr, m_iLastIDR));
+    pcSlice->setNalUnitType(getNalUnitType(pocCurr, m_iLastIDR, isField));
     if( pcSlice->getSliceType() == B_SLICE )
     {
@@ -559,4 +563,13 @@
       }
     }
+
+// To be checked!
+    if( pcSlice->getSliceType() == B_SLICE )
+    {
+      if( m_pcCfg->getGOPEntry( ( pcSlice->getRapPicFlag() && getLayerId() > 0 ) ? MAX_GOP : iGOPid ).m_sliceType == 'I' ) 
+      { 
+        pcSlice->setSliceType( I_SLICE );
+      }
+    }
 #else
     if(pcSlice->getSliceType()==B_SLICE&&m_pcCfg->getGOPEntry(iGOPid).m_sliceType=='P')
@@ -564,6 +577,11 @@
       pcSlice->setSliceType(P_SLICE);
     }
+    if(pcSlice->getSliceType()==B_SLICE&&m_pcCfg->getGOPEntry(iGOPid).m_sliceType=='I')
+    {
+      pcSlice->setSliceType(I_SLICE);
+    }
+    
     // Set the nal unit type
-    pcSlice->setNalUnitType(getNalUnitType(pocCurr, m_iLastIDR));
+    pcSlice->setNalUnitType(getNalUnitType(pocCurr, m_iLastIDR, isField));
 #endif
     if(pcSlice->getTemporalLayerNonReferenceFlag())
@@ -589,19 +607,31 @@
     m_pcEncTop->selectReferencePictureSet(pcSlice, pocCurr, iGOPid);
     pcSlice->getRPS()->setNumberOfLongtermPictures(0);
-
-#if FIX1071
+#if FIX1172
+    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
+      || 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 )  // IRAP picture
+    {
+      m_associatedIRAPType = pcSlice->getNalUnitType();
+      m_associatedIRAPPOC = pocCurr;
+    }
+    pcSlice->setAssociatedIRAPType(m_associatedIRAPType);
+    pcSlice->setAssociatedIRAPPOC(m_associatedIRAPPOC);
+#endif
+
     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());
 
-    if(pcSlice->getTLayer() > 0)
+    if(pcSlice->getTLayer() > 0 
+      &&  !( pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_RADL_N     // Check if not a leading picture
+          || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_RADL_R
+          || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_N
+          || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_R )
+        )
     {
       if(pcSlice->isTemporalLayerSwitchingPoint(rcListPic) || pcSlice->getSPS()->getTemporalIdNestingFlag())
@@ -613,5 +643,5 @@
         else
         {
-          pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TLA_R);
+          pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TSA_R);
         }
       }
@@ -907,5 +937,4 @@
     pcPic->getSlice(pcSlice->getSliceIdx())->setMvdL1ZeroFlag(pcSlice->getMvdL1ZeroFlag());
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
     Double lambda            = 0.0;
     Int actualHeadBits       = 0;
@@ -944,15 +973,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 )
           {
@@ -963,10 +986,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 );
       }
@@ -984,9 +1003,5 @@
 #endif
         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 );
 #if KWU_RC_MADPRED_E0227
@@ -1000,5 +1015,4 @@
       m_pcSliceEncoder->resetQP( pcPic, sliceQP, lambda );
     }
-#endif
 
     UInt uiNumSlices = 1;
@@ -1203,8 +1217,7 @@
 
     // SAO parameter estimation using non-deblocked pixels for LCU bottom and right boundary areas
-    if( m_pcCfg->getSaoLcuBasedOptimization() && m_pcCfg->getSaoLcuBoundary() )
-    {
-      m_pcSAO->resetStats();
-      m_pcSAO->calcSaoStatsCu_BeforeDblk( pcPic );
+    if( pcSlice->getSPS()->getUseSAO() && m_pcCfg->getSaoLcuBoundary() )
+    {
+      m_pcSAO->getPreDBFStatistics(pcPic);
     }
 
@@ -1218,24 +1231,4 @@
     m_pcLoopFilter->loopFilterPic( pcPic );
 
-    pcSlice = pcPic->getSlice(0);
-    if(pcSlice->getSPS()->getUseSAO())
-    {
-      std::vector<Bool> LFCrossSliceBoundaryFlag;
-      for(Int s=0; s< uiNumSlices; s++)
-      {
-        LFCrossSliceBoundaryFlag.push_back(  ((uiNumSlices==1)?true:pcPic->getSlice(s)->getLFCrossSliceBoundaryFlag()) );
-      }
-      m_storedStartCUAddrForEncodingSlice.resize(uiNumSlices+1);
-      pcPic->createNonDBFilterInfo(m_storedStartCUAddrForEncodingSlice, 0, &LFCrossSliceBoundaryFlag ,pcPic->getPicSym()->getNumTiles() ,bLFCrossTileBoundary);
-    }
-
-
-    pcSlice = pcPic->getSlice(0);
-
-    if(pcSlice->getSPS()->getUseSAO())
-    {
-      m_pcSAO->createPicSaoInfo(pcPic);
-    }
-
     /////////////////////////////////////////////////////////////////////////////////////////////////// File writing
     // Set entropy coder
@@ -1254,7 +1247,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 H_MV
@@ -1296,7 +1287,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 H_MV
@@ -1313,7 +1302,6 @@
       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 PPS_FIX_DEPTH
       }
@@ -1343,5 +1331,5 @@
         {
           SOPcurrPOC += deltaPOC;
-          SOPDescriptionSEI.m_sopDescVclNaluType[i] = getNalUnitType(SOPcurrPOC, m_iLastIDR);
+          SOPDescriptionSEI.m_sopDescVclNaluType[i] = getNalUnitType(SOPcurrPOC, m_iLastIDR, isField);
           SOPDescriptionSEI.m_sopDescTemporalId[i] = m_pcCfg->getGOPEntry(j).m_temporalId;
           SOPDescriptionSEI.m_sopDescStRpsIdx[i] = m_pcEncTop->getReferencePictureSetIdxForSOP(pcSlice, SOPcurrPOC, j);
@@ -1621,11 +1609,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?
@@ -1748,7 +1732,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
@@ -1794,31 +1776,24 @@
               m_pcEntropyCoder->resetEntropy();
               m_pcEntropyCoder->setBitstream( m_pcBitCounter );
-              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());
-#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();
+            Bool sliceEnabled[NUM_SAO_COMPONENTS];
+            m_pcSAO->initRDOCabacCoder(m_pcEncTop->getRDGoOnSbacCoder(), pcSlice);
+            m_pcSAO->SAOProcess(pcPic
+              , sliceEnabled
+              , pcPic->getSlice(0)->getLambdas()
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+              , m_pcCfg->getSaoLcuBoundary()
+#endif
+              );
               m_pcSAO->PCMLFDisableProcess(pcPic);
-            }
-#if SAO_RDO
-            m_pcEntropyCoder->setEntropyCoder ( m_pcCavlcCoder, pcSlice );
-#endif
-            processingState = ENCODE_SLICE;
-
+
+            //assign SAO slice header
             for(Int s=0; s< uiNumSlices; s++)
             {
-              if (pcSlice->getSPS()->getUseSAO())
-              {
-                pcPic->getSlice(s)->setSaoEnabledFlag((pcSlice->getPic()->getPicSym()->getSaoParam()->bSaoFlag[0]==1)?true:false);
+              pcPic->getSlice(s)->setSaoEnabledFlag(sliceEnabled[SAO_Y]);
+              assert(sliceEnabled[SAO_Cb] == sliceEnabled[SAO_Cr]);
+              pcPic->getSlice(s)->setSaoEnabledFlagChroma(sliceEnabled[SAO_Cb]);
               }
             }
+          processingState = ENCODE_SLICE;
           }
           break;
@@ -1831,13 +1806,4 @@
         }
       } // end iteration over slices
-
-      if(pcSlice->getSPS()->getUseSAO())
-      {
-        if(pcSlice->getSPS()->getUseSAO())
-        {
-          m_pcSAO->destroyPicSaoInfo();
-        }
-        pcPic->destroyNonDBFilterInfo();
-      }
 #if H_3D
       pcPic->compressMotion(2); 
@@ -1919,5 +1885,5 @@
 
     //In case of field coding, compute the interlaced PSNR for both fields
-    if (isField && ((!pcPic->isTopField() && isTff) || (pcPic->isTopField() && !isTff)))
+    if (isField && ((!pcPic->isTopField() && isTff) || (pcPic->isTopField() && !isTff)) && (pcPic->getPOC()%m_iGopSize != 1))
     {
       //get complementary top field
@@ -1931,4 +1897,16 @@
       xCalculateInterlacedAddPSNR(pcPicTop, pcPic, pcPicTop->getPicYuvRec(), pcPic->getPicYuvRec(), accessUnit, dEncTime );
     }
+    else if (isField && pcPic->getPOC()!= 0 && (pcPic->getPOC()%m_iGopSize == 0))
+    {
+      //get complementary bottom field
+      TComPic* pcPicBottom;
+      TComList<TComPic*>::iterator   iterPic = rcListPic.begin();
+      while ((*iterPic)->getPOC() != pcPic->getPOC()+1)
+      {
+        iterPic ++;
+      }
+      pcPicBottom = *(iterPic);
+      xCalculateInterlacedAddPSNR(pcPic, pcPicBottom, pcPic->getPicYuvRec(), pcPicBottom->getPicYuvRec(), accessUnit, dEncTime );
+    }
     
       if (digestStr)
@@ -1947,10 +1925,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();
@@ -1959,13 +1933,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() );
 
@@ -1980,11 +1946,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() ) &&
@@ -2173,10 +2132,4 @@
       delete[] pcSubstreamsOut;
   }
-#if !KWU_FIX_URQ && !RATE_CONTROL_LAMBDA_DOMAIN
-  if(m_pcCfg->getUseRateCtrl())
-  {
-    m_pcRateCtrl->updateRCGOPStatus();
-  }
-#endif
   delete pcBitstreamRedirect;
 
@@ -2262,19 +2215,4 @@
   m_pcEntropyCoder->resetEntropy    ();
   m_pcEntropyCoder->setBitstream    ( m_pcBitCounter );
-  pcSlice = pcPic->getSlice(0);
-  if(pcSlice->getSPS()->getUseSAO())
-  {
-    std::vector<Bool> LFCrossSliceBoundaryFlag(1, true);
-    std::vector<Int>  sliceStartAddress;
-    sliceStartAddress.push_back(0);
-    sliceStartAddress.push_back(pcPic->getNumCUsInFrame()* pcPic->getNumPartInCU());
-    pcPic->createNonDBFilterInfo(sliceStartAddress, 0, &LFCrossSliceBoundaryFlag);
-  }
-  
-  if( pcSlice->getSPS()->getUseSAO())
-  {
-    pcPic->destroyNonDBFilterInfo();
-  }
-  
   m_pcEntropyCoder->resetEntropy    ();
   ruiBits += m_pcEntropyCoder->getNumberOfWrittenBits();
@@ -2454,5 +2392,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";
@@ -2702,6 +2640,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;
@@ -2862,5 +2800,5 @@
  * This function checks the configuration and returns the appropriate nal_unit_type for the picture.
  */
-NalUnitType TEncGOP::getNalUnitType(Int pocCurr, Int lastIDR)
+NalUnitType TEncGOP::getNalUnitType(Int pocCurr, Int lastIDR, Bool isField)
 {
   if (pocCurr == 0)
@@ -2868,5 +2806,5 @@
     return NAL_UNIT_CODED_SLICE_IDR_W_RADL;
   }
-  if (pocCurr % m_pcCfg->getIntraPeriod() == 0)
+  if ((pocCurr - isField) % m_pcCfg->getIntraPeriod() == 0)
   {
     if (m_pcCfg->getDecodingRefreshType() == 1)
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncGOP.h
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncGOP.h	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncGOP.h	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -125,4 +125,8 @@
   std::vector<Int>        m_storedStartCUAddrForEncodingSlice;
   std::vector<Int>        m_storedStartCUAddrForEncodingSliceSegment;
+#if FIX1172
+  NalUnitType             m_associatedIRAPType;
+  Int                     m_associatedIRAPPOC;
+#endif
 
   std::vector<Int> m_vRVM_RP;
@@ -181,5 +185,5 @@
 
   TEncSlice*  getSliceEncoder()   { return m_pcSliceEncoder; }
-  NalUnitType getNalUnitType( Int pocCurr, Int lastIdr );
+  NalUnitType getNalUnitType( Int pocCurr, Int lastIdr, Bool isField );
   Void arrangeLongtermPicturesInRPS(TComSlice *, TComList<TComPic*>& );
 protected:
@@ -187,6 +191,6 @@
 
 protected:
+
   Void xInitGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, bool isField );
-
   Void  xInitGOP          ( Int iPOC, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut );
   Void  xGetBuffer        ( TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, Int iNumPicRcvd, Int iTimeOffset, TComPic*& rpcPic, TComPicYuv*& rpcPicYuvRecOut, Int pocCurr, bool isField );
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncPic.cpp
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncPic.cpp	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncPic.cpp	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncPic.h
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncPic.h	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncPic.h	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncPreanalyzer.cpp
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncPreanalyzer.cpp	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncPreanalyzer.cpp	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncPreanalyzer.h
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncPreanalyzer.h	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncPreanalyzer.h	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncRateCtrl.cpp
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncRateCtrl.cpp	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncRateCtrl.cpp	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -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,8 +480,4 @@
 
   m_LCUs         = NULL;
-#if !M0036_RC_IMPROVEMENT
-  m_lastPicture  = NULL;
-#endif
-
 #if KWU_RC_MADPRED_E0227
   m_lastIVPicture = NULL;
@@ -543,7 +485,4 @@
 
   m_picActualHeaderBits = 0;
-#if !M0036_RC_IMPROVEMENT
-  m_totalMAD            = 0.0;
-#endif
   m_picActualBits       = 0;
   m_picQP               = 0;
@@ -574,9 +513,5 @@
   }
 
-#if M0036_RC_IMPROVEMENT
   targetBits  = Int( ((Double)GOPbitsLeft) * currPicRatio / totalPicRatio );
-#else
-  targetBits  = Int( GOPbitsLeft * currPicRatio / totalPicRatio );
-#endif
 
   if ( targetBits < 100 )
@@ -691,9 +626,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 );
@@ -708,7 +639,4 @@
   }
   m_picActualHeaderBits = 0;
-#if !M0036_RC_IMPROVEMENT
-  m_totalMAD            = 0.0;
-#endif
   m_picActualBits       = 0;
   m_picQP               = 0;
@@ -723,17 +651,4 @@
 
 
-#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
-
 #if KWU_RC_MADPRED_E0227
   list<TEncRCPic*>::reverse_iterator it;
@@ -775,14 +690,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)
@@ -794,7 +704,4 @@
     estLambda = alpha * pow( bpp, beta );
   }
-#else
-  Double estLambda = alpha * pow( bpp, beta );
-#endif  
   
   Double lastLevelLambda = -1.0;
@@ -844,10 +751,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() )
@@ -861,8 +766,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 );
@@ -879,5 +780,4 @@
     m_LCUs[i].m_bitWeight = BUTargetBits;
   }
-#endif
 
   return estLambda;
@@ -989,9 +889,52 @@
 
 
-#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 (eSliceType == I_SLICE)
+  {
+    Int noOfLCUsLeft = m_numberOfLCU - LCUIdx + 1;
+    Int bitrateWindow = min(4,noOfLCUsLeft);
+    Double MAD      = getLCU(LCUIdx).m_costIntra;
+
+    if (m_remainingCostIntra > 0.1 )
+    {
+      Double weightedBitsLeft = (m_bitsLeft*bitrateWindow+(m_bitsLeft-getLCU(LCUIdx).m_targetBitsLeft)*noOfLCUsLeft)/(Double)bitrateWindow;
+      avgBits = Int( MAD*weightedBitsLeft/m_remainingCostIntra );
+    }
+    else
+    {
+      avgBits = Int( m_bitsLeft / m_LCULeft );
+    }
+    m_remainingCostIntra -= MAD;
+  }
+  else
+  {
+  Double totalWeight = 0;
+  for ( Int i=LCUIdx; i<m_numberOfLCU; i++ )
+  {
+    totalWeight += m_LCUs[i].m_bitWeight;
+  }
+  Int realInfluenceLCU = min( g_RCLCUSmoothWindowSize, getLCULeft() );
+  avgBits = (Int)( m_LCUs[LCUIdx].m_bitWeight - ( totalWeight - m_bitsLeft ) / realInfluenceLCU + 0.5 );
+  }
+
+  if ( avgBits < 1 )
+  {
+    avgBits = 1;
+  }
+
+  bpp = ( Double )avgBits/( Double )m_LCUs[ LCUIdx ].m_numberOfPixel;
+  m_LCUs[ LCUIdx ].m_targetBits = avgBits;
+
+  return bpp;
+}
+
+
+#if KWU_RC_MADPRED_E0227
+Double TEncRCPic::getLCUTargetBppforInterView( list<TEncRCPic*>& listPreviousPictures, TComDataCU* pcCU, Double basePos, Double curPos, Double focalLen, Double znear, Double zfar, Int direction, Int* disparity )
 {
   Int   LCUIdx    = getLCUCoded();
@@ -1003,83 +946,4 @@
 #endif
 
-#if RATE_CONTROL_INTRA
-  if (eSliceType == I_SLICE){
-    Int noOfLCUsLeft = m_numberOfLCU - LCUIdx + 1;
-    Int bitrateWindow = min(4,noOfLCUsLeft);
-    Double MAD      = getLCU(LCUIdx).m_costIntra;
-
-    if (m_remainingCostIntra > 0.1 )
-    {
-      Double weightedBitsLeft = (m_bitsLeft*bitrateWindow+(m_bitsLeft-getLCU(LCUIdx).m_targetBitsLeft)*noOfLCUsLeft)/(Double)bitrateWindow;
-      avgBits = Int( MAD*weightedBitsLeft/m_remainingCostIntra );
-    }
-    else
-    {
-      avgBits = Int( m_bitsLeft / m_LCULeft );
-    }
-    m_remainingCostIntra -= MAD;
-  }
-  else
-  {
-#endif
-#if M0036_RC_IMPROVEMENT
-  Double totalWeight = 0;
-  for ( Int i=LCUIdx; i<m_numberOfLCU; i++ )
-  {
-    totalWeight += m_LCUs[i].m_bitWeight;
-  }
-  Int realInfluenceLCU = min( g_RCLCUSmoothWindowSize, getLCULeft() );
-  avgBits = (Int)( m_LCUs[LCUIdx].m_bitWeight - ( totalWeight - m_bitsLeft ) / realInfluenceLCU + 0.5 );
-#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 )
-  {
-    avgBits = 1;
-  }
-
-  bpp = ( Double )avgBits/( Double )m_LCUs[ LCUIdx ].m_numberOfPixel;
-  m_LCUs[ LCUIdx ].m_targetBits = avgBits;
-
-  return bpp;
-}
-
-
-#if KWU_RC_MADPRED_E0227
-Double TEncRCPic::getLCUTargetBppforInterView( list<TEncRCPic*>& listPreviousPictures, TComDataCU* pcCU, Double basePos, Double curPos, Double focalLen, Double znear, Double zfar, Int direction, Int* disparity )
-{
-  Int   LCUIdx    = getLCUCoded();
-  Double bpp      = -1.0;
-  Int avgBits     = 0;
-#if !M0036_RC_IMPROVEMENT
-  Double totalMAD = -1.0;
-  Double MAD      = -1.0;
-#endif
-
   Double totalMAD = -1.0;
   Double MAD      = -1.0;
@@ -1300,11 +1164,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;
@@ -1319,18 +1178,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;
@@ -1340,24 +1190,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()
 {
@@ -1414,13 +1244,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;
@@ -1435,8 +1257,6 @@
   }
   m_picLambda           = averageLambda;
-#if !M0036_RC_IMPROVEMENT || KWU_RC_MADPRED_E0227
 #if KWU_RC_MADPRED_E0227
   m_totalMAD = 0;
-#endif
   for ( Int i=0; i<m_numberOfLCU; i++ )
   {
@@ -1447,5 +1267,4 @@
   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)
   {
@@ -1454,5 +1273,4 @@
   else
   {
-#endif
   // update parameters
   Double picActualBits = ( Double )m_picActualBits;
@@ -1461,20 +1279,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;
@@ -1488,21 +1297,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;
@@ -1512,5 +1310,4 @@
   m_encRCSeq->setPicPara( m_frameLevel, rcPara );
 
-#if M0036_RC_IMPROVEMENT
   if ( m_frameLevel == 1 )
   {
@@ -1519,8 +1316,6 @@
     m_encRCSeq->setLastLambda( updateLastLambda );
   }
-#endif
-}
-
-#if RATE_CONTROL_INTRA
+}
+
 Int TEncRCPic::getRefineBitsForIntra( Int orgBits )
 {
@@ -1611,5 +1406,4 @@
   return estLambda;
 }
-#endif
 
 TEncRateCtrl::TEncRateCtrl()
@@ -1645,5 +1439,4 @@
 }
 
-#if M0036_RC_IMPROVEMENT
 #if KWU_RC_MADPRED_E0227
 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], Int layerID )
@@ -1651,7 +1444,4 @@
 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] )
 #endif
-#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();
@@ -1668,10 +1458,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;
@@ -1696,9 +1482,5 @@
   }
 
-#if M0036_RC_IMPROVEMENT
   if ( keepHierBits > 0 )
-#else
-  if ( keepHierBits )
-#endif
   {
     Double bpp = (Double)( targetBitrate / (Double)( frameRate*picWidth*picHeight ) );
@@ -1733,10 +1515,8 @@
         bitsRatio[3] = 14;
       }
-#if M0036_RC_IMPROVEMENT
       if ( keepHierBits == 2 )
       {
         adaptiveBit = 1;
       }
-#endif
     }
     else if ( GOPSize == 8 && !isLowdelay )
@@ -1786,18 +1566,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
     }
   }
@@ -1812,9 +1586,5 @@
     }
   }
-#if M0036_RC_IMPROVEMENT
   if ( keepHierBits > 0 )
-#else
-  if ( keepHierBits )
-#endif
   {
     if ( GOPSize == 4 && isLowdelay )
@@ -1851,9 +1621,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 );
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncRateCtrl.h
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncRateCtrl.h	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncRateCtrl.h	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -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,18 +83,10 @@
   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
-
 #if KWU_RC_MADPRED_E0227
   Double m_MAD;
-
   Int m_CUWidth;
   Int m_CUHeight;
@@ -121,9 +108,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[] );
@@ -132,10 +115,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:
@@ -175,9 +153,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:
@@ -208,8 +184,6 @@
   Bool m_useLCUSeparateModel;
 
-#if M0036_RC_IMPROVEMENT
   Int m_adaptiveBit;
   Double m_lastLambda;
-#endif
 };
 
@@ -227,8 +201,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:
@@ -266,9 +238,5 @@
   Double estimatePicLambdaIV( list<TEncRCPic*>& listPreviousPictures, Int curPOC );
 #endif
-#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);
@@ -279,35 +247,17 @@
   Double getLCUTargetBpp(SliceType eSliceType);
   Double getLCUEstLambdaAndQP(Double bpp, Int clipPicQP, Int *estQP);
-#else
-  Double getLCUTargetBpp();
-#endif
-
 #if KWU_RC_MADPRED_E0227
   Double getLCUTargetBppforInterView( list<TEncRCPic*>& listPreviousPictures, TComDataCU* pcCU, Double basePos, Double curPos, Double focalLen, Double znear, Double zfar, Int direction, Int* disparity );
 #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 KWU_RC_MADPRED_E0227
   Void addToPictureLsitIV( list<TEncRCPic*>& listPreviousPictures );
   Void setIVPic( TEncRCPic* baseRCPic );
-#endif
-
-#if !M0036_RC_IMPROVEMENT
-  Double getEffectivePercentage();
 #endif
   Double calAverageQP();
@@ -326,7 +276,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; }
@@ -338,14 +285,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
-
 #if KWU_RC_MADPRED_E0227
   Double getTotalMAD()                                    { return m_totalMAD; }
@@ -368,5 +308,4 @@
   Void setLayerID(Int layerid)                              { m_LayerID = layerid; }
 #endif
-
 private:
   TEncRCSeq* m_encRCSeq;
@@ -390,15 +329,9 @@
   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
-
 #if KWU_RC_MADPRED_E0227
   Double m_totalMAD;
@@ -417,12 +350,8 @@
 
 public:
-#if M0036_RC_IMPROVEMENT
 #if KWU_RC_MADPRED_E0227
   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], Int layerID );
 #else
   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] );
-#endif
-#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();
@@ -443,5 +372,4 @@
   Void setLayerID(Int layerid)     { m_LayerID = layerid; }
 #endif
-
 private:
   TEncRCSeq* m_encRCSeq;
@@ -450,5 +378,4 @@
   list<TEncRCPic*> m_listRCPictures;
   Int        m_RCQP;
-
 #if KWU_RC_MADPRED_E0227
   Int m_LayerID;
@@ -456,136 +383,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);
-#if KWU_RC_MADPRED_E0227
-  Void          updateLCUDataEnhancedView(TComDataCU* pcCU, UInt64 uiBits, Int qp, Double basePos, Double curPos, Double focalLen, Double znear, Double zfar, Int direction);
-#endif
-  Void          updateFrameData       (UInt64 actualFrameBits);
-  Double        xAdjustmentBits       (Int& reductionBits, Int& compensationBits);
-  Int           getGOPId              ()                                          { return m_indexFrame; }
-};
-#endif
-
-#endif
-
-
+#endif
+
+
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -45,51 +45,13 @@
 //! \{
 
-TEncSampleAdaptiveOffset::TEncSampleAdaptiveOffset()
-{
-  m_pcEntropyCoder = NULL;
-  m_pppcRDSbacCoder = NULL;
-  m_pcRDGoOnSbacCoder = NULL;
-  m_pppcBinCoderCABAC = NULL;            
-  m_iCount = NULL;     
-  m_iOffset = NULL;      
-  m_iOffsetOrg = NULL;  
-  m_iRate = NULL;       
-  m_iDist = NULL;        
-  m_dCost = NULL;        
-  m_dCostPartBest = NULL; 
-  m_iDistOrg = NULL;      
-  m_iTypePartBest = NULL; 
-#if SAO_ENCODING_CHOICE_CHROMA
-  m_depthSaoRate[0][0] = 0;
-  m_depthSaoRate[0][1] = 0;
-  m_depthSaoRate[0][2] = 0;
-  m_depthSaoRate[0][3] = 0;
-  m_depthSaoRate[1][0] = 0;
-  m_depthSaoRate[1][1] = 0;
-  m_depthSaoRate[1][2] = 0;
-  m_depthSaoRate[1][3] = 0;
-#endif
-}
-TEncSampleAdaptiveOffset::~TEncSampleAdaptiveOffset()
-{
-
-}
-// ====================================================================================================================
-// Constants
-// ====================================================================================================================
-
-
-// ====================================================================================================================
-// Tables
-// ====================================================================================================================
-
-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))));
-}
 
 /** 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)
 {
@@ -98,2064 +60,375 @@
 
 
-
-/** process SAO for one partition
- * \param  *psQTPart, iPartIdx, dLambda
- */
-Void TEncSampleAdaptiveOffset::rdoSaoOnePart(SAOQTPart *psQTPart, Int iPartIdx, Double dLambda, Int yCbCr)
-{
-  Int iTypeIdx;
-  Int iNumTotalType = MAX_NUM_SAO_TYPE;
-  SAOQTPart*  pOnePart = &(psQTPart[iPartIdx]);
-
-  Int64 iEstDist;
-  Int iClassIdx;
-  Int uiShift = 2 * DISTORTION_PRECISION_ADJUSTMENT((yCbCr == 0 ? g_bitDepthY : g_bitDepthC)-8);
-  UInt uiDepth = pOnePart->PartLevel;
-
-  m_iDistOrg [iPartIdx] =  0;
-
-  Double  bestRDCostTableBo = MAX_DOUBLE;
-  Int     bestClassTableBo    = 0;
-  Int     currentDistortionTableBo[MAX_NUM_SAO_CLASS];
-  Double  currentRdCostTableBo[MAX_NUM_SAO_CLASS];
-
-  Int addr;
-  Int allowMergeLeft;
-  Int allowMergeUp;
-  Int frameWidthInCU = m_pcPic->getFrameWidthInCU();
-  SaoLcuParam  saoLcuParamRdo;
-
-  for (iTypeIdx=-1; iTypeIdx<iNumTotalType; iTypeIdx++)
-  {
-    if( m_bUseSBACRD )
-    {
-      m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
-      m_pcRDGoOnSbacCoder->resetBits();
-    }
-    else
-    {
-      m_pcEntropyCoder->resetEntropy();
-      m_pcEntropyCoder->resetBits();
-    }
-
-    iEstDist = 0;
-
-    if (iTypeIdx == -1)
-    {      
-      for (Int ry = pOnePart->StartCUY; ry<= pOnePart->EndCUY; ry++)
-      {
-        for (Int rx = pOnePart->StartCUX; rx <= pOnePart->EndCUX; rx++)
-        {
-          addr = ry * frameWidthInCU + rx;          
-
-          // get bits for iTypeIdx = -1
-          allowMergeLeft = 1;
-          allowMergeUp   = 1;
-          if (rx != 0)
-          { 
-            // check tile id and slice id 
-            if ( (m_pcPic->getPicSym()->getTileIdxMap(addr-1) != m_pcPic->getPicSym()->getTileIdxMap(addr)) || (m_pcPic->getCU(addr-1)->getSlice()->getSliceIdx() != m_pcPic->getCU(addr)->getSlice()->getSliceIdx()))
-            {
-              allowMergeLeft = 0;
-            }
-          }
-          if (ry!=0)
-          {
-            if ( (m_pcPic->getPicSym()->getTileIdxMap(addr-m_iNumCuInWidth) != m_pcPic->getPicSym()->getTileIdxMap(addr)) || (m_pcPic->getCU(addr-m_iNumCuInWidth)->getSlice()->getSliceIdx() != m_pcPic->getCU(addr)->getSlice()->getSliceIdx()))
-            {
-              allowMergeUp = 0;
-            }
-          }
-
-          // reset
-          resetSaoUnit(&saoLcuParamRdo);
-
-          // set merge flag
-          saoLcuParamRdo.mergeUpFlag   = 1;
-          saoLcuParamRdo.mergeLeftFlag = 1;
-
-          if (ry == pOnePart->StartCUY) 
-          {
-            saoLcuParamRdo.mergeUpFlag = 0;
-          } 
-          
-          if (rx == pOnePart->StartCUX) 
-          {
-            saoLcuParamRdo.mergeLeftFlag = 0;
-          }
-
-          m_pcEntropyCoder->encodeSaoUnitInterleaving(yCbCr, 1, rx, ry,  &saoLcuParamRdo, 1,  1,  allowMergeLeft, allowMergeUp);
-
-        }
-      }
-    }
-
-    if (iTypeIdx>=0)
-    {
-      iEstDist = estSaoTypeDist(iPartIdx, iTypeIdx, uiShift, dLambda, currentDistortionTableBo, currentRdCostTableBo);
-      if( iTypeIdx == SAO_BO )
-      {
-        // Estimate Best Position
-        Double currentRDCost = 0.0;
-
-        for(Int i=0; i< SAO_MAX_BO_CLASSES -SAO_BO_LEN +1; i++)
-        {
-          currentRDCost = 0.0;
-          for(UInt uj = i; uj < i+SAO_BO_LEN; uj++)
-          {
-            currentRDCost += currentRdCostTableBo[uj];
-          }
-
-          if( currentRDCost < bestRDCostTableBo)
-          {
-            bestRDCostTableBo = currentRDCost;
-            bestClassTableBo  = i;
-          }
-        }
-
-        // Re code all Offsets
-        // Code Center
-        for(iClassIdx = bestClassTableBo; iClassIdx < bestClassTableBo+SAO_BO_LEN; iClassIdx++)
-        {
-          iEstDist += currentDistortionTableBo[iClassIdx];
-        }
-      }
-
-      for (Int ry = pOnePart->StartCUY; ry<= pOnePart->EndCUY; ry++)
-      {
-        for (Int rx = pOnePart->StartCUX; rx <= pOnePart->EndCUX; rx++)
-        {
-          addr = ry * frameWidthInCU + rx;          
-
-          // get bits for iTypeIdx = -1
-          allowMergeLeft = 1;
-          allowMergeUp   = 1;
-          if (rx != 0)
-          { 
-            // check tile id and slice id 
-            if ( (m_pcPic->getPicSym()->getTileIdxMap(addr-1) != m_pcPic->getPicSym()->getTileIdxMap(addr)) || (m_pcPic->getCU(addr-1)->getSlice()->getSliceIdx() != m_pcPic->getCU(addr)->getSlice()->getSliceIdx()))
-            {
-              allowMergeLeft = 0;
-            }
-          }
-          if (ry!=0)
-          {
-            if ( (m_pcPic->getPicSym()->getTileIdxMap(addr-m_iNumCuInWidth) != m_pcPic->getPicSym()->getTileIdxMap(addr)) || (m_pcPic->getCU(addr-m_iNumCuInWidth)->getSlice()->getSliceIdx() != m_pcPic->getCU(addr)->getSlice()->getSliceIdx()))
-            {
-              allowMergeUp = 0;
-            }
-          }
-
-          // reset
-          resetSaoUnit(&saoLcuParamRdo);
-          
-          // set merge flag
-          saoLcuParamRdo.mergeUpFlag   = 1;
-          saoLcuParamRdo.mergeLeftFlag = 1;
-
-          if (ry == pOnePart->StartCUY) 
-          {
-            saoLcuParamRdo.mergeUpFlag = 0;
-          } 
-          
-          if (rx == pOnePart->StartCUX) 
-          {
-            saoLcuParamRdo.mergeLeftFlag = 0;
-          }
-
-          // set type and offsets
-          saoLcuParamRdo.typeIdx = iTypeIdx;
-          saoLcuParamRdo.subTypeIdx = (iTypeIdx==SAO_BO)?bestClassTableBo:0;
-          saoLcuParamRdo.length = m_iNumClass[iTypeIdx];
-          for (iClassIdx = 0; iClassIdx < saoLcuParamRdo.length; iClassIdx++)
-          {
-            saoLcuParamRdo.offset[iClassIdx] = (Int)m_iOffset[iPartIdx][iTypeIdx][iClassIdx+saoLcuParamRdo.subTypeIdx+1];
-          }
-
-          m_pcEntropyCoder->encodeSaoUnitInterleaving(yCbCr, 1, rx, ry,  &saoLcuParamRdo, 1,  1,  allowMergeLeft, allowMergeUp);
-
-        }
-      }
-
-      m_iDist[iPartIdx][iTypeIdx] = iEstDist;
-      m_iRate[iPartIdx][iTypeIdx] = m_pcEntropyCoder->getNumberOfWrittenBits();
-
-      m_dCost[iPartIdx][iTypeIdx] = (Double)((Double)m_iDist[iPartIdx][iTypeIdx] + dLambda * (Double) m_iRate[iPartIdx][iTypeIdx]);
-
-      if(m_dCost[iPartIdx][iTypeIdx] < m_dCostPartBest[iPartIdx])
-      {
-        m_iDistOrg [iPartIdx] = 0;
-        m_dCostPartBest[iPartIdx] = m_dCost[iPartIdx][iTypeIdx];
-        m_iTypePartBest[iPartIdx] = iTypeIdx;
-        if( m_bUseSBACRD )
-          m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[pOnePart->PartLevel][CI_TEMP_BEST] );
-      }
-    }
-    else
-    {
-      if(m_iDistOrg[iPartIdx] < m_dCostPartBest[iPartIdx] )
-      {
-        m_dCostPartBest[iPartIdx] = (Double) m_iDistOrg[iPartIdx] + m_pcEntropyCoder->getNumberOfWrittenBits()*dLambda ; 
-        m_iTypePartBest[iPartIdx] = -1;
-        if( m_bUseSBACRD )
-        {
-          m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[pOnePart->PartLevel][CI_TEMP_BEST] );
-        }
-      }
-    }
-  }
-
-  pOnePart->bProcessed = true;
-  pOnePart->bSplit     = false;
-  pOnePart->iMinDist   =        m_iTypePartBest[iPartIdx] >= 0 ? m_iDist[iPartIdx][m_iTypePartBest[iPartIdx]] : m_iDistOrg[iPartIdx];
-  pOnePart->iMinRate   = (Int) (m_iTypePartBest[iPartIdx] >= 0 ? m_iRate[iPartIdx][m_iTypePartBest[iPartIdx]] : 0);
-  pOnePart->dMinCost   = pOnePart->iMinDist + dLambda * pOnePart->iMinRate;
-  pOnePart->iBestType  = m_iTypePartBest[iPartIdx];
-  if (pOnePart->iBestType != -1)
-  {
-    //     pOnePart->bEnableFlag =  1;
-    pOnePart->iLength = m_iNumClass[pOnePart->iBestType];
-    Int minIndex = 0;
-    if( pOnePart->iBestType == SAO_BO )
-    {
-      pOnePart->subTypeIdx = bestClassTableBo;
-      minIndex = pOnePart->subTypeIdx;
-    }
-    for (Int i=0; i< pOnePart->iLength ; i++)
-    {
-      pOnePart->iOffset[i] = (Int) m_iOffset[iPartIdx][pOnePart->iBestType][minIndex+i+1];
-    }
-
-  }
-  else
-  {
-    //     pOnePart->bEnableFlag = 0;
-    pOnePart->iLength     = 0;
-  }
-}
-
-/** Run partition tree disable
- */
-Void TEncSampleAdaptiveOffset::disablePartTree(SAOQTPart *psQTPart, Int iPartIdx)
-{
-  SAOQTPart*  pOnePart= &(psQTPart[iPartIdx]);
-  pOnePart->bSplit      = false;
-  pOnePart->iLength     =  0;
-  pOnePart->iBestType   = -1;
-
-  if (pOnePart->PartLevel < m_uiMaxSplitLevel)
-  {
-    for (Int i=0; i<NUM_DOWN_PART; i++)
-    {
-      disablePartTree(psQTPart, pOnePart->DownPartsIdx[i]);
-    }
-  }
-}
-
-/** Run quadtree decision function
- * \param  iPartIdx, pcPicOrg, pcPicDec, pcPicRest, &dCostFinal
- */
-Void TEncSampleAdaptiveOffset::runQuadTreeDecision(SAOQTPart *psQTPart, Int iPartIdx, Double &dCostFinal, Int iMaxLevel, Double dLambda, Int yCbCr)
-{
-  SAOQTPart*  pOnePart = &(psQTPart[iPartIdx]);
-
-  UInt uiDepth = pOnePart->PartLevel;
-  UInt uhNextDepth = uiDepth+1;
-
-  if (iPartIdx == 0)
-  {
-    dCostFinal = 0;
-  }
-
-  //SAO for this part
-  if(!pOnePart->bProcessed)
-  {
-    rdoSaoOnePart (psQTPart, iPartIdx, dLambda, yCbCr);
-  }
-
-  //SAO for sub 4 parts
-  if (pOnePart->PartLevel < iMaxLevel)
-  {
-    Double      dCostNotSplit = dLambda + pOnePart->dMinCost;
-    Double      dCostSplit    = dLambda;
-
-    for (Int i=0; i< NUM_DOWN_PART ;i++)
-    {
-      if( m_bUseSBACRD )  
-      {
-        if ( 0 == i) //initialize RD with previous depth buffer
-        {
-          m_pppcRDSbacCoder[uhNextDepth][CI_CURR_BEST]->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
-        }
-        else
-        {
-          m_pppcRDSbacCoder[uhNextDepth][CI_CURR_BEST]->load(m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]);
-        }
-      }  
-      runQuadTreeDecision(psQTPart, pOnePart->DownPartsIdx[i], dCostFinal, iMaxLevel, dLambda, yCbCr);
-      dCostSplit += dCostFinal;
-      if( m_bUseSBACRD )
-      {
-        m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]->load(m_pppcRDSbacCoder[uhNextDepth][CI_TEMP_BEST]);
-      }
-    }
-
-    if(dCostSplit < dCostNotSplit)
-    {
-      dCostFinal = dCostSplit;
-      pOnePart->bSplit      = true;
-      pOnePart->iLength     =  0;
-      pOnePart->iBestType   = -1;
-      if( m_bUseSBACRD )
-      {
-        m_pppcRDSbacCoder[uiDepth][CI_NEXT_BEST]->load(m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]);
-      }
-    }
-    else
-    {
-      dCostFinal = dCostNotSplit;
-      pOnePart->bSplit = false;
-      for (Int i=0; i<NUM_DOWN_PART; i++)
-      {
-        disablePartTree(psQTPart, pOnePart->DownPartsIdx[i]);
-      }
-      if( m_bUseSBACRD )
-      {
-        m_pppcRDSbacCoder[uiDepth][CI_NEXT_BEST]->load(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
-      }
-    }
-  }
-  else
-  {
-    dCostFinal = pOnePart->dMinCost;
-  }
-}
-
-/** delete allocated memory of TEncSampleAdaptiveOffset class.
- */
-Void TEncSampleAdaptiveOffset::destroyEncBuffer()
-{
-  for (Int i=0;i<m_iNumTotalParts;i++)
-  {
-    for (Int j=0;j<MAX_NUM_SAO_TYPE;j++)
-    {
-      if (m_iCount [i][j])
-      {
-        delete [] m_iCount [i][j]; 
-      }
-      if (m_iOffset[i][j])
-      {
-        delete [] m_iOffset[i][j]; 
-      }
-      if (m_iOffsetOrg[i][j])
-      {
-        delete [] m_iOffsetOrg[i][j]; 
-      }
-    }
-    if (m_iRate[i])
-    {
-      delete [] m_iRate[i];
-    }
-    if (m_iDist[i])
-    {
-      delete [] m_iDist[i]; 
-    }
-    if (m_dCost[i])
-    {
-      delete [] m_dCost[i]; 
-    }
-    if (m_iCount [i])
-    {
-      delete [] m_iCount [i]; 
-    }
-    if (m_iOffset[i])
-    {
-      delete [] m_iOffset[i]; 
-    }
-    if (m_iOffsetOrg[i])
-    {
-      delete [] m_iOffsetOrg[i]; 
-    }
-
-  }
-  if (m_iDistOrg)
-  {
-    delete [] m_iDistOrg ; m_iDistOrg = NULL;
-  }
-  if (m_dCostPartBest)
-  {
-    delete [] m_dCostPartBest ; m_dCostPartBest = NULL;
-  }
-  if (m_iTypePartBest)
-  {
-    delete [] m_iTypePartBest ; m_iTypePartBest = NULL;
-  }
-  if (m_iRate)
-  {
-    delete [] m_iRate ; m_iRate = NULL;
-  }
-  if (m_iDist)
-  {
-    delete [] m_iDist ; m_iDist = NULL;
-  }
-  if (m_dCost)
-  {
-    delete [] m_dCost ; m_dCost = NULL;
-  }
-  if (m_iCount)
-  {
-    delete [] m_iCount  ; m_iCount = NULL;
-  }
-  if (m_iOffset)
-  {
-    delete [] m_iOffset ; m_iOffset = NULL;
-  }
-  if (m_iOffsetOrg)
-  {
-    delete [] m_iOffsetOrg ; m_iOffsetOrg = NULL;
-  }
-  Int numLcu = m_iNumCuInWidth * m_iNumCuInHeight;
-
-  for (Int i=0;i<numLcu;i++)
-  {
-    for (Int j=0;j<3;j++)
-    {
-      for (Int k=0;k<MAX_NUM_SAO_TYPE;k++)
-      {
-        if (m_count_PreDblk [i][j][k])
-        {
-          delete [] m_count_PreDblk [i][j][k]; 
-        }
-        if (m_offsetOrg_PreDblk[i][j][k])
-        {
-          delete [] m_offsetOrg_PreDblk[i][j][k];
-        }
-      }
-      if (m_count_PreDblk [i][j])
-      {
-        delete [] m_count_PreDblk [i][j]; 
-      }
-      if (m_offsetOrg_PreDblk[i][j])
-      {
-        delete [] m_offsetOrg_PreDblk[i][j]; 
-      }
-    }
-    if (m_count_PreDblk [i])
-    {
-      delete [] m_count_PreDblk [i]; 
-    }
-    if (m_offsetOrg_PreDblk[i])
-    {
-      delete [] m_offsetOrg_PreDblk[i]; 
-    }
-  }
-  if (m_count_PreDblk)
-  {
-    delete [] m_count_PreDblk  ; m_count_PreDblk = NULL;
-  }
-  if (m_offsetOrg_PreDblk)
-  {
-    delete [] m_offsetOrg_PreDblk ; m_offsetOrg_PreDblk = NULL;
-  }
-
-  Int iMaxDepth = 4;
-  Int iDepth;
-  for ( iDepth = 0; iDepth < iMaxDepth+1; iDepth++ )
-  {
-    for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
-    {
-      delete m_pppcRDSbacCoder[iDepth][iCIIdx];
-      delete m_pppcBinCoderCABAC[iDepth][iCIIdx];
-    }
-  }
-
-  for ( iDepth = 0; iDepth < iMaxDepth+1; iDepth++ )
-  {
-    delete [] m_pppcRDSbacCoder[iDepth];
-    delete [] m_pppcBinCoderCABAC[iDepth];
-  }
-
-  delete [] m_pppcRDSbacCoder;
-  delete [] m_pppcBinCoderCABAC;
-}
-
-/** create Encoder Buffer for SAO
- * \param 
- */
-Void TEncSampleAdaptiveOffset::createEncBuffer()
-{
-  m_iDistOrg = new Int64 [m_iNumTotalParts]; 
-  m_dCostPartBest = new Double [m_iNumTotalParts]; 
-  m_iTypePartBest = new Int [m_iNumTotalParts]; 
-
-  m_iRate = new Int64* [m_iNumTotalParts];
-  m_iDist = new Int64* [m_iNumTotalParts];
-  m_dCost = new Double*[m_iNumTotalParts];
-
-  m_iCount  = new Int64 **[m_iNumTotalParts];
-  m_iOffset = new Int64 **[m_iNumTotalParts];
-  m_iOffsetOrg = new Int64 **[m_iNumTotalParts];
-
-  for (Int i=0;i<m_iNumTotalParts;i++)
-  {
-    m_iRate[i] = new Int64  [MAX_NUM_SAO_TYPE];
-    m_iDist[i] = new Int64  [MAX_NUM_SAO_TYPE]; 
-    m_dCost[i] = new Double [MAX_NUM_SAO_TYPE]; 
-
-    m_iCount [i] = new Int64 *[MAX_NUM_SAO_TYPE]; 
-    m_iOffset[i] = new Int64 *[MAX_NUM_SAO_TYPE]; 
-    m_iOffsetOrg[i] = new Int64 *[MAX_NUM_SAO_TYPE]; 
-
-    for (Int j=0;j<MAX_NUM_SAO_TYPE;j++)
-    {
-      m_iCount [i][j]   = new Int64 [MAX_NUM_SAO_CLASS]; 
-      m_iOffset[i][j]   = new Int64 [MAX_NUM_SAO_CLASS]; 
-      m_iOffsetOrg[i][j]= new Int64 [MAX_NUM_SAO_CLASS]; 
-    }
-  }
-  Int numLcu = m_iNumCuInWidth * m_iNumCuInHeight;
-  m_count_PreDblk  = new Int64 ***[numLcu];
-  m_offsetOrg_PreDblk = new Int64 ***[numLcu];
-  for (Int i=0; i<numLcu; i++)
-  {
-    m_count_PreDblk[i]  = new Int64 **[3];
-    m_offsetOrg_PreDblk[i] = new Int64 **[3];
-
-    for (Int j=0;j<3;j++)
-    {
-      m_count_PreDblk [i][j] = new Int64 *[MAX_NUM_SAO_TYPE]; 
-      m_offsetOrg_PreDblk[i][j] = new Int64 *[MAX_NUM_SAO_TYPE]; 
-
-      for (Int k=0;k<MAX_NUM_SAO_TYPE;k++)
-      {
-        m_count_PreDblk [i][j][k]   = new Int64 [MAX_NUM_SAO_CLASS]; 
-        m_offsetOrg_PreDblk[i][j][k]= new Int64 [MAX_NUM_SAO_CLASS]; 
-      }
-    }
-  }
-
-  Int iMaxDepth = 4;
-  m_pppcRDSbacCoder = new TEncSbac** [iMaxDepth+1];
-#if FAST_BIT_EST
-  m_pppcBinCoderCABAC = new TEncBinCABACCounter** [iMaxDepth+1];
-#else
-  m_pppcBinCoderCABAC = new TEncBinCABAC** [iMaxDepth+1];
-#endif
-
-  for ( Int iDepth = 0; iDepth < iMaxDepth+1; iDepth++ )
-  {
-    m_pppcRDSbacCoder[iDepth] = new TEncSbac* [CI_NUM];
-#if FAST_BIT_EST
-    m_pppcBinCoderCABAC[iDepth] = new TEncBinCABACCounter* [CI_NUM];
-#else
-    m_pppcBinCoderCABAC[iDepth] = new TEncBinCABAC* [CI_NUM];
-#endif
-    for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
-    {
-      m_pppcRDSbacCoder[iDepth][iCIIdx] = new TEncSbac;
-#if FAST_BIT_EST
-      m_pppcBinCoderCABAC [iDepth][iCIIdx] = new TEncBinCABACCounter;
-#else
-      m_pppcBinCoderCABAC [iDepth][iCIIdx] = new TEncBinCABAC;
-#endif
-      m_pppcRDSbacCoder   [iDepth][iCIIdx]->init( m_pppcBinCoderCABAC [iDepth][iCIIdx] );
-    }
-  }
-}
-
-/** Start SAO encoder
- * \param pcPic, pcEntropyCoder, pppcRDSbacCoder, pcRDGoOnSbacCoder 
- */
-Void TEncSampleAdaptiveOffset::startSaoEnc( TComPic* pcPic, TEncEntropy* pcEntropyCoder, TEncSbac*** pppcRDSbacCoder, TEncSbac* pcRDGoOnSbacCoder)
-{
-    m_bUseSBACRD = true;
-  m_pcPic = pcPic;
-  m_pcEntropyCoder = pcEntropyCoder;
-
+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_pcEntropyCoder->setEntropyCoder(m_pcRDGoOnSbacCoder, pcPic->getSlice(0));
-  m_pcEntropyCoder->resetEntropy();
-  m_pcEntropyCoder->resetBits();
-
-  if( m_bUseSBACRD )
-  {
-    m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[0][CI_NEXT_BEST]);
-    m_pppcRDSbacCoder[0][CI_CURR_BEST]->load( m_pppcRDSbacCoder[0][CI_NEXT_BEST]);
-  }
-}
-
-/** End SAO encoder
- */
-Void TEncSampleAdaptiveOffset::endSaoEnc()
-{
-  m_pcPic = NULL;
-  m_pcEntropyCoder = NULL;
-}
-
-inline Int xSign(Int x)
-{
-  return ((x >> 31) | ((Int)( (((UInt) -x)) >> 31)));
-}
-
-/** Calculate SAO statistics for non-cross-slice or non-cross-tile processing
- * \param  pRecStart to-be-filtered block buffer pointer
- * \param  pOrgStart original block buffer pointer
- * \param  stride picture buffer stride
- * \param  ppStat statistics buffer
- * \param  ppCount counter buffer
- * \param  width block width
- * \param  height block height
- * \param  pbBorderAvail availabilities of block border pixels
- */
-Void TEncSampleAdaptiveOffset::calcSaoStatsBlock( Pel* pRecStart, Pel* pOrgStart, Int stride, Int64** ppStats, Int64** ppCount, UInt width, UInt height, Bool* pbBorderAvail, Int iYCbCr)
-{
-  Int64 *stats, *count;
-  Int classIdx, posShift, startX, endX, startY, endY, signLeft,signRight,signDown,signDown1;
-  Pel *pOrg, *pRec;
-  UInt edgeType;
-  Int x, y;
-  Pel *pTableBo = (iYCbCr==0)?m_lumaTableBo:m_chromaTableBo;
-
-  //--------- Band offset-----------//
-  stats = ppStats[SAO_BO];
-  count = ppCount[SAO_BO];
-  pOrg   = pOrgStart;
-  pRec   = pRecStart;
-  for (y=0; y< height; y++)
-  {
-    for (x=0; x< width; x++)
-    {
-      classIdx = pTableBo[pRec[x]];
-      if (classIdx)
-      {
-        stats[classIdx] += (pOrg[x] - pRec[x]); 
-        count[classIdx] ++;
-      }
-    }
-    pOrg += stride;
-    pRec += stride;
-  }
-  //---------- Edge offset 0--------------//
-  stats = ppStats[SAO_EO_0];
-  count = ppCount[SAO_EO_0];
-  pOrg   = pOrgStart;
-  pRec   = pRecStart;
-
-
-  startX = (pbBorderAvail[SGU_L]) ? 0 : 1;
-  endX   = (pbBorderAvail[SGU_R]) ? width : (width -1);
-  for (y=0; y< height; y++)
-  {
-    signLeft = xSign(pRec[startX] - pRec[startX-1]);
-    for (x=startX; x< endX; x++)
-    {
-      signRight =  xSign(pRec[x] - pRec[x+1]); 
-      edgeType =  signRight + signLeft + 2;
-      signLeft  = -signRight;
-
-      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
-      count[m_auiEoTable[edgeType]] ++;
-    }
-    pRec  += stride;
-    pOrg += stride;
-  }
-
-  //---------- Edge offset 1--------------//
-  stats = ppStats[SAO_EO_1];
-  count = ppCount[SAO_EO_1];
-  pOrg   = pOrgStart;
-  pRec   = pRecStart;
-
-  startY = (pbBorderAvail[SGU_T]) ? 0 : 1;
-  endY   = (pbBorderAvail[SGU_B]) ? height : height-1;
-  if (!pbBorderAvail[SGU_T])
-  {
-    pRec  += stride;
-    pOrg  += stride;
-  }
-
-  for (x=0; x< width; x++)
-  {
-    m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-stride]);
-  }
-  for (y=startY; y<endY; y++)
-  {
-    for (x=0; x< width; x++)
-    {
-      signDown     =  xSign(pRec[x] - pRec[x+stride]); 
-      edgeType    =  signDown + m_iUpBuff1[x] + 2;
-      m_iUpBuff1[x] = -signDown;
-
-      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
-      count[m_auiEoTable[edgeType]] ++;
-    }
-    pOrg += stride;
-    pRec += stride;
-  }
-  //---------- Edge offset 2--------------//
-  stats = ppStats[SAO_EO_2];
-  count = ppCount[SAO_EO_2];
-  pOrg   = pOrgStart;
-  pRec   = pRecStart;
-
-  posShift= stride + 1;
-
-  startX = (pbBorderAvail[SGU_L]) ? 0 : 1 ;
-  endX   = (pbBorderAvail[SGU_R]) ? width : (width-1);
-
-  //prepare 2nd line upper sign
-  pRec += stride;
-  for (x=startX; x< endX+1; x++)
-  {
-    m_iUpBuff1[x] = xSign(pRec[x] - pRec[x- posShift]);
-  }
-
-  //1st line
-  pRec -= stride;
-  if(pbBorderAvail[SGU_TL])
-  {
-    x= 0;
-    edgeType      =  xSign(pRec[x] - pRec[x- posShift]) - m_iUpBuff1[x+1] + 2;
-    stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
-    count[m_auiEoTable[edgeType]] ++;
-  }
-  if(pbBorderAvail[SGU_T])
-  {
-    for(x= 1; x< endX; x++)
-    {
-      edgeType      =  xSign(pRec[x] - pRec[x- posShift]) - m_iUpBuff1[x+1] + 2;
-      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
-      count[m_auiEoTable[edgeType]] ++;
-    }
-  }
-  pRec   += stride;
-  pOrg   += stride;
-
-  //middle lines
-  for (y= 1; y< height-1; y++)
-  {
-    for (x=startX; x<endX; x++)
-    {
-      signDown1      =  xSign(pRec[x] - pRec[x+ posShift]) ;
-      edgeType      =  signDown1 + m_iUpBuff1[x] + 2;
-      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
-      count[m_auiEoTable[edgeType]] ++;
-
-      m_iUpBufft[x+1] = -signDown1; 
-    }
-    m_iUpBufft[startX] = xSign(pRec[stride+startX] - pRec[startX-1]);
-
-    ipSwap     = m_iUpBuff1;
-    m_iUpBuff1 = m_iUpBufft;
-    m_iUpBufft = ipSwap;
-
-    pRec  += stride;
-    pOrg  += stride;
-  }
-
-  //last line
-  if(pbBorderAvail[SGU_B])
-  {
-    for(x= startX; x< width-1; x++)
-    {
-      edgeType =  xSign(pRec[x] - pRec[x+ posShift]) + m_iUpBuff1[x] + 2;
-      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
-      count[m_auiEoTable[edgeType]] ++;
-    }
-  }
-  if(pbBorderAvail[SGU_BR])
-  {
-    x= width -1;
-    edgeType =  xSign(pRec[x] - pRec[x+ posShift]) + m_iUpBuff1[x] + 2;
-    stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
-    count[m_auiEoTable[edgeType]] ++;
-  }
-
-  //---------- Edge offset 3--------------//
-
-  stats = ppStats[SAO_EO_3];
-  count = ppCount[SAO_EO_3];
-  pOrg   = pOrgStart;
-  pRec   = pRecStart;
-
-  posShift     = stride - 1;
-  startX = (pbBorderAvail[SGU_L]) ? 0 : 1;
-  endX   = (pbBorderAvail[SGU_R]) ? width : (width -1);
-
-  //prepare 2nd line upper sign
-  pRec += stride;
-  for (x=startX-1; x< endX; x++)
-  {
-    m_iUpBuff1[x] = xSign(pRec[x] - pRec[x- posShift]);
-  }
-
-
-  //first line
-  pRec -= stride;
-  if(pbBorderAvail[SGU_T])
-  {
-    for(x= startX; x< width -1; x++)
-    {
-      edgeType = xSign(pRec[x] - pRec[x- posShift]) -m_iUpBuff1[x-1] + 2;
-      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
-      count[m_auiEoTable[edgeType]] ++;
-    }
-  }
-  if(pbBorderAvail[SGU_TR])
-  {
-    x= width-1;
-    edgeType = xSign(pRec[x] - pRec[x- posShift]) -m_iUpBuff1[x-1] + 2;
-    stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
-    count[m_auiEoTable[edgeType]] ++;
-  }
-  pRec  += stride;
-  pOrg  += stride;
-
-  //middle lines
-  for (y= 1; y< height-1; y++)
-  {
-    for(x= startX; x< endX; x++)
-    {
-      signDown1      =  xSign(pRec[x] - pRec[x+ posShift]) ;
-      edgeType      =  signDown1 + m_iUpBuff1[x] + 2;
-
-      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
-      count[m_auiEoTable[edgeType]] ++;
-      m_iUpBuff1[x-1] = -signDown1; 
-
-    }
-    m_iUpBuff1[endX-1] = xSign(pRec[endX-1 + stride] - pRec[endX]);
-
-    pRec  += stride;
-    pOrg  += stride;
-  }
-
-  //last line
-  if(pbBorderAvail[SGU_BL])
-  {
-    x= 0;
-    edgeType = xSign(pRec[x] - pRec[x+ posShift]) + m_iUpBuff1[x] + 2;
-    stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
-    count[m_auiEoTable[edgeType]] ++;
-
-  }
-  if(pbBorderAvail[SGU_B])
-  {
-    for(x= 1; x< endX; x++)
-    {
-      edgeType = xSign(pRec[x] - pRec[x+ posShift]) + m_iUpBuff1[x] + 2;
-      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
-      count[m_auiEoTable[edgeType]] ++;
-    }
-  }
-}
-
-/** Calculate SAO statistics for current LCU
- * \param  iAddr,  iPartIdx,  iYCbCr
- */
-Void TEncSampleAdaptiveOffset::calcSaoStatsCu(Int iAddr, Int iPartIdx, Int iYCbCr)
-{
-  if(!m_bUseNIF)
-  {
-    calcSaoStatsCuOrg( iAddr, iPartIdx, iYCbCr);
-  }
-  else
-  {
-    Int64** ppStats = m_iOffsetOrg[iPartIdx];
-    Int64** ppCount = m_iCount    [iPartIdx];
-
-    //parameters
-    Int  isChroma = (iYCbCr != 0)? 1:0;
-    Int  stride   = (iYCbCr != 0)?(m_pcPic->getCStride()):(m_pcPic->getStride());
-    Pel* pPicOrg = getPicYuvAddr (m_pcPic->getPicYuvOrg(), iYCbCr);
-    Pel* pPicRec  = getPicYuvAddr(m_pcYuvTmp, iYCbCr);
-
-    std::vector<NDBFBlockInfo>& vFilterBlocks = *(m_pcPic->getCU(iAddr)->getNDBFilterBlocks());
-
-    //variables
-    UInt  xPos, yPos, width, height;
-    Bool* pbBorderAvail;
-    UInt  posOffset;
-
-    for(Int i=0; i< vFilterBlocks.size(); i++)
-    {
-      xPos        = vFilterBlocks[i].posX   >> isChroma;
-      yPos        = vFilterBlocks[i].posY   >> isChroma;
-      width       = vFilterBlocks[i].width  >> isChroma;
-      height      = vFilterBlocks[i].height >> isChroma;
-      pbBorderAvail = vFilterBlocks[i].isBorderAvailable;
-
-      posOffset = (yPos* stride) + xPos;
-
-      calcSaoStatsBlock(pPicRec+ posOffset, pPicOrg+ posOffset, stride, ppStats, ppCount,width, height, pbBorderAvail, iYCbCr);
-    }
-  }
-
-}
-
-/** Calculate SAO statistics for current LCU without non-crossing slice
- * \param  iAddr,  iPartIdx,  iYCbCr
- */
-Void TEncSampleAdaptiveOffset::calcSaoStatsCuOrg(Int iAddr, Int iPartIdx, Int iYCbCr)
-{
-  Int x,y;
-  TComDataCU *pTmpCu = m_pcPic->getCU(iAddr);
-  TComSPS *pTmpSPS =  m_pcPic->getSlice(0)->getSPS();
-
-  Pel* pOrg;
-  Pel* pRec;
-  Int iStride;
-  Int iLcuHeight = pTmpSPS->getMaxCUHeight();
-  Int iLcuWidth  = pTmpSPS->getMaxCUWidth();
-  UInt uiLPelX   = pTmpCu->getCUPelX();
-  UInt uiTPelY   = pTmpCu->getCUPelY();
-  UInt uiRPelX;
-  UInt uiBPelY;
-  Int64* iStats;
-  Int64* iCount;
-  Int iClassIdx;
-  Int iPicWidthTmp;
-  Int iPicHeightTmp;
-  Int iStartX;
-  Int iStartY;
-  Int iEndX;
-  Int iEndY;
-  Pel* pTableBo = (iYCbCr==0)?m_lumaTableBo:m_chromaTableBo;
-
-  Int iIsChroma = (iYCbCr!=0)? 1:0;
-  Int numSkipLine = iIsChroma? 2:4;
-  if (m_saoLcuBasedOptimization == 0)
-  {
-    numSkipLine = 0;
-  }
-
-  Int numSkipLineRight = iIsChroma? 3:5;
-  if (m_saoLcuBasedOptimization == 0)
-  {
-    numSkipLineRight = 0;
-  }
-
-  iPicWidthTmp  = m_iPicWidth  >> iIsChroma;
-  iPicHeightTmp = m_iPicHeight >> iIsChroma;
-  iLcuWidth     = iLcuWidth    >> iIsChroma;
-  iLcuHeight    = iLcuHeight   >> iIsChroma;
-  uiLPelX       = uiLPelX      >> iIsChroma;
-  uiTPelY       = uiTPelY      >> iIsChroma;
-  uiRPelX       = uiLPelX + iLcuWidth  ;
-  uiBPelY       = uiTPelY + iLcuHeight ;
-  uiRPelX       = uiRPelX > iPicWidthTmp  ? iPicWidthTmp  : uiRPelX;
-  uiBPelY       = uiBPelY > iPicHeightTmp ? iPicHeightTmp : uiBPelY;
-  iLcuWidth     = uiRPelX - uiLPelX;
-  iLcuHeight    = uiBPelY - uiTPelY;
-
-  iStride    =  (iYCbCr == 0)? m_pcPic->getStride(): m_pcPic->getCStride();
-
-//if(iSaoType == BO_0 || iSaoType == BO_1)
-  {
-    if( m_saoLcuBasedOptimization && m_saoLcuBoundary )
-    {
-      numSkipLine = iIsChroma? 1:3;
-      numSkipLineRight = iIsChroma? 2:4;
-    }
-    iStats = m_iOffsetOrg[iPartIdx][SAO_BO];
-    iCount = m_iCount    [iPartIdx][SAO_BO];
-
-    pOrg = getPicYuvAddr(m_pcPic->getPicYuvOrg(), iYCbCr, iAddr);
-    pRec = getPicYuvAddr(m_pcPic->getPicYuvRec(), iYCbCr, iAddr);
-
-    iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth : iLcuWidth-numSkipLineRight;
-    iEndY   = (uiBPelY == iPicHeightTmp) ? iLcuHeight : iLcuHeight-numSkipLine;
-    for (y=0; y<iEndY; y++)
-    {
-      for (x=0; x<iEndX; x++)
-      {
-        iClassIdx = pTableBo[pRec[x]];
-        if (iClassIdx)
-        {
-          iStats[iClassIdx] += (pOrg[x] - pRec[x]); 
-          iCount[iClassIdx] ++;
-        }
-      }
-      pOrg += iStride;
-      pRec += iStride;
-    }
-
-  }
-  Int iSignLeft;
-  Int iSignRight;
-  Int iSignDown;
-  Int iSignDown1;
-  Int iSignDown2;
-
-  UInt uiEdgeType;
-
-//if (iSaoType == EO_0  || iSaoType == EO_1 || iSaoType == EO_2 || iSaoType == EO_3)
-  {
-  //if (iSaoType == EO_0)
-    {
-      if( m_saoLcuBasedOptimization && m_saoLcuBoundary )
-      {
-        numSkipLine = iIsChroma? 1:3;
-        numSkipLineRight = iIsChroma? 3:5;
-      }
-      iStats = m_iOffsetOrg[iPartIdx][SAO_EO_0];
-      iCount = m_iCount    [iPartIdx][SAO_EO_0];
-
-      pOrg = getPicYuvAddr(m_pcPic->getPicYuvOrg(), iYCbCr, iAddr);
-      pRec = getPicYuvAddr(m_pcPic->getPicYuvRec(), iYCbCr, iAddr);
-
-      iStartX = (uiLPelX == 0) ? 1 : 0;
-      iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth-1 : iLcuWidth-numSkipLineRight;
-      for (y=0; y<iLcuHeight-numSkipLine; y++)
-      {
-        iSignLeft = xSign(pRec[iStartX] - pRec[iStartX-1]);
-        for (x=iStartX; x< iEndX; x++)
-        {
-          iSignRight =  xSign(pRec[x] - pRec[x+1]); 
-          uiEdgeType =  iSignRight + iSignLeft + 2;
-          iSignLeft  = -iSignRight;
-
-          iStats[m_auiEoTable[uiEdgeType]] += (pOrg[x] - pRec[x]);
-          iCount[m_auiEoTable[uiEdgeType]] ++;
-        }
-        pOrg += iStride;
-        pRec += iStride;
-      }
-    }
-
-  //if (iSaoType == EO_1)
-    {
-      if( m_saoLcuBasedOptimization && m_saoLcuBoundary )
-      {
-        numSkipLine = iIsChroma? 2:4;
-        numSkipLineRight = iIsChroma? 2:4;
-      }
-      iStats = m_iOffsetOrg[iPartIdx][SAO_EO_1];
-      iCount = m_iCount    [iPartIdx][SAO_EO_1];
-
-      pOrg = getPicYuvAddr(m_pcPic->getPicYuvOrg(), iYCbCr, iAddr);
-      pRec = getPicYuvAddr(m_pcPic->getPicYuvRec(), iYCbCr, iAddr);
-
-      iStartY = (uiTPelY == 0) ? 1 : 0;
-      iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth : iLcuWidth-numSkipLineRight;
-      iEndY   = (uiBPelY == iPicHeightTmp) ? iLcuHeight-1 : iLcuHeight-numSkipLine;
-      if (uiTPelY == 0)
-      {
-        pOrg += iStride;
-        pRec += iStride;
-      }
-
-      for (x=0; x< iLcuWidth; x++)
-      {
-        m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-iStride]);
-      }
-      for (y=iStartY; y<iEndY; y++)
-      {
-        for (x=0; x<iEndX; x++)
-        {
-          iSignDown     =  xSign(pRec[x] - pRec[x+iStride]); 
-          uiEdgeType    =  iSignDown + m_iUpBuff1[x] + 2;
-          m_iUpBuff1[x] = -iSignDown;
-
-          iStats[m_auiEoTable[uiEdgeType]] += (pOrg[x] - pRec[x]);
-          iCount[m_auiEoTable[uiEdgeType]] ++;
-        }
-        pOrg += iStride;
-        pRec += iStride;
-      }
-    }
-  //if (iSaoType == EO_2)
-    {
-      if( m_saoLcuBasedOptimization && m_saoLcuBoundary )
-      {
-        numSkipLine = iIsChroma? 2:4;
-        numSkipLineRight = iIsChroma? 3:5;
-      }
-      iStats = m_iOffsetOrg[iPartIdx][SAO_EO_2];
-      iCount = m_iCount    [iPartIdx][SAO_EO_2];
-
-      pOrg = getPicYuvAddr(m_pcPic->getPicYuvOrg(), iYCbCr, iAddr);
-      pRec = getPicYuvAddr(m_pcPic->getPicYuvRec(), iYCbCr, iAddr);
-
-      iStartX = (uiLPelX == 0) ? 1 : 0;
-      iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth-1 : iLcuWidth-numSkipLineRight;
-
-      iStartY = (uiTPelY == 0) ? 1 : 0;
-      iEndY   = (uiBPelY == iPicHeightTmp) ? iLcuHeight-1 : iLcuHeight-numSkipLine;
-      if (uiTPelY == 0)
-      {
-        pOrg += iStride;
-        pRec += iStride;
-      }
-
-      for (x=iStartX; x<iEndX; x++)
-      {
-        m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-iStride-1]);
-      }
-      for (y=iStartY; y<iEndY; y++)
-      {
-        iSignDown2 = xSign(pRec[iStride+iStartX] - pRec[iStartX-1]);
-        for (x=iStartX; x<iEndX; x++)
-        {
-          iSignDown1      =  xSign(pRec[x] - pRec[x+iStride+1]) ;
-          uiEdgeType      =  iSignDown1 + m_iUpBuff1[x] + 2;
-          m_iUpBufft[x+1] = -iSignDown1; 
-          iStats[m_auiEoTable[uiEdgeType]] += (pOrg[x] - pRec[x]);
-          iCount[m_auiEoTable[uiEdgeType]] ++;
-        }
-        m_iUpBufft[iStartX] = iSignDown2;
-        ipSwap     = m_iUpBuff1;
-        m_iUpBuff1 = m_iUpBufft;
-        m_iUpBufft = ipSwap;
-
-        pRec += iStride;
-        pOrg += iStride;
-      }
-    } 
-  //if (iSaoType == EO_3  )
-    {
-      if( m_saoLcuBasedOptimization && m_saoLcuBoundary )
-      {
-        numSkipLine = iIsChroma? 2:4;
-        numSkipLineRight = iIsChroma? 3:5;
-      }
-      iStats = m_iOffsetOrg[iPartIdx][SAO_EO_3];
-      iCount = m_iCount    [iPartIdx][SAO_EO_3];
-
-      pOrg = getPicYuvAddr(m_pcPic->getPicYuvOrg(), iYCbCr, iAddr);
-      pRec = getPicYuvAddr(m_pcPic->getPicYuvRec(), iYCbCr, iAddr);
-
-      iStartX = (uiLPelX == 0) ? 1 : 0;
-      iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth-1 : iLcuWidth-numSkipLineRight;
-
-      iStartY = (uiTPelY == 0) ? 1 : 0;
-      iEndY   = (uiBPelY == iPicHeightTmp) ? iLcuHeight-1 : iLcuHeight-numSkipLine;
-      if (iStartY == 1)
-      {
-        pOrg += iStride;
-        pRec += iStride;
-      }
-
-      for (x=iStartX-1; x<iEndX; x++)
-      {
-        m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-iStride+1]);
-      }
-
-      for (y=iStartY; y<iEndY; y++)
-      {
-        for (x=iStartX; x<iEndX; x++)
-        {
-          iSignDown1      =  xSign(pRec[x] - pRec[x+iStride-1]) ;
-          uiEdgeType      =  iSignDown1 + m_iUpBuff1[x] + 2;
-          m_iUpBuff1[x-1] = -iSignDown1; 
-          iStats[m_auiEoTable[uiEdgeType]] += (pOrg[x] - pRec[x]);
-          iCount[m_auiEoTable[uiEdgeType]] ++;
-        }
-        m_iUpBuff1[iEndX-1] = xSign(pRec[iEndX-1 + iStride] - pRec[iEndX]);
-
-        pRec += iStride;
-        pOrg += iStride;
-      } 
-    } 
-  }
-}
-
-
-Void TEncSampleAdaptiveOffset::calcSaoStatsCu_BeforeDblk( TComPic* pcPic )
-{
-  Int addr, yCbCr;
-  Int x,y;
-  TComSPS *pTmpSPS =  pcPic->getSlice(0)->getSPS();
-
-  Pel* pOrg;
-  Pel* pRec;
-  Int stride;
-  Int lcuHeight = pTmpSPS->getMaxCUHeight();
-  Int lcuWidth  = pTmpSPS->getMaxCUWidth();
-  UInt rPelX;
-  UInt bPelY;
-  Int64* stats;
-  Int64* count;
-  Int classIdx;
-  Int picWidthTmp = 0;
-  Int picHeightTmp = 0;
-  Int startX;
-  Int startY;
-  Int endX;
-  Int endY;
-  Int firstX, firstY;
-
-  Int idxY;
-  Int idxX;
-  Int frameHeightInCU = m_iNumCuInHeight;
-  Int frameWidthInCU  = m_iNumCuInWidth;
-  Int j, k;
-
-  Int isChroma;
-  Int numSkipLine, numSkipLineRight;
-
-  UInt lPelX, tPelY;
-  TComDataCU *pTmpCu;
-  Pel* pTableBo;
-
-  for (idxY = 0; idxY< frameHeightInCU; idxY++)
-  {
-    for (idxX = 0; idxX< frameWidthInCU; idxX++)
-    {
-      lcuHeight = pTmpSPS->getMaxCUHeight();
-      lcuWidth  = pTmpSPS->getMaxCUWidth();
-      addr     = idxX  + frameWidthInCU*idxY;
-      pTmpCu = pcPic->getCU(addr);
-      lPelX   = pTmpCu->getCUPelX();
-      tPelY   = pTmpCu->getCUPelY();
-      for( yCbCr = 0; yCbCr < 3; yCbCr++ )
-      {
-        isChroma = (yCbCr!=0)? 1:0;
-
-        for ( j=0;j<MAX_NUM_SAO_TYPE;j++)
-        {
-          for ( k=0;k< MAX_NUM_SAO_CLASS;k++)
-          {
-            m_count_PreDblk    [addr][yCbCr][j][k] = 0;
-            m_offsetOrg_PreDblk[addr][yCbCr][j][k] = 0;
-          }  
-        }
-        if( yCbCr == 0 )
-        {
-          picWidthTmp  = m_iPicWidth;
-          picHeightTmp = m_iPicHeight;
-        }
-        else if( yCbCr == 1 )
-        {
-          picWidthTmp  = m_iPicWidth  >> isChroma;
-          picHeightTmp = m_iPicHeight >> isChroma;
-          lcuWidth     = lcuWidth    >> isChroma;
-          lcuHeight    = lcuHeight   >> isChroma;
-          lPelX       = lPelX      >> isChroma;
-          tPelY       = tPelY      >> isChroma;
-        }
-        rPelX       = lPelX + lcuWidth  ;
-        bPelY       = tPelY + lcuHeight ;
-        rPelX       = rPelX > picWidthTmp  ? picWidthTmp  : rPelX;
-        bPelY       = bPelY > picHeightTmp ? picHeightTmp : bPelY;
-        lcuWidth     = rPelX - lPelX;
-        lcuHeight    = bPelY - tPelY;
-
-        stride    =  (yCbCr == 0)? pcPic->getStride(): pcPic->getCStride();
-        pTableBo = (yCbCr==0)?m_lumaTableBo:m_chromaTableBo;
-
-        //if(iSaoType == BO)
-
-        numSkipLine = isChroma? 1:3;
-        numSkipLineRight = isChroma? 2:4;
-
-        stats = m_offsetOrg_PreDblk[addr][yCbCr][SAO_BO];
-        count = m_count_PreDblk[addr][yCbCr][SAO_BO];
-
-        pOrg = getPicYuvAddr(pcPic->getPicYuvOrg(), yCbCr, addr);
-        pRec = getPicYuvAddr(pcPic->getPicYuvRec(), yCbCr, addr);
-
-        startX   = (rPelX == picWidthTmp) ? lcuWidth : lcuWidth-numSkipLineRight;
-        startY   = (bPelY == picHeightTmp) ? lcuHeight : lcuHeight-numSkipLine;
-
-        for (y=0; y<lcuHeight; y++)
-        {
-          for (x=0; x<lcuWidth; x++)
-          {
-            if( x < startX && y < startY )
-              continue;
-
-            classIdx = pTableBo[pRec[x]];
-            if (classIdx)
-            {
-              stats[classIdx] += (pOrg[x] - pRec[x]); 
-              count[classIdx] ++;
-            }
-          }
-          pOrg += stride;
-          pRec += stride;
-        }
-
-        Int signLeft;
-        Int signRight;
-        Int signDown;
-        Int signDown1;
-        Int signDown2;
-
-        UInt uiEdgeType;
-
-        //if (iSaoType == EO_0)
-
-        numSkipLine = isChroma? 1:3;
-        numSkipLineRight = isChroma? 3:5;
-
-        stats = m_offsetOrg_PreDblk[addr][yCbCr][SAO_EO_0];
-        count = m_count_PreDblk[addr][yCbCr][SAO_EO_0];
-
-        pOrg = getPicYuvAddr(pcPic->getPicYuvOrg(), yCbCr, addr);
-        pRec = getPicYuvAddr(pcPic->getPicYuvRec(), yCbCr, addr);
-
-        startX   = (rPelX == picWidthTmp) ? lcuWidth-1 : lcuWidth-numSkipLineRight;
-        startY   = (bPelY == picHeightTmp) ? lcuHeight : lcuHeight-numSkipLine;
-        firstX   = (lPelX == 0) ? 1 : 0;
-        endX   = (rPelX == picWidthTmp) ? lcuWidth-1 : lcuWidth;
-
-        for (y=0; y<lcuHeight; y++)
-        {
-          signLeft = xSign(pRec[firstX] - pRec[firstX-1]);
-          for (x=firstX; x< endX; x++)
-          {
-            signRight =  xSign(pRec[x] - pRec[x+1]); 
-            uiEdgeType =  signRight + signLeft + 2;
-            signLeft  = -signRight;
-
-            if( x < startX && y < startY )
-              continue;
-
-            stats[m_auiEoTable[uiEdgeType]] += (pOrg[x] - pRec[x]);
-            count[m_auiEoTable[uiEdgeType]] ++;
-          }
-          pOrg += stride;
-          pRec += stride;
-        }
-
-        //if (iSaoType == EO_1)
-
-        numSkipLine = isChroma? 2:4;
-        numSkipLineRight = isChroma? 2:4;
-
-        stats = m_offsetOrg_PreDblk[addr][yCbCr][SAO_EO_1];
-        count = m_count_PreDblk[addr][yCbCr][SAO_EO_1];
-
-        pOrg = getPicYuvAddr(pcPic->getPicYuvOrg(), yCbCr, addr);
-        pRec = getPicYuvAddr(pcPic->getPicYuvRec(), yCbCr, addr);
-
-        startX   = (rPelX == picWidthTmp) ? lcuWidth : lcuWidth-numSkipLineRight;
-        startY   = (bPelY == picHeightTmp) ? lcuHeight-1 : lcuHeight-numSkipLine;
-        firstY = (tPelY == 0) ? 1 : 0;
-        endY   = (bPelY == picHeightTmp) ? lcuHeight-1 : lcuHeight;
-        if (firstY == 1)
-        {
-          pOrg += stride;
-          pRec += stride;
-        }
-
-        for (x=0; x< lcuWidth; x++)
-        {
-          m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-stride]);
-        }
-        for (y=firstY; y<endY; y++)
-        {
-          for (x=0; x<lcuWidth; x++)
-          {
-            signDown     =  xSign(pRec[x] - pRec[x+stride]); 
-            uiEdgeType    =  signDown + m_iUpBuff1[x] + 2;
-            m_iUpBuff1[x] = -signDown;
-
-            if( x < startX && y < startY )
-              continue;
-
-            stats[m_auiEoTable[uiEdgeType]] += (pOrg[x] - pRec[x]);
-            count[m_auiEoTable[uiEdgeType]] ++;
-          }
-          pOrg += stride;
-          pRec += stride;
-        }
-
-        //if (iSaoType == EO_2)
-
-        numSkipLine = isChroma? 2:4;
-        numSkipLineRight = isChroma? 3:5;
-
-        stats = m_offsetOrg_PreDblk[addr][yCbCr][SAO_EO_2];
-        count = m_count_PreDblk[addr][yCbCr][SAO_EO_2];
-
-        pOrg = getPicYuvAddr(pcPic->getPicYuvOrg(), yCbCr, addr);
-        pRec = getPicYuvAddr(pcPic->getPicYuvRec(), yCbCr, addr);
-
-        startX   = (rPelX == picWidthTmp) ? lcuWidth-1 : lcuWidth-numSkipLineRight;
-        startY   = (bPelY == picHeightTmp) ? lcuHeight-1 : lcuHeight-numSkipLine;
-        firstX   = (lPelX == 0) ? 1 : 0;
-        firstY = (tPelY == 0) ? 1 : 0;
-        endX   = (rPelX == picWidthTmp) ? lcuWidth-1 : lcuWidth;
-        endY   = (bPelY == picHeightTmp) ? lcuHeight-1 : lcuHeight;
-        if (firstY == 1)
-        {
-          pOrg += stride;
-          pRec += stride;
-        }
-
-        for (x=firstX; x<endX; x++)
-        {
-          m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-stride-1]);
-        }
-        for (y=firstY; y<endY; y++)
-        {
-          signDown2 = xSign(pRec[stride+startX] - pRec[startX-1]);
-          for (x=firstX; x<endX; x++)
-          {
-            signDown1      =  xSign(pRec[x] - pRec[x+stride+1]) ;
-            uiEdgeType      =  signDown1 + m_iUpBuff1[x] + 2;
-            m_iUpBufft[x+1] = -signDown1; 
-
-            if( x < startX && y < startY )
-              continue;
-
-            stats[m_auiEoTable[uiEdgeType]] += (pOrg[x] - pRec[x]);
-            count[m_auiEoTable[uiEdgeType]] ++;
-          }
-          m_iUpBufft[firstX] = signDown2;
-          ipSwap     = m_iUpBuff1;
-          m_iUpBuff1 = m_iUpBufft;
-          m_iUpBufft = ipSwap;
-
-          pRec += stride;
-          pOrg += stride;
-        }
-
-        //if (iSaoType == EO_3)
-
-        numSkipLine = isChroma? 2:4;
-        numSkipLineRight = isChroma? 3:5;
-
-        stats = m_offsetOrg_PreDblk[addr][yCbCr][SAO_EO_3];
-        count = m_count_PreDblk[addr][yCbCr][SAO_EO_3];
-
-        pOrg = getPicYuvAddr(pcPic->getPicYuvOrg(), yCbCr, addr);
-        pRec = getPicYuvAddr(pcPic->getPicYuvRec(), yCbCr, addr);
-
-        startX   = (rPelX == picWidthTmp) ? lcuWidth-1 : lcuWidth-numSkipLineRight;
-        startY   = (bPelY == picHeightTmp) ? lcuHeight-1 : lcuHeight-numSkipLine;
-        firstX   = (lPelX == 0) ? 1 : 0;
-        firstY = (tPelY == 0) ? 1 : 0;
-        endX   = (rPelX == picWidthTmp) ? lcuWidth-1 : lcuWidth;
-        endY   = (bPelY == picHeightTmp) ? lcuHeight-1 : lcuHeight;
-        if (firstY == 1)
-        {
-          pOrg += stride;
-          pRec += stride;
-        }
-
-        for (x=firstX-1; x<endX; x++)
-        {
-          m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-stride+1]);
-        }
-
-        for (y=firstY; y<endY; y++)
-        {
-          for (x=firstX; x<endX; x++)
-          {
-            signDown1      =  xSign(pRec[x] - pRec[x+stride-1]) ;
-            uiEdgeType      =  signDown1 + m_iUpBuff1[x] + 2;
-            m_iUpBuff1[x-1] = -signDown1; 
-
-            if( x < startX && y < startY )
-              continue;
-
-            stats[m_auiEoTable[uiEdgeType]] += (pOrg[x] - pRec[x]);
-            count[m_auiEoTable[uiEdgeType]] ++;
-          }
-          m_iUpBuff1[endX-1] = xSign(pRec[endX-1 + stride] - pRec[endX]);
-
-          pRec += stride;
-          pOrg += stride;
-        }
-      }
-    }
-  }
-}
-
-
-/** get SAO statistics
- * \param  *psQTPart,  iYCbCr
- */
-Void TEncSampleAdaptiveOffset::getSaoStats(SAOQTPart *psQTPart, Int iYCbCr)
-{
-  Int iLevelIdx, iPartIdx, iTypeIdx, iClassIdx;
-  Int i;
-  Int iNumTotalType = MAX_NUM_SAO_TYPE;
-  Int LcuIdxX;
-  Int LcuIdxY;
-  Int iAddr;
-  Int iFrameWidthInCU = m_pcPic->getFrameWidthInCU();
-  Int iDownPartIdx;
-  Int iPartStart;
-  Int iPartEnd;
-  SAOQTPart*  pOnePart; 
-
-  if (m_uiMaxSplitLevel == 0)
-  {
-    iPartIdx = 0;
-    pOnePart = &(psQTPart[iPartIdx]);
-    for (LcuIdxY = pOnePart->StartCUY; LcuIdxY<= pOnePart->EndCUY; LcuIdxY++)
-    {
-      for (LcuIdxX = pOnePart->StartCUX; LcuIdxX<= pOnePart->EndCUX; LcuIdxX++)
-      {
-        iAddr = LcuIdxY*iFrameWidthInCU + LcuIdxX;
-        calcSaoStatsCu(iAddr, iPartIdx, iYCbCr);
-      }
-    }
-  }
-  else
-  {
-    for(iPartIdx=m_aiNumCulPartsLevel[m_uiMaxSplitLevel-1]; iPartIdx<m_aiNumCulPartsLevel[m_uiMaxSplitLevel]; iPartIdx++)
-    {
-      pOnePart = &(psQTPart[iPartIdx]);
-      for (LcuIdxY = pOnePart->StartCUY; LcuIdxY<= pOnePart->EndCUY; LcuIdxY++)
-      {
-        for (LcuIdxX = pOnePart->StartCUX; LcuIdxX<= pOnePart->EndCUX; LcuIdxX++)
-        {
-          iAddr = LcuIdxY*iFrameWidthInCU + LcuIdxX;
-          calcSaoStatsCu(iAddr, iPartIdx, iYCbCr);
-        }
-      }
-    }
-    for (iLevelIdx = m_uiMaxSplitLevel-1; iLevelIdx>=0; iLevelIdx-- )
-    {
-      iPartStart = (iLevelIdx > 0) ? m_aiNumCulPartsLevel[iLevelIdx-1] : 0;
-      iPartEnd   = m_aiNumCulPartsLevel[iLevelIdx];
-
-      for(iPartIdx = iPartStart; iPartIdx < iPartEnd; iPartIdx++)
-      {
-        pOnePart = &(psQTPart[iPartIdx]);
-        for (i=0; i< NUM_DOWN_PART; i++)
-        {
-          iDownPartIdx = pOnePart->DownPartsIdx[i];
-          for (iTypeIdx=0; iTypeIdx<iNumTotalType; iTypeIdx++)
-          {
-            for (iClassIdx=0; iClassIdx< (iTypeIdx < SAO_BO ? m_iNumClass[iTypeIdx] : SAO_MAX_BO_CLASSES) +1; iClassIdx++)
-            {
-              m_iOffsetOrg[iPartIdx][iTypeIdx][iClassIdx] += m_iOffsetOrg[iDownPartIdx][iTypeIdx][iClassIdx];
-              m_iCount [iPartIdx][iTypeIdx][iClassIdx]    += m_iCount [iDownPartIdx][iTypeIdx][iClassIdx];
-            }
-          }
-        }
-      }
-    }
-  }
-}
-
-/** reset offset statistics 
- * \param 
- */
-Void TEncSampleAdaptiveOffset::resetStats()
-{
-  for (Int i=0;i<m_iNumTotalParts;i++)
-  {
-    m_dCostPartBest[i] = MAX_DOUBLE;
-    m_iTypePartBest[i] = -1;
-    m_iDistOrg[i] = 0;
-    for (Int j=0;j<MAX_NUM_SAO_TYPE;j++)
-    {
-      m_iDist[i][j] = 0;
-      m_iRate[i][j] = 0;
-      m_dCost[i][j] = 0;
-      for (Int k=0;k<MAX_NUM_SAO_CLASS;k++)
-      {
-        m_iCount [i][j][k] = 0;
-        m_iOffset[i][j][k] = 0;
-        m_iOffsetOrg[i][j][k] = 0;
-      }  
-    }
-  }
-}
-
-#if SAO_CHROMA_LAMBDA 
-/** Sample adaptive offset process
- * \param pcSaoParam
- * \param dLambdaLuma
- * \param dLambdaChroma
- */
-#if SAO_ENCODING_CHOICE
-Void TEncSampleAdaptiveOffset::SAOProcess(SAOParam *pcSaoParam, Double dLambdaLuma, Double dLambdaChroma, Int depth)
-#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
-{
-  if(m_bUseNIF)
-  {
-    m_pcPic->getPicYuvRec()->copyToPic(m_pcYuvTmp);
-  }
-
-  m_uiSaoBitIncreaseY = max(g_bitDepthY - 10, 0);
-  m_uiSaoBitIncreaseC = max(g_bitDepthC - 10, 0);
-  m_iOffsetThY = 1 << min(g_bitDepthY - 5, 5);
-  m_iOffsetThC = 1 << min(g_bitDepthC - 5, 5);
-  resetSAOParam(pcSaoParam);
-  if( !m_saoLcuBasedOptimization || !m_saoLcuBoundary )
-  {
-    resetStats();
-  }
-  Double dCostFinal = 0;
-  if ( m_saoLcuBasedOptimization)
-  {
-#if SAO_ENCODING_CHOICE
-    rdoSaoUnitAll(pcSaoParam, dLambdaLuma, dLambdaChroma, depth);
-#else
-    rdoSaoUnitAll(pcSaoParam, dLambdaLuma, dLambdaChroma);
-#endif
-  }
-  else
-  {
-    pcSaoParam->bSaoFlag[0] = 1;
-    pcSaoParam->bSaoFlag[1] = 0;
-    dCostFinal = 0;
-    Double lambdaRdo =  dLambdaLuma;
-    resetStats();
-    getSaoStats(pcSaoParam->psSaoPart[0], 0);
-    runQuadTreeDecision(pcSaoParam->psSaoPart[0], 0, dCostFinal, m_uiMaxSplitLevel, lambdaRdo, 0);
-    pcSaoParam->bSaoFlag[0] = dCostFinal < 0 ? 1:0;
-    if(pcSaoParam->bSaoFlag[0])
-    {
-      convertQT2SaoUnit(pcSaoParam, 0, 0);
-      assignSaoUnitSyntax(pcSaoParam->saoLcuParam[0],  pcSaoParam->psSaoPart[0], pcSaoParam->oneUnitFlag[0], 0);
-    }
-  }
-  if (pcSaoParam->bSaoFlag[0])
-  {
-    processSaoUnitAll( pcSaoParam->saoLcuParam[0], pcSaoParam->oneUnitFlag[0], 0);
-  }
-  if (pcSaoParam->bSaoFlag[1])
-  {
-    processSaoUnitAll( pcSaoParam->saoLcuParam[1], pcSaoParam->oneUnitFlag[1], 1);
-    processSaoUnitAll( pcSaoParam->saoLcuParam[2], pcSaoParam->oneUnitFlag[2], 2);
-  }
-}
-/** Check merge SAO unit
- * \param saoUnitCurr current SAO unit 
- * \param saoUnitCheck SAO unit tobe check
- * \param dir direction
- */
-Void TEncSampleAdaptiveOffset::checkMerge(SaoLcuParam * saoUnitCurr, SaoLcuParam * saoUnitCheck, Int dir)
-{
-  Int i ;
-  Int countDiff = 0;
-  if (saoUnitCurr->partIdx != saoUnitCheck->partIdx)
-  {
-    if (saoUnitCurr->typeIdx !=-1)
-    {
-      if (saoUnitCurr->typeIdx == saoUnitCheck->typeIdx)
-      {
-        for (i=0;i<saoUnitCurr->length;i++)
-        {
-          countDiff += (saoUnitCurr->offset[i] != saoUnitCheck->offset[i]);
-        }
-        countDiff += (saoUnitCurr->subTypeIdx != saoUnitCheck->subTypeIdx);
-        if (countDiff ==0)
-        {
-          saoUnitCurr->partIdx = saoUnitCheck->partIdx;
-          if (dir == 1)
-          {
-            saoUnitCurr->mergeUpFlag = 1;
-            saoUnitCurr->mergeLeftFlag = 0;
-          }
-          else
-          {
-            saoUnitCurr->mergeUpFlag = 0;
-            saoUnitCurr->mergeLeftFlag = 1;
-          }
-        }
-      }
-    }
-    else
-    {
-      if (saoUnitCurr->typeIdx == saoUnitCheck->typeIdx)
-      {
-        saoUnitCurr->partIdx = saoUnitCheck->partIdx;
-        if (dir == 1)
-        {
-          saoUnitCurr->mergeUpFlag = 1;
-          saoUnitCurr->mergeLeftFlag = 0;
-        }
-        else
-        {
-          saoUnitCurr->mergeUpFlag = 0;
-          saoUnitCurr->mergeLeftFlag = 1;
-        }
-      }
-    }
-  }
-}
-/** Assign SAO unit syntax from picture-based algorithm
- * \param saoLcuParam SAO LCU parameters
- * \param saoPart SAO part
- * \param oneUnitFlag SAO one unit flag
- * \param iYCbCr color component Index
- */
-Void TEncSampleAdaptiveOffset::assignSaoUnitSyntax(SaoLcuParam* saoLcuParam,  SAOQTPart* saoPart, Bool &oneUnitFlag, Int yCbCr)
-{
-  if (saoPart->bSplit == 0)
-  {
-    oneUnitFlag = 1;
-  }
-  else
-  {
-    Int i,j, addr, addrUp, addrLeft,  idx, idxUp, idxLeft,  idxCount;
-
-    oneUnitFlag = 0;
-
-    idxCount = -1;
-    saoLcuParam[0].mergeUpFlag = 0;
-    saoLcuParam[0].mergeLeftFlag = 0;
-
-    for (j=0;j<m_iNumCuInHeight;j++)
-    {
-      for (i=0;i<m_iNumCuInWidth;i++)
-      {
-        addr     = i + j*m_iNumCuInWidth;
-        addrLeft = (addr%m_iNumCuInWidth == 0) ? -1 : addr - 1;
-        addrUp   = (addr<m_iNumCuInWidth)      ? -1 : addr - m_iNumCuInWidth;
-        idx      = saoLcuParam[addr].partIdxTmp;
-        idxLeft  = (addrLeft == -1) ? -1 : saoLcuParam[addrLeft].partIdxTmp;
-        idxUp    = (addrUp == -1)   ? -1 : saoLcuParam[addrUp].partIdxTmp;
-
-        if(idx!=idxLeft && idx!=idxUp)
-        {
-          saoLcuParam[addr].mergeUpFlag   = 0; idxCount++;
-          saoLcuParam[addr].mergeLeftFlag = 0;
-          saoLcuParam[addr].partIdx = idxCount;
-        }
-        else if (idx==idxLeft)
-        {
-          saoLcuParam[addr].mergeUpFlag   = 1;
-          saoLcuParam[addr].mergeLeftFlag = 1;
-          saoLcuParam[addr].partIdx = saoLcuParam[addrLeft].partIdx;
-        }
-        else if (idx==idxUp)
-        {
-          saoLcuParam[addr].mergeUpFlag   = 1;
-          saoLcuParam[addr].mergeLeftFlag = 0;
-          saoLcuParam[addr].partIdx = saoLcuParam[addrUp].partIdx;
-        }
-        if (addrUp != -1)
-        {
-          checkMerge(&saoLcuParam[addr], &saoLcuParam[addrUp], 1);
-        }
-        if (addrLeft != -1)
-        {
-          checkMerge(&saoLcuParam[addr], &saoLcuParam[addrLeft], 0);
-        }
-      }
-    }
-  }
-}
-/** rate distortion optimization of all SAO units
- * \param saoParam SAO parameters
- * \param lambda 
- * \param lambdaChroma
- */
-#if SAO_ENCODING_CHOICE
-Void TEncSampleAdaptiveOffset::rdoSaoUnitAll(SAOParam *saoParam, Double lambda, Double lambdaChroma, Int depth)
-#else
-Void TEncSampleAdaptiveOffset::rdoSaoUnitAll(SAOParam *saoParam, Double lambda, Double lambdaChroma)
-#endif
-{
-
-  Int idxY;
-  Int idxX;
-  Int frameHeightInCU = saoParam->numCuInHeight;
-  Int frameWidthInCU  = saoParam->numCuInWidth;
-  Int j, k;
-  Int addr = 0;
-  Int addrUp = -1;
-  Int addrLeft = -1;
-  Int compIdx = 0;
-  SaoLcuParam mergeSaoParam[3][2];
-  Double compDistortion[3];
-
-  saoParam->bSaoFlag[0] = true;
-  saoParam->bSaoFlag[1] = true;
-  saoParam->oneUnitFlag[0] = false;
-  saoParam->oneUnitFlag[1] = false;
-  saoParam->oneUnitFlag[2] = false;
+  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_lambda[SAO_Y]= lambdas[0]; m_lambda[SAO_Cb]= lambdas[1]; m_lambda[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
-  Int numNoSao[2];
-  numNoSao[0] = 0;// Luma 
-  numNoSao[1] = 0;// Chroma 
-  if( depth > 0 && m_depthSaoRate[0][depth-1] > SAO_ENCODING_RATE )
-  {
-    saoParam->bSaoFlag[0] = false;
-  }
-  if( depth > 0 && m_depthSaoRate[1][depth-1] > SAO_ENCODING_RATE_CHROMA )
-  {
-    saoParam->bSaoFlag[1] = false;
-  }
-#else
-  Int numNoSao = 0;
-
-  if( depth > 0 && m_depth0SaoRate > SAO_ENCODING_RATE )
-  {
-    saoParam->bSaoFlag[0] = false;
-    saoParam->bSaoFlag[1] = false;
-  }
-#endif
-#endif
-
-  for (idxY = 0; idxY< frameHeightInCU; idxY++)
-  {
-    for (idxX = 0; idxX< frameWidthInCU; idxX++)
-    {
-      addr     = idxX  + frameWidthInCU*idxY;
-      addrUp   = addr < frameWidthInCU ? -1:idxX   + frameWidthInCU*(idxY-1);
-      addrLeft = idxX == 0               ? -1:idxX-1 + frameWidthInCU*idxY;
-      Int allowMergeLeft = 1;
-      Int allowMergeUp   = 1;
-      UInt rate;
-      Double bestCost, mergeCost;
-      if (idxX!=0)
-      { 
-        // check tile id and slice id 
-        if ( (m_pcPic->getPicSym()->getTileIdxMap(addr-1) != m_pcPic->getPicSym()->getTileIdxMap(addr)) || (m_pcPic->getCU(addr-1)->getSlice()->getSliceIdx() != m_pcPic->getCU(addr)->getSlice()->getSliceIdx()))
-        {
-          allowMergeLeft = 0;
-        }
-      }
-      else
-      {
-        allowMergeLeft = 0;
-      }
-      if (idxY!=0)
-      {
-        if ( (m_pcPic->getPicSym()->getTileIdxMap(addr-m_iNumCuInWidth) != m_pcPic->getPicSym()->getTileIdxMap(addr)) || (m_pcPic->getCU(addr-m_iNumCuInWidth)->getSlice()->getSliceIdx() != m_pcPic->getCU(addr)->getSlice()->getSliceIdx()))
-        {
-          allowMergeUp = 0;
-        }
-      }
-      else
-      {
-        allowMergeUp = 0;
-      }
-
-      compDistortion[0] = 0; 
-      compDistortion[1] = 0; 
-      compDistortion[2] = 0;
-      m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_CURR_BEST]);
-      if (allowMergeLeft)
-      {
-        m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMerge(0); 
-      }
-      if (allowMergeUp)
-      {
-        m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMerge(0);
-      }
-      m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[0][CI_TEMP_BEST] );
-      // reset stats Y, Cb, Cr
-      for ( compIdx=0;compIdx<3;compIdx++)
-      {
-        for ( j=0;j<MAX_NUM_SAO_TYPE;j++)
-        {
-          for ( k=0;k< MAX_NUM_SAO_CLASS;k++)
-          {
-            m_iOffset   [compIdx][j][k] = 0;
-            if( m_saoLcuBasedOptimization && m_saoLcuBoundary ){
-              m_iCount    [compIdx][j][k] = m_count_PreDblk    [addr][compIdx][j][k];
-              m_iOffsetOrg[compIdx][j][k] = m_offsetOrg_PreDblk[addr][compIdx][j][k];
-            }
-            else
-            {
-              m_iCount    [compIdx][j][k] = 0;
-              m_iOffsetOrg[compIdx][j][k] = 0;
-            }
-          }  
-        }
-        saoParam->saoLcuParam[compIdx][addr].typeIdx       =  -1;
-        saoParam->saoLcuParam[compIdx][addr].mergeUpFlag   = 0;
-        saoParam->saoLcuParam[compIdx][addr].mergeLeftFlag = 0;
-        saoParam->saoLcuParam[compIdx][addr].subTypeIdx    = 0;
-#if SAO_ENCODING_CHOICE
-  if( (compIdx ==0 && saoParam->bSaoFlag[0])|| (compIdx >0 && saoParam->bSaoFlag[1]) )
-#endif
-        {
-          calcSaoStatsCu(addr, compIdx,  compIdx);
-
-       }
-      }
-      saoComponentParamDist(allowMergeLeft, allowMergeUp, saoParam, addr, addrUp, addrLeft, 0,  lambda, &mergeSaoParam[0][0], &compDistortion[0]);
-      sao2ChromaParamDist(allowMergeLeft, allowMergeUp, saoParam, addr, addrUp, addrLeft, lambdaChroma, &mergeSaoParam[1][0], &mergeSaoParam[2][0], &compDistortion[0]);
-     if( saoParam->bSaoFlag[0] || saoParam->bSaoFlag[1] )
-      {
-        // Cost of new SAO_params
-        m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_CURR_BEST]);
-        m_pcRDGoOnSbacCoder->resetBits();
-        if (allowMergeLeft)
-        {
-          m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMerge(0); 
-        }
-        if (allowMergeUp)
-        {
-          m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMerge(0);
-        }
-        for ( compIdx=0;compIdx<3;compIdx++)
-        {
-        if( (compIdx ==0 && saoParam->bSaoFlag[0]) || (compIdx >0 && saoParam->bSaoFlag[1]))
-          {
-           m_pcEntropyCoder->encodeSaoOffset(&saoParam->saoLcuParam[compIdx][addr], compIdx);
-          }
-        }
-
-        rate = m_pcEntropyCoder->getNumberOfWrittenBits();
-        bestCost = compDistortion[0] + (Double)rate;
-        m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[0][CI_TEMP_BEST]);
-
-        // Cost of Merge
-        for(Int mergeUp=0; mergeUp<2; ++mergeUp)
-        {
-          if ( (allowMergeLeft && (mergeUp==0)) || (allowMergeUp && (mergeUp==1)) )
-          {
-            m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_CURR_BEST]);
-            m_pcRDGoOnSbacCoder->resetBits();
-            if (allowMergeLeft)
-            {
-              m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMerge(1-mergeUp); 
-            }
-            if ( allowMergeUp && (mergeUp==1) )
-            {
-              m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMerge(1); 
-            }
-
-            rate = m_pcEntropyCoder->getNumberOfWrittenBits();
-            mergeCost = compDistortion[mergeUp+1] + (Double)rate;
-            if (mergeCost < bestCost)
-            {
-              bestCost = mergeCost;
-              m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[0][CI_TEMP_BEST]);              
-              for ( compIdx=0;compIdx<3;compIdx++)
-              {
-                mergeSaoParam[compIdx][mergeUp].mergeLeftFlag = 1-mergeUp;
-                mergeSaoParam[compIdx][mergeUp].mergeUpFlag = mergeUp;
-                if( (compIdx==0 && saoParam->bSaoFlag[0]) || (compIdx>0 && saoParam->bSaoFlag[1]))
-                {
-                  copySaoUnit(&saoParam->saoLcuParam[compIdx][addr], &mergeSaoParam[compIdx][mergeUp] );             
-                }
-              }
-            }
-          }
-        }
-#if SAO_ENCODING_CHOICE
-#if SAO_ENCODING_CHOICE_CHROMA
-if( saoParam->saoLcuParam[0][addr].typeIdx == -1)
-{
-  numNoSao[0]++;
-}
-if( saoParam->saoLcuParam[1][addr].typeIdx == -1)
-{
-  numNoSao[1]+=2;
-}
-#else
-        for ( compIdx=0;compIdx<3;compIdx++)
-        {
-          if( depth == 0 && saoParam->saoLcuParam[compIdx][addr].typeIdx == -1)
-          {
-            numNoSao++;
-          }
-        }
-#endif
-#endif
-        m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_TEMP_BEST]);
-        m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[0][CI_CURR_BEST]);
-      }
-    }
-  }
-#if SAO_ENCODING_CHOICE
-#if SAO_ENCODING_CHOICE_CHROMA
-  if( !saoParam->bSaoFlag[0])
-  {
-    m_depthSaoRate[0][depth] = 1.0;
-  }
-  else
-  {
-    m_depthSaoRate[0][depth] = numNoSao[0]/((Double) frameHeightInCU*frameWidthInCU);
-  }
-  if( !saoParam->bSaoFlag[1]) 
-  {
-    m_depthSaoRate[1][depth] = 1.0;
-  }
-  else 
-  {
-    m_depthSaoRate[1][depth] = numNoSao[1]/((Double) frameHeightInCU*frameWidthInCU*2);
-  }
-#else
-  if( depth == 0)
-  {
-    // update SAO Rate
-    m_depth0SaoRate = numNoSao/((Double) frameHeightInCU*frameWidthInCU*3);
-  }
-#endif
-#endif
-
-}
-/** rate distortion optimization of SAO unit 
- * \param saoParam SAO parameters
- * \param addr address 
- * \param addrUp above address
- * \param addrLeft left address 
- * \param yCbCr color component index
- * \param lambda 
- */
-inline Int64 TEncSampleAdaptiveOffset::estSaoTypeDist(Int compIdx, Int typeIdx, Int shift, Double lambda, Int *currentDistortionTableBo, Double *currentRdCostTableBo)
-{
-  Int64 estDist = 0;
-  Int classIdx;
-  Int bitDepth = (compIdx==0) ? g_bitDepthY : g_bitDepthC;
-  Int saoBitIncrease = (compIdx==0) ? m_uiSaoBitIncreaseY : m_uiSaoBitIncreaseC;
-  Int saoOffsetTh = (compIdx==0) ? m_iOffsetThY : m_iOffsetThC;
-
-  for(classIdx=1; classIdx < ( (typeIdx < SAO_BO) ?  m_iNumClass[typeIdx]+1 : SAO_MAX_BO_CLASSES+1); classIdx++)
-  {
-    if( typeIdx == SAO_BO)
-    {
-      currentDistortionTableBo[classIdx-1] = 0;
-      currentRdCostTableBo[classIdx-1] = lambda;
-    }
-    if(m_iCount [compIdx][typeIdx][classIdx])
-    {
-      m_iOffset[compIdx][typeIdx][classIdx] = (Int64) xRoundIbdi(bitDepth, (Double)(m_iOffsetOrg[compIdx][typeIdx][classIdx]<<(bitDepth-8)) / (Double)(m_iCount [compIdx][typeIdx][classIdx]<<saoBitIncrease));
-      m_iOffset[compIdx][typeIdx][classIdx] = Clip3(-saoOffsetTh+1, saoOffsetTh-1, (Int)m_iOffset[compIdx][typeIdx][classIdx]);
-      if (typeIdx < 4)
-      {
-        if ( m_iOffset[compIdx][typeIdx][classIdx]<0 && classIdx<3 )
-        {
-          m_iOffset[compIdx][typeIdx][classIdx] = 0;
-        }
-        if ( m_iOffset[compIdx][typeIdx][classIdx]>0 && classIdx>=3)
-        {
-          m_iOffset[compIdx][typeIdx][classIdx] = 0;
-        }
-      }
-      m_iOffset[compIdx][typeIdx][classIdx] = estIterOffset( typeIdx, classIdx, lambda, m_iOffset[compIdx][typeIdx][classIdx], m_iCount [compIdx][typeIdx][classIdx], m_iOffsetOrg[compIdx][typeIdx][classIdx], shift, saoBitIncrease, currentDistortionTableBo, currentRdCostTableBo, saoOffsetTh );
-    }
-    else
-    {
-      m_iOffsetOrg[compIdx][typeIdx][classIdx] = 0;
-      m_iOffset[compIdx][typeIdx][classIdx] = 0;
-    }
-    if( typeIdx != SAO_BO )
-    {
-      estDist   += estSaoDist( m_iCount [compIdx][typeIdx][classIdx], m_iOffset[compIdx][typeIdx][classIdx] << saoBitIncrease, m_iOffsetOrg[compIdx][typeIdx][classIdx], shift);
-    }
-
-  }
-  return estDist;
-}
-
-inline Int64 TEncSampleAdaptiveOffset::estSaoDist(Int64 count, Int64 offset, Int64 offsetOrg, Int shift)
-{
-  return (( count*offset*offset-offsetOrg*offset*2 ) >> shift);
-}
-inline Int64 TEncSampleAdaptiveOffset::estIterOffset(Int typeIdx, Int classIdx, Double lambda, Int64 offsetInput, Int64 count, Int64 offsetOrg, Int shift, Int bitIncrease, Int *currentDistortionTableBo, Double *currentRdCostTableBo, Int offsetTh )
-{
-  //Clean up, best_q_offset.
-  Int64 iterOffset, tempOffset;
+    // 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;
-  Int64 offsetOutput = 0;
+  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. 
@@ -2163,13 +436,13 @@
   while (iterOffset != 0)
   {
-    // Calculate the bits required for signalling the offset
-    tempRate = (typeIdx == SAO_BO) ? (abs((Int)iterOffset)+2) : (abs((Int)iterOffset)+1);
-    if (abs((Int)iterOffset)==offsetTh-1) 
+    // 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 dequntization before distorion calculation
+    // Do the dequantization before distortion calculation
     tempOffset  = iterOffset << bitIncrease;
-    tempDist    = estSaoDist( count, tempOffset, offsetOrg, shift);
+    tempDist    = estSaoDist( count, tempOffset, diffSum, shift);
     tempCost    = ((Double)tempDist + lambda * (Double) tempRate);
     if(tempCost < tempMinCost)
@@ -2177,9 +450,6 @@
       tempMinCost = tempCost;
       offsetOutput = iterOffset;
-      if(typeIdx == SAO_BO)
-      {
-        currentDistortionTableBo[classIdx-1] = (Int) tempDist;
-        currentRdCostTableBo[classIdx-1] = tempCost;
-      }
+      bestDist = tempDist;
+      bestCost = tempCost;
     }
     iterOffset = (iterOffset > 0) ? (iterOffset-1):(iterOffset+1);
@@ -2189,310 +459,856 @@
 
 
-Void TEncSampleAdaptiveOffset::saoComponentParamDist(Int allowMergeLeft, Int allowMergeUp, SAOParam *saoParam, Int addr, Int addrUp, Int addrLeft, Int yCbCr, Double lambda, SaoLcuParam *compSaoParam, Double *compDistortion)
-{
-  Int typeIdx;
-
-  Int64 estDist;
-  Int classIdx;
-  Int shift = 2 * DISTORTION_PRECISION_ADJUSTMENT(((yCbCr==0)?g_bitDepthY:g_bitDepthC)-8);
-  Int64 bestDist;
-
-  SaoLcuParam*  saoLcuParam = &(saoParam->saoLcuParam[yCbCr][addr]);
-  SaoLcuParam*  saoLcuParamNeighbor = NULL; 
-
-  resetSaoUnit(saoLcuParam);
-  resetSaoUnit(&compSaoParam[0]);
-  resetSaoUnit(&compSaoParam[1]);
-
-
-  Double dCostPartBest = MAX_DOUBLE;
-
-  Double  bestRDCostTableBo = MAX_DOUBLE;
-  Int     bestClassTableBo    = 0;
-  Int     currentDistortionTableBo[MAX_NUM_SAO_CLASS];
-  Double  currentRdCostTableBo[MAX_NUM_SAO_CLASS];
-
-
-  SaoLcuParam   saoLcuParamRdo;   
-  Double   estRate = 0;
-
-  resetSaoUnit(&saoLcuParamRdo);
-
-  m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_TEMP_BEST]);
+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_lambda[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_lambda[compIdx];
+          if( quantOffsets[classIdx] != 0 ) //iterative adjustment only when derived offset is not zero
+          {
+            quantOffsets[classIdx] = estIterOffset( typeIdc, classIdx, m_lambda[compIdx], quantOffsets[classIdx], statData.count[classIdx], statData.diff[classIdx], shift, m_offsetStepLog2[compIdx], distBOClasses[classIdx], costBOClasses[classIdx], offsetTh );
+          }
+        }
+
+        //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;
+  UInt previousWrittenBits;
+  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_pcEntropyCoder->encodeSaoOffset(&saoLcuParamRdo, yCbCr);
-  
-  dCostPartBest = m_pcEntropyCoder->getNumberOfWrittenBits()*lambda ; 
-  copySaoUnit(saoLcuParam, &saoLcuParamRdo );
-  bestDist = 0;
-  
-
-
-  for (typeIdx=0; typeIdx<MAX_NUM_SAO_TYPE; typeIdx++)
-  {
-    estDist = estSaoTypeDist(yCbCr, typeIdx, shift, lambda, currentDistortionTableBo, currentRdCostTableBo);
-
-    if( typeIdx == SAO_BO )
-    {
-      // Estimate Best Position
-      Double currentRDCost = 0.0;
-
-      for(Int i=0; i< SAO_MAX_BO_CLASSES -SAO_BO_LEN +1; i++)
-      {
-        currentRDCost = 0.0;
-        for(UInt uj = i; uj < i+SAO_BO_LEN; uj++)
-        {
-          currentRDCost += currentRdCostTableBo[uj];
-        }
-
-        if( currentRDCost < bestRDCostTableBo)
-        {
-          bestRDCostTableBo = currentRDCost;
-          bestClassTableBo  = i;
-        }
-      }
-
-      // Re code all Offsets
-      // Code Center
-      estDist = 0;
-      for(classIdx = bestClassTableBo; classIdx < bestClassTableBo+SAO_BO_LEN; classIdx++)
-      {
-        estDist += currentDistortionTableBo[classIdx];
-      }
-    }
-    resetSaoUnit(&saoLcuParamRdo);
-    saoLcuParamRdo.length = m_iNumClass[typeIdx];
-    saoLcuParamRdo.typeIdx = typeIdx;
-    saoLcuParamRdo.mergeLeftFlag = 0;
-    saoLcuParamRdo.mergeUpFlag   = 0;
-    saoLcuParamRdo.subTypeIdx = (typeIdx == SAO_BO) ? bestClassTableBo : 0;
-    for (classIdx = 0; classIdx < saoLcuParamRdo.length; classIdx++)
-    {
-      saoLcuParamRdo.offset[classIdx] = (Int)m_iOffset[yCbCr][typeIdx][classIdx+saoLcuParamRdo.subTypeIdx+1];
-    }
-    m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_TEMP_BEST]);
+  m_pcRDGoOnSbacCoder->codeSAOOffsetParam(compIdx, modeParam[compIdx], sliceEnabled[compIdx]);
+  modeDist[compIdx] = 0;
+  minCost= m_lambda[compIdx]*((Double)m_pcRDGoOnSbacCoder->getNumberOfWrittenBits());
+  m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
+  if(sliceEnabled[compIdx])
+  {
+    for(Int typeIdc=0; typeIdc< NUM_SAO_NEW_TYPES; typeIdc++)
+    {
+      testOffset[compIdx].modeIdc = SAO_MODE_NEW;
+      testOffset[compIdx].typeIdc = typeIdc;
+
+      //derive coded offset
+      deriveOffsets(ctu, compIdx, typeIdc, blkStats[ctu][compIdx][typeIdc], testOffset[compIdx].offset, testOffset[compIdx].typeAuxInfo);
+
+      //inversed quantized offsets
+      invertQuantOffsets(compIdx, typeIdc, testOffset[compIdx].typeAuxInfo, invQuantOffset, testOffset[compIdx].offset);
+
+      //get distortion
+      dist[compIdx] = getDistortion(ctu, compIdx, testOffset[compIdx].typeIdc, testOffset[compIdx].typeAuxInfo, invQuantOffset, blkStats[ctu][compIdx][typeIdc]);
+
+      //get rate
+      m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
+      m_pcRDGoOnSbacCoder->resetBits();
+      m_pcRDGoOnSbacCoder->codeSAOOffsetParam(compIdx, testOffset[compIdx], sliceEnabled[compIdx]);
+      rate = m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
+      cost = (Double)dist[compIdx] + m_lambda[compIdx]*((Double)rate);
+      if(cost < minCost)
+      {
+        minCost = cost;
+        modeDist[compIdx] = dist[compIdx];
+        modeParam[compIdx]= testOffset[compIdx];
+        m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
+      }
+    }
+  }
+  m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
+  m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
+
+  //------ chroma --------//
+  //"off" case as initial cost
+  cost = 0;
+  previousWrittenBits = 0;
+  m_pcRDGoOnSbacCoder->resetBits();
+  for (Int component = SAO_Cb; component < NUM_SAO_COMPONENTS; component++)
+  {
+    modeParam[component].modeIdc = SAO_MODE_OFF; 
+    modeDist [component] = 0;
+
+    m_pcRDGoOnSbacCoder->codeSAOOffsetParam(component, modeParam[component], sliceEnabled[component]);
+
+    const UInt currentWrittenBits = m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
+    cost += m_lambda[component] * (currentWrittenBits - previousWrittenBits);
+    previousWrittenBits = currentWrittenBits;
+  }
+
+  minCost = cost;
+
+  //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++)
+  {
+    m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
     m_pcRDGoOnSbacCoder->resetBits();
-    m_pcEntropyCoder->encodeSaoOffset(&saoLcuParamRdo, yCbCr);
-
-    estRate = m_pcEntropyCoder->getNumberOfWrittenBits();
-    m_dCost[yCbCr][typeIdx] = (Double)((Double)estDist + lambda * (Double) estRate);
-
-    if(m_dCost[yCbCr][typeIdx] < dCostPartBest)
-    {
-      dCostPartBest = m_dCost[yCbCr][typeIdx];
-      copySaoUnit(saoLcuParam, &saoLcuParamRdo );
-      bestDist = estDist;       
-    }
-  }
-  compDistortion[0] += ((Double)bestDist/lambda);
-  m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_TEMP_BEST]);
- m_pcEntropyCoder->encodeSaoOffset(saoLcuParam, yCbCr);
-  m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[0][CI_TEMP_BEST] );
-
-
-  // merge left or merge up
-
-  for (Int idxNeighbor=0;idxNeighbor<2;idxNeighbor++) 
-  {
-    saoLcuParamNeighbor = NULL;
-    if (allowMergeLeft && addrLeft>=0 && idxNeighbor ==0)
-    {
-      saoLcuParamNeighbor = &(saoParam->saoLcuParam[yCbCr][addrLeft]);
-    }
-    else if (allowMergeUp && addrUp>=0 && idxNeighbor ==1)
-    {
-      saoLcuParamNeighbor = &(saoParam->saoLcuParam[yCbCr][addrUp]);
-    }
-    if (saoLcuParamNeighbor!=NULL)
-    {
-      estDist = 0;
-      typeIdx = saoLcuParamNeighbor->typeIdx;
-      if (typeIdx>=0) 
-      {
-        Int mergeBandPosition = (typeIdx == SAO_BO)?saoLcuParamNeighbor->subTypeIdx:0;
-        Int   merge_iOffset;
-        for(classIdx = 0; classIdx < m_iNumClass[typeIdx]; classIdx++)
-        {
-          merge_iOffset = saoLcuParamNeighbor->offset[classIdx];
-          estDist   += estSaoDist(m_iCount [yCbCr][typeIdx][classIdx+mergeBandPosition+1], merge_iOffset, m_iOffsetOrg[yCbCr][typeIdx][classIdx+mergeBandPosition+1],  shift);
-        }
-      }
-      else
-      {
-        estDist = 0;
-      }
-
-      copySaoUnit(&compSaoParam[idxNeighbor], saoLcuParamNeighbor );
-      compSaoParam[idxNeighbor].mergeUpFlag   = idxNeighbor;
-      compSaoParam[idxNeighbor].mergeLeftFlag = !idxNeighbor;
-
-      compDistortion[idxNeighbor+1] += ((Double)estDist/lambda);
-    } 
-  } 
-}
-Void TEncSampleAdaptiveOffset::sao2ChromaParamDist(Int allowMergeLeft, Int allowMergeUp, SAOParam *saoParam, Int addr, Int addrUp, Int addrLeft, Double lambda, SaoLcuParam *crSaoParam, SaoLcuParam *cbSaoParam, Double *distortion)
-{
-  Int typeIdx;
-
-  Int64 estDist[2];
-  Int classIdx;
-  Int shift = 2 * DISTORTION_PRECISION_ADJUSTMENT(g_bitDepthC-8);
-  Int64 bestDist = 0;
-
-  SaoLcuParam*  saoLcuParam[2] = {&(saoParam->saoLcuParam[1][addr]), &(saoParam->saoLcuParam[2][addr])};
-  SaoLcuParam*  saoLcuParamNeighbor[2] = {NULL, NULL}; 
-  SaoLcuParam*  saoMergeParam[2][2];
-  saoMergeParam[0][0] = &crSaoParam[0];
-  saoMergeParam[0][1] = &crSaoParam[1]; 
-  saoMergeParam[1][0] = &cbSaoParam[0];
-  saoMergeParam[1][1] = &cbSaoParam[1];
-
-  resetSaoUnit(saoLcuParam[0]);
-  resetSaoUnit(saoLcuParam[1]);
-  resetSaoUnit(saoMergeParam[0][0]);
-  resetSaoUnit(saoMergeParam[0][1]);
-  resetSaoUnit(saoMergeParam[1][0]);
-  resetSaoUnit(saoMergeParam[1][1]);
-
-
-  Double costPartBest = MAX_DOUBLE;
-
-  Double  bestRDCostTableBo;
-  Int     bestClassTableBo[2]    = {0, 0};
-  Int     currentDistortionTableBo[MAX_NUM_SAO_CLASS];
-  Double  currentRdCostTableBo[MAX_NUM_SAO_CLASS];
-
-  SaoLcuParam   saoLcuParamRdo[2];   
-  Double   estRate = 0;
-
-  resetSaoUnit(&saoLcuParamRdo[0]);
-  resetSaoUnit(&saoLcuParamRdo[1]);
-
-  m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_TEMP_BEST]);
+    previousWrittenBits = 0;
+    cost = 0;
+
+    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]);
+      
+      m_pcRDGoOnSbacCoder->codeSAOOffsetParam(compIdx, testOffset[compIdx], sliceEnabled[compIdx]);
+
+      const UInt currentWrittenBits = m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
+      cost += dist[compIdx] + (m_lambda[compIdx] * (currentWrittenBits - previousWrittenBits));
+      previousWrittenBits = currentWrittenBits;
+    }
+
+    if(cost < minCost)
+    {
+      minCost = cost;
+      for(compIdx= SAO_Cb; compIdx< NUM_SAO_COMPONENTS; compIdx++)
+      {
+        modeDist [compIdx] = dist      [compIdx];
+        modeParam[compIdx] = testOffset[compIdx];
+      }
+    }
+  }
+
+
+  //----- re-gen rate & normalized cost----//
+  modeNormCost = 0;
+  for(UInt component = SAO_Y; component < NUM_SAO_COMPONENTS; component++)
+  {
+    modeNormCost += (Double)modeDist[component] / m_lambda[component];
+  }
+  m_pcRDGoOnSbacCoder->load(cabacCoderRDO[inCabacLabel]);
   m_pcRDGoOnSbacCoder->resetBits();
-  m_pcEntropyCoder->encodeSaoOffset(&saoLcuParamRdo[0], 1);
-  m_pcEntropyCoder->encodeSaoOffset(&saoLcuParamRdo[1], 2);
-  
-  costPartBest = m_pcEntropyCoder->getNumberOfWrittenBits()*lambda ; 
-  copySaoUnit(saoLcuParam[0], &saoLcuParamRdo[0] );
-  copySaoUnit(saoLcuParam[1], &saoLcuParamRdo[1] );
-
-  for (typeIdx=0; typeIdx<MAX_NUM_SAO_TYPE; typeIdx++)
-  {
-    if( typeIdx == SAO_BO )
-    {
-      // Estimate Best Position
-      for(Int compIdx = 0; compIdx < 2; compIdx++)
-      {
-        Double currentRDCost = 0.0;
-        bestRDCostTableBo = MAX_DOUBLE;
-        estDist[compIdx] = estSaoTypeDist(compIdx+1, typeIdx, shift, lambda, currentDistortionTableBo, currentRdCostTableBo);
-        for(Int i=0; i< SAO_MAX_BO_CLASSES -SAO_BO_LEN +1; i++)
-        {
-          currentRDCost = 0.0;
-          for(UInt uj = i; uj < i+SAO_BO_LEN; uj++)
+  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_lambda[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++)
           {
-            currentRDCost += currentRdCostTableBo[uj];
+            signRight =  (Char)m_sign[srcLine[x] - srcLine[x+1]]; 
+            edgeType  =  signRight + signLeft;
+            signLeft  = -signRight;
+
+            diff [edgeType] += (orgLine[x] - srcLine[x]);
+            count[edgeType] ++;
           }
-
-          if( currentRDCost < bestRDCostTableBo)
+          srcLine  += srcStride;
+          orgLine  += orgStride;
+        }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        if(isCalculatePreDeblockSamples)
+        {
+          if(isBelowAvail)
           {
-            bestRDCostTableBo = currentRDCost;
-            bestClassTableBo[compIdx]  = i;
+            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;
+            }
           }
         }
-
-        // Re code all Offsets
-        // Code Center
-        estDist[compIdx] = 0;
-        for(classIdx = bestClassTableBo[compIdx]; classIdx < bestClassTableBo[compIdx]+SAO_BO_LEN; classIdx++)
-        {
-          estDist[compIdx] += currentDistortionTableBo[classIdx];
-        }
-      }
-    }
-    else
-    {
-      estDist[0] = estSaoTypeDist(1, typeIdx, shift, lambda, currentDistortionTableBo, currentRdCostTableBo);
-      estDist[1] = estSaoTypeDist(2, typeIdx, shift, lambda, currentDistortionTableBo, currentRdCostTableBo);
-    }
-
-    m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_TEMP_BEST]);
-    m_pcRDGoOnSbacCoder->resetBits();
-
-    for(Int compIdx = 0; compIdx < 2; compIdx++)
-    {
-      resetSaoUnit(&saoLcuParamRdo[compIdx]);
-      saoLcuParamRdo[compIdx].length = m_iNumClass[typeIdx];
-      saoLcuParamRdo[compIdx].typeIdx = typeIdx;
-      saoLcuParamRdo[compIdx].mergeLeftFlag = 0;
-      saoLcuParamRdo[compIdx].mergeUpFlag   = 0;
-      saoLcuParamRdo[compIdx].subTypeIdx = (typeIdx == SAO_BO) ? bestClassTableBo[compIdx] : 0;
-      for (classIdx = 0; classIdx < saoLcuParamRdo[compIdx].length; classIdx++)
-      {
-        saoLcuParamRdo[compIdx].offset[classIdx] = (Int)m_iOffset[compIdx+1][typeIdx][classIdx+saoLcuParamRdo[compIdx].subTypeIdx+1];
-      }
-
-      m_pcEntropyCoder->encodeSaoOffset(&saoLcuParamRdo[compIdx], compIdx+1);
-    }
-    estRate = m_pcEntropyCoder->getNumberOfWrittenBits();
-    m_dCost[1][typeIdx] = (Double)((Double)(estDist[0] + estDist[1])  + lambda * (Double) estRate);
-    
-    if(m_dCost[1][typeIdx] < costPartBest)
-    {
-      costPartBest = m_dCost[1][typeIdx];
-      copySaoUnit(saoLcuParam[0], &saoLcuParamRdo[0] );
-      copySaoUnit(saoLcuParam[1], &saoLcuParamRdo[1] );
-      bestDist = (estDist[0]+estDist[1]);       
-    }
-  }
-
-  distortion[0] += ((Double)bestDist/lambda);
-  m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_TEMP_BEST]);
-  m_pcEntropyCoder->encodeSaoOffset(saoLcuParam[0], 1);
-  m_pcEntropyCoder->encodeSaoOffset(saoLcuParam[1], 2);
-  m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[0][CI_TEMP_BEST] );
-
-  // merge left or merge up
-
-  for (Int idxNeighbor=0;idxNeighbor<2;idxNeighbor++) 
-  {
-    for(Int compIdx = 0; compIdx < 2; compIdx++)
-    {
-      saoLcuParamNeighbor[compIdx] = NULL;
-      if (allowMergeLeft && addrLeft>=0 && idxNeighbor ==0)
-      {
-        saoLcuParamNeighbor[compIdx] = &(saoParam->saoLcuParam[compIdx+1][addrLeft]);
-      }
-      else if (allowMergeUp && addrUp>=0 && idxNeighbor ==1)
-      {
-        saoLcuParamNeighbor[compIdx] = &(saoParam->saoLcuParam[compIdx+1][addrUp]);
-      }
-      if (saoLcuParamNeighbor[compIdx]!=NULL)
-      {
-        estDist[compIdx] = 0;
-        typeIdx = saoLcuParamNeighbor[compIdx]->typeIdx;
-        if (typeIdx>=0) 
-        {
-          Int mergeBandPosition = (typeIdx == SAO_BO)?saoLcuParamNeighbor[compIdx]->subTypeIdx:0;
-          Int   merge_iOffset;
-          for(classIdx = 0; classIdx < m_iNumClass[typeIdx]; classIdx++)
+#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
           {
-            merge_iOffset = saoLcuParamNeighbor[compIdx]->offset[classIdx];
-            estDist[compIdx]   += estSaoDist(m_iCount [compIdx+1][typeIdx][classIdx+mergeBandPosition+1], merge_iOffset, m_iOffsetOrg[compIdx+1][typeIdx][classIdx+mergeBandPosition+1],  shift);
+            signDown  = (Char)m_sign[srcLine[x] - srcLineBelow[x]]; 
+            edgeType  = signDown + signUpLine[x];
+            signUpLine[x]= -signDown;
+
+            diff [edgeType] += (orgLine[x] - srcLine[x]);
+            count[edgeType] ++;
           }
-        }
-        else
-        {
-          estDist[compIdx] = 0;
-        }
-
-        copySaoUnit(saoMergeParam[compIdx][idxNeighbor], saoLcuParamNeighbor[compIdx] );
-        saoMergeParam[compIdx][idxNeighbor]->mergeUpFlag   = idxNeighbor;
-        saoMergeParam[compIdx][idxNeighbor]->mergeLeftFlag = !idxNeighbor;
-        distortion[idxNeighbor+1] += ((Double)estDist[compIdx]/lambda);
-      }
-    } 
-  } 
+          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);
+      }
+    }
+  }
 }
 
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -54,82 +54,108 @@
 // ====================================================================================================================
 
+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
 {
-private:
-  TEncEntropy*      m_pcEntropyCoder;
-  TEncSbac***       m_pppcRDSbacCoder;              ///< for CABAC
-  TEncSbac*         m_pcRDGoOnSbacCoder;
-#if FAST_BIT_EST
-  TEncBinCABACCounter*** m_pppcBinCoderCABAC;            ///< temporal CABAC state storage for RD computation
-#else
-  TEncBinCABAC***   m_pppcBinCoderCABAC;            ///< temporal CABAC state storage for RD computation
-#endif
-  
-  Int64  ***m_iCount;      //[MAX_NUM_SAO_PART][MAX_NUM_SAO_TYPE][MAX_NUM_SAO_CLASS]; 
-  Int64  ***m_iOffset;     //[MAX_NUM_SAO_PART][MAX_NUM_SAO_TYPE][MAX_NUM_SAO_CLASS]; 
-  Int64  ***m_iOffsetOrg;  //[MAX_NUM_SAO_PART][MAX_NUM_SAO_TYPE]; 
-  Int64  ****m_count_PreDblk;      //[LCU][YCbCr][MAX_NUM_SAO_TYPE][MAX_NUM_SAO_CLASS]; 
-  Int64  ****m_offsetOrg_PreDblk;  //[LCU][YCbCr][MAX_NUM_SAO_TYPE][MAX_NUM_SAO_CLASS]; 
-  Int64  **m_iRate;        //[MAX_NUM_SAO_PART][MAX_NUM_SAO_TYPE]; 
-  Int64  **m_iDist;        //[MAX_NUM_SAO_PART][MAX_NUM_SAO_TYPE]; 
-  Double **m_dCost;        //[MAX_NUM_SAO_PART][MAX_NUM_SAO_TYPE]; 
-  Double *m_dCostPartBest; //[MAX_NUM_SAO_PART]; 
-  Int64  *m_iDistOrg;      //[MAX_NUM_SAO_PART]; 
-  Int    *m_iTypePartBest; //[MAX_NUM_SAO_PART]; 
-  Int     m_iOffsetThY;
-  Int     m_iOffsetThC;
-  Bool    m_bUseSBACRD;
-#if SAO_ENCODING_CHOICE
-#if SAO_ENCODING_CHOICE_CHROMA
-  Double  m_depthSaoRate[2][4];
-#else
-  Double  m_depth0SaoRate;
-#endif
-#endif
-
 public:
-  TEncSampleAdaptiveOffset         ();
+  TEncSampleAdaptiveOffset();
   virtual ~TEncSampleAdaptiveOffset();
 
-  Void startSaoEnc( TComPic* pcPic, TEncEntropy* pcEntropyCoder, TEncSbac*** pppcRDSbacCoder, TEncSbac* pcRDGoOnSbacCoder);
-  Void endSaoEnc();
-  Void resetStats();
-#if SAO_CHROMA_LAMBDA
+  //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_lambda[NUM_SAO_COMPONENTS];
+
+  //statistics
+  SAOStatData***         m_statData; //[ctu][comp][classes]
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  SAOStatData***         m_preDBFstatData;
+#endif
 #if SAO_ENCODING_CHOICE
-  Void SAOProcess(SAOParam *pcSaoParam, Double dLambda, Double dLambdaChroma, Int depth);
-#else
-  Void SAOProcess(SAOParam *pcSaoParam, Double dLambda, Double dLambdaChroma);
+  Double                 m_saoDisabledRate[NUM_SAO_COMPONENTS][MAX_TLAYER];
 #endif
-#else
-  Void SAOProcess(SAOParam *pcSaoParam, Double dLambda);
-#endif
-
-  Void runQuadTreeDecision(SAOQTPart *psQTPart, Int iPartIdx, Double &dCostFinal, Int iMaxLevel, Double dLambda, Int yCbCr);
-  Void rdoSaoOnePart(SAOQTPart *psQTPart, Int iPartIdx, Double dLambda, Int yCbCr);
-  
-  Void disablePartTree(SAOQTPart *psQTPart, Int iPartIdx);
-  Void getSaoStats(SAOQTPart *psQTPart, Int iYCbCr);
-  Void calcSaoStatsCu(Int iAddr, Int iPartIdx, Int iYCbCr);
-  Void calcSaoStatsBlock( Pel* pRecStart, Pel* pOrgStart, Int stride, Int64** ppStats, Int64** ppCount, UInt width, UInt height, Bool* pbBorderAvail, Int iYCbCr);
-  Void calcSaoStatsCuOrg(Int iAddr, Int iPartIdx, Int iYCbCr);
-  Void calcSaoStatsCu_BeforeDblk( TComPic* pcPic );
-  Void destroyEncBuffer();
-  Void createEncBuffer();
-  Void assignSaoUnitSyntax(SaoLcuParam* saoLcuParam,  SAOQTPart* saoPart, Bool &oneUnitFlag, Int yCbCr);
-  Void checkMerge(SaoLcuParam * lcuParamCurr,SaoLcuParam * lcuParamCheck, Int dir);
-#if SAO_ENCODING_CHOICE
-  Void rdoSaoUnitAll(SAOParam *saoParam, Double lambda, Double lambdaChroma, Int depth);
-#else
-  Void rdoSaoUnitAll(SAOParam *saoParam, Double lambda, Double lambdaChroma);
-#endif
-  Void saoComponentParamDist(Int allowMergeLeft, Int allowMergeUp, SAOParam *saoParam, Int addr, Int addrUp, Int addrLeft, Int yCbCr, Double lambda, SaoLcuParam *compSaoParam, Double *distortion);
-  Void sao2ChromaParamDist(Int allowMergeLeft, Int allowMergeUp, SAOParam *saoParam, Int addr, Int addrUp, Int addrLeft, Double lambda, SaoLcuParam *crSaoParam, SaoLcuParam *cbSaoParam, Double *distortion);
-  inline Int64 estSaoDist(Int64 count, Int64 offset, Int64 offsetOrg, Int shift);
-  inline Int64 estIterOffset(Int typeIdx, Int classIdx, Double lambda, Int64 offsetInput, Int64 count, Int64 offsetOrg, Int shift, Int bitIncrease, Int *currentDistortionTableBo, Double *currentRdCostTableBo, Int offsetTh );
-  inline Int64 estSaoTypeDist(Int compIdx, Int typeIdx, Int shift, Double lambda, Int *currentDistortionTableBo, Double *currentRdCostTableBo);
-  Void setMaxNumOffsetsPerPic(Int iVal) {m_maxNumOffsetsPerPic = iVal; }
-  Int  getMaxNumOffsetsPerPic() {return m_maxNumOffsetsPerPic; }
+  Int                    m_skipLinesR[NUM_SAO_COMPONENTS][NUM_SAO_NEW_TYPES];
+  Int                    m_skipLinesB[NUM_SAO_COMPONENTS][NUM_SAO_NEW_TYPES];
 };
-
 //! \}
 
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncSbac.cpp
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncSbac.cpp	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncSbac.cpp	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -84,5 +84,4 @@
 , m_cCUAbsSCModel             ( 1,             1,               NUM_ABS_FLAG_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
 , m_cMVPIdxSCModel            ( 1,             1,               NUM_MVP_IDX_CTX               , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCUAMPSCModel             ( 1,             1,               NUM_CU_AMP_CTX                , m_contextModels + m_numContextModels, m_numContextModels)
 , m_cSaoMergeSCModel          ( 1,             1,               NUM_SAO_MERGE_FLAG_CTX   , m_contextModels + m_numContextModels, m_numContextModels)
 , m_cSaoTypeIdxSCModel        ( 1,             1,               NUM_SAO_TYPE_IDX_CTX          , m_contextModels + m_numContextModels, m_numContextModels)
@@ -153,5 +152,4 @@
 #endif
   m_cCUPartSizeSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_PART_SIZE );
-  m_cCUAMPSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_CU_AMP_POS );
   m_cCUPredModeSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_PRED_MODE );
   m_cCUIntraPredSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_INTRA_PRED_MODE );
@@ -254,5 +252,4 @@
 #endif
       curCost += m_cCUPartSizeSCModel.calcCost        ( curSliceType, qp, (UChar*)INIT_PART_SIZE );
-      curCost += m_cCUAMPSCModel.calcCost             ( curSliceType, qp, (UChar*)INIT_CU_AMP_POS );
       curCost += m_cCUPredModeSCModel.calcCost        ( curSliceType, qp, (UChar*)INIT_PRED_MODE );
       curCost += m_cCUIntraPredSCModel.calcCost       ( curSliceType, qp, (UChar*)INIT_INTRA_PRED_MODE );
@@ -326,5 +323,4 @@
 #endif
   m_cCUPartSizeSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_PART_SIZE );
-  m_cCUAMPSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_CU_AMP_POS );
   m_cCUPredModeSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_PRED_MODE );
   m_cCUIntraPredSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_INTRA_PRED_MODE );
@@ -348,5 +344,4 @@
   m_cTransformSkipSCModel.initBuffer     ( eSliceType, iQp, (UChar*)INIT_TRANSFORMSKIP_FLAG );
   m_CUTransquantBypassFlagSCModel.initBuffer( eSliceType, iQp, (UChar*)INIT_CU_TRANSQUANT_BYPASS_FLAG );
-
 #if H_3D_DIM
   m_cDepthIntraModeSCModel.initBuffer    ( eSliceType, iQp, (UChar*)INIT_DEPTH_INTRA_MODE );
@@ -794,9 +789,9 @@
         if (eSize == SIZE_2NxN)
         {
-          m_pcBinIf->encodeBin(1, m_cCUAMPSCModel.get( 0, 0, 0 ));
+          m_pcBinIf->encodeBin(1, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
         }
         else
         {
-          m_pcBinIf->encodeBin(0, m_cCUAMPSCModel.get( 0, 0, 0 ));          
+          m_pcBinIf->encodeBin(0, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
           m_pcBinIf->encodeBinEP((eSize == SIZE_2NxnU? 0: 1));
         }
@@ -818,9 +813,9 @@
         if (eSize == SIZE_Nx2N)
         {
-          m_pcBinIf->encodeBin(1, m_cCUAMPSCModel.get( 0, 0, 0 ));
+          m_pcBinIf->encodeBin(1, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
         }
         else
         {
-          m_pcBinIf->encodeBin(0, m_cCUAMPSCModel.get( 0, 0, 0 ));
+          m_pcBinIf->encodeBin(0, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
           m_pcBinIf->encodeBinEP((eSize == SIZE_nLx2N? 0: 1));
         }
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncSbac.h
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncSbac.h	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncSbac.h	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -111,4 +111,12 @@
   Void  codeScalingList      ( TComScalingList* /*scalingList*/     ){ assert (0);  return;};
 
+  Void codeSAOOffsetParam(Int compIdx, SAOOffset& ctbParam, Bool sliceEnabled);
+  Void codeSAOBlkParam(SAOBlkParam& saoBlkParam
+                    , Bool* sliceEnabled
+                    , Bool leftMergeAvail
+                    , Bool aboveMergeAvail
+                    , Bool onlyEstMergeInfo = false
+                    );
+
 private:
   Void  xWriteUnarySymbol    ( UInt uiSymbol, ContextModel* pcSCModel, Int iOffset );
@@ -245,39 +253,8 @@
   ContextModel3DBuffer m_cMVPIdxSCModel;
   
-  ContextModel3DBuffer m_cCUAMPSCModel;
   ContextModel3DBuffer m_cSaoMergeSCModel;
   ContextModel3DBuffer m_cSaoTypeIdxSCModel;
   ContextModel3DBuffer m_cTransformSkipSCModel;
   ContextModel3DBuffer m_CUTransquantBypassFlagSCModel;
-
-#if H_3D_DIM
-  ContextModel3DBuffer m_cDepthIntraModeSCModel;
-  ContextModel3DBuffer m_cDdcFlagSCModel;
-  ContextModel3DBuffer m_cDdcDataSCModel;
-#if QC_GENERIC_SDC_G0122
-  ContextModel3DBuffer m_cAngleFlagSCModel;
-#if !QC_SDC_UNIFY_G0130
-  ContextModel3DBuffer m_cIntraSdcFlagSCModel;
-#endif
-#endif
-#if H_3D_DIM_DMM
-  ContextModel3DBuffer m_cDmm1DataSCModel;
-#endif
-#if H_3D_DIM_SDC  
-  ContextModel3DBuffer m_cSDCResidualFlagSCModel;
-  ContextModel3DBuffer m_cSDCResidualSCModel;
-#endif
-#endif
-#if H_3D_INTER_SDC && !QC_SDC_UNIFY_G0130
-  ContextModel3DBuffer m_cInterSDCFlagSCModel;
-  ContextModel3DBuffer m_cInterSDCResidualSCModel;
-  ContextModel3DBuffer m_cInterSDCResidualSignFlagSCModel;
-#endif
-#if QC_SDC_UNIFY_G0130
-  ContextModel3DBuffer m_cSDCFlagSCModel;
-#endif
-#if H_3D_DBBP
-  ContextModel3DBuffer m_cDBBPFlagSCModel;
-#endif
 };
 
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncSearch.cpp
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncSearch.cpp	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncSearch.cpp	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -202,6 +202,4 @@
   m_pppcRDSbacCoder     = pppcRDSbacCoder;
   m_pcRDGoOnSbacCoder   = pcRDGoOnSbacCoder;
-  
-  m_bUseSBACRD          = pppcRDSbacCoder ? true : false;
   
   for (Int iDir = 0; iDir < 2; iDir++)
@@ -745,7 +743,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;
@@ -787,5 +789,4 @@
   UInt  uiLog2TrafoSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth()] + 2 - uiFullDepth;
 
-  {
     if( pcCU->getPredictionMode(0) == MODE_INTRA && pcCU->getPartitionSize(0) == SIZE_NxN && uiTrDepth == 0 )
     {
@@ -812,5 +813,4 @@
       }
     }
-  }
   
   if ( bChroma )
@@ -819,8 +819,12 @@
     {
       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 );
     }
+  }
   }
 
@@ -835,5 +839,4 @@
   }
   
-  {
     //===== Cbfs =====
     if( bLuma )
@@ -842,5 +845,4 @@
     }
   }
-}
 
 Void
@@ -1212,5 +1214,5 @@
   {
     Int scalingListType = 0 + g_eTTable[(Int)TEXT_LUMA];
-    assert(scalingListType < 6);
+    assert(scalingListType < SCALING_LIST_NUM);
     m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_LUMA,pcCU->getLumaIntraDir( uiAbsPartIdx ), piResi, uiStride, pcCoeff, uiWidth, uiHeight, scalingListType, useTransformSkip );
   }
@@ -1412,5 +1414,5 @@
 
 #if RDOQ_CHROMA_LAMBDA 
-    m_pcTrQuant->selectLambda      (TEXT_CHROMA);  
+    m_pcTrQuant->selectLambda(eText);
 #endif
     m_pcTrQuant->transformNxN      ( pcCU, piResi, uiStride, pcCoeff, 
@@ -1425,5 +1427,5 @@
     {
       Int scalingListType = 0 + g_eTTable[(Int)eText];
-      assert(scalingListType < 6);
+      assert(scalingListType < SCALING_LIST_NUM);
       m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_CHROMA, REG_DCT, piResi, uiStride, pcCoeff, uiWidth, uiHeight, scalingListType, useTransformSkipChroma );
     }
@@ -1464,9 +1466,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
 }
 
@@ -1553,5 +1551,4 @@
   checkTransformSkip         &= (widthTransformSkip == 4 && heightTransformSkip == 4);
   checkTransformSkip         &= (!pcCU->getCUTransquantBypass(0));
-  checkTransformSkip         &= (!((pcCU->getQP( 0 ) == 0) && (pcCU->getSlice()->getSPS()->getUseLossless())));
   if ( m_pcEncCfg->getUseTransformSkipFast() )
   {
@@ -1563,8 +1560,5 @@
     {
       //----- store original entropy coding status -----
-      if( m_bUseSBACRD)
-      {
         m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
-      }
 #if H_3D_VSO
       Dist   singleDistYTmp     = 0;
@@ -1641,10 +1635,7 @@
           {
             xStoreIntraResultQT(pcCU, uiTrDepth, uiAbsPartIdx,bLumaOnly );
-            if( m_bUseSBACRD) 
-            {
               m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_TEMP_BEST ] );
             }
           }
-        }
         if(modeId == firstCheckId)
         {
@@ -1667,9 +1658,6 @@
           }
         }
-        if(m_bUseSBACRD)
-        {
           m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiFullDepth ][ CI_TEMP_BEST ] );
         } 
-      }
 
       if( !bLumaOnly )
@@ -1696,5 +1684,5 @@
       pcCU ->setTransformSkipSubParts ( 0, TEXT_LUMA, uiAbsPartIdx, uiFullDepth ); 
       //----- store original entropy coding status -----
-      if( m_bUseSBACRD && bCheckSplit )
+      if( bCheckSplit )
       {
         m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
@@ -1742,6 +1730,4 @@
   {
     //----- store full entropy coding status, load original entropy coding status -----
-    if( m_bUseSBACRD )
-    {
       if( bCheckFull )
       {
@@ -1753,5 +1739,5 @@
         m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
       }
-    }
+
     //----- code splitted block -----
     Double  dSplitCost      = 0.0;
@@ -1798,8 +1784,6 @@
     }
     //----- restore context states -----
-    if( m_bUseSBACRD )
-    {
       m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
-    }
+
     //----- determine rate and r-d cost -----
     UInt uiSplitBits = xGetIntraBitsQT( pcCU, uiTrDepth, uiAbsPartIdx, true, !bLumaOnly, false );
@@ -1821,8 +1805,5 @@
     }
     //----- set entropy coding status -----
-    if( m_bUseSBACRD )
-    {
       m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_TEST ] );
-    }
     
     //--- set transform index and Cbf values ---
@@ -2718,8 +2699,5 @@
     {
         //use RDO to decide whether Cr/Cb takes TS
-        if( m_bUseSBACRD )
-        {
           m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[uiFullDepth][CI_QT_TRAFO_ROOT] );
-        }
 
         for(Int chromaId = 0; chromaId < 2; chromaId ++)
@@ -2772,10 +2750,7 @@
               {
                 xStoreIntraResultChromaQT(pcCU, uiTrDepth, uiAbsPartIdx,chromaId);
-                if( m_bUseSBACRD) 
-                {
                   m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_TEMP_BEST ] );
                 }
               }
-            }
             if(chromaModeId == firstCheckId)
             {
@@ -2788,9 +2763,6 @@
             xLoadIntraResultChromaQT(pcCU, uiTrDepth, uiAbsPartIdx,chromaId);
             pcCU->setCbfSubParts ( singleCbfC << uiTrDepth, (TextType)(chromaId + 2), uiAbsPartIdx, pcCU->getDepth(0) + actualTrDepth );
-            if(m_bUseSBACRD)
-            {
               m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiFullDepth ][ CI_TEMP_BEST ] );
             } 
-          }
           pcCU ->setTransformSkipSubParts( bestModeId, (TextType)(chromaId + 2), uiAbsPartIdx, pcCU->getDepth( 0 ) +  actualTrDepth ); 
           ruiDist += singleDistC;
@@ -2798,11 +2770,8 @@
           if(chromaId == 0)
           {
-            if( m_bUseSBACRD )
-            {
               m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[uiFullDepth][CI_QT_TRAFO_ROOT] );
             }
           }
         }
-    }
     else
     {
@@ -3217,8 +3186,5 @@
 #endif
       // set context models
-      if( m_bUseSBACRD )
-      {
         m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
-      }
       
       // determine residual for partition
@@ -3350,8 +3316,5 @@
       
       // set context models
-      if( m_bUseSBACRD )
-      {
         m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
-      }
       
       // determine residual for partition
@@ -3521,8 +3484,5 @@
   
   //===== reset context models =====
-  if(m_bUseSBACRD)
-  {
     m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
-  }
   
   //===== set distortion (rate and r-d costs are determined later) =====
@@ -3556,8 +3516,5 @@
   {
     //----- restore context models -----
-    if( m_bUseSBACRD )
-    {
       m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
-    }
     
     //----- chroma coding -----
@@ -3565,5 +3522,5 @@
     pcCU->setChromIntraDirSubParts  ( uiModeList[uiMode], 0, uiDepth );
     xRecurIntraChromaCodingQT       ( pcCU,   0, 0, pcOrgYuv, pcPredYuv, pcResiYuv, uiDist );
-    if( m_bUseSBACRD && pcCU->getSlice()->getPPS()->getUseTransformSkip() )
+    if( pcCU->getSlice()->getPPS()->getUseTransformSkip() )
     {
       m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
@@ -3597,9 +3554,6 @@
   
   //----- restore context models -----
-  if( m_bUseSBACRD )
-  {
     m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
   }
-}
 
 /** Function for encoding and reconstructing luma/chroma samples of a PCM mode CU.
@@ -3761,8 +3715,5 @@
   dCost = m_pcRdCost->calcRdCost( uiBits, uiDistortion );
 
-  if(m_bUseSBACRD)
-  {
     m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
-  }
 
   pcCU->getTotalBits()       = uiBits;
@@ -3789,9 +3740,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
 #if H_3D_IC
   cDistParam.bUseIC = false;
@@ -3942,5 +3889,4 @@
   for( UInt uiMergeCand = 0; uiMergeCand < numValidMergeCand; ++uiMergeCand )
   {
-    {
       UInt uiCostCand = MAX_UINT;
       UInt uiBitsCand = 0;
@@ -4044,5 +3990,4 @@
     }
   }
-}
 
 /** convert bi-pred merge candidates to uni-pred
@@ -4181,5 +4126,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];
 
@@ -4594,18 +4542,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->setInterDirSubParts( 3, uiPartAddr, iPartIdx, pcCU->getDepth(0) );
@@ -4623,8 +4567,6 @@
           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) );
       
@@ -4639,8 +4581,6 @@
           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) );
       
@@ -4729,5 +4669,4 @@
         pcCU->setDvInfoSubParts(inheritedVSPDisInfo[uiMRGIndex].m_acDvInfo, uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
 #endif
-
 #if MTK_DDD_G0063
         if( uiMRGIndex == pcCU->getUseDDDCandIdx() )
@@ -4743,5 +4682,4 @@
         }
 #endif
-
 #if H_3D_SPIVMP
         pcCU->setSPIVMPFlagSubParts(bSPIVMPFlag[uiMRGIndex], uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );  
@@ -4749,9 +4687,6 @@
         {
           UInt uiSPAddr;
-
           Int iNumSPInOneLine, iNumSP, iSPWidth, iSPHeight;
-
           pcCU->getSPPara(iRoiWidth, iRoiHeight, iNumSP, iNumSPInOneLine, iSPWidth, iSPHeight);
-
           for (Int iPartitionIdx = 0; iPartitionIdx < iNumSP; iPartitionIdx++)
           {
@@ -4761,5 +4696,4 @@
             pcCU->getCUMvField( REF_PIC_LIST_1 )->setMvFieldSP(pcCU, uiSPAddr, pcMvFieldSP[2*iPartitionIdx + 1], iSPWidth, iSPHeight);
           }
-
           if ( pcCU->getInterDir(uiPartAddr) == 3 && pcCU->isBipredRestriction(iPartIdx) )
           {
@@ -4768,5 +4702,4 @@
             pcCU->setInterDirSubParts( 1, uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ));
           }
-
         }
         else
@@ -4783,5 +4716,4 @@
           Int width, height;
           pcCU->getPartIndexAndSize( iPartIdx, partAddrTemp, width, height ); // true or pcCU->getTotalNumPart()==256
-
           if( uiMRGInterDir & 0x01 )
           {
@@ -4806,11 +4738,7 @@
         else
 #endif
-        {
           pcCU->setInterDirSubParts  ( uiMRGInterDir, uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
-          {
             pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( cMRGMvField[0], ePartSize, uiPartAddr, 0, iPartIdx );
             pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMRGMvField[1], ePartSize, uiPartAddr, 0, iPartIdx );
-          }
-        }
 
         pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvd    ( cMvZero,            ePartSize, uiPartAddr, 0, iPartIdx );
@@ -4827,5 +4755,4 @@
         pcCU->setSPIVMPFlagSubParts(0, uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) ); 
 #endif
-
 #if MTK_DDD_G0063
         pcCU->setUseDDD( false, uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
@@ -4838,9 +4765,7 @@
         pcCU->setDvInfoSubParts(OriginalDvInfo, uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
 #endif
-        {
           pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( cMEMvField[0], ePartSize, uiPartAddr, 0, iPartIdx );
           pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMEMvField[1], ePartSize, uiPartAddr, 0, iPartIdx );
         }
-      }
 #if H_3D_SPIVMP
       delete[] pcMvFieldSP;
@@ -4997,5 +4922,7 @@
   
   if (iNum == 1)
+  {
     return 0;
+  }
   
   UInt uiLength = 1;
@@ -5177,17 +5104,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
@@ -5288,9 +5207,5 @@
   m_pcRdCost->setCostScale ( 1 );
   
-  {
-    xPatternSearchFracDIF( pcCU, pcPatternKey, piRefY, iRefStride, &rcMv, cMvHalf, cMvQter, ruiCost
-                          ,bBi
-                          );
-  }
+    xPatternSearchFracDIF( pcCU, pcPatternKey, piRefY, iRefStride, &rcMv, cMvHalf, cMvQter, ruiCost,bBi );
   
   
@@ -5696,5 +5611,4 @@
 #endif
 
-    if( m_bUseSBACRD )
       m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_CURR_BEST]);
     
@@ -5729,5 +5643,4 @@
     pcCU->getTotalCost() = m_pcRdCost->calcRdCost( uiBits, uiDistortion );
 
-    if( m_bUseSBACRD )
       m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_TEMP_BEST]);
     
@@ -5771,8 +5684,5 @@
     uiBits = 0;
     uiDistortion = 0;
-    if( m_bUseSBACRD )
-    {
       m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ pcCU->getDepth( 0 ) ][ CI_CURR_BEST ] );
-    }    
 
 #if H_3D_VSO // M16 // M18
@@ -5836,8 +5746,5 @@
     }
     
-    if( m_bUseSBACRD )
-    {
       m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_CURR_BEST] );
-    }
 #if 0 // check
     {
@@ -5845,8 +5752,5 @@
       m_pcEntropyCoder->encodeCoeff( pcCU, 0, pcCU->getDepth(0), pcCU->getWidth(0), pcCU->getHeight(0) );
       const UInt uiBitsForCoeff = m_pcEntropyCoder->getNumberOfWrittenBits();
-      if( m_bUseSBACRD )
-      {
         m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_CURR_BEST] );
-      }
       if( uiBitsForCoeff != uiBits )
         assert( 0 );
@@ -5904,6 +5808,4 @@
       dCostBest        = dCost;
       qpBest           = qp;
-      if( m_bUseSBACRD )
-      {
         m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ pcCU->getDepth( 0 ) ][ CI_TEMP_BEST ] );
       }
@@ -5917,5 +5819,4 @@
     }
 #endif
-  }
   
   assert ( dCostBest != MAX_DOUBLE );
@@ -5923,9 +5824,6 @@
   if( qpMin != qpMax && qpBest != qpMax )
   {
-    if( m_bUseSBACRD )
-    {
       assert( 0 ); // check
       m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ pcCU->getDepth( 0 ) ][ CI_TEMP_BEST ] );
-    }
     // copy best cbf and trIdx to pcCU
     const UInt uiQPartNum = pcCU->getPic()->getNumPartInCU() >> (pcCU->getDepth(0) << 1);
@@ -5957,13 +5855,7 @@
 #endif
   // 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
 #if H_3D_VSO // M23
   }
@@ -5984,5 +5876,4 @@
   
   pcCU->setQPSubParts( qpBest, 0, pcCU->getDepth(0) );
-
 #if H_3D_VSO // M24 // necessary??
   if( m_pcRdCost->getUseRenModel() && !m_pcRdCost->getUseEstimatedVSD() )
@@ -6216,7 +6107,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) );
@@ -6247,8 +6142,5 @@
   UInt uiBestTransformMode[3] = {0};
 
-  if( m_bUseSBACRD )
-  {
     m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
-  }
   
   if( bCheckFull )
@@ -6316,5 +6208,5 @@
 
 #if RDOQ_CHROMA_LAMBDA 
-      m_pcTrQuant->selectLambda(TEXT_CHROMA); 
+      m_pcTrQuant->selectLambda(TEXT_CHROMA_U);
 #endif
 
@@ -6327,4 +6219,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
@@ -6339,7 +6236,5 @@
     m_pcEntropyCoder->resetBits();
     
-    {
       m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
-    }
     
     m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrY, uiAbsPartIdx,  trWidth,  trHeight,    uiDepth, TEXT_LUMA );
@@ -6350,13 +6245,9 @@
     if( bCodeChroma )
     {
-      {
         m_pcEntropyCoder->encodeQtCbf   ( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrMode );
-      }
       m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrU, uiAbsPartIdx, trWidthC, trHeightC, uiDepth, TEXT_CHROMA_U );
       uiSingleBitsU = m_pcEntropyCoder->getNumberOfWrittenBits() - uiSingleBitsY;
       
-      {
         m_pcEntropyCoder->encodeQtCbf   ( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrMode );
-      }
       m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrV, uiAbsPartIdx, trWidthC, trHeightC, uiDepth, TEXT_CHROMA_V );
       uiSingleBitsV = m_pcEntropyCoder->getNumberOfWrittenBits() - ( uiSingleBitsY + uiSingleBitsU );
@@ -6400,5 +6291,5 @@
 
       Int scalingListType = 3 + g_eTTable[(Int)TEXT_LUMA];
-      assert(scalingListType < 6);     
+      assert(scalingListType < SCALING_LIST_NUM);
       m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_LUMA,REG_DCT, pcResiCurrY, m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(),  pcCoeffCurrY, trWidth, trHeight, scalingListType );//this is for inter mode only
 
@@ -6423,5 +6314,6 @@
       }
 #else      
-      const UInt uiNonzeroDistY = m_pcRdCost->getDistPart(g_bitDepthY, m_pcQTTempTComYuv[uiQTTempAccessLayer].getLumaAddr( absTUPartIdx ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(),      pcResi->getLumaAddr( absTUPartIdx ), pcResi->getStride(), trWidth,trHeight );
+      const UInt uiNonzeroDistY = m_pcRdCost->getDistPart(g_bitDepthY, m_pcQTTempTComYuv[uiQTTempAccessLayer].getLumaAddr( absTUPartIdx ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(),
+      pcResi->getLumaAddr( absTUPartIdx ), pcResi->getStride(), trWidth,trHeight );
 #endif
       if (pcCU->isLosslessCoded(0)) 
@@ -6500,7 +6392,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 )
@@ -6516,12 +6406,10 @@
 
         Int scalingListType = 3 + g_eTTable[(Int)TEXT_CHROMA_U];
-        assert(scalingListType < 6);
+        assert(scalingListType < SCALING_LIST_NUM);
         m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_CHROMA,REG_DCT, pcResiCurrU, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(), pcCoeffCurrU, trWidthC, trHeightC, scalingListType  );
         
         const UInt uiNonzeroDistU = m_pcRdCost->getDistPart(g_bitDepthC, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCbAddr( absTUPartIdxC), m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(),
                                                             pcResi->getCbAddr( absTUPartIdxC), pcResi->getCStride(), trWidthC, trHeightC
-#if WEIGHTED_CHROMA_DISTORTION
                                                             , TEXT_CHROMA_U
-#endif
                                                             );
 
@@ -6559,5 +6447,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 );
@@ -6575,7 +6463,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 )
@@ -6590,12 +6476,10 @@
 
         Int scalingListType = 3 + g_eTTable[(Int)TEXT_CHROMA_V];
-        assert(scalingListType < 6);
+        assert(scalingListType < SCALING_LIST_NUM);
         m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_CHROMA,REG_DCT, pcResiCurrV, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(), pcCoeffCurrV, trWidthC, trHeightC, scalingListType );
         
         const UInt uiNonzeroDistV = m_pcRdCost->getDistPart(g_bitDepthC, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCrAddr( absTUPartIdxC ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(),
                                                             pcResi->getCrAddr( absTUPartIdxC ), pcResi->getCStride(), trWidthC, trHeightC
-#if WEIGHTED_CHROMA_DISTORTION
                                                             , TEXT_CHROMA_V
-#endif
                                                             );
         if (pcCU->isLosslessCoded(0)) 
@@ -6632,5 +6516,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 );
@@ -6681,8 +6565,5 @@
       }
 
-      if( m_bUseSBACRD )
-      {
         m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
-      }
 
       pcCU->setTransformSkipSubParts ( 1, TEXT_LUMA, uiAbsPartIdx, uiDepth );
@@ -6715,5 +6596,5 @@
 
         Int scalingListType = 3 + g_eTTable[(Int)TEXT_LUMA];
-        assert(scalingListType < 6);     
+        assert(scalingListType < SCALING_LIST_NUM);
 
         m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_LUMA,REG_DCT, pcResiCurrY, m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(),  pcCoeffCurrY, trWidth, trHeight, scalingListType, true );
@@ -6794,8 +6675,5 @@
       }
 
-      if( m_bUseSBACRD )
-      {
         m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
-      }
 
       pcCU->setTransformSkipSubParts ( 1, TEXT_CHROMA_U, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC ); 
@@ -6811,5 +6689,5 @@
 
 #if RDOQ_CHROMA_LAMBDA 
-      m_pcTrQuant->selectLambda(TEXT_CHROMA); 
+      m_pcTrQuant->selectLambda(TEXT_CHROMA_U);
 #endif
 
@@ -6821,4 +6699,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
@@ -6844,5 +6725,5 @@
 
         Int scalingListType = 3 + g_eTTable[(Int)TEXT_CHROMA_U];
-        assert(scalingListType < 6);
+        assert(scalingListType < SCALING_LIST_NUM);
 
         m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_CHROMA,REG_DCT, pcResiCurrU, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(), pcCoeffCurrU, trWidthC, trHeightC, scalingListType, true  );
@@ -6850,7 +6731,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
                                                  );
 
@@ -6888,5 +6767,5 @@
 
         Int scalingListType = 3 + g_eTTable[(Int)TEXT_CHROMA_V];
-        assert(scalingListType < 6);
+        assert(scalingListType < SCALING_LIST_NUM);
 
         m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_CHROMA,REG_DCT, pcResiCurrV, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(), pcCoeffCurrV, trWidthC, trHeightC, scalingListType, true );
@@ -6894,7 +6773,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
                                                  );
 
@@ -6926,19 +6803,12 @@
     }
 
-    if( m_bUseSBACRD )
-    {
       m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
-    }
-
     m_pcEntropyCoder->resetBits();
 
-    {
       if( uiLog2TrSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
       {
         m_pcEntropyCoder->encodeTransformSubdivFlag( 0, 5 - uiLog2TrSize );
       }
-    }
-
-    {
+
       if( bCodeChroma )
       {
@@ -6948,5 +6818,4 @@
 
       m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
-    }
 
     m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrY, uiAbsPartIdx, trWidth, trHeight,    uiDepth, TEXT_LUMA );
@@ -6972,5 +6841,5 @@
   if( bCheckSplit )
   {
-    if( m_bUseSBACRD && bCheckFull )
+    if( bCheckFull )
     {
       m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_TEST ] );
@@ -7012,16 +6881,11 @@
     }
     
-    if( m_bUseSBACRD )
-    {
       m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
-    }
     m_pcEntropyCoder->resetBits();
     
-    {
       xEncodeResidualQT( pcCU, uiAbsPartIdx, uiDepth, true,  TEXT_LUMA );
       xEncodeResidualQT( pcCU, uiAbsPartIdx, uiDepth, false, TEXT_LUMA );
       xEncodeResidualQT( pcCU, uiAbsPartIdx, uiDepth, false, TEXT_CHROMA_U );
       xEncodeResidualQT( pcCU, uiAbsPartIdx, uiDepth, false, TEXT_CHROMA_V );
-    }
     
     uiSubdivBits = m_pcEntropyCoder->getNumberOfWrittenBits();
@@ -7050,10 +6914,7 @@
     }
     assert( bCheckFull );
-    if( m_bUseSBACRD )
-    {
-      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_TEST ] );
-    }
-  }
-
+
+    m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_TEST ] );
+  }
 #if H_3D_VSO // M33
   if( m_pcRdCost->getUseRenModel() && !m_pcRdCost->getUseEstimatedVSD() )
@@ -7061,8 +6922,6 @@
     UInt  uiWidth     = 1<< uiLog2TrSize;
     UInt  uiHeight    = 1<< uiLog2TrSize;
-
     Pel*  piSrc;
     UInt  uiSrcStride;
-
     if ( uiAbsSumY )
     {
@@ -7077,9 +6936,7 @@
       uiSrcStride = pcPred->getStride  ();
     }
-
     m_pcRdCost->setRenModelData( pcCU, uiAbsPartIdx, piSrc, (Int) uiSrcStride, (Int) uiWidth, (Int) uiHeight );
   }
 #endif
-
   rdCost += dSingleCost;
   ruiBits += uiSingleBits;
@@ -7106,12 +6963,9 @@
   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 )
@@ -7135,5 +6989,4 @@
       }
     }
-  }
   
   if( !bSubdiv )
@@ -7159,8 +7012,6 @@
     if( bSubdivAndCbf )
     {
-      {
         m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
       }
-    }
     else
     {
@@ -7229,9 +7080,7 @@
       if( bCodeChroma )
       {
-        {
           m_pcQTTempTComYuv[uiQTTempAccessLayer].copyPartToPartChroma( pcResi, uiAbsPartIdx, 1 << uiLog2TrSizeC, 1 << uiLog2TrSizeC );
         }
       }
-    }
     else
     {
@@ -7279,6 +7128,4 @@
 UInt TEncSearch::xModeBitsIntra( TComDataCU* pcCU, UInt uiMode, UInt uiPU, UInt uiPartOffset, UInt uiDepth, UInt uiInitTrDepth )
 {
-  if( m_bUseSBACRD )
-  {
     // Reload only contexts required for coding intra mode information
     m_pcRDGoOnSbacCoder->loadIntraDirModeLuma( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
@@ -7286,5 +7133,4 @@
     m_pcRDGoOnSbacCoder->loadIntraDepthMode( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
 #endif
-  }
   
   pcCU->setLumaIntraDirSubParts ( uiMode, uiPartOffset, uiDepth + uiInitTrDepth );
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncSearch.h
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncSearch.h	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncSearch.h	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -114,5 +114,4 @@
   TEncSbac***     m_pppcRDSbacCoder;
   TEncSbac*       m_pcRDGoOnSbacCoder;
-  Bool            m_bUseSBACRD;
   DistParam       m_cDistParam;
   
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncSlice.cpp
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -266,5 +266,5 @@
   
   eSliceType=B_SLICE;
-  eSliceType = (pocLast == 0 || pocCurr % m_pcCfg->getIntraPeriod() == 0 || m_pcGOPEncoder->getGOPSize() == 0) ? I_SLICE : eSliceType;
+  eSliceType = (pocLast == 0 || (pocCurr - isField) % m_pcCfg->getIntraPeriod() == 0 || m_pcGOPEncoder->getGOPSize() == 0) ? I_SLICE : eSliceType;
   
   rpcSlice->setSliceType    ( eSliceType );
@@ -296,5 +296,5 @@
   if(eSliceType!=I_SLICE)
   {
-    if (!(( m_pcCfg->getMaxDeltaQP() == 0 ) && (dQP == -rpcSlice->getSPS()->getQpBDOffsetY() ) && (rpcSlice->getSPS()->getUseLossless()))) 
+    if (!(( m_pcCfg->getMaxDeltaQP() == 0 ) && (dQP == -rpcSlice->getSPS()->getQpBDOffsetY() ) && (rpcSlice->getPPS()->getTransquantBypassEnableFlag())))
     {
 #if H_MV
@@ -312,10 +312,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
@@ -399,28 +393,7 @@
   // store lambda
   m_pcRdCost ->setLambda( dLambda );
-
-#if H_3D_VSO
-  m_pcRdCost->setUseLambdaScaleVSO  ( (m_pcCfg->getUseVSO() ||  m_pcCfg->getForceLambdaScaleVSO()) && m_pcCfg->getIsDepth() );
-  m_pcRdCost->setLambdaVSO          ( dLambda * m_pcCfg->getLambdaScaleVSO() );
-
-  // Should be moved to TEncTop
-  
-  // SAIT_VSO_EST_A0033
-  m_pcRdCost->setDisparityCoeff( m_pcCfg->getDispCoeff() );
-
-  // LGE_WVSO_A0119
-  if( m_pcCfg->getUseWVSO() && m_pcCfg->getIsDepth() )
-  {
-    m_pcRdCost->setDWeight  ( m_pcCfg->getDWeight()   );
-    m_pcRdCost->setVSOWeight( m_pcCfg->getVSOWeight() );
-    m_pcRdCost->setVSDWeight( m_pcCfg->getVSDWeight() );
-  }
-
-#endif
-
-#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;
@@ -428,26 +401,23 @@
   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
-  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] = {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
@@ -460,5 +430,5 @@
   }
 #else
-  eSliceType = (pocLast == 0 || pocCurr % m_pcCfg->getIntraPeriod() == 0 || m_pcGOPEncoder->getGOPSize() == 0) ? I_SLICE : eSliceType;
+eSliceType = (pocLast == 0 || (pocCurr - isField) % m_pcCfg->getIntraPeriod() == 0 || m_pcGOPEncoder->getGOPSize() == 0) ? I_SLICE : eSliceType;
 #endif
 
@@ -570,5 +540,4 @@
 }
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
 Void TEncSlice::resetQP( TComPic* pic, Int sliceQP, Double lambda )
 {
@@ -579,8 +548,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;
@@ -588,132 +556,23 @@
   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]);
+
 
 #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;
-    }
-
-    qp = max( -pcSPS->getQpBDOffsetY(), min( MAX_QP, (Int) floor( recalQP + 0.5 ) ) );
-
-    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
@@ -755,5 +614,4 @@
   }
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
   if ( m_pcCfg->getUseRateCtrl() )
   {
@@ -761,5 +619,4 @@
     assert(0);
   }
-#endif
   
   TComSlice* pcSlice        = rpcPic->getSlice(getSliceIdx());
@@ -793,9 +650,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;
@@ -803,25 +659,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
@@ -857,8 +709,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;
@@ -866,30 +717,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)
 {
@@ -925,5 +771,4 @@
   m_pcRateCtrl->getRCPic()->setTotalIntraCost(iSumHadSlice);
 }
-#endif
 
 Void TEncSlice::compressSlice( TComPic*& rpcPic )
@@ -943,6 +788,4 @@
   
   // set entropy coder
-  if( m_pcCfg->getUseSBACRD() )
-  {
     m_pcSbacCoder->init( m_pcBinCABAC );
     m_pcEntropyCoder->setEntropyCoder   ( m_pcSbacCoder, pcSlice );
@@ -952,11 +795,4 @@
     pppcRDSbacCoder->setBinCountingEnableFlag( false );
     pppcRDSbacCoder->setBinsCoded( 0 );
-  }
-  else
-  {
-    m_pcEntropyCoder->setEntropyCoder ( m_pcCavlcCoder, pcSlice );
-    m_pcEntropyCoder->resetEntropy      ();
-    m_pcEntropyCoder->setBitstream    ( m_pcBitCounter );
-  }
   
   //------------------------------------------------------------------------------
@@ -1016,6 +852,4 @@
   }
 #endif
-  if( m_pcCfg->getUseSBACRD() )
-  {
     iNumSubstreams = pcSlice->getPPS()->getNumSubstreams();
     uiTilesAcross = rpcPic->getPicSym()->getNumColumnsMinus1()+1;
@@ -1037,7 +871,4 @@
       ppppcRDSbacCoders[ui][0][CI_CURR_BEST]->load(m_pppcRDSbacCoder[0][CI_CURR_BEST]);
     }
-  }
-  //if( m_pcCfg->getUseSBACRD() )
-  {
     delete[] m_pcBufferLowLatSbacCoders;
     delete[] m_pcBufferLowLatBinCoderCABACs;
@@ -1050,5 +881,5 @@
     for (UInt ui = 0; ui < uiTilesAcross; ui++)
       m_pcBufferLowLatSbacCoders[ui].load(m_pppcRDSbacCoder[0][CI_CURR_BEST]);  //init. state
-  }
+
   UInt uiWidthInLCUs  = rpcPic->getPicSym()->getFrameWidthInCU();
   //UInt uiHeightInLCUs = rpcPic->getPicSym()->getFrameHeightInCU();
@@ -1121,31 +952,5 @@
     }
 #endif
-#if !RATE_CONTROL_LAMBDA_DOMAIN
-    if(m_pcCfg->getUseRateCtrl())
-    {
-#if KWU_RC_MADPRED_E0227
-      if(pcSlice->getLayerId() != 0 && m_pcCfg->getUseDepthMADPred() && !pcSlice->getIsDepth())
-      {
-        Double zn, zf, focallength, position, camshift;
-        Double basepos;
-        Bool bInterpolated;
-        Int direction = pcSlice->getViewId() - pcCU->getSlice()->getIvPic(false, 0)->getViewId();
-
-        pcEncTop->getCamParam()->xGetZNearZFar(pcEncTop->getCamParam()->getBaseViewNumbers()[pcSlice->getViewIndex()], pcSlice->getPOC(), zn, zf);
-        pcEncTop->getCamParam()->xGetGeometryData(pcEncTop->getCamParam()->getBaseViewNumbers()[0], pcSlice->getPOC(), focallength, basepos, camshift, bInterpolated);
-        pcEncTop->getCamParam()->xGetGeometryData(pcEncTop->getCamParam()->getBaseViewNumbers()[pcSlice->getViewIndex()], pcSlice->getPOC(), focallength, position, camshift, bInterpolated);
-
-        m_pcRateCtrl->updateLCUDataEnhancedView(pcCU, pcCU->getTotalBits(), pcCU->getQP(0), basepos, position, focallength, zn, zf, (direction > 0 ? 1 : -1));
-      }
-#endif
-      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() )
-    {
       uiTileCol = rpcPic->getPicSym()->getTileIdxMap(uiCUAddr) % (rpcPic->getPicSym()->getNumColumnsMinus1()+1); // what column of tiles are we in?
       uiTileStartLCU = rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(uiCUAddr))->getFirstCUAddr();
@@ -1192,5 +997,4 @@
       }
       m_pppcRDSbacCoder[0][CI_CURR_BEST]->load( ppppcRDSbacCoders[uiSubStrm][0][CI_CURR_BEST] ); //this load is used to simplify the code
-    }
 
     // reset the entropy coder
@@ -1210,7 +1014,5 @@
       m_pcEntropyCoder->setEntropyCoder     ( m_pcSbacCoder, pcSlice );
     }
-    // if RD based on SBAC is used
-    if( m_pcCfg->getUseSBACRD() )
-    {
+
       // set go-on entropy coder
       m_pcEntropyCoder->setEntropyCoder ( m_pcRDGoOnSbacCoder, pcSlice );
@@ -1219,5 +1021,4 @@
       ((TEncBinCABAC*)m_pcRDGoOnSbacCoder->getEncBinIf())->setBinCountingEnableFlag(true);
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
       Double oldLambda = m_pcRdCost->getLambda();
       if ( m_pcCfg->getUseRateCtrl() )
@@ -1227,9 +1028,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();
@@ -1255,5 +1052,4 @@
           {
 #endif
-#if RATE_CONTROL_INTRA
           bpp = m_pcRateCtrl->getRCPic()->getLCUTargetBpp(pcSlice->getSliceType());
           if ( rpcPic->getSlice( 0 )->getSliceType() == I_SLICE)
@@ -1266,12 +1062,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 KWU_RC_MADPRED_E0227
-          }
-#endif
 #if KWU_RC_MADPRED_E0227
           estLambda = m_pcRateCtrl->getRCPic()->getLCUEstLambda( bpp );
@@ -1281,12 +1069,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
         }
@@ -1295,54 +1082,8 @@
         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();
-        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() );
-        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
       m_pcEntropyCoder->setEntropyCoder ( m_pppcRDSbacCoder[0][CI_CURR_BEST], pcSlice );
@@ -1366,8 +1107,6 @@
         break;
       }
-      if( m_pcCfg->getUseSBACRD() )
-      {
-         ppppcRDSbacCoders[uiSubStrm][0][CI_CURR_BEST]->load( m_pppcRDSbacCoder[0][CI_CURR_BEST] );
        
+    ppppcRDSbacCoders[uiSubStrm][0][CI_CURR_BEST]->load( m_pppcRDSbacCoder[0][CI_CURR_BEST] );
          //Store probabilties of second LCU in line into buffer
          if ( ( uiCol == uiTileLCUX+1) && (depSliceSegmentsEnabled || (pcSlice->getPPS()->getNumSubstreams() > 1)) && m_pcCfg->getWaveFrontsynchro())
@@ -1375,11 +1114,8 @@
           m_pcBufferSbacCoders[uiTileCol].loadContexts(ppppcRDSbacCoders[uiSubStrm][0][CI_CURR_BEST]);
         }
-      }
-
-#if TICKET_1090_FIX
-#if RATE_CONTROL_LAMBDA_DOMAIN
+
       if ( m_pcCfg->getUseRateCtrl() )
       {
-#if !M0036_RC_IMPROVEMENT || KWU_RC_MADPRED_E0227
+#if KWU_RC_MADPRED_E0227
         UInt SAD    = m_pcCuEncoder->getLCUPredictionSAD();
         Int height  = min( pcSlice->getSPS()->getMaxCUHeight(),pcSlice->getSPS()->getPicHeightInLumaSamples() - uiCUAddr / rpcPic->getFrameWidthInCU() * pcSlice->getSPS()->getMaxCUHeight() );
@@ -1413,29 +1149,6 @@
         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
-    else
-    {
-      m_pcCuEncoder->compressCU( pcCU );
-      m_pcCuEncoder->encodeCU( pcCU );
-      if (m_pcCfg->getSliceMode()==FIXED_NUMBER_OF_BYTES && ( ( pcSlice->getSliceBits()+ m_pcEntropyCoder->getNumberOfWrittenBits() ) ) > m_pcCfg->getSliceArgument()<<3)
-      {
-        pcSlice->setNextSlice( true );
-        break;
-      }
-      if (m_pcCfg->getSliceSegmentMode()==FIXED_NUMBER_OF_BYTES && pcSlice->getSliceSegmentBits()+ m_pcEntropyCoder->getNumberOfWrittenBits()> m_pcCfg->getSliceSegmentArgument()<<3 &&pcSlice->getSliceCurEndCUAddr()!=pcSlice->getSliceSegmentCurEndCUAddr())
-      {
-        pcSlice->setNextSliceSegment( true );
-        break;
-      }
     }
     
@@ -1443,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)
@@ -1455,4 +1161,15 @@
     pcSlice->setNextSlice( true );
   }
+  if(m_pcCfg->getSliceMode()==FIXED_NUMBER_OF_BYTES || m_pcCfg->getSliceSegmentMode()==FIXED_NUMBER_OF_BYTES)
+  {
+    if(pcSlice->getSliceCurEndCUAddr()<=pcSlice->getSliceSegmentCurEndCUAddr())
+    {
+       pcSlice->setNextSlice( true );
+    }
+    else
+    {
+       pcSlice->setNextSliceSegment( true );
+    }
+  }
   if( depSliceSegmentsEnabled )
   {
@@ -1464,10 +1181,4 @@
   }
   xRestoreWPparam( pcSlice );
-#if !RATE_CONTROL_LAMBDA_DOMAIN
-  if(m_pcCfg->getUseRateCtrl())
-  {
-    m_pcRateCtrl->updateFrameData(m_uiPicTotalBits);
-  }
-#endif
 }
 
@@ -1582,6 +1293,4 @@
        uiCUAddr = rpcPic->getPicSym()->getCUOrderMap(++uiEncCUOrder) )
   {
-    if( m_pcCfg->getUseSBACRD() )
-    {
       uiTileCol = rpcPic->getPicSym()->getTileIdxMap(uiCUAddr) % (rpcPic->getPicSym()->getNumColumnsMinus1()+1); // what column of tiles are we in?
       uiTileStartLCU = rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(uiCUAddr))->getFirstCUAddr();
@@ -1632,5 +1341,5 @@
       }
       m_pcSbacCoder->load(&pcSbacCoders[uiSubStrm]);  //this load is used to simplify the code (avoid to change all the call to m_pcSbacCoder)
-    }
+
     // reset the entropy coder
     if( uiCUAddr == rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(uiCUAddr))->getFirstCUAddr() &&                                   // must be first CU of tile
@@ -1676,84 +1385,30 @@
 #endif
     TComDataCU*& pcCU = rpcPic->getCU( uiCUAddr );    
-    if ( pcSlice->getSPS()->getUseSAO() && (pcSlice->getSaoEnabledFlag()||pcSlice->getSaoEnabledFlagChroma()) )
-    {
-      SAOParam *saoParam = pcSlice->getPic()->getPicSym()->getSaoParam();
-      Int iNumCuInWidth     = saoParam->numCuInWidth;
-      Int iCUAddrInSlice    = uiCUAddr - rpcPic->getPicSym()->getCUOrderMap(pcSlice->getSliceCurStartCUAddr()/rpcPic->getNumPartInCU());
-      Int iCUAddrUpInSlice  = iCUAddrInSlice - iNumCuInWidth;
-      Int rx = uiCUAddr % iNumCuInWidth;
-      Int ry = uiCUAddr / iNumCuInWidth;
-      Int allowMergeLeft = 1;
-      Int allowMergeUp   = 1;
-      if (rx!=0)
-      {
-        if (rpcPic->getPicSym()->getTileIdxMap(uiCUAddr-1) != rpcPic->getPicSym()->getTileIdxMap(uiCUAddr))
-        {
-          allowMergeLeft = 0;
-        }
-      }
-      if (ry!=0)
-      {
-        if (rpcPic->getPicSym()->getTileIdxMap(uiCUAddr-iNumCuInWidth) != rpcPic->getPicSym()->getTileIdxMap(uiCUAddr))
-        {
-          allowMergeUp = 0;
-        }
-      }
-      Int addr = pcCU->getAddr();
-      allowMergeLeft = allowMergeLeft && (rx>0) && (iCUAddrInSlice!=0);
-      allowMergeUp = allowMergeUp && (ry>0) && (iCUAddrUpInSlice>=0);
-      if( saoParam->bSaoFlag[0] || saoParam->bSaoFlag[1] )
-      {
-        Int mergeLeft = saoParam->saoLcuParam[0][addr].mergeLeftFlag;
-        Int mergeUp = saoParam->saoLcuParam[0][addr].mergeUpFlag;
-        if (allowMergeLeft)
-        {
-          m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMerge(mergeLeft); 
-        }
-        else
-        {
-          mergeLeft = 0;
-        }
-        if(mergeLeft == 0)
-        {
-          if (allowMergeUp)
-          {
-            m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMerge(mergeUp);
-          }
-          else
-          {
-            mergeUp = 0;
-          }
-          if(mergeUp == 0)
-          {
-            for (Int compIdx=0;compIdx<3;compIdx++)
-            {
-            if( (compIdx == 0 && saoParam->bSaoFlag[0]) || (compIdx > 0 && saoParam->bSaoFlag[1]))
-              {
-                m_pcEntropyCoder->encodeSaoOffset(&saoParam->saoLcuParam[compIdx][addr], compIdx);
-              }
-            }
-          }
-        }
-      }
-    }
-    else if (pcSlice->getSPS()->getUseSAO())
-    {
-      Int addr = pcCU->getAddr();
-      SAOParam *saoParam = pcSlice->getPic()->getPicSym()->getSaoParam();
-      for (Int cIdx=0; cIdx<3; cIdx++)
-      {
-        SaoLcuParam *saoLcuParam = &(saoParam->saoLcuParam[cIdx][addr]);
-        if ( ((cIdx == 0) && !pcSlice->getSaoEnabledFlag()) || ((cIdx == 1 || cIdx == 2) && !pcSlice->getSaoEnabledFlagChroma()))
-        {
-          saoLcuParam->mergeUpFlag   = 0;
-          saoLcuParam->mergeLeftFlag = 0;
-          saoLcuParam->subTypeIdx    = 0;
-          saoLcuParam->typeIdx       = -1;
-          saoLcuParam->offset[0]     = 0;
-          saoLcuParam->offset[1]     = 0;
-          saoLcuParam->offset[2]     = 0;
-          saoLcuParam->offset[3]     = 0;
-        }
+    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);
       }
     }
@@ -1773,6 +1428,4 @@
     g_bJustDoIt = g_bEncDecTraceDisable;
 #endif    
-    if( m_pcCfg->getUseSBACRD() )
-    {
        pcSbacCoders[uiSubStrm].load(m_pcSbacCoder);   //load back status of the entropy coder after encoding the LCU into relevant bitstream entropy coder
        
@@ -1784,8 +1437,4 @@
       }
     }
-#if H_3D_QTLPC
-    rpcPic->setReduceBitsFlag(false);
-#endif
-  }
   if( depSliceSegmentsEnabled )
   {
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncSlice.h
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncSlice.h	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncSlice.h	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -107,5 +107,4 @@
   UInt                    m_uiSliceIdx;
   std::vector<TEncSbac*> CTXMem;
-
 #if MTK_DDD_G0063
   Int          m_iDDDScale;
@@ -129,15 +128,9 @@
                                 Int iGOPid,   TComSlice*& rpcSlice, TComSPS* pSPS, TComPPS *pPPS, bool isField  );
 #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: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncTop.cpp
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncTop.cpp	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncTop.cpp	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -106,9 +106,10 @@
   if (m_bUseSAO)
   {
-    m_cEncSAO.setSaoLcuBoundary(getSaoLcuBoundary());
-    m_cEncSAO.setSaoLcuBasedOptimization(getSaoLcuBasedOptimization());
-    m_cEncSAO.setMaxNumOffsetsPerPic(getMaxNumOffsetsPerPic());
-    m_cEncSAO.create( getSourceWidth(), getSourceHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight );
-    m_cEncSAO.createEncBuffer();
+    m_cEncSAO.create( getSourceWidth(), getSourceHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+    m_cEncSAO.createEncData(getSaoLcuBoundary());
+#else
+    m_cEncSAO.createEncData();
+#endif
   }
 #if ADAPTIVE_QP_SELECTION
@@ -120,5 +121,4 @@
   m_cLoopFilter.        create( g_uiMaxCUDepth );
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
   if ( m_RCEnableRateControl )
   {
@@ -131,13 +131,4 @@
 #endif
   }
-#else
-#if KWU_FIX_URQ
-  if(m_enableRateCtrl)
-#endif
-    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 )
-  {
     m_pppcRDSbacCoder = new TEncSbac** [g_uiMaxCUDepth+1];
 #if FAST_BIT_EST
@@ -168,5 +159,4 @@
     }
   }
-}
 
 /**
@@ -195,6 +185,5 @@
     m_pcSbacCoders[ui].init( &m_pcBinCoderCABACs[ui] );
   }
-  if( m_bUseSBACRD )
-  {
+
     m_ppppcRDSbacCoders      = new TEncSbac***    [iNumSubstreams];
     m_ppppcBinCodersCABAC    = new TEncBinCABAC***[iNumSubstreams];
@@ -218,5 +207,4 @@
     }
   }
-}
 
 Void TEncTop::destroy ()
@@ -228,12 +216,10 @@
   if (m_cSPS.getUseSAO())
   {
+    m_cEncSAO.destroyEncData();
     m_cEncSAO.destroy();
-    m_cEncSAO.destroyEncBuffer();
   }
   m_cLoopFilter.        destroy();
   m_cRateCtrl.          destroy();
-  // SBAC RD
-  if( m_bUseSBACRD )
-  {
+
     Int iDepth;
     for ( iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
@@ -276,5 +262,4 @@
     delete[] m_ppppcRDSbacCoders;
     delete[] m_ppppcBinCodersCABAC;
-  }
   delete[] m_pcSbacCoders;
   delete[] m_pcBinCoderCABACs;
@@ -439,11 +424,8 @@
 #endif
   
-#if RATE_CONTROL_LAMBDA_DOMAIN
   if ( m_RCEnableRateControl )
   {
     m_cRateCtrl.initRCGOP( m_iNumPicRcvd );
   }
-#endif
-
 #if H_MV
   }
@@ -457,10 +439,8 @@
 #endif
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
   if ( m_RCEnableRateControl )
   {
     m_cRateCtrl.destroyRCGOP();
   }
-#endif
   
   iNumEncoded         = m_iNumPicRcvd;
@@ -510,5 +490,4 @@
     TComPic *pcTopField;
     xGetNewPicBuffer( pcTopField );
-    pcTopField->getPicSym()->allocSaoParam(&m_cEncSAO);
     pcTopField->setReconMark (false);
     
@@ -532,10 +511,4 @@
     Pel * pcTopFieldV =  pcTopField->getPicYuvOrg()->getCrAddr();
     
-    // compute image characteristics
-    if ( getUseAdaptiveQP() )
-    {
-      m_cPreanalyzer.xPreanalyze( dynamic_cast<TEncPic*>( pcTopField ) );
-    }
-    
     /* -- Defield -- */
     
@@ -546,4 +519,9 @@
     separateFields(PicBufV + nPadChroma + (nStride >> 1)*nPadChroma, pcTopFieldV, nStride >> 1, nWidth >> 1, nHeight >> 1, isTop);
     
+    // compute image characteristics
+    if ( getUseAdaptiveQP() )
+    {
+      m_cPreanalyzer.xPreanalyze( dynamic_cast<TEncPic*>( pcTopField ) );
+    }    
   }
   
@@ -562,8 +540,7 @@
     TComPic* pcBottomField;
     xGetNewPicBuffer( pcBottomField );
-    pcBottomField->getPicSym()->allocSaoParam(&m_cEncSAO);
     pcBottomField->setReconMark (false);
     
-    TComPicYuv* rpcPicYuvRec = new TComPicYuv;
+    TComPicYuv* rpcPicYuvRec;
     if ( rcListPicYuvRecOut.size() == (UInt)m_iGOPSize )
     {
@@ -572,4 +549,5 @@
     else
     {
+      rpcPicYuvRec = new TComPicYuv;
       rpcPicYuvRec->create( m_iSourceWidth, m_iSourceHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
     }
@@ -595,10 +573,4 @@
     Pel * pcBottomFieldV =  pcBottomField->getPicYuvOrg()->getCrAddr();
     
-    // Compute image characteristics
-    if ( getUseAdaptiveQP() )
-    {
-      m_cPreanalyzer.xPreanalyze( dynamic_cast<TEncPic*>( pcBottomField ) );
-    }
-    
     /* -- Defield -- */
     
@@ -609,4 +581,9 @@
     separateFields(PicBufV + nPadChroma + (nStride >> 1)*nPadChroma, pcBottomFieldV, nStride >> 1, nWidth >> 1, nHeight >> 1, isTop);
     
+    // Compute image characteristics
+    if ( getUseAdaptiveQP() )
+    {
+      m_cPreanalyzer.xPreanalyze( dynamic_cast<TEncPic*>( pcBottomField ) );
+    }    
   }
   
@@ -624,7 +601,4 @@
   m_uiNumAllPicCoded += iNumEncoded;
 }
-#endif
-
-
 
 // ====================================================================================================================
@@ -671,8 +645,4 @@
       rpcPic->create( m_iSourceWidth, m_iSourceHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, 
                       m_conformanceWindow, m_defaultDisplayWindow, m_numReorderPics);
-    }
-    if (getUseSAO())
-    {
-      rpcPic->getPicSym()->allocSaoParam(&m_cEncSAO);
     }
     m_cListPic.pushBack( rpcPic );
@@ -760,5 +730,4 @@
   
   m_cSPS.setTMVPFlagsPresent(false);
-  m_cSPS.setUseLossless   ( m_useLossless  );
 
   m_cSPS.setMaxTrSize   ( 1 << m_uiQuadtreeTULog2MaxSize );
@@ -794,5 +763,5 @@
   m_cSPS.setMaxTLayers( m_maxTempLayer );
   m_cSPS.setTemporalIdNestingFlag( ( m_maxTempLayer == 1 ) ? true : false );
-  for ( i = 0; i < m_cSPS.getMaxTLayers(); i++ )
+  for ( i = 0; i < min(m_cSPS.getMaxTLayers(),(UInt) MAX_TLAYER); i++ )
   {
     m_cSPS.setMaxDecPicBuffering(m_maxDecPicBuffering[i], i);
@@ -860,35 +829,14 @@
   m_cPPS.setSPSId( getLayerIdInVps() );
 #endif
-
 #if H_3D
   m_cPPS.setDLT( getDLT() );
 #endif
-
   m_cPPS.setConstrainedIntraPred( m_bUseConstrainedIntraPred );
   Bool bUseDQP = (getMaxCuDQPDepth() > 0)? true : false;
 
-  Int lowestQP = - m_cSPS.getQpBDOffsetY();
-
-  if(getUseLossless())
-  {
-    if ((getMaxCuDQPDepth() == 0) && (getMaxDeltaQP() == 0 ) && (getQP() == lowestQP) )
-    {
-      bUseDQP = false;
-    }
-    else
-    {
-      bUseDQP = true;
-    }
-  }
-  else
-  {
-    if(bUseDQP == false)
-    {
       if((getMaxDeltaQP() != 0 )|| getUseAdaptiveQP())
       {
         bUseDQP = true;
       }
-    }
-  }
 
   if(bUseDQP)
@@ -905,5 +853,4 @@
   }
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
   if ( m_RCEnableRateControl )
   {
@@ -912,13 +859,4 @@
     m_cPPS.setMinCuDQPSize( m_cPPS.getSPS()->getMaxCUWidth() >> ( m_cPPS.getMaxCuDQPDepth()) );
   }
-#endif 
-#if !RATE_CONTROL_LAMBDA_DOMAIN && KWU_FIX_URQ
-  if ( m_enableRateCtrl )
-  {
-    m_cPPS.setUseDQP(true);
-    m_cPPS.setMaxCuDQPDepth( 0 );
-    m_cPPS.setMinCuDQPSize( m_cPPS.getSPS()->getMaxCUWidth() >> ( m_cPPS.getMaxCuDQPDepth()) );
-  } 
-#endif
 
   m_cPPS.setChromaCbQpOffset( m_chromaCbQpOffset );
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncTop.h
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncTop.h	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/TEncTop.h	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -82,5 +82,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
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/WeightPredAnalysis.cpp
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/WeightPredAnalysis.cpp	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/WeightPredAnalysis.cpp	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/WeightPredAnalysis.h
===================================================================
--- branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/WeightPredAnalysis.h	(revision 836)
+++ branches/HTM-10.0rc1-dev0/source/Lib/TLibEncoder/WeightPredAnalysis.h	(revision 837)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
