Index: branches/SHM-4.1-dev/source/App/TAppDecoder/TAppDecTop.cpp
===================================================================
--- branches/SHM-4.1-dev/source/App/TAppDecoder/TAppDecTop.cpp	(revision 531)
+++ branches/SHM-4.1-dev/source/App/TAppDecoder/TAppDecTop.cpp	(revision 532)
@@ -145,4 +145,7 @@
   // main decoder loop
   Bool openedReconFile[MAX_LAYERS]; // reconstruction file not yet opened. (must be performed after SPS is seen)
+  Bool loopFiltered[MAX_LAYERS];
+  memset( loopFiltered, false, sizeof( loopFiltered ) );
+
   for(UInt layer=0; layer<=m_tgtLayerId; layer++)
   {
@@ -223,5 +226,6 @@
       }
     }
-    if (bNewPicture || !bitstreamFile)
+
+    if (bNewPicture || !bitstreamFile || nalu.m_nalUnitType == NAL_UNIT_EOS)
     {
 #if O0194_DIFFERENT_BITDEPTH_EL_BL
@@ -230,5 +234,9 @@
       g_bitDepthC = g_bitDepthCLayer[curLayerId];
 #endif
-      m_acTDecTop[curLayerId].executeLoopFilters(poc, pcListPic);
+      if (!loopFiltered[curLayerId] || bitstreamFile)
+      {
+        m_acTDecTop[curLayerId].executeLoopFilters(poc, pcListPic);
+      }
+      loopFiltered[curLayerId] = (nalu.m_nalUnitType == NAL_UNIT_EOS);
 #if EARLY_REF_PIC_MARKING
       m_acTDecTop[curLayerId].earlyPicMarking(m_iMaxTemporalLayer, m_targetDecLayerIdSet);
@@ -256,4 +264,8 @@
         xFlushOutput( pcListPic, curLayerId );
       }
+      if (nalu.m_nalUnitType == NAL_UNIT_EOS)
+      {
+        xFlushOutput( pcListPic, curLayerId );        
+      }
       // write reconstruction to file
       if(bNewPicture)
@@ -316,4 +328,5 @@
   // main decoder loop
   Bool openedReconFile = false; // reconstruction file not yet opened. (must be performed after SPS is seen)
+  Bool loopFiltered = false;
 
 #if SYNTAX_OUTPUT
@@ -384,7 +397,11 @@
       }
     }
-    if (bNewPicture || !bitstreamFile)
-    {
-      m_cTDecTop.executeLoopFilters(poc, pcListPic);
+    if (bNewPicture || !bitstreamFile || nalu.m_nalUnitType == NAL_UNIT_EOS)
+    {
+      if (!loopFiltered || bitstreamFile)
+      {
+        m_cTDecTop.executeLoopFilters(poc, pcListPic);
+      }
+      loopFiltered = (nalu.m_nalUnitType == NAL_UNIT_EOS);
     }
 
@@ -408,4 +425,8 @@
         xFlushOutput( pcListPic );
       }
+      if (nalu.m_nalUnitType == NAL_UNIT_EOS)
+      {
+        xFlushOutput( pcListPic );        
+      }
       // write reconstruction to file
       if(bNewPicture)
@@ -506,6 +527,6 @@
 
 /** \param pcListPic list of pictures to be written to file
-\todo            DYN_REF_FREE should be revised
-*/
+    \todo            DYN_REF_FREE should be revised
+ */
 #if SVC_EXTENSION
 Void TAppDecTop::xWriteOutput( TComList<TComPic*>* pcListPic, UInt layerId, UInt tId )
Index: branches/SHM-4.1-dev/source/App/TAppEncoder/TAppEncCfg.cpp
===================================================================
--- branches/SHM-4.1-dev/source/App/TAppEncoder/TAppEncCfg.cpp	(revision 531)
+++ branches/SHM-4.1-dev/source/App/TAppEncoder/TAppEncCfg.cpp	(revision 532)
@@ -791,5 +791,7 @@
   ("MaxNumOffsetsPerPic",      m_maxNumOffsetsPerPic,       2048,  "Max number of SAO offset per picture (Default: 2048)")   
   ("SAOLcuBoundary",           m_saoLcuBoundary,            false, "0: right/bottom LCU boundary areas skipped from SAO parameter estimation, 1: non-deblocked pixels are used for those areas")
+#if !HM_CLEANUP_SAO
   ("SAOLcuBasedOptimization",  m_saoLcuBasedOptimization,   true,  "0: SAO picture-based optimization, 1: SAO LCU-based optimization ")
+#endif  
   ("SliceMode",                m_sliceMode,                0,     "0: Disable all Recon slice limits, 1: Enforce max # of LCUs, 2: Enforce max # of bytes, 3:specify tiles per dependent slice")
   ("SliceArgument",            m_sliceArgument,            0,     "Depending on SliceMode being:"
@@ -845,5 +847,4 @@
   ("FIS", m_useFastIntraScalable, false, "Fast Intra Decision for Scalable HEVC")
 #endif
-#if RATE_CONTROL_LAMBDA_DOMAIN
 #if RC_SHVC_HARMONIZATION
   ("RateControl%d", cfg_RCEnableRateControl, false, MAX_LAYERS, "Rate control: enable rate control for layer %d")
@@ -857,18 +858,9 @@
   ( "RateControl",         m_RCEnableRateControl,   false, "Rate control: enable rate control" )
   ( "TargetBitrate",       m_RCTargetBitrate,           0, "Rate control: target bitrate" )
-#if M0036_RC_IMPROVEMENT
   ( "KeepHierarchicalBit", m_RCKeepHierarchicalBit,     0, "Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation" )
-#else
-  ( "KeepHierarchicalBit", m_RCKeepHierarchicalBit, false, "Rate control: keep hierarchical bit allocation in rate control algorithm" )
-#endif
   ( "LCULevelRateControl", m_RCLCULevelRC,           true, "Rate control: true: LCU level RC; false: picture level RC" )
   ( "RCLCUSeparateModel",  m_RCUseLCUSeparateModel,  true, "Rate control: use LCU level separate R-lambda model" )
   ( "InitialQP",           m_RCInitialQP,               0, "Rate control: initial QP" )
   ( "RCForceIntraQP",      m_RCForceIntraQP,        false, "Rate control: force intra QP to be equal to initial QP" )
-#endif
-#else
-  ("RateCtrl,-rc", m_enableRateCtrl, false, "Rate control on/off")
-  ("TargetBitrate,-tbr", m_targetBitrate, 0, "Input target bitrate")
-  ("NumLCUInUnit,-nu", m_numLCUInUnit, 0, "Number of LCUs in an Unit")
 #endif
 
@@ -2200,5 +2192,4 @@
   }
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
 #if RC_SHVC_HARMONIZATION
   for ( Int layer=0; layer<m_numLayers; layer++ )
@@ -2229,17 +2220,4 @@
     }
     xConfirmPara( m_uiDeltaQpRD > 0, "Rate control cannot be used together with slice level multiple-QP optimization!\n" );
-  }
-#endif
-#else
-  if(m_enableRateCtrl)
-  {
-    Int numLCUInWidth  = (m_iSourceWidth  / m_uiMaxCUWidth) + (( m_iSourceWidth  %  m_uiMaxCUWidth ) ? 1 : 0);
-    Int numLCUInHeight = (m_iSourceHeight / m_uiMaxCUHeight)+ (( m_iSourceHeight %  m_uiMaxCUHeight) ? 1 : 0);
-    Int numLCUInPic    =  numLCUInWidth * numLCUInHeight;
-
-    xConfirmPara( (numLCUInPic % m_numLCUInUnit) != 0, "total number of LCUs in a frame should be completely divided by NumLCUInUnit" );
-
-    m_iMaxDeltaQP       = MAX_DELTA_QP;
-    m_iMaxCuDQPDepth    = MAX_CUDQP_DEPTH;
   }
 #endif
@@ -2521,5 +2499,4 @@
   printf("Cross-layer sample alignment : %d\n", m_phaseAlignFlag);
 #endif
-#if RATE_CONTROL_LAMBDA_DOMAIN
 #if !RC_SHVC_HARMONIZATION
   printf("RateControl                  : %d\n", m_RCEnableRateControl );
@@ -2534,12 +2511,5 @@
   }
 #endif
-#else
-  printf("RateControl                  : %d\n", m_enableRateCtrl);
-  if(m_enableRateCtrl)
-  {
-    printf("TargetBitrate                : %d\n", m_targetBitrate);
-    printf("NumLCUInUnit                 : %d\n", m_numLCUInUnit);
-  }
-#endif
+
   printf("Max Num Merge Candidates     : %d\n", m_maxNumMergeCand);
   printf("\n");
@@ -2582,6 +2552,7 @@
   printf("PCM:%d ", (m_usePCM && (1<<m_uiPCMLog2MinSize) <= m_uiMaxCUWidth)? 1 : 0);
 #endif
+#if !HM_CLEANUP_SAO
   printf("SAOLcuBasedOptimization:%d ", (m_saoLcuBasedOptimization)?(1):(0));
-
+#endif
   printf("LosslessCuEnabled:%d ", (m_useLossless)? 1:0 );
   printf("WPP:%d ", (Int)m_useWeightedPred);
Index: branches/SHM-4.1-dev/source/App/TAppEncoder/TAppEncCfg.h
===================================================================
--- branches/SHM-4.1-dev/source/App/TAppEncoder/TAppEncCfg.h	(revision 531)
+++ branches/SHM-4.1-dev/source/App/TAppEncoder/TAppEncCfg.h	(revision 532)
@@ -187,5 +187,7 @@
   Int       m_maxNumOffsetsPerPic;                            ///< SAO maximun number of offset per picture
   Bool      m_saoLcuBoundary;                                 ///< SAO parameter estimation using non-deblocked pixels for LCU bottom and right boundary areas
+#if !HM_CLEANUP_SAO
   Bool      m_saoLcuBasedOptimization;                        ///< SAO LCU-based optimization
+#endif
   // coding tools (loop filter)
   Bool      m_bLoopFilterDisable;                             ///< flag for using deblocking filter
@@ -295,22 +297,12 @@
   Int       m_TMVPModeId;
   Int       m_signHideFlag;
-#if RATE_CONTROL_LAMBDA_DOMAIN
 #if !RC_SHVC_HARMONIZATION
   Bool      m_RCEnableRateControl;                ///< enable rate control or not
   Int       m_RCTargetBitrate;                    ///< target bitrate when rate control is enabled
-#if M0036_RC_IMPROVEMENT
   Int       m_RCKeepHierarchicalBit;              ///< 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation
-#else
-  Bool      m_RCKeepHierarchicalBit;              ///< whether keeping hierarchical bit allocation structure or not
-#endif
   Bool      m_RCLCULevelRC;                       ///< true: LCU level rate control; false: picture level rate control
   Bool      m_RCUseLCUSeparateModel;              ///< use separate R-lambda model at LCU level
   Int       m_RCInitialQP;                        ///< inital QP for rate control
   Bool      m_RCForceIntraQP;                     ///< force all intra picture to use initial QP or not
-#endif
-#else
-  Bool      m_enableRateCtrl;                                   ///< Flag for using rate control algorithm
-  Int       m_targetBitrate;                                 ///< target bitrate
-  Int       m_numLCUInUnit;                                  ///< Total number of LCUs in a frame should be completely divided by the NumLCUInUnit
 #endif
   Int       m_useScalingListId;                               ///< using quantization matrix
Index: branches/SHM-4.1-dev/source/App/TAppEncoder/TAppEncTop.cpp
===================================================================
--- branches/SHM-4.1-dev/source/App/TAppEncoder/TAppEncTop.cpp	(revision 531)
+++ branches/SHM-4.1-dev/source/App/TAppEncoder/TAppEncTop.cpp	(revision 532)
@@ -470,5 +470,7 @@
 
     m_acTEncTop[layer].setSaoLcuBoundary (m_saoLcuBoundary);
+#if !HM_CLEANUP_SAO
     m_acTEncTop[layer].setSaoLcuBasedOptimization (m_saoLcuBasedOptimization);
+#endif
     m_acTEncTop[layer].setPCMInputBitDepthFlag  ( m_bPCMInputBitDepthFlag);
     m_acTEncTop[layer].setPCMFilterDisableFlag  ( m_bPCMFilterDisableFlag);
@@ -546,5 +548,4 @@
     m_acTEncTop[layer].setScalingListFile            ( m_scalingListFile   );
     m_acTEncTop[layer].setSignHideFlag(m_signHideFlag);
-#if RATE_CONTROL_LAMBDA_DOMAIN
 #if RC_SHVC_HARMONIZATION
     m_acTEncTop[layer].setUseRateCtrl     (m_acLayerCfg[layer].getRCEnableRateControl());
@@ -563,9 +564,4 @@
     m_acTEncTop[layer].setInitialQP           ( m_RCInitialQP );
     m_acTEncTop[layer].setForceIntraQP        ( m_RCForceIntraQP );
-#endif
-#else
-    m_acTEncTop[layer].setUseRateCtrl     ( m_enableRateCtrl);
-    m_acTEncTop[layer].setTargetBitrate   ( m_targetBitrate);
-    m_acTEncTop[layer].setNumLCUInUnit    ( m_numLCUInUnit);
 #endif
     m_acTEncTop[layer].setTransquantBypassEnableFlag(m_TransquantBypassEnableFlag);
@@ -788,5 +784,7 @@
 
   m_cTEncTop.setSaoLcuBoundary (m_saoLcuBoundary);
+#if !HM_CLEANUP_SAO
   m_cTEncTop.setSaoLcuBasedOptimization (m_saoLcuBasedOptimization);
+#endif
   m_cTEncTop.setPCMInputBitDepthFlag  ( m_bPCMInputBitDepthFlag);
   m_cTEncTop.setPCMFilterDisableFlag  ( m_bPCMFilterDisableFlag);
@@ -856,5 +854,4 @@
   m_cTEncTop.setScalingListFile            ( m_scalingListFile   );
   m_cTEncTop.setSignHideFlag(m_signHideFlag);
-#if RATE_CONTROL_LAMBDA_DOMAIN
   m_cTEncTop.setUseRateCtrl         ( m_RCEnableRateControl );
   m_cTEncTop.setTargetBitrate       ( m_RCTargetBitrate );
@@ -864,9 +861,4 @@
   m_cTEncTop.setInitialQP           ( m_RCInitialQP );
   m_cTEncTop.setForceIntraQP        ( m_RCForceIntraQP );
-#else
-  m_cTEncTop.setUseRateCtrl     ( m_enableRateCtrl);
-  m_cTEncTop.setTargetBitrate   ( m_targetBitrate);
-  m_cTEncTop.setNumLCUInUnit    ( m_numLCUInUnit);
-#endif
   m_cTEncTop.setTransquantBypassEnableFlag(m_TransquantBypassEnableFlag);
   m_cTEncTop.setCUTransquantBypassFlagValue(m_CUTransquantBypassFlagValue);
@@ -2131,5 +2123,5 @@
     case NAL_UNIT_CODED_SLICE_TRAIL_R:
     case NAL_UNIT_CODED_SLICE_TRAIL_N:
-    case NAL_UNIT_CODED_SLICE_TLA_R:
+    case NAL_UNIT_CODED_SLICE_TSA_R:
     case NAL_UNIT_CODED_SLICE_TSA_N:
     case NAL_UNIT_CODED_SLICE_STSA_R:
Index: branches/SHM-4.1-dev/source/Lib/TAppCommon/program_options_lite.cpp
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TAppCommon/program_options_lite.cpp	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TAppCommon/program_options_lite.cpp	(revision 532)
@@ -38,4 +38,5 @@
 #include <list>
 #include <map>
+#include <algorithm>
 #include "program_options_lite.h"
 
Index: branches/SHM-4.1-dev/source/Lib/TLibCommon/CommonDef.h
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibCommon/CommonDef.h	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibCommon/CommonDef.h	(revision 532)
@@ -40,5 +40,4 @@
 
 #include <algorithm>
-#include <vector>
 #if _MSC_VER > 1000
 // disable "signed and unsigned mismatch"
@@ -57,7 +56,8 @@
 
 #if SVC_EXTENSION
-#define NV_VERSION        "4.0"                 ///< Current software version
+#include <vector>
+#define NV_VERSION        "4.1"                 ///< Current software version
 #else
-#define NV_VERSION        "12.0"                ///< Current software version
+#define NV_VERSION        "12.1"                ///< Current software version
 #endif
 
@@ -209,5 +209,5 @@
   
   NAL_UNIT_CODED_SLICE_TSA_N,     // 2
-  NAL_UNIT_CODED_SLICE_TLA_R,       // 3
+  NAL_UNIT_CODED_SLICE_TSA_R,       // 3
   
   NAL_UNIT_CODED_SLICE_STSA_N,    // 4
Index: branches/SHM-4.1-dev/source/Lib/TLibCommon/NAL.h
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibCommon/NAL.h	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibCommon/NAL.h	(revision 532)
@@ -76,5 +76,5 @@
     return m_nalUnitType == NAL_UNIT_CODED_SLICE_TRAIL_R
         || m_nalUnitType == NAL_UNIT_CODED_SLICE_TRAIL_N
-        || m_nalUnitType == NAL_UNIT_CODED_SLICE_TLA_R
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_TSA_R
         || m_nalUnitType == NAL_UNIT_CODED_SLICE_TSA_N
         || m_nalUnitType == NAL_UNIT_CODED_SLICE_STSA_R
Index: branches/SHM-4.1-dev/source/Lib/TLibCommon/TComDataCU.cpp
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibCommon/TComDataCU.cpp	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibCommon/TComDataCU.cpp	(revision 532)
@@ -309,5 +309,5 @@
   }
 }
-
+#if !HM_CLEANUP_SAO
 const NDBFBlockInfo& NDBFBlockInfo::operator= (const NDBFBlockInfo& src)
 {
@@ -328,5 +328,5 @@
 }
 
-
+#endif
 // ====================================================================================================================
 // Public member functions
@@ -3638,5 +3638,5 @@
   return getPic()->getPicSym()->getInverseCUOrderMap(m_uiCUAddr)*(1<<(m_pcSlice->getSPS()->getMaxCUDepth()<<1))+m_uiAbsIdxInLCU; 
 }
-
+#if !HM_CLEANUP_SAO
 /** Set neighboring blocks availabilities for non-deblocked filtering 
  * \param numLCUInPicWidth number of LCUs in picture width
@@ -4008,4 +4008,6 @@
 }
 
+#endif
+
 #if SVC_EXTENSION
 TComDataCU*  TComDataCU::getBaseColCU( UInt refLayerIdc, UInt uiCuAbsPartIdx, UInt &uiCUAddrBase, UInt &uiAbsPartIdxBase, Int iMotionMapping )
Index: branches/SHM-4.1-dev/source/Lib/TLibCommon/TComDataCU.h
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibCommon/TComDataCU.h	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibCommon/TComDataCU.h	(revision 532)
@@ -55,4 +55,5 @@
 //! \{
 
+#if !HM_CLEANUP_SAO
 // ====================================================================================================================
 // Non-deblocking in-loop filter processing block data structure
@@ -92,4 +93,5 @@
   const NDBFBlockInfo& operator= (const NDBFBlockInfo& src);  //!< "=" operator
 };
+#endif
 
 
@@ -159,7 +161,8 @@
   Pel*          m_pcIPCMSampleCr;     ///< PCM sample buffer (Cr)
 
+#if !HM_CLEANUP_SAO
   Int*          m_piSliceSUMap;       ///< pointer of slice ID map
   std::vector<NDBFBlockInfo> m_vNDFBlock;
-
+#endif
   // -------------------------------------------------------------------------------------------------------------------
   // neighbour access variables
@@ -389,4 +392,5 @@
   Void          setIPCMFlagSubParts   (Bool bIpcmFlag, UInt uiAbsPartIdx, UInt uiDepth);
 
+#if !HM_CLEANUP_SAO
   /// get slice ID for SU
   Int           getSUSliceID          (UInt uiIdx)              {return m_piSliceSUMap[uiIdx];      } 
@@ -403,4 +407,5 @@
                                           ,Bool bTopTileBoundary, Bool bDownTileBoundary, Bool bLeftTileBoundary, Bool bRightTileBoundary
                                           ,Bool bIndependentTileBoundaryEnabled );
+#endif
   // -------------------------------------------------------------------------------------------------------------------
   // member functions for accessing partition information
Index: branches/SHM-4.1-dev/source/Lib/TLibCommon/TComPic.cpp
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibCommon/TComPic.cpp	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibCommon/TComPic.cpp	(revision 532)
@@ -59,4 +59,5 @@
 , m_bNeededForOutput                      (false)
 , m_uiCurrSliceIdx                        (0)
+#if !HM_CLEANUP_SAO
 , m_pSliceSUMap                           (NULL)
 , m_pbValidSlice                          (NULL)
@@ -65,4 +66,5 @@
 , m_bIndependentTileBoundaryForNDBFilter  (false)
 , m_pNDBFilterYuvTmp                      (NULL)
+#endif
 , m_bCheckLTMSB                           (false)
 {
@@ -212,5 +214,12 @@
   } 
 }
-
+#if HM_CLEANUP_SAO
+Bool  TComPic::getSAOMergeAvailability(Int currAddr, Int mergeAddr)
+{
+  Bool mergeCtbInSliceSeg = (mergeAddr >= getPicSym()->getCUOrderMap(getCU(currAddr)->getSlice()->getSliceCurStartCUAddr()/getNumPartInCU()));
+  Bool mergeCtbInTile     = (getPicSym()->getTileIdxMap(mergeAddr) == getPicSym()->getTileIdxMap(currAddr));
+  return (mergeCtbInSliceSeg && mergeCtbInTile);
+}
+#else
 /** Create non-deblocked filter information
  * \param pSliceStartAddress array for storing slice start addresses
@@ -548,4 +557,5 @@
 
 }
+#endif
 
 #if SVC_EXTENSION
Index: branches/SHM-4.1-dev/source/Lib/TLibCommon/TComPic.h
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibCommon/TComPic.h	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibCommon/TComPic.h	(revision 532)
@@ -75,4 +75,5 @@
   Bool                  m_bNeededForOutput;
   UInt                  m_uiCurrSliceIdx;         // Index of current slice
+#if !HM_CLEANUP_SAO
   Int*                  m_pSliceSUMap;
   Bool*                 m_pbValidSlice;
@@ -81,4 +82,5 @@
   Bool                  m_bIndependentTileBoundaryForNDBFilter;
   TComPicYuv*           m_pNDBFilterYuvTmp;    //!< temporary picture buffer when non-cross slice/tile boundary in-loop filtering is enabled
+#endif
   Bool                  m_bCheckLTMSB;
   
@@ -199,4 +201,7 @@
   Window&       getDefDisplayWindow()   { return m_defaultDisplayWindow; }
 
+#if HM_CLEANUP_SAO
+  Bool          getSAOMergeAvailability(Int currAddr, Int mergeAddr);
+#else
   Void          createNonDBFilterInfo   (std::vector<Int> sliceStartAddress, Int sliceGranularityDepth
                                         ,std::vector<Bool>* LFCrossSliceBoundary
@@ -211,4 +216,5 @@
   TComPicYuv*   getYuvPicBufferForIndependentBoundaryProcessing()             {return m_pNDBFilterYuvTmp;}
   std::vector<TComDataCU*>& getOneSliceCUDataForNDBFilter      (Int sliceID) { return m_vSliceCUDataLink[sliceID];}
+#endif
 
   /* field coding parameters*/
Index: branches/SHM-4.1-dev/source/Lib/TLibCommon/TComPicSym.cpp
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibCommon/TComPicSym.cpp	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibCommon/TComPicSym.cpp	(revision 532)
@@ -67,4 +67,7 @@
 ,m_puiTileIdxMap(NULL)
 ,m_puiInverseCUOrderMap(NULL)
+#if HM_CLEANUP_SAO
+,m_saoBlkParams(NULL)
+#endif
 {};
 
@@ -127,5 +130,10 @@
     m_puiInverseCUOrderMap[i] = i;
   }
+
+#if HM_CLEANUP_SAO
+  m_saoBlkParams = new SAOBlkParam[m_uiNumCUsInFrame];
+#else
   m_saoParam = NULL;
+#endif
 }
 
@@ -183,4 +191,10 @@
   m_puiInverseCUOrderMap = NULL;
   
+#if HM_CLEANUP_SAO
+  if(m_saoBlkParams)
+  {
+    delete[] m_saoBlkParams; m_saoBlkParams = NULL;
+  }
+#else
   if (m_saoParam)
   {
@@ -189,4 +203,5 @@
     m_saoParam = NULL;
   }
+#endif
 }
 
@@ -332,4 +347,114 @@
 }
 
+
+#if HM_CLEANUP_SAO
+Void TComPicSym::deriveLoopFilterBoundaryAvailibility(Int ctu,
+                                                      Bool& isLeftAvail,
+                                                      Bool& isRightAvail,
+                                                      Bool& isAboveAvail,
+                                                      Bool& isBelowAvail,
+                                                      Bool& isAboveLeftAvail,
+                                                      Bool& isAboveRightAvail,
+                                                      Bool& isBelowLeftAvail,
+                                                      Bool& isBelowRightAvail
+                                                      )
+{
+
+  isLeftAvail      = (ctu % m_uiWidthInCU != 0);
+  isRightAvail     = (ctu % m_uiWidthInCU != m_uiWidthInCU-1);
+  isAboveAvail     = (ctu >= m_uiWidthInCU );
+  isBelowAvail     = (ctu <  m_uiNumCUsInFrame - m_uiWidthInCU);
+  isAboveLeftAvail = (isAboveAvail && isLeftAvail);
+  isAboveRightAvail= (isAboveAvail && isRightAvail);
+  isBelowLeftAvail = (isBelowAvail && isLeftAvail);
+  isBelowRightAvail= (isBelowAvail && isRightAvail);
+
+  Bool isLoopFiltAcrossTilePPS = getCU(ctu)->getSlice()->getPPS()->getLoopFilterAcrossTilesEnabledFlag();
+
+  {
+    TComDataCU* ctuCurr  = getCU(ctu);
+    TComDataCU* ctuLeft  = isLeftAvail ?getCU(ctu-1):NULL;
+    TComDataCU* ctuRight = isRightAvail?getCU(ctu+1):NULL;
+    TComDataCU* ctuAbove = isAboveAvail?getCU(ctu-m_uiWidthInCU):NULL;
+    TComDataCU* ctuBelow = isBelowAvail?getCU(ctu+m_uiWidthInCU):NULL;
+    TComDataCU* ctuAboveLeft  = isAboveLeftAvail ? getCU(ctu-m_uiWidthInCU-1):NULL;
+    TComDataCU* ctuAboveRigtht= isAboveRightAvail? getCU(ctu-m_uiWidthInCU+1):NULL;
+    TComDataCU* ctuBelowLeft  = isBelowLeftAvail ? getCU(ctu+m_uiWidthInCU-1):NULL;
+    TComDataCU* ctuBelowRight = isBelowRightAvail? getCU(ctu+m_uiWidthInCU+1):NULL;
+
+    {
+      //left
+      if(ctuLeft != NULL)
+      {
+        isLeftAvail = (ctuCurr->getSlice()->getSliceCurStartCUAddr() != ctuLeft->getSlice()->getSliceCurStartCUAddr())?ctuCurr->getSlice()->getLFCrossSliceBoundaryFlag():true;
+      }
+      //above
+      if(ctuAbove != NULL)
+      {
+        isAboveAvail = (ctuCurr->getSlice()->getSliceCurStartCUAddr() != ctuAbove->getSlice()->getSliceCurStartCUAddr())?ctuCurr->getSlice()->getLFCrossSliceBoundaryFlag():true;
+      }
+      //right
+      if(ctuRight != NULL)
+      {
+        isRightAvail = (ctuCurr->getSlice()->getSliceCurStartCUAddr() != ctuRight->getSlice()->getSliceCurStartCUAddr())?ctuRight->getSlice()->getLFCrossSliceBoundaryFlag():true;
+      }
+      //below
+      if(ctuBelow != NULL)
+      {
+        isBelowAvail = (ctuCurr->getSlice()->getSliceCurStartCUAddr() != ctuBelow->getSlice()->getSliceCurStartCUAddr())?ctuBelow->getSlice()->getLFCrossSliceBoundaryFlag():true;
+      }
+      //above-left
+      if(ctuAboveLeft != NULL)
+      {
+        isAboveLeftAvail = (ctuCurr->getSlice()->getSliceCurStartCUAddr() != ctuAboveLeft->getSlice()->getSliceCurStartCUAddr())?ctuCurr->getSlice()->getLFCrossSliceBoundaryFlag():true;
+      }
+      //below-right
+      if(ctuBelowRight != NULL)
+      {
+        isBelowRightAvail = (ctuCurr->getSlice()->getSliceCurStartCUAddr() != ctuBelowRight->getSlice()->getSliceCurStartCUAddr())?ctuBelowRight->getSlice()->getLFCrossSliceBoundaryFlag():true;
+      }
+
+
+      //above-right
+      if(ctuAboveRigtht != NULL)
+      {
+        Int curSliceStartTS  = getCUOrderMap(ctuCurr->getSlice()->getSliceCurStartCUAddr()/m_uiNumPartitions);
+        Int aboveRigthtSliceStartTS = getCUOrderMap(ctuAboveRigtht->getSlice()->getSliceCurStartCUAddr()/m_uiNumPartitions);
+
+        isAboveRightAvail = (curSliceStartTS == aboveRigthtSliceStartTS)?(true):
+          (
+          (curSliceStartTS > aboveRigthtSliceStartTS)?(ctuCurr->getSlice()->getLFCrossSliceBoundaryFlag())
+          :(ctuAboveRigtht->getSlice()->getLFCrossSliceBoundaryFlag())
+          );          
+      }
+      //below-left
+      if(ctuBelowLeft != NULL)
+      {
+        Int curSliceStartTS       = getCUOrderMap(ctuCurr->getSlice()->getSliceCurStartCUAddr()/m_uiNumPartitions);
+        Int belowLeftSliceStartTS = getCUOrderMap(ctuBelowLeft->getSlice()->getSliceCurStartCUAddr()/m_uiNumPartitions);
+
+        isBelowLeftAvail = (curSliceStartTS == belowLeftSliceStartTS)?(true):
+          (
+          (curSliceStartTS > belowLeftSliceStartTS)?(ctuCurr->getSlice()->getLFCrossSliceBoundaryFlag())
+          :(ctuBelowLeft->getSlice()->getLFCrossSliceBoundaryFlag())
+          );
+      }        
+    }
+
+    if(!isLoopFiltAcrossTilePPS)
+    {      
+      isLeftAvail      = (!isLeftAvail      ) ?false:(getTileIdxMap( ctuLeft->getAddr()         ) == getTileIdxMap( ctu ));
+      isAboveAvail     = (!isAboveAvail     ) ?false:(getTileIdxMap( ctuAbove->getAddr()        ) == getTileIdxMap( ctu ));
+      isRightAvail     = (!isRightAvail     ) ?false:(getTileIdxMap( ctuRight->getAddr()        ) == getTileIdxMap( ctu ));
+      isBelowAvail     = (!isBelowAvail     ) ?false:(getTileIdxMap( ctuBelow->getAddr()        ) == getTileIdxMap( ctu ));
+      isAboveLeftAvail = (!isAboveLeftAvail ) ?false:(getTileIdxMap( ctuAboveLeft->getAddr()    ) == getTileIdxMap( ctu ));
+      isAboveRightAvail= (!isAboveRightAvail) ?false:(getTileIdxMap( ctuAboveRigtht->getAddr()  ) == getTileIdxMap( ctu ));
+      isBelowLeftAvail = (!isBelowLeftAvail ) ?false:(getTileIdxMap( ctuBelowLeft->getAddr()    ) == getTileIdxMap( ctu ));
+      isBelowRightAvail= (!isBelowRightAvail) ?false:(getTileIdxMap( ctuBelowRight->getAddr()   ) == getTileIdxMap( ctu ));
+    }
+  }
+
+}
+#else
 Void TComPicSym::allocSaoParam(TComSampleAdaptiveOffset *sao)
 {
@@ -337,4 +462,5 @@
   sao->allocSaoParam(m_saoParam);
 }
+#endif
 
 TComTile::TComTile()
Index: branches/SHM-4.1-dev/source/Lib/TLibCommon/TComPicSym.h
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibCommon/TComPicSym.h	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibCommon/TComPicSym.h	(revision 532)
@@ -112,5 +112,10 @@
   UInt*         m_puiInverseCUOrderMap;
 
+#if HM_CLEANUP_SAO
+  SAOBlkParam *m_saoBlkParams;
+#else
   SAOParam *m_saoParam;
+#endif
+
 public:
   Void        create  ( Int iPicWidth, Int iPicHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth );
@@ -171,6 +176,13 @@
   Void         xInitTiles();
   UInt         xCalculateNxtCUAddr( UInt uiCurrCUAddr );
+#if HM_CLEANUP_SAO
+  SAOBlkParam* getSAOBlkParam() { return m_saoBlkParams;}
+  Void deriveLoopFilterBoundaryAvailibility(Int ctu, Bool& isLeftAvail,Bool& isRightAvail,Bool& isAboveAvail,Bool& isBelowAvail,Bool& isAboveLeftAvail,Bool& isAboveRightAvail,Bool& isBelowLeftAvail,Bool& isBelowRightAvail);
+#else
   Void allocSaoParam(TComSampleAdaptiveOffset *sao);
   SAOParam *getSaoParam() { return m_saoParam; }
+#endif
+
+
 };// END CLASS DEFINITION TComPicSym
 
Index: branches/SHM-4.1-dev/source/Lib/TLibCommon/TComRdCost.cpp
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibCommon/TComRdCost.cpp	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibCommon/TComRdCost.cpp	(revision 532)
@@ -330,9 +330,5 @@
 
 // Setting the Distortion Parameter for Inter (subpel ME with step)
-#if NS_HAD
-Void TComRdCost::setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, Int iStep, DistParam& rcDistParam, Bool bHADME, Bool bUseNSHAD )
-#else
 Void TComRdCost::setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, Int iStep, DistParam& rcDistParam, Bool bHADME )
-#endif
 {
 #if O0194_WEIGHTED_PREDICTION_CGS
@@ -353,7 +349,4 @@
   rcDistParam.iCols    = pcPatternKey->getROIYWidth();
   rcDistParam.iRows    = pcPatternKey->getROIYHeight();
-#if NS_HAD
-  rcDistParam.bUseNSHAD = bUseNSHAD;
-#endif
 
   // set distortion function
@@ -386,9 +379,5 @@
 
 Void
-#if NS_HAD
-TComRdCost::setDistParam( DistParam& rcDP, Pel* p1, Int iStride1, Pel* p2, Int iStride2, Int iWidth, Int iHeight, Bool bHadamard, Bool bUseNSHAD )
-#else
 TComRdCost::setDistParam( DistParam& rcDP, Int bitDepth, Pel* p1, Int iStride1, Pel* p2, Int iStride2, Int iWidth, Int iHeight, Bool bHadamard )
-#endif
 {
   rcDP.pOrg       = p1;
@@ -402,7 +391,4 @@
   rcDP.bitDepth   = bitDepth;
   rcDP.DistFunc   = m_afpDistortFunc[ ( bHadamard ? DF_HADS : DF_SADS ) + g_aucConvertToBit[ iWidth ] + 1 ];
-#if NS_HAD
-  rcDP.bUseNSHAD  = bUseNSHAD;
-#endif
 }
 
@@ -453,9 +439,5 @@
 }
 
-#if WEIGHTED_CHROMA_DISTORTION
 UInt TComRdCost::getDistPart(Int bitDepth, Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, TextType eText, DFunc eDFunc)
-#else
-UInt TComRdCost::getDistPart(Int bitDepth, Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, DFunc eDFunc )
-#endif
 {
   DistParam cDtParam;
@@ -471,5 +453,4 @@
   cDtParam.bitDepth = bitDepth;
 
-#if WEIGHTED_CHROMA_DISTORTION
   if (eText == TEXT_CHROMA_U)
   {
@@ -484,26 +465,5 @@
     return cDtParam.DistFunc( &cDtParam );
   }
-#else
-  return cDtParam.DistFunc( &cDtParam );
-#endif
-}
-
-#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
-UInt TComRdCost::getSADPart ( Int bitDepth, Pel* pelCur, Int curStride,  Pel* pelOrg, Int orgStride, UInt width, UInt height )
-{
-  UInt SAD = 0;
-  Int shift = DISTORTION_PRECISION_ADJUSTMENT(bitDepth-8);
-  for ( Int i=0; i<height; i++ )
-  {
-    for( Int j=0; j<width; j++ )
-    {
-      SAD += abs((pelCur[j] - pelOrg[j])) >> shift;
-    }
-    pelCur = pelCur + curStride;
-    pelOrg = pelOrg + orgStride;
-  }
-  return SAD;
-}
-#endif
+}
 
 // ====================================================================================================================
@@ -1579,252 +1539,4 @@
 }
 
-#if NS_HAD
-UInt TComRdCost::xCalcHADs16x4( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
-{
-  Int k, i, j, jj, sad=0;
-  Int diff[64], m1[4][16], m2[4][16];
-  assert( iStep == 1 );
-  for( k = 0; k < 64; k += 16 )
-  {
-    diff[k+0] = piOrg[0] - piCur[0];
-    diff[k+1] = piOrg[1] - piCur[1];
-    diff[k+2] = piOrg[2] - piCur[2];
-    diff[k+3] = piOrg[3] - piCur[3];
-    diff[k+4] = piOrg[4] - piCur[4];
-    diff[k+5] = piOrg[5] - piCur[5];
-    diff[k+6] = piOrg[6] - piCur[6];
-    diff[k+7] = piOrg[7] - piCur[7];
-
-    diff[k+8]  = piOrg[8]  - piCur[8] ;
-    diff[k+9]  = piOrg[9]  - piCur[9] ;
-    diff[k+10] = piOrg[10] - piCur[10];
-    diff[k+11] = piOrg[11] - piCur[11];
-    diff[k+12] = piOrg[12] - piCur[12];
-    diff[k+13] = piOrg[13] - piCur[13];
-    diff[k+14] = piOrg[14] - piCur[14];
-    diff[k+15] = piOrg[15] - piCur[15];
-
-    piCur += iStrideCur;
-    piOrg += iStrideOrg;
-  }
-
-  //horizontal
-  for (j=0; j < 4; j++)
-  {
-    jj = j << 4;
-
-    m2[j][0]  = diff[jj  ] + diff[jj+8];
-    m2[j][1]  = diff[jj+1] + diff[jj+9];
-    m2[j][2]  = diff[jj+2] + diff[jj+10];
-    m2[j][3]  = diff[jj+3] + diff[jj+11];
-    m2[j][4]  = diff[jj+4] + diff[jj+12];
-    m2[j][5]  = diff[jj+5] + diff[jj+13];
-    m2[j][6]  = diff[jj+6] + diff[jj+14];
-    m2[j][7]  = diff[jj+7] + diff[jj+15];
-    m2[j][8]  = diff[jj  ] - diff[jj+8];
-    m2[j][9]  = diff[jj+1] - diff[jj+9];
-    m2[j][10] = diff[jj+2] - diff[jj+10];
-    m2[j][11] = diff[jj+3] - diff[jj+11];
-    m2[j][12] = diff[jj+4] - diff[jj+12];
-    m2[j][13] = diff[jj+5] - diff[jj+13];
-    m2[j][14] = diff[jj+6] - diff[jj+14];
-    m2[j][15] = diff[jj+7] - diff[jj+15];
-
-    m1[j][0]  = m2[j][0]  + m2[j][4];
-    m1[j][1]  = m2[j][1]  + m2[j][5];
-    m1[j][2]  = m2[j][2]  + m2[j][6];
-    m1[j][3]  = m2[j][3]  + m2[j][7];
-    m1[j][4]  = m2[j][0]  - m2[j][4];
-    m1[j][5]  = m2[j][1]  - m2[j][5];
-    m1[j][6]  = m2[j][2]  - m2[j][6];
-    m1[j][7]  = m2[j][3]  - m2[j][7];
-    m1[j][8]  = m2[j][8]  + m2[j][12];
-    m1[j][9]  = m2[j][9]  + m2[j][13];
-    m1[j][10] = m2[j][10] + m2[j][14];
-    m1[j][11] = m2[j][11] + m2[j][15];
-    m1[j][12] = m2[j][8]  - m2[j][12];
-    m1[j][13] = m2[j][9]  - m2[j][13];
-    m1[j][14] = m2[j][10] - m2[j][14];
-    m1[j][15] = m2[j][11] - m2[j][15];
-
-    m2[j][0]  = m1[j][0]  + m1[j][2];
-    m2[j][1]  = m1[j][1]  + m1[j][3];
-    m2[j][2]  = m1[j][0]  - m1[j][2];
-    m2[j][3]  = m1[j][1]  - m1[j][3];
-    m2[j][4]  = m1[j][4]  + m1[j][6];
-    m2[j][5]  = m1[j][5]  + m1[j][7];
-    m2[j][6]  = m1[j][4]  - m1[j][6];
-    m2[j][7]  = m1[j][5]  - m1[j][7];
-    m2[j][8]  = m1[j][8]  + m1[j][10];
-    m2[j][9]  = m1[j][9]  + m1[j][11];
-    m2[j][10] = m1[j][8]  - m1[j][10];
-    m2[j][11] = m1[j][9]  - m1[j][11];
-    m2[j][12] = m1[j][12] + m1[j][14];
-    m2[j][13] = m1[j][13] + m1[j][15];
-    m2[j][14] = m1[j][12] - m1[j][14];
-    m2[j][15] = m1[j][13] - m1[j][15];
-
-    m1[j][0]  = m2[j][0]  + m2[j][1];
-    m1[j][1]  = m2[j][0]  - m2[j][1];
-    m1[j][2]  = m2[j][2]  + m2[j][3];
-    m1[j][3]  = m2[j][2]  - m2[j][3];
-    m1[j][4]  = m2[j][4]  + m2[j][5];
-    m1[j][5]  = m2[j][4]  - m2[j][5];
-    m1[j][6]  = m2[j][6]  + m2[j][7];
-    m1[j][7]  = m2[j][6]  - m2[j][7];
-    m1[j][8]  = m2[j][8]  + m2[j][9];
-    m1[j][9]  = m2[j][8]  - m2[j][9];
-    m1[j][10] = m2[j][10] + m2[j][11];
-    m1[j][11] = m2[j][10] - m2[j][11];
-    m1[j][12] = m2[j][12] + m2[j][13];
-    m1[j][13] = m2[j][12] - m2[j][13];
-    m1[j][14] = m2[j][14] + m2[j][15];
-    m1[j][15] = m2[j][14] - m2[j][15];
-  }
-
-  //vertical
-  for (i=0; i < 16; i++)
-  {
-    m2[0][i] = m1[0][i] + m1[2][i];
-    m2[1][i] = m1[1][i] + m1[3][i];
-    m2[2][i] = m1[0][i] - m1[2][i];
-    m2[3][i] = m1[1][i] - m1[3][i];
-
-    m1[0][i] = m2[0][i] + m2[1][i];
-    m1[1][i] = m2[0][i] - m2[1][i];
-    m1[2][i] = m2[2][i] + m2[3][i];
-    m1[3][i] = m2[2][i] - m2[3][i];
-  }
-
-  for (i = 0; i < 4; i++)
-  {
-    for (j = 0; j < 16; j++)
-    {
-      sad += abs(m1[i][j]);
-    }
-  }
-
-  sad=((sad+2)>>2);
-
-  return sad;
-}
-
-UInt TComRdCost::xCalcHADs4x16( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
-{
-  Int k, i, j, jj, sad=0;
-  Int diff[64], m1[16][4], m2[16][4], m3[16][4];
-  assert( iStep == 1 );
-  for( k = 0; k < 64; k += 4 )
-  {
-    diff[k+0] = piOrg[0] - piCur[0];
-    diff[k+1] = piOrg[1] - piCur[1];
-    diff[k+2] = piOrg[2] - piCur[2];
-    diff[k+3] = piOrg[3] - piCur[3];
-
-    piCur += iStrideCur;
-    piOrg += iStrideOrg;
-  }
-
-  //horizontal
-  for (j=0; j < 16; j++)
-  {
-    jj = j << 2;
-    m2[j][0] = diff[jj  ] + diff[jj+2];
-    m2[j][1] = diff[jj+1] + diff[jj+3];
-    m2[j][2] = diff[jj  ] - diff[jj+2];
-    m2[j][3] = diff[jj+1] - diff[jj+3];
-
-    m1[j][0] = m2[j][0] + m2[j][1];
-    m1[j][1] = m2[j][0] - m2[j][1];
-    m1[j][2] = m2[j][2] + m2[j][3];
-    m1[j][3] = m2[j][2] - m2[j][3];
-  }
-
-  //vertical
-  for (i=0; i < 4; i++)
-  {
-    m2[0][i]  = m1[0][i] + m1[8][i];
-    m2[1][i]  = m1[1][i] + m1[9][i];
-    m2[2][i]  = m1[2][i] + m1[10][i];
-    m2[3][i]  = m1[3][i] + m1[11][i];
-    m2[4][i]  = m1[4][i] + m1[12][i];
-    m2[5][i]  = m1[5][i] + m1[13][i];
-    m2[6][i]  = m1[6][i] + m1[14][i];
-    m2[7][i]  = m1[7][i] + m1[15][i];
-    m2[8][i]  = m1[0][i] - m1[8][i];
-    m2[9][i]  = m1[1][i] - m1[9][i];
-    m2[10][i] = m1[2][i] - m1[10][i];
-    m2[11][i] = m1[3][i] - m1[11][i];
-    m2[12][i] = m1[4][i] - m1[12][i];
-    m2[13][i] = m1[5][i] - m1[13][i];
-    m2[14][i] = m1[6][i] - m1[14][i];
-    m2[15][i] = m1[7][i] - m1[15][i];
-
-    m3[0][i]  = m2[0][i]  + m2[4][i];
-    m3[1][i]  = m2[1][i]  + m2[5][i];
-    m3[2][i]  = m2[2][i]  + m2[6][i];
-    m3[3][i]  = m2[3][i]  + m2[7][i];
-    m3[4][i]  = m2[0][i]  - m2[4][i];
-    m3[5][i]  = m2[1][i]  - m2[5][i];
-    m3[6][i]  = m2[2][i]  - m2[6][i];
-    m3[7][i]  = m2[3][i]  - m2[7][i];
-    m3[8][i]  = m2[8][i]  + m2[12][i];
-    m3[9][i]  = m2[9][i]  + m2[13][i];
-    m3[10][i] = m2[10][i] + m2[14][i];
-    m3[11][i] = m2[11][i] + m2[15][i];
-    m3[12][i] = m2[8][i]  - m2[12][i];
-    m3[13][i] = m2[9][i]  - m2[13][i];
-    m3[14][i] = m2[10][i] - m2[14][i];
-    m3[15][i] = m2[11][i] - m2[15][i];
-
-    m1[0][i]  = m3[0][i]  + m3[2][i];
-    m1[1][i]  = m3[1][i]  + m3[3][i];
-    m1[2][i]  = m3[0][i]  - m3[2][i];
-    m1[3][i]  = m3[1][i]  - m3[3][i];
-    m1[4][i]  = m3[4][i]  + m3[6][i];
-    m1[5][i]  = m3[5][i]  + m3[7][i];
-    m1[6][i]  = m3[4][i]  - m3[6][i];
-    m1[7][i]  = m3[5][i]  - m3[7][i];
-    m1[8][i]  = m3[8][i]  + m3[10][i];
-    m1[9][i]  = m3[9][i]  + m3[11][i];
-    m1[10][i] = m3[8][i]  - m3[10][i];
-    m1[11][i] = m3[9][i]  - m3[11][i];
-    m1[12][i] = m3[12][i] + m3[14][i];
-    m1[13][i] = m3[13][i] + m3[15][i];
-    m1[14][i] = m3[12][i] - m3[14][i];
-    m1[15][i] = m3[13][i] - m3[15][i];
-
-    m2[0][i]  = m1[0][i]  + m1[1][i];
-    m2[1][i]  = m1[0][i]  - m1[1][i];
-    m2[2][i]  = m1[2][i]  + m1[3][i];
-    m2[3][i]  = m1[2][i]  - m1[3][i];
-    m2[4][i]  = m1[4][i]  + m1[5][i];
-    m2[5][i]  = m1[4][i]  - m1[5][i];
-    m2[6][i]  = m1[6][i]  + m1[7][i];
-    m2[7][i]  = m1[6][i]  - m1[7][i];
-    m2[8][i]  = m1[8][i]  + m1[9][i];
-    m2[9][i]  = m1[8][i]  - m1[9][i];
-    m2[10][i] = m1[10][i] + m1[11][i];
-    m2[11][i] = m1[10][i] - m1[11][i];
-    m2[12][i] = m1[12][i] + m1[13][i];
-    m2[13][i] = m1[12][i] - m1[13][i];
-    m2[14][i] = m1[14][i] + m1[15][i];
-    m2[15][i] = m1[14][i] - m1[15][i];
-  }
-
-  for (i = 0; i < 16; i++)
-  {
-    for (j = 0; j < 4; j++)
-    {
-      sad += abs(m2[i][j]);
-    }
-  }
-
-  sad=((sad+2)>>2);
-
-  return sad;
-}
-#endif
-
 UInt TComRdCost::xGetHADs4( DistParam* pcDtParam )
 {
@@ -1909,9 +1621,5 @@
   UInt uiSum = 0;
 
-#if NS_HAD
-  if( ( ( iRows % 8 == 0) && (iCols % 8 == 0) && ( iRows == iCols ) ) || ( ( iRows % 8 == 0 ) && (iCols % 8 == 0) && !pcDtParam->bUseNSHAD ) )
-#else
   if( ( iRows % 8 == 0) && (iCols % 8 == 0) )
-#endif
   {
     Int  iOffsetOrg = iStrideOrg<<3;
@@ -1927,34 +1635,4 @@
     }
   }
-#if NS_HAD
-  else if ( ( iCols > 8 ) && ( iCols > iRows ) && pcDtParam->bUseNSHAD )
-  {
-    Int  iOffsetOrg = iStrideOrg<<2;
-    Int  iOffsetCur = iStrideCur<<2;
-    for ( y=0; y<iRows; y+= 4 )
-    {
-      for ( x=0; x<iCols; x+= 16 )
-      {
-        uiSum += xCalcHADs16x4( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
-      }
-      piOrg += iOffsetOrg;
-      piCur += iOffsetCur;
-    }
-  }
-  else if ( ( iRows > 8 ) && ( iCols < iRows ) && pcDtParam->bUseNSHAD )
-  {
-    Int  iOffsetOrg = iStrideOrg<<4;
-    Int  iOffsetCur = iStrideCur<<4;
-    for ( y=0; y<iRows; y+= 16 )
-    {
-      for ( x=0; x<iCols; x+= 4 )
-      {
-        uiSum += xCalcHADs4x16( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
-      }
-      piOrg += iOffsetOrg;
-      piCur += iOffsetCur;
-    }
-  }
-#endif
   else if( ( iRows % 4 == 0) && (iCols % 4 == 0) )
   {
Index: branches/SHM-4.1-dev/source/Lib/TLibCommon/TComRdCost.h
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibCommon/TComRdCost.h	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibCommon/TComRdCost.h	(revision 532)
@@ -84,8 +84,4 @@
   UInt            uiComp;           // uiComp = 0 (luma Y), 1 (chroma U), 2 (chroma V)
 
-#if NS_HAD
-  Bool            bUseNSHAD;
-#endif
-
   // (vertical) subsampling shift (for reducing complexity)
   // - 0 = no subsampling, 1 = even rows, 2 = every 4th, etc.
@@ -104,7 +100,4 @@
     iSubShift = 0;
     bitDepth = 0;
-#if NS_HAD
-    bUseNSHAD = false;
-#endif
   }
 };
@@ -123,8 +116,6 @@
 #endif  
   
-#if WEIGHTED_CHROMA_DISTORTION
   Double                  m_cbDistortionWeight; 
   Double                  m_crDistortionWeight; 
-#endif
   Double                  m_dLambda;
   Double                  m_sqrtLambda;
@@ -155,8 +146,6 @@
   Double  calcRdCost64( UInt64 uiBits, UInt64 uiDistortion, Bool bFlag = false, DFunc eDFunc = DF_DEFAULT );
   
-#if WEIGHTED_CHROMA_DISTORTION
   Void    setCbDistortionWeight      ( Double cbDistortionWeight) { m_cbDistortionWeight = cbDistortionWeight; };
   Void    setCrDistortionWeight      ( Double crDistortionWeight) { m_crDistortionWeight = crDistortionWeight; };
-#endif
   Void    setLambda      ( Double dLambda );
   Void    setFrameLambda ( Double dLambda ) { m_dFrameLambda = dLambda; }
@@ -164,10 +153,6 @@
   Double  getSqrtLambda ()   { return m_sqrtLambda; }
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
   Double  getLambda() { return m_dLambda; }
-#if M0036_RC_IMPROVEMENT
   Double  getChromaWeight () {return((m_cbDistortionWeight+m_crDistortionWeight)/2.0);}
-#endif
-#endif
   
   // Distortion Functions
@@ -176,11 +161,6 @@
   Void    setDistParam( UInt uiBlkWidth, UInt uiBlkHeight, DFunc eDFunc, DistParam& rcDistParam );
   Void    setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride,            DistParam& rcDistParam );
-#if NS_HAD
-  Void    setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, Int iStep, DistParam& rcDistParam, Bool bHADME=false, Bool bUseNSHAD=false );
-  Void    setDistParam( DistParam& rcDP, Int bitDepth, Pel* p1, Int iStride1, Pel* p2, Int iStride2, Int iWidth, Int iHeight, Bool bHadamard = false, Bool bUseNSHAD=false );
-#else
   Void    setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, Int iStep, DistParam& rcDistParam, Bool bHADME=false );
   Void    setDistParam( DistParam& rcDP, Int bitDepth, Pel* p1, Int iStride1, Pel* p2, Int iStride2, Int iWidth, Int iHeight, Bool bHadamard = false );
-#endif
   
   UInt    calcHAD(Int bitDepth, Pel* pi0, Int iStride0, Pel* pi1, Int iStride1, Int iWidth, Int iHeight );
@@ -253,19 +233,8 @@
   static UInt xCalcHADs4x4      ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
   static UInt xCalcHADs8x8      ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
-#if NS_HAD
-  static UInt xCalcHADs16x4     ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
-  static UInt xCalcHADs4x16     ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
-#endif
   
 public:
-#if WEIGHTED_CHROMA_DISTORTION
   UInt   getDistPart(Int bitDepth, Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, TextType eText = TEXT_LUMA, DFunc eDFunc = DF_SSE );
-#else
-  UInt   getDistPart(Int bitDepth, Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, DFunc eDFunc = DF_SSE );
-#endif
-
-#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
-  UInt   getSADPart ( Int bitDepth, Pel* pelCur, Int curStride,  Pel* pelOrg, Int orgStride, UInt width, UInt height );
-#endif
+
 };// END CLASS DEFINITION TComRdCost
 
Index: branches/SHM-4.1-dev/source/Lib/TLibCommon/TComRom.cpp
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibCommon/TComRom.cpp	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibCommon/TComRom.cpp	(revision 532)
@@ -363,15 +363,4 @@
 const UInt g_uiGroupIdx[ 32 ]   = {0,1,2,3,4,4,5,5,6,6,6,6,7,7,7,7,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9};
 
-// Rice parameters for absolute transform levels
-const UInt g_auiGoRiceRange[5] =
-{
-  7, 14, 26, 46, 78
-};
-
-const UInt g_auiGoRicePrefixLen[5] =
-{
-  8, 7, 6, 5, 4
-};
-
 Void initSigLastScan(UInt* pBuffD, UInt* pBuffH, UInt* pBuffV, Int iWidth, Int iHeight)
 {
Index: branches/SHM-4.1-dev/source/Lib/TLibCommon/TComRom.h
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibCommon/TComRom.h	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibCommon/TComRom.h	(revision 532)
@@ -131,7 +131,4 @@
 extern const UInt   g_uiMinInGroup[ 10 ];
 
-extern const UInt   g_auiGoRiceRange[5];                  //!< maximum value coded with Rice codes
-extern const UInt   g_auiGoRicePrefixLen[5];              //!< prefix length for each maximum value
-  
 extern const UInt   g_sigLastScan8x8[ 3 ][ 4 ];           //!< coefficient group scan order for 8x8 TUs
 extern       UInt   g_sigLastScanCG32x32[ 64 ];
Index: branches/SHM-4.1-dev/source/Lib/TLibCommon/TComSampleAdaptiveOffset.cpp
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibCommon/TComSampleAdaptiveOffset.cpp	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibCommon/TComSampleAdaptiveOffset.cpp	(revision 532)
@@ -44,4 +44,659 @@
 //! \ingroup TLibCommon
 //! \{
+#if HM_CLEANUP_SAO
+UInt g_saoMaxOffsetQVal[NUM_SAO_COMPONENTS]; 
+
+SAOOffset::SAOOffset()
+{ 
+  reset();
+}
+
+SAOOffset::~SAOOffset()
+{
+
+}
+
+Void SAOOffset::reset()
+{
+  modeIdc = SAO_MODE_OFF;
+  typeIdc = -1;
+  typeAuxInfo = -1;
+  ::memset(offset, 0, sizeof(Int)* MAX_NUM_SAO_CLASSES);
+}
+
+const SAOOffset& SAOOffset::operator= (const SAOOffset& src)
+{
+  modeIdc = src.modeIdc;
+  typeIdc = src.typeIdc;
+  typeAuxInfo = src.typeAuxInfo;
+  ::memcpy(offset, src.offset, sizeof(Int)* MAX_NUM_SAO_CLASSES);
+
+  return *this;
+}
+
+
+SAOBlkParam::SAOBlkParam()
+{
+  reset();
+}
+
+SAOBlkParam::~SAOBlkParam()
+{
+
+}
+
+Void SAOBlkParam::reset()
+{
+  for(Int compIdx=0; compIdx< 3; compIdx++)
+  {
+    offsetParam[compIdx].reset();
+  }
+}
+
+const SAOBlkParam& SAOBlkParam::operator= (const SAOBlkParam& src)
+{
+  for(Int compIdx=0; compIdx< 3; compIdx++)
+  {
+    offsetParam[compIdx] = src.offsetParam[compIdx];
+  }
+  return *this;
+
+}
+
+TComSampleAdaptiveOffset::TComSampleAdaptiveOffset()
+{
+  m_tempPicYuv = NULL;
+  for(Int compIdx=0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
+  {
+    m_offsetClipTable[compIdx] = NULL;
+  }
+  m_signTable = NULL; 
+
+  
+  m_lineBufWidth = 0;
+  m_signLineBuf1 = NULL;
+  m_signLineBuf2 = NULL;
+}
+
+
+TComSampleAdaptiveOffset::~TComSampleAdaptiveOffset()
+{
+  destroy();
+  
+  if (m_signLineBuf1) delete[] m_signLineBuf1; m_signLineBuf1 = NULL;
+  if (m_signLineBuf2) delete[] m_signLineBuf2; m_signLineBuf2 = NULL;
+}
+
+#if AUXILIARY_PICTURES
+Void TComSampleAdaptiveOffset::create( Int picWidth, Int picHeight, ChromaFormat chromaFormatIDC, UInt maxCUWidth, UInt maxCUHeight, UInt maxCUDepth )
+#else
+Void TComSampleAdaptiveOffset::create( Int picWidth, Int picHeight, UInt maxCUWidth, UInt maxCUHeight, UInt maxCUDepth )
+#endif
+{
+  destroy();
+
+  m_picWidth = picWidth;    
+  m_picHeight= picHeight;
+  m_maxCUWidth= maxCUWidth; 
+  m_maxCUHeight= maxCUHeight;
+
+  m_numCTUInWidth = (m_picWidth/m_maxCUWidth) + ((m_picWidth % m_maxCUWidth)?1:0);
+  m_numCTUInHeight= (m_picHeight/m_maxCUHeight) + ((m_picHeight % m_maxCUHeight)?1:0);
+  m_numCTUsPic = m_numCTUInHeight*m_numCTUInWidth;
+
+  //temporary picture buffer
+  if ( !m_tempPicYuv )
+  {
+    m_tempPicYuv = new TComPicYuv;
+#if AUXILIARY_PICTURES
+    m_tempPicYuv->create( m_picWidth, m_picHeight, chromaFormatIDC, m_maxCUWidth, m_maxCUHeight, maxCUDepth );
+#else
+    m_tempPicYuv->create( m_picWidth, m_picHeight, m_maxCUWidth, m_maxCUHeight, maxCUDepth );
+#endif
+  }
+
+  //bit-depth related
+  for(Int compIdx =0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
+  {
+    Int bitDepthSample = (compIdx == SAO_Y)?g_bitDepthY:g_bitDepthC;
+    m_offsetStepLog2  [compIdx] = max(bitDepthSample - MAX_SAO_TRUNCATED_BITDEPTH, 0);
+    g_saoMaxOffsetQVal[compIdx] = (1<<(min(bitDepthSample,MAX_SAO_TRUNCATED_BITDEPTH)-5))-1; //Table 9-32, inclusive
+  }
+
+  //look-up table for clipping
+  for(Int compIdx =0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
+  {
+    Int bitDepthSample = (compIdx == SAO_Y)?g_bitDepthY:g_bitDepthC; //exclusive
+    Int maxSampleValue = (1<< bitDepthSample); //exclusive
+    Int maxOffsetValue = (g_saoMaxOffsetQVal[compIdx] << m_offsetStepLog2[compIdx]); 
+
+    m_offsetClipTable[compIdx] = new Int[(maxSampleValue + maxOffsetValue -1)+ (maxOffsetValue)+1 ]; //positive & negative range plus 0
+    m_offsetClip[compIdx] = &(m_offsetClipTable[compIdx][maxOffsetValue]);
+
+    //assign clipped values 
+    Int* offsetClipPtr = m_offsetClip[compIdx];
+    for(Int k=0; k< maxSampleValue; k++)
+    {
+      *(offsetClipPtr + k) = k;
+    }
+    for(Int k=0; k< maxOffsetValue; k++ )
+    {
+      *(offsetClipPtr + maxSampleValue+ k) = maxSampleValue-1;
+      *(offsetClipPtr -k -1 )              = 0;
+    }
+    if(compIdx == SAO_Y) //g_bitDepthY is always larger than or equal to g_bitDepthC
+    {
+      m_signTable = new Short[ 2*(maxSampleValue-1) + 1 ];
+      m_sign = &(m_signTable[maxSampleValue-1]);
+
+      m_sign[0] = 0;
+      for(Int k=1; k< maxSampleValue; k++)
+      {
+        m_sign[k] = 1;
+        m_sign[-k]= -1;
+      }
+    }
+  }  
+
+}
+
+Void TComSampleAdaptiveOffset::destroy()
+{
+  if ( m_tempPicYuv )
+  {
+    m_tempPicYuv->destroy();
+    delete m_tempPicYuv;
+    m_tempPicYuv = NULL;
+  }
+
+  for(Int compIdx=0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
+  {
+    if(m_offsetClipTable[compIdx])
+    {
+      delete[] m_offsetClipTable[compIdx]; m_offsetClipTable[compIdx] = NULL;
+    }
+  }
+  if( m_signTable )
+  {
+    delete[] m_signTable; m_signTable = NULL;
+  }
+}
+
+Void TComSampleAdaptiveOffset::invertQuantOffsets(Int compIdx, Int typeIdc, Int typeAuxInfo, Int* dstOffsets, Int* srcOffsets)
+{
+  Int codedOffset[MAX_NUM_SAO_CLASSES];
+
+  ::memcpy(codedOffset, srcOffsets, sizeof(Int)*MAX_NUM_SAO_CLASSES);
+  ::memset(dstOffsets, 0, sizeof(Int)*MAX_NUM_SAO_CLASSES);
+
+  if(typeIdc == SAO_TYPE_START_BO)
+  {
+    for(Int i=0; i< 4; i++)
+    {
+      dstOffsets[(typeAuxInfo+ i)%NUM_SAO_BO_CLASSES] = codedOffset[(typeAuxInfo+ i)%NUM_SAO_BO_CLASSES]*(1<<m_offsetStepLog2[compIdx]);
+    }
+  }
+  else //EO
+  {
+    for(Int i=0; i< NUM_SAO_EO_CLASSES; i++)
+    {
+      dstOffsets[i] = codedOffset[i] *(1<<m_offsetStepLog2[compIdx]);
+    }
+    assert(dstOffsets[SAO_CLASS_EO_PLAIN] == 0); //keep EO plain offset as zero
+  }
+
+}
+
+Int TComSampleAdaptiveOffset::getMergeList(TComPic* pic, Int ctu, SAOBlkParam* blkParams, std::vector<SAOBlkParam*>& mergeList)
+{
+  Int ctuX = ctu % m_numCTUInWidth;
+  Int ctuY = ctu / m_numCTUInWidth;
+  Int mergedCTUPos;
+  Int numValidMergeCandidates = 0;
+
+  for(Int mergeType=0; mergeType< NUM_SAO_MERGE_TYPES; mergeType++)
+  {
+    SAOBlkParam* mergeCandidate = NULL;
+
+    switch(mergeType)
+    {
+    case SAO_MERGE_ABOVE:
+      {
+        if(ctuY > 0)
+        {
+          mergedCTUPos = ctu- m_numCTUInWidth;
+          if( pic->getSAOMergeAvailability(ctu, mergedCTUPos) )
+          {
+            mergeCandidate = &(blkParams[mergedCTUPos]);
+          }
+        }
+      }
+      break;
+    case SAO_MERGE_LEFT:
+      {
+        if(ctuX > 0)
+        {
+          mergedCTUPos = ctu- 1;
+          if( pic->getSAOMergeAvailability(ctu, mergedCTUPos) )
+          {
+            mergeCandidate = &(blkParams[mergedCTUPos]);
+          }
+        }
+      }
+      break;
+    default:
+      {
+        printf("not a supported merge type");
+        assert(0);
+        exit(-1);
+      }
+    }
+
+    mergeList.push_back(mergeCandidate);
+    if (mergeCandidate != NULL)
+    {
+      numValidMergeCandidates++;
+    }
+  }
+
+  return numValidMergeCandidates;
+}
+
+
+Void TComSampleAdaptiveOffset::reconstructBlkSAOParam(SAOBlkParam& recParam, std::vector<SAOBlkParam*>& mergeList)
+{
+  for(Int compIdx=0; compIdx< NUM_SAO_COMPONENTS; compIdx++)
+  {
+    SAOOffset& offsetParam = recParam[compIdx];
+
+    if(offsetParam.modeIdc == SAO_MODE_OFF)
+    {
+      continue;
+    }
+
+    switch(offsetParam.modeIdc)
+    {
+    case SAO_MODE_NEW:
+      {
+        invertQuantOffsets(compIdx, offsetParam.typeIdc, offsetParam.typeAuxInfo, offsetParam.offset, offsetParam.offset);
+      }
+      break;
+    case SAO_MODE_MERGE:
+      {
+        SAOBlkParam* mergeTarget = mergeList[offsetParam.typeIdc];
+        assert(mergeTarget != NULL);
+
+        offsetParam = (*mergeTarget)[compIdx];
+      }
+      break;
+    default:
+      {
+        printf("Not a supported mode");
+        assert(0);
+        exit(-1);
+      }
+    }
+  }
+}
+
+Void TComSampleAdaptiveOffset::reconstructBlkSAOParams(TComPic* pic, SAOBlkParam* saoBlkParams)
+{
+  m_picSAOEnabled[SAO_Y] = m_picSAOEnabled[SAO_Cb] = m_picSAOEnabled[SAO_Cr] = false;
+
+  for(Int ctu=0; ctu< m_numCTUsPic; ctu++)
+  {
+    std::vector<SAOBlkParam*> mergeList;
+    getMergeList(pic, ctu, saoBlkParams, mergeList);
+
+    reconstructBlkSAOParam(saoBlkParams[ctu], mergeList);
+
+    for(Int compIdx=0; compIdx< NUM_SAO_COMPONENTS; compIdx++)
+    {
+      if(saoBlkParams[ctu][compIdx].modeIdc != SAO_MODE_OFF)
+      {
+        m_picSAOEnabled[compIdx] = true;
+      }
+    }
+  }
+
+
+}
+
+
+Void TComSampleAdaptiveOffset::offsetBlock(Int compIdx, Int typeIdx, Int* offset  
+                                          , Pel* srcBlk, Pel* resBlk, Int srcStride, Int resStride,  Int width, Int height
+                                          , Bool isLeftAvail,  Bool isRightAvail, Bool isAboveAvail, Bool isBelowAvail, Bool isAboveLeftAvail, Bool isAboveRightAvail, Bool isBelowLeftAvail, Bool isBelowRightAvail)
+{
+  if(m_lineBufWidth != m_maxCUWidth)
+  {
+    m_lineBufWidth = m_maxCUWidth;
+    
+    if (m_signLineBuf1) delete[] m_signLineBuf1; m_signLineBuf1 = NULL;
+    m_signLineBuf1 = new Char[m_lineBufWidth+1];
+    
+    if (m_signLineBuf2) delete[] m_signLineBuf2; m_signLineBuf2 = NULL;
+    m_signLineBuf2 = new Char[m_lineBufWidth+1];
+  }
+
+  Int* offsetClip = m_offsetClip[compIdx];
+
+  Int x,y, startX, startY, endX, endY, edgeType;
+  Int firstLineStartX, firstLineEndX, lastLineStartX, lastLineEndX;
+  Char signLeft, signRight, signDown;
+
+  Pel* srcLine = srcBlk;
+  Pel* resLine = resBlk;
+
+  switch(typeIdx)
+  {
+  case SAO_TYPE_EO_0:
+    {
+      offset += 2;
+      startX = isLeftAvail ? 0 : 1;
+      endX   = isRightAvail ? width : (width -1);
+      for (y=0; y< height; y++)
+      {
+        signLeft = (Char)m_sign[srcLine[startX] - srcLine[startX-1]];
+        for (x=startX; x< endX; x++)
+        {
+          signRight = (Char)m_sign[srcLine[x] - srcLine[x+1]]; 
+          edgeType =  signRight + signLeft;
+          signLeft  = -signRight;
+
+          resLine[x] = offsetClip[srcLine[x] + offset[edgeType]];
+        }
+        srcLine  += srcStride;
+        resLine += resStride;
+      }
+
+    }
+    break;
+  case SAO_TYPE_EO_90:
+    {
+      offset += 2;
+      Char *signUpLine = m_signLineBuf1;
+
+      startY = isAboveAvail ? 0 : 1;
+      endY   = isBelowAvail ? height : height-1;
+      if (!isAboveAvail)
+      {
+        srcLine += srcStride;
+        resLine += resStride;
+      }
+
+      Pel* srcLineAbove= srcLine- srcStride;
+      for (x=0; x< width; x++)
+      {
+        signUpLine[x] = (Char)m_sign[srcLine[x] - srcLineAbove[x]];
+      }
+
+      Pel* srcLineBelow;
+      for (y=startY; y<endY; y++)
+      {
+        srcLineBelow= srcLine+ srcStride;
+
+        for (x=0; x< width; x++)
+        {
+          signDown  = (Char)m_sign[srcLine[x] - srcLineBelow[x]]; 
+          edgeType = signDown + signUpLine[x];
+          signUpLine[x]= -signDown;
+
+          resLine[x] = offsetClip[srcLine[x] + offset[edgeType]];
+        }
+        srcLine += srcStride;
+        resLine += resStride;
+      }
+
+    }
+    break;
+  case SAO_TYPE_EO_135:
+    {
+      offset += 2;
+      Char *signUpLine, *signDownLine, *signTmpLine;
+
+      signUpLine  = m_signLineBuf1;
+      signDownLine= m_signLineBuf2;
+
+      startX = isLeftAvail ? 0 : 1 ;
+      endX   = isRightAvail ? width : (width-1);
+
+      //prepare 2nd line's upper sign
+      Pel* srcLineBelow= srcLine+ srcStride;
+      for (x=startX; x< endX+1; x++)
+      {
+        signUpLine[x] = (Char)m_sign[srcLineBelow[x] - srcLine[x- 1]];
+      }
+
+      //1st line
+      Pel* srcLineAbove= srcLine- srcStride;
+      firstLineStartX = isAboveLeftAvail ? 0 : 1;
+      firstLineEndX   = isAboveAvail? endX: 1;
+      for(x= firstLineStartX; x< firstLineEndX; x++)
+      {
+        edgeType  =  m_sign[srcLine[x] - srcLineAbove[x- 1]] - signUpLine[x+1];
+        resLine[x] = offsetClip[srcLine[x] + offset[edgeType]];
+      }
+      srcLine  += srcStride;
+      resLine  += resStride;
+
+
+      //middle lines
+      for (y= 1; y< height-1; y++)
+      {
+        srcLineBelow= srcLine+ srcStride;
+
+        for (x=startX; x<endX; x++)
+        {
+          signDown =  (Char)m_sign[srcLine[x] - srcLineBelow[x+ 1]] ;
+          edgeType =  signDown + signUpLine[x];
+          resLine[x] = offsetClip[srcLine[x] + offset[edgeType]];
+
+          signDownLine[x+1] = -signDown; 
+        }
+        signDownLine[startX] = (Char)m_sign[srcLineBelow[startX] - srcLine[startX-1]];
+
+        signTmpLine  = signUpLine;
+        signUpLine   = signDownLine;
+        signDownLine = signTmpLine;
+
+        srcLine += srcStride;
+        resLine += resStride;
+      }
+
+      //last line
+      srcLineBelow= srcLine+ srcStride;
+      lastLineStartX = isBelowAvail ? startX : (width -1);
+      lastLineEndX   = isBelowRightAvail ? width : (width -1);
+      for(x= lastLineStartX; x< lastLineEndX; x++)
+      {
+        edgeType =  m_sign[srcLine[x] - srcLineBelow[x+ 1]] + signUpLine[x];
+        resLine[x] = offsetClip[srcLine[x] + offset[edgeType]];
+
+      }
+    }
+    break;
+  case SAO_TYPE_EO_45:
+    {
+      offset += 2;
+      Char *signUpLine = m_signLineBuf1+1;
+
+      startX = isLeftAvail ? 0 : 1;
+      endX   = isRightAvail ? width : (width -1);
+
+      //prepare 2nd line upper sign
+      Pel* srcLineBelow= srcLine+ srcStride;
+      for (x=startX-1; x< endX; x++)
+      {
+        signUpLine[x] = (Char)m_sign[srcLineBelow[x] - srcLine[x+1]];
+      }
+
+
+      //first line
+      Pel* srcLineAbove= srcLine- srcStride;
+      firstLineStartX = isAboveAvail ? startX : (width -1 );
+      firstLineEndX   = isAboveRightAvail ? width : (width-1);
+      for(x= firstLineStartX; x< firstLineEndX; x++)
+      {
+        edgeType = m_sign[srcLine[x] - srcLineAbove[x+1]] -signUpLine[x-1];
+        resLine[x] = offsetClip[srcLine[x] + offset[edgeType]];
+      }
+      srcLine += srcStride;
+      resLine += resStride;
+
+      //middle lines
+      for (y= 1; y< height-1; y++)
+      {
+        srcLineBelow= srcLine+ srcStride;
+
+        for(x= startX; x< endX; x++)
+        {
+          signDown =  (Char)m_sign[srcLine[x] - srcLineBelow[x-1]] ;
+          edgeType =  signDown + signUpLine[x];
+          resLine[x] = offsetClip[srcLine[x] + offset[edgeType]];
+          signUpLine[x-1] = -signDown; 
+        }
+        signUpLine[endX-1] = (Char)m_sign[srcLineBelow[endX-1] - srcLine[endX]];
+        srcLine  += srcStride;
+        resLine += resStride;
+      }
+
+      //last line
+      srcLineBelow= srcLine+ srcStride;
+      lastLineStartX = isBelowLeftAvail ? 0 : 1;
+      lastLineEndX   = isBelowAvail ? endX : 1;
+      for(x= lastLineStartX; x< lastLineEndX; x++)
+      {
+        edgeType = m_sign[srcLine[x] - srcLineBelow[x-1]] + signUpLine[x];
+        resLine[x] = offsetClip[srcLine[x] + offset[edgeType]];
+
+      }
+    }
+    break;
+  case SAO_TYPE_BO:
+    {
+      Int shiftBits = ((compIdx == SAO_Y)?g_bitDepthY:g_bitDepthC)- NUM_SAO_BO_CLASSES_LOG2;
+      for (y=0; y< height; y++)
+      {
+        for (x=0; x< width; x++)
+        {
+          resLine[x] = offsetClip[ srcLine[x] + offset[srcLine[x] >> shiftBits] ];
+        }
+        srcLine += srcStride;
+        resLine += resStride;
+      }
+    }
+    break;
+  default:
+    {
+      printf("Not a supported SAO types\n");
+      assert(0);
+      exit(-1);
+    }
+  }
+
+
+}
+
+Void TComSampleAdaptiveOffset::offsetCTU(Int ctu, TComPicYuv* srcYuv, TComPicYuv* resYuv, SAOBlkParam& saoblkParam, TComPic* pPic)
+{
+  Bool isLeftAvail,isRightAvail,isAboveAvail,isBelowAvail,isAboveLeftAvail,isAboveRightAvail,isBelowLeftAvail,isBelowRightAvail;
+
+  if( 
+    (saoblkParam[SAO_Y ].modeIdc == SAO_MODE_OFF) &&
+    (saoblkParam[SAO_Cb].modeIdc == SAO_MODE_OFF) &&
+    (saoblkParam[SAO_Cr].modeIdc == SAO_MODE_OFF)
+    )
+  {
+    return;
+  }
+
+  //block boundary availability
+  pPic->getPicSym()->deriveLoopFilterBoundaryAvailibility(ctu, isLeftAvail,isRightAvail,isAboveAvail,isBelowAvail,isAboveLeftAvail,isAboveRightAvail,isBelowLeftAvail,isBelowRightAvail);
+
+  Int yPos   = (ctu / m_numCTUInWidth)*m_maxCUHeight;
+  Int xPos   = (ctu % m_numCTUInWidth)*m_maxCUWidth;
+  Int height = (yPos + m_maxCUHeight > m_picHeight)?(m_picHeight- yPos):m_maxCUHeight;
+  Int width  = (xPos + m_maxCUWidth  > m_picWidth )?(m_picWidth - xPos):m_maxCUWidth;
+
+  for(Int compIdx= 0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
+  {
+    SAOOffset& ctbOffset = saoblkParam[compIdx];
+
+    if(ctbOffset.modeIdc != SAO_MODE_OFF)
+    {
+      Bool isLuma     = (compIdx == SAO_Y);
+      Int  formatShift= isLuma?0:1;
+
+      Int  blkWidth   = (width  >> formatShift);
+      Int  blkHeight  = (height >> formatShift);
+      Int  blkYPos    = (yPos   >> formatShift);
+      Int  blkXPos    = (xPos   >> formatShift);
+
+      Int  srcStride = isLuma?srcYuv->getStride():srcYuv->getCStride();
+      Pel* srcBlk    = getPicBuf(srcYuv, compIdx)+ (yPos >> formatShift)*srcStride+ (xPos >> formatShift);
+
+      Int  resStride  = isLuma?resYuv->getStride():resYuv->getCStride();
+      Pel* resBlk     = getPicBuf(resYuv, compIdx)+ blkYPos*resStride+ blkXPos;
+
+      offsetBlock( compIdx, ctbOffset.typeIdc, ctbOffset.offset
+                  , srcBlk, resBlk, srcStride, resStride, blkWidth, blkHeight
+                  , isLeftAvail, isRightAvail
+                  , isAboveAvail, isBelowAvail
+                  , isAboveLeftAvail, isAboveRightAvail
+                  , isBelowLeftAvail, isBelowRightAvail
+                  );
+    }
+  } //compIdx
+
+}
+
+
+Void TComSampleAdaptiveOffset::SAOProcess(TComPic* pDecPic)
+{
+  if(!m_picSAOEnabled[SAO_Y] && !m_picSAOEnabled[SAO_Cb] && !m_picSAOEnabled[SAO_Cr])
+  {
+    return;
+  }
+  TComPicYuv* resYuv = pDecPic->getPicYuvRec();
+  TComPicYuv* srcYuv = m_tempPicYuv;
+  resYuv->copyToPic(srcYuv);
+  for(Int ctu= 0; ctu < m_numCTUsPic; ctu++)
+  {
+    offsetCTU(ctu, srcYuv, resYuv, (pDecPic->getPicSym()->getSAOBlkParam())[ctu], pDecPic);
+  } //ctu
+}
+
+
+Pel* TComSampleAdaptiveOffset::getPicBuf(TComPicYuv* pPicYuv, Int compIdx)
+{
+  Pel* pBuf = NULL;
+  switch(compIdx)
+  {
+  case SAO_Y:
+    {
+      pBuf = pPicYuv->getLumaAddr();
+    }
+    break;
+  case SAO_Cb:
+    {
+      pBuf = pPicYuv->getCbAddr();
+    }
+    break;
+  case SAO_Cr:
+    {
+      pBuf = pPicYuv->getCrAddr();
+    }
+    break;
+  default:
+    {
+      printf("Not a legal component ID for SAO\n");
+      assert(0);
+      exit(-1);
+    }
+  }
+
+  return pBuf;
+}
+#else
 
 SAOParam::~SAOParam()
@@ -1364,5 +2019,5 @@
   }
 }
-
+#endif
 /** PCM LF disable process. 
  * \param pcPic picture (TComPic) pointer
Index: branches/SHM-4.1-dev/source/Lib/TLibCommon/TComSampleAdaptiveOffset.h
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibCommon/TComSampleAdaptiveOffset.h	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibCommon/TComSampleAdaptiveOffset.h	(revision 532)
@@ -45,4 +45,66 @@
 //! \{
 
+
+#if HM_CLEANUP_SAO
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+#define MAX_SAO_TRUNCATED_BITDEPTH     10 
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+extern UInt g_saoMaxOffsetQVal[NUM_SAO_COMPONENTS]; 
+
+class TComSampleAdaptiveOffset
+{
+public:
+  TComSampleAdaptiveOffset();
+  virtual ~TComSampleAdaptiveOffset();
+  Void SAOProcess(TComPic* pDecPic);
+#if AUXILIARY_PICTURES
+  Void create( Int picWidth, Int picHeight, ChromaFormat chromaFormatIDC, UInt maxCUWidth, UInt maxCUHeight, UInt maxCUDepth );
+#else
+  Void create( Int picWidth, Int picHeight, UInt maxCUWidth, UInt maxCUHeight, UInt maxCUDepth );
+#endif
+  Void destroy();
+  Void reconstructBlkSAOParams(TComPic* pic, SAOBlkParam* saoBlkParams);
+  Void PCMLFDisableProcess (TComPic* pcPic);
+protected:
+  Void offsetBlock(Int compIdx, Int typeIdx, Int* offset, Pel* srcBlk, Pel* resBlk, Int srcStride, Int resStride,  Int width, Int height
+                  , Bool isLeftAvail, Bool isRightAvail, Bool isAboveAvail, Bool isBelowAvail, Bool isAboveLeftAvail, Bool isAboveRightAvail, Bool isBelowLeftAvail, Bool isBelowRightAvail);
+  Pel* getPicBuf(TComPicYuv* pPicYuv, Int compIdx);
+  Void invertQuantOffsets(Int compIdx, Int typeIdc, Int typeAuxInfo, Int* dstOffsets, Int* srcOffsets);
+  Void reconstructBlkSAOParam(SAOBlkParam& recParam, std::vector<SAOBlkParam*>& mergeList);
+  Int  getMergeList(TComPic* pic, Int ctu, SAOBlkParam* blkParams, std::vector<SAOBlkParam*>& mergeList);
+  Void offsetCTU(Int ctu, TComPicYuv* srcYuv, TComPicYuv* resYuv, SAOBlkParam& saoblkParam, TComPic* pPic);
+  Void xPCMRestoration(TComPic* pcPic);
+  Void xPCMCURestoration ( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth );
+  Void xPCMSampleRestoration (TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, TextType ttText);
+protected:
+  UInt m_offsetStepLog2[NUM_SAO_COMPONENTS]; //offset step  
+  Int* m_offsetClip[NUM_SAO_COMPONENTS]; //clip table for fast operation
+  Short* m_sign; //sign table for fast operation
+  TComPicYuv*   m_tempPicYuv; //temporary buffer
+  Int m_picWidth;
+  Int m_picHeight;
+  Int m_maxCUWidth;
+  Int m_maxCUHeight;
+  Int m_numCTUInWidth;
+  Int m_numCTUInHeight;
+  Int m_numCTUsPic;
+  
+  
+  Int m_lineBufWidth;
+  Char* m_signLineBuf1;
+  Char* m_signLineBuf2;
+private:
+  Bool m_picSAOEnabled[NUM_SAO_COMPONENTS];
+  Int*   m_offsetClipTable[NUM_SAO_COMPONENTS];
+  Short* m_signTable;
+
+};
+#else
+
 // ====================================================================================================================
 // Constants
@@ -145,4 +207,6 @@
 };
 
+#endif
+
 //! \}
 #endif
Index: branches/SHM-4.1-dev/source/Lib/TLibCommon/TComSlice.cpp
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibCommon/TComSlice.cpp	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibCommon/TComSlice.cpp	(revision 532)
@@ -76,10 +76,4 @@
 , m_colFromL0Flag                 ( 1 )
 , m_colRefIdx                     ( 0 )
-#if SAO_CHROMA_LAMBDA
-, m_dLambdaLuma( 0.0 )
-, m_dLambdaChroma( 0.0 )
-#else
-, m_dLambda                       ( 0.0 )
-#endif
 , m_uiTLayer                      ( 0 )
 , m_bTLayerSwitchingFlag          ( false )
@@ -142,4 +136,9 @@
   initEqualRef();
   
+  for (Int component = 0; component < 3; component++)
+  {
+    m_lambdas[component] = 0.0;
+  }
+  
   for ( Int idx = 0; idx < MAX_NUM_REF; idx++ )
   {
@@ -156,4 +155,7 @@
   initWpAcDcParam();
   m_saoEnabledFlag = false;
+#if HM_CLEANUP_SAO
+  m_saoEnabledFlagChroma = false;
+#endif
 }
 
@@ -360,5 +362,4 @@
 }
 
-#if FIX1071
 #if SVC_EXTENSION
 Void TComSlice::setRefPicList( TComList<TComPic*>& rcListPic, Bool checkNumPocTotalCurr, TComPic** ilpPic)
@@ -366,11 +367,6 @@
 Void TComSlice::setRefPicList( TComList<TComPic*>& rcListPic, Bool checkNumPocTotalCurr )
 #endif
-#else
-Void TComSlice::setRefPicList( TComList<TComPic*>& rcListPic )
-#endif
-{
-#if FIX1071
+{
   if (!checkNumPocTotalCurr)
-#endif
   {
     if (m_eSliceType == I_SLICE)
@@ -602,5 +598,5 @@
   Int numPocTotalCurr = NumPocStCurr0 + NumPocStCurr1 + NumPocLtCurr;
 #endif //SVC_EXTENSION
-#if FIX1071
+
   if (checkNumPocTotalCurr)
   {
@@ -632,5 +628,4 @@
     m_aiNumRefIdx[1] = getNumRefIdx(REF_PIC_LIST_1);
   }
-#endif
 
 #if M0457_IL_SAMPLE_PRED_ONLY_FLAG
@@ -1192,10 +1187,5 @@
   m_colFromL0Flag        = pSrc->m_colFromL0Flag;
   m_colRefIdx            = pSrc->m_colRefIdx;
-#if SAO_CHROMA_LAMBDA 
-  m_dLambdaLuma          = pSrc->m_dLambdaLuma;
-  m_dLambdaChroma        = pSrc->m_dLambdaChroma;
-#else
-  m_dLambda              = pSrc->m_dLambda;
-#endif
+  setLambdas(pSrc->getLambdas());
   for (i = 0; i < 2; i++)
   {
@@ -1522,5 +1512,5 @@
     assert(rpcPic->getSlice( 0 )->isReferenced()==0||rpcPic->getUsedByCurr()==0||rpcPic->getTLayer()<=this->getTLayer());
     //check that pictures of higher or equal temporal layer are not in the RPS if the current picture is a TSA picture
-    if(this->getNalUnitType() == NAL_UNIT_CODED_SLICE_TLA_R || this->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_N)
+    if(this->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_R || this->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_N)
     {
       assert(rpcPic->getSlice( 0 )->isReferenced()==0||rpcPic->getTLayer()<this->getTLayer());
@@ -1681,9 +1671,5 @@
 /** Function for constructing an explicit Reference Picture Set out of the available pictures in a referenced Reference Picture Set
 */
-#if FIX1071
 Void TComSlice::createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool isRAP)
-#else
-Void TComSlice::createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet)
-#endif
 {
   TComPic* rpcPic;
@@ -1710,9 +1696,5 @@
         // and should be added to the explicit Reference Picture Set
         pcRPS->setDeltaPOC(k, pReferencePictureSet->getDeltaPOC(i));
-#if FIX1071
         pcRPS->setUsed(k, pReferencePictureSet->getUsed(i) && (!isRAP));
-#else
-        pcRPS->setUsed(k, pReferencePictureSet->getUsed(i));
-#endif
         if(pcRPS->getDeltaPOC(k) < 0)
         {
@@ -2870,5 +2852,5 @@
     for(UInt listId=0;listId<g_scalingListNum[sizeId];listId++)
     {
-      getScalingList()->processDefaultMarix(sizeId, listId);
+      getScalingList()->processDefaultMatrix(sizeId, listId);
     }
   }
@@ -3045,5 +3027,5 @@
  * \param Index of input matrix
  */
-Void TComScalingList::processDefaultMarix(UInt sizeId, UInt listId)
+Void TComScalingList::processDefaultMatrix(UInt sizeId, UInt listId)
 {
   ::memcpy(getScalingListAddress(sizeId, listId),getScalingListDefaultAddress(sizeId,listId),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]));
@@ -3062,5 +3044,5 @@
       if(getScalingListDC(sizeId,listId) == 0)
       {
-        processDefaultMarix(sizeId, listId);
+        processDefaultMatrix(sizeId, listId);
       }
     }
@@ -3250,5 +3232,5 @@
 #endif
 
-Void TComSlice::setBaseColPic(  TComList<TComPic*>& rcListPic, UInt refLayerIdc )
+Bool TComSlice::setBaseColPic(  TComList<TComPic*>& rcListPic, UInt refLayerIdc )
 {  
   if(m_layerId == 0)
@@ -3258,12 +3240,16 @@
   }        
 #if POC_RESET_FLAG
-  if( this->getPocResetFlag() )
-  {
-    setBaseColPic(refLayerIdc, xGetRefPic(rcListPic, 0)); 
+  TComPic* pic = xGetRefPic( rcListPic, m_bPocResetFlag ? 0 : m_iPOC );
+
+  if( pic )
+  {
+    setBaseColPic(refLayerIdc, pic );
   }
   else
   {
-    setBaseColPic(refLayerIdc, xGetRefPic(rcListPic, getPOC())); 
-  }
+    return false;
+  }
+  
+  return true;
 #else
   setBaseColPic(refLayerIdc, xGetRefPic(rcListPic, getPOC())); 
Index: branches/SHM-4.1-dev/source/Lib/TLibCommon/TComSlice.h
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibCommon/TComSlice.h	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibCommon/TComSlice.h	(revision 532)
@@ -156,5 +156,4 @@
   Void     setScalingListPresentFlag    (Bool b)                               { m_scalingListPresentFlag = b;    }
   Bool     getScalingListPresentFlag    ()                                     { return m_scalingListPresentFlag; }
-
   Int*     getScalingListAddress          (UInt sizeId, UInt listId)           { return m_scalingListCoef[sizeId][listId]; } //!< get matrix coefficient
   Bool     checkPredMode                  (UInt sizeId, UInt listId);
@@ -162,6 +161,7 @@
   UInt     getRefMatrixId                 (UInt sizeId, UInt listId)           { return m_refMatrixId[sizeId][listId]; }     //!< get reference matrix ID
   Int*     getScalingListDefaultAddress   (UInt sizeId, UInt listId);                                                        //!< get default matrix coefficient
-  Void     processDefaultMarix            (UInt sizeId, UInt listId);
+  Void     processDefaultMatrix            (UInt sizeId, UInt listId);
   Void     setScalingListDC               (UInt sizeId, UInt listId, UInt u)   { m_scalingListDC[sizeId][listId] = u; }      //!< set DC value
+
   Int      getScalingListDC               (UInt sizeId, UInt listId)           { return m_scalingListDC[sizeId][listId]; }   //!< get DC value
   Void     checkDcOfMatrix                ();
@@ -1579,7 +1579,5 @@
   Int      m_deblockingFilterTcOffsetDiv2;      //< tc offset for deblocking filter
   Bool     m_scalingListPresentFlag;
-
   TComScalingList*     m_scalingList;   //!< ScalingList class pointer
-
   Bool m_listsModificationPresentFlag;
   UInt m_log2ParallelMergeLevelMinus2;
@@ -1813,10 +1811,5 @@
   UInt        m_maxNumMergeCand;
 
-#if SAO_CHROMA_LAMBDA
-  Double      m_dLambdaLuma;
-  Double      m_dLambdaChroma;
-#else
-  Double      m_dLambda;
-#endif
+  Double      m_lambdas[3];
 
   Bool        m_abEqualRef  [2][MAX_NUM_REF][MAX_NUM_REF];
@@ -2004,12 +1997,8 @@
   Void      setDepth            ( Int iDepth )                  { m_iDepth            = iDepth; }
 
-#if FIX1071
 #if SVC_EXTENSION
   Void      setRefPicList       ( TComList<TComPic*>& rcListPic, Bool checkNumPocTotalCurr = false, TComPic** ilpPic = NULL );
 #else
   Void      setRefPicList       ( TComList<TComPic*>& rcListPic, Bool checkNumPocTotalCurr = false );
-#endif
-#else
-  Void      setRefPicList       ( TComList<TComPic*>& rcListPic );
 #endif
   Void      setRefPOCList       ();
@@ -2023,12 +2012,6 @@
   Bool      isInterP        ()                          { return  m_eSliceType == P_SLICE;  }
   
-#if SAO_CHROMA_LAMBDA  
-  Void      setLambda( Double d, Double e ) { m_dLambdaLuma = d; m_dLambdaChroma = e;}
-  Double    getLambdaLuma() { return m_dLambdaLuma;        }
-  Double    getLambdaChroma() { return m_dLambdaChroma;        }
-#else
-  Void      setLambda( Double d ) { m_dLambda = d; }
-  Double    getLambda() { return m_dLambda;        }
-#endif
+  Void      setLambdas ( const Double lambdas[3] ) { for (Int component = 0; component < 3; component++) m_lambdas[component] = lambdas[component]; }
+  const Double* getLambdas() const { return m_lambdas; }
   
   Void      initEqualRef();
@@ -2057,9 +2040,5 @@
   Bool isStepwiseTemporalLayerSwitchingPointCandidate( TComList<TComPic*>& rcListPic );
   Int       checkThatAllRefPicsAreAvailable( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool printErrors, Int pocRandomAccess = 0);
-#if FIX1071
   Void      createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool isRAP);
-#else
-  Void      createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet);
-#endif
 
   Void setMaxNumMergeCand               (UInt val )         { m_maxNumMergeCand = val;                    }
Index: branches/SHM-4.1-dev/source/Lib/TLibCommon/TComTrQuant.cpp
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibCommon/TComTrQuant.cpp	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibCommon/TComTrQuant.cpp	(revision 532)
@@ -54,8 +54,8 @@
   {
     iNNZbeforePos0 = 0;
-  d64CodedLevelandDist = 0;
-  d64UncodedDist = 0;
-  d64SigCost = 0;
-  d64SigCost_0 = 0;
+    d64CodedLevelandDist = 0;
+    d64UncodedDist = 0;
+    d64SigCost = 0;
+    d64SigCost_0 = 0;
   }
 #endif
@@ -1944,5 +1944,5 @@
               Int64 costUp   = rdFactor * ( - deltaU[uiBlkPos] ) + rateIncUp[uiBlkPos] ;
               Int64 costDown = rdFactor * (   deltaU[uiBlkPos] ) + rateIncDown[uiBlkPos] 
-              -   ( abs(piDstCoeff[uiBlkPos])==1?((1<<15)+sigRateDelta[uiBlkPos]):0 );
+              -   ((abs(piDstCoeff[uiBlkPos]) == 1) ? sigRateDelta[uiBlkPos] : 0);
               
               if(lastCG==1 && lastNZPosInCG==n && abs(piDstCoeff[uiBlkPos])==1)
@@ -2163,5 +2163,5 @@
   {
     Double dErr         = Double( lLevelDouble  - ( uiAbsLevel << iQBits ) );
-    Double dCurrCost    = dErr * dErr * dTemp + xGetICRateCost( uiAbsLevel, ui16CtxNumOne, ui16CtxNumAbs, ui16AbsGoRice, c1Idx, c2Idx );
+    Double dCurrCost    = dErr * dErr * dTemp + xGetICost(xGetICRate( uiAbsLevel, ui16CtxNumOne, ui16CtxNumAbs, ui16AbsGoRice, c1Idx, c2Idx ));
     dCurrCost          += dCurrCostSig;
 
@@ -2184,5 +2184,5 @@
  * \returns cost of given absolute transform level
  */
-__inline Double TComTrQuant::xGetICRateCost  ( UInt                            uiAbsLevel,
+__inline Int TComTrQuant::xGetICRate  ( UInt                            uiAbsLevel,
                                                UShort                          ui16CtxNumOne,
                                                UShort                          ui16CtxNumAbs,
@@ -2192,5 +2192,5 @@
                                                ) const
 {
-  Double iRate = xGetIEPRate();
+  Int iRate = Int(xGetIEPRate());
   UInt baseLevel  =  (c1Idx < C1FLAG_NUMBER)? (2 + (c2Idx < C2FLAG_NUMBER)) : 1;
 
@@ -2236,66 +2236,5 @@
   else
   {
-    assert (0);
-  }
-  return xGetICost( iRate );
-}
-
-__inline Int TComTrQuant::xGetICRate  ( UInt                            uiAbsLevel,
-                                       UShort                          ui16CtxNumOne,
-                                       UShort                          ui16CtxNumAbs,
-                                       UShort                          ui16AbsGoRice
-                                     , UInt                            c1Idx,
-                                       UInt                            c2Idx
-                                       ) const
-{
-  Int iRate = 0;
-  UInt baseLevel  =  (c1Idx < C1FLAG_NUMBER)? (2 + (c2Idx < C2FLAG_NUMBER)) : 1;
-
-  if ( uiAbsLevel >= baseLevel )
-  {
-    UInt uiSymbol     = uiAbsLevel - baseLevel;
-    UInt uiMaxVlc     = g_auiGoRiceRange[ ui16AbsGoRice ];
-    Bool bExpGolomb   = ( uiSymbol > uiMaxVlc );
-
-    if( bExpGolomb )
-    {
-      uiAbsLevel  = uiSymbol - uiMaxVlc;
-      Int iEGS    = 1;  for( UInt uiMax = 2; uiAbsLevel >= uiMax; uiMax <<= 1, iEGS += 2 );
-      iRate      += iEGS << 15;
-      uiSymbol    = min<UInt>( uiSymbol, ( uiMaxVlc + 1 ) );
-    }
-
-    UShort ui16PrefLen = UShort( uiSymbol >> ui16AbsGoRice ) + 1;
-    UShort ui16NumBins = min<UInt>( ui16PrefLen, g_auiGoRicePrefixLen[ ui16AbsGoRice ] ) + ui16AbsGoRice;
-
-    iRate += ui16NumBins << 15;
-
-    if (c1Idx < C1FLAG_NUMBER)
-    {
-      iRate += m_pcEstBitsSbac->m_greaterOneBits[ ui16CtxNumOne ][ 1 ];
-
-      if (c2Idx < C2FLAG_NUMBER)
-      {
-        iRate += m_pcEstBitsSbac->m_levelAbsBits[ ui16CtxNumAbs ][ 1 ];
-      }
-    }
-  }
-  else
-  if( uiAbsLevel == 0 )
-  {
-    return 0;
-  }
-  else if( uiAbsLevel == 1 )
-  {
-    iRate += m_pcEstBitsSbac->m_greaterOneBits[ ui16CtxNumOne ][ 0 ];
-  }
-  else if( uiAbsLevel == 2 )
-  {
-    iRate += m_pcEstBitsSbac->m_greaterOneBits[ ui16CtxNumOne ][ 1 ];
-    iRate += m_pcEstBitsSbac->m_levelAbsBits[ ui16CtxNumAbs ][ 0 ];
-  }
-  else
-  {
-    assert(0);
+    iRate = 0;
   }
   return iRate;
Index: branches/SHM-4.1-dev/source/Lib/TLibCommon/TComTrQuant.h
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibCommon/TComTrQuant.h	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibCommon/TComTrQuant.h	(revision 532)
@@ -150,6 +150,6 @@
 
 #if RDOQ_CHROMA_LAMBDA 
-  Void setLambda(Double dLambdaLuma, Double dLambdaChroma) { m_dLambdaLuma = dLambdaLuma; m_dLambdaChroma = dLambdaChroma; }
-  Void selectLambda(TextType eTType) { m_dLambda = (eTType == TEXT_LUMA) ? m_dLambdaLuma : m_dLambdaChroma; }
+  Void setLambdas ( const Double lambdas[3] ) { for (Int component = 0; component < 3; component++) m_lambdas[component] = lambdas[component]; }
+  Void selectLambda(TextType eTType) { m_dLambda = (eTType == TEXT_LUMA) ? m_lambdas[0] : ((eTType == TEXT_CHROMA_U) ? m_lambdas[1] : m_lambdas[2]); }
 #else
   Void setLambda(Double dLambda) { m_dLambda = dLambda;}
@@ -207,6 +207,5 @@
   QpParam  m_cQP;
 #if RDOQ_CHROMA_LAMBDA
-  Double   m_dLambdaLuma;
-  Double   m_dLambdaChroma;
+  Double   m_lambdas[3];
 #endif
   Double   m_dLambda;
@@ -273,11 +272,4 @@
                                              Double                          dTemp,
                                              Bool                            bLast        ) const;
-  __inline Double xGetICRateCost   ( UInt                            uiAbsLevel,
-                                     UShort                          ui16CtxNumOne,
-                                     UShort                          ui16CtxNumAbs,
-                                     UShort                          ui16AbsGoRice 
-                                   , UInt                            c1Idx,
-                                     UInt                            c2Idx
-                                     ) const;
 __inline Int xGetICRate  ( UInt                            uiAbsLevel,
                            UShort                          ui16CtxNumOne,
Index: branches/SHM-4.1-dev/source/Lib/TLibCommon/TypeDef.h
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibCommon/TypeDef.h	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibCommon/TypeDef.h	(revision 532)
@@ -219,5 +219,8 @@
 //! \{
 
-#define FIX1071 1 ///< fix for issue #1071
+#define HM_CLEANUP_SAO                  1  ///< JCTVC-N0230, 1) three SAO encoder-only software bugfixes. 2) new SAO implementation without picture quadtree, fine-grained slice legacies, and other redundancies.
+#if HM_CLEANUP_SAO  
+#define SAO_ENCODE_ALLOW_USE_PREDEBLOCK 1
+#endif
 
 #define MAX_NUM_PICS_IN_SOP           1024
@@ -238,10 +241,4 @@
 #define MAX_VPS_NUH_RESERVED_ZERO_LAYER_ID_PLUS1  1
 #endif
-#define RATE_CONTROL_LAMBDA_DOMAIN                  1  ///< JCTVC-K0103, rate control by R-lambda model
-#define M0036_RC_IMPROVEMENT                        1  ///< JCTVC-M0036, improvement for R-lambda model based rate control
-#define TICKET_1090_FIX                             1
-
-#define RC_FIX                                      1  /// suggested fix for M0036
-#define RATE_CONTROL_INTRA                          1  ///< JCTVC-M0257, rate control for intra 
 
 #define MAX_CPB_CNT                     32  ///< Upper bound of (cpb_cnt_minus1 + 1)
@@ -262,7 +259,7 @@
 #define C1FLAG_NUMBER               8 // maximum number of largerThan1 flag coded in one chunk :  16 in HM5
 #define C2FLAG_NUMBER               1 // maximum number of largerThan2 flag coded in one chunk:  16 in HM5 
-
+#if !HM_CLEANUP_SAO
 #define REMOVE_SAO_LCU_ENC_CONSTRAINTS_3 1  ///< disable the encoder constraint that conditionally disable SAO for chroma for entire slice in interleaved mode
-
+#endif
 #define SAO_ENCODING_CHOICE              1  ///< I0184: picture early termination
 #if SAO_ENCODING_CHOICE
@@ -278,7 +275,5 @@
 #define MAX_NUM_PPS                64
 
-#define WEIGHTED_CHROMA_DISTORTION  1   ///< F386: weighting of chroma for RDO
 #define RDOQ_CHROMA_LAMBDA          1   ///< F386: weighting of chroma for RDOQ
-#define SAO_CHROMA_LAMBDA           1   ///< F386: weighting of chroma for SAO
 
 #define MIN_SCAN_POS_CROSS          4
@@ -294,6 +289,4 @@
 #define LEVEL_RANGE                         30     ///< G382: max coefficient level in statistics collection
 #endif
-
-#define NS_HAD                               0
 
 #define HHI_RQT_INTRA_SPEEDUP             1           ///< tests one best mode with full rqt
@@ -362,6 +355,4 @@
 #define AMP_MRG                               1           ///< encoder only force merge for AMP partition (no motion search for AMP)
 #endif
-
-#define SCALING_LIST_OUTPUT_RESULT    0 //JCTVC-G880/JCTVC-G1016 quantization matrices
 
 #define CABAC_INIT_PRESENT_FLAG     1
@@ -423,4 +414,97 @@
 };
 
+#if HM_CLEANUP_SAO
+enum SAOComponentIdx
+{
+  SAO_Y =0,
+  SAO_Cb,
+  SAO_Cr,
+  NUM_SAO_COMPONENTS
+};
+
+enum SAOMode //mode
+{
+  SAO_MODE_OFF = 0,
+  SAO_MODE_NEW,
+  SAO_MODE_MERGE,
+  NUM_SAO_MODES
+};
+
+enum SAOModeMergeTypes 
+{
+  SAO_MERGE_LEFT =0,
+  SAO_MERGE_ABOVE,
+  NUM_SAO_MERGE_TYPES
+};
+
+
+enum SAOModeNewTypes 
+{
+  SAO_TYPE_START_EO =0,
+  SAO_TYPE_EO_0 = SAO_TYPE_START_EO,
+  SAO_TYPE_EO_90,
+  SAO_TYPE_EO_135,
+  SAO_TYPE_EO_45,
+  
+  SAO_TYPE_START_BO,
+  SAO_TYPE_BO = SAO_TYPE_START_BO,
+
+  NUM_SAO_NEW_TYPES
+};
+#define NUM_SAO_EO_TYPES_LOG2 2
+
+enum SAOEOClasses 
+{
+  SAO_CLASS_EO_FULL_VALLEY = 0,
+  SAO_CLASS_EO_HALF_VALLEY = 1,
+  SAO_CLASS_EO_PLAIN       = 2,
+  SAO_CLASS_EO_HALF_PEAK   = 3,
+  SAO_CLASS_EO_FULL_PEAK   = 4,
+  NUM_SAO_EO_CLASSES,
+};
+
+
+#define NUM_SAO_BO_CLASSES_LOG2  5
+enum SAOBOClasses
+{
+  //SAO_CLASS_BO_BAND0 = 0,
+  //SAO_CLASS_BO_BAND1,
+  //SAO_CLASS_BO_BAND2,
+  //...
+  //SAO_CLASS_BO_BAND31,
+
+  NUM_SAO_BO_CLASSES = (1<<NUM_SAO_BO_CLASSES_LOG2),
+};
+#define MAX_NUM_SAO_CLASSES  32  //(NUM_SAO_EO_GROUPS > NUM_SAO_BO_GROUPS)?NUM_SAO_EO_GROUPS:NUM_SAO_BO_GROUPS
+
+struct SAOOffset
+{
+  Int modeIdc; //NEW, MERGE, OFF
+  Int typeIdc; //NEW: EO_0, EO_90, EO_135, EO_45, BO. MERGE: left, above
+  Int typeAuxInfo; //BO: starting band index
+  Int offset[MAX_NUM_SAO_CLASSES];
+
+  SAOOffset();
+  ~SAOOffset();
+  Void reset();
+
+  const SAOOffset& operator= (const SAOOffset& src);
+};
+
+struct SAOBlkParam
+{
+
+  SAOBlkParam();
+  ~SAOBlkParam();
+  Void reset();
+  const SAOBlkParam& operator= (const SAOBlkParam& src);
+  SAOOffset& operator[](Int compIdx){ return offsetParam[compIdx];}
+private:
+  SAOOffset offsetParam[NUM_SAO_COMPONENTS];
+
+};
+
+
+#else
 #define NUM_DOWN_PART 4
 
@@ -494,5 +578,5 @@
   ~SAOParam();
 };
-
+#endif
 /// parameters for deblocking filter
 typedef struct _LFCUParam
Index: branches/SHM-4.1-dev/source/Lib/TLibDecoder/NALread.cpp
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibDecoder/NALread.cpp	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibDecoder/NALread.cpp	(revision 532)
@@ -126,5 +126,5 @@
   else
   {
-    assert( nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_TLA_R
+    assert( nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_TSA_R
          && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_TSA_N
          && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_STSA_R
Index: branches/SHM-4.1-dev/source/Lib/TLibDecoder/TDecCAVLC.cpp
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibDecoder/TDecCAVLC.cpp	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibDecoder/TDecCAVLC.cpp	(revision 532)
@@ -1938,5 +1938,4 @@
             Int pocLTCurr = rpcSlice->getPOC() - deltaPocMSBCycleLT * maxPicOrderCntLSB
                                         - iPOClsb + pocLsbLt;
-
             rps->setPOC     (j, pocLTCurr);
             rps->setDeltaPOC(j, - rpcSlice->getPOC() + pocLTCurr);
@@ -2876,5 +2875,4 @@
   UInt  code, sizeId, listId;
   Bool scalingListPredModeFlag;
-
   //for each size
   for(sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
@@ -2961,4 +2959,5 @@
   return (cnt>0);
 }
+
 //! \}
 
Index: branches/SHM-4.1-dev/source/Lib/TLibDecoder/TDecCu.cpp
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibDecoder/TDecCu.cpp	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibDecoder/TDecCu.cpp	(revision 532)
@@ -963,3 +963,4 @@
 
 }
+
 //! \}
Index: branches/SHM-4.1-dev/source/Lib/TLibDecoder/TDecEntropy.h
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibDecoder/TDecEntropy.h	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibDecoder/TDecEntropy.h	(revision 532)
@@ -106,5 +106,4 @@
   virtual Void parseCoeffNxN( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType ) = 0;
   virtual Void parseTransformSkipFlags ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, UInt uiDepth, TextType eTType) = 0;
-
   virtual Void updateContextTables( SliceType eSliceType, Int iQp ) = 0;
   
@@ -166,4 +165,5 @@
   Void updateContextTables    ( SliceType eSliceType, Int iQp ) { m_pcEntropyDecoderIf->updateContextTables( eSliceType, iQp ); }
   
+  
 private:
   Void xDecodeTransform        ( TComDataCU* pcCU, UInt offsetLuma, UInt offsetChroma, UInt uiAbsPartIdx, UInt uiDepth, UInt width, UInt height, UInt uiTrIdx, Bool& bCodeDQP );
Index: branches/SHM-4.1-dev/source/Lib/TLibDecoder/TDecGop.cpp
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibDecoder/TDecGop.cpp	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibDecoder/TDecGop.cpp	(revision 532)
@@ -128,5 +128,5 @@
   //-- For time output for each slice
   long iBeforeTime = clock();
-  
+#if !HM_CLEANUP_SAO
   UInt uiStartCUAddr   = pcSlice->getSliceSegmentCurStartCUAddr();
 
@@ -136,5 +136,5 @@
     m_sliceStartCUAddress.push_back(uiSliceStartCuAddr);
   }
-
+#endif
   m_pcSbacDecoder->init( (TDecBinIf*)m_pcBinCABAC );
   m_pcEntropyDecoder->setEntropyDecoder (m_pcSbacDecoder);
@@ -163,9 +163,10 @@
   m_pcEntropyDecoder->setBitstream      ( ppcSubstreams[0] );
   m_pcEntropyDecoder->resetEntropy      (pcSlice);
-
+#if !HM_CLEANUP_SAO
   if(uiSliceStartCuAddr == uiStartCUAddr)
   {
     m_LFCrossSliceBoundaryFlag.push_back( pcSlice->getLFCrossSliceBoundaryFlag());
   }
+#endif
   m_pcSbacDecoders[0].load(m_pcSbacDecoder);
   m_pcSliceDecoder->decompressSlice( ppcSubstreams, rpcPic, m_pcSbacDecoder, m_pcSbacDecoders);
@@ -195,5 +196,5 @@
   m_pcLoopFilter->setCfg(bLFCrossTileBoundary);
   m_pcLoopFilter->loopFilterPic( rpcPic );
-
+#if !HM_CLEANUP_SAO
   if(pcSlice->getSPS()->getUseSAO())
   {
@@ -201,7 +202,12 @@
     rpcPic->createNonDBFilterInfo(m_sliceStartCUAddress, 0, &m_LFCrossSliceBoundaryFlag, rpcPic->getPicSym()->getNumTiles(), bLFCrossTileBoundary);
   }
-
+#endif
   if( pcSlice->getSPS()->getUseSAO() )
   {
+#if HM_CLEANUP_SAO
+    m_pcSAO->reconstructBlkSAOParams(rpcPic, rpcPic->getPicSym()->getSAOBlkParam());
+    m_pcSAO->SAOProcess(rpcPic);
+    m_pcSAO->PCMLFDisableProcess(rpcPic);
+#else
     {
       SAOParam *saoParam = rpcPic->getPicSym()->getSaoParam();
@@ -214,11 +220,12 @@
       m_pcSAO->destroyPicSaoInfo();
     }
-  }
-
+#endif
+  }
+#if !HM_CLEANUP_SAO
   if(pcSlice->getSPS()->getUseSAO())
   {
     rpcPic->destroyNonDBFilterInfo();
   }
-
+#endif
   rpcPic->compressMotion(); 
   Char c = (pcSlice->isIntra() ? 'I' : pcSlice->isInterP() ? 'P' : 'B');
@@ -283,6 +290,8 @@
   rpcPic->setOutputMark(true);
   rpcPic->setReconMark(true);
+#if !HM_CLEANUP_SAO
   m_sliceStartCUAddress.clear();
   m_LFCrossSliceBoundaryFlag.clear();
+#endif
 }
 
Index: branches/SHM-4.1-dev/source/Lib/TLibDecoder/TDecGop.h
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibDecoder/TDecGop.h	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibDecoder/TDecGop.h	(revision 532)
@@ -83,8 +83,9 @@
   Int                   m_decodedPictureHashSEIEnabled;  ///< Checksum(3)/CRC(2)/MD5(1)/disable(0) acting on decoded picture hash SEI message
 
+#if !HM_CLEANUP_SAO
   //! list that contains the CU address of each slice plus the end address 
   std::vector<Int> m_sliceStartCUAddress;
   std::vector<Bool> m_LFCrossSliceBoundaryFlag;
-
+#endif
 #if SVC_EXTENSION
   UInt                  m_layerId;
Index: branches/SHM-4.1-dev/source/Lib/TLibDecoder/TDecSbac.cpp
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibDecoder/TDecSbac.cpp	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibDecoder/TDecSbac.cpp	(revision 532)
@@ -368,5 +368,7 @@
 #if AUXILIARY_PICTURES
         if (format == CHROMA_400)
+        {
           uiSample = uiGrayVal;
+        }
         else
 #endif
@@ -389,5 +391,7 @@
 #if AUXILIARY_PICTURES
         if (format == CHROMA_400)
+        {
           uiSample = uiGrayVal;
+        }
         else
 #endif
@@ -1378,12 +1382,154 @@
     if (uiCode == 0)
     {
+#if HM_CLEANUP_SAO
+      ruiVal = 1;
+#else
       ruiVal = 5;
+#endif
     }
     else
     {
+#if HM_CLEANUP_SAO
+      ruiVal = 2;
+#else
       ruiVal = 1;
-    }
-  }
-}
+#endif
+    }
+  }
+}
+
+#if HM_CLEANUP_SAO
+
+Void TDecSbac::parseSaoSign(UInt& val)
+{
+  m_pcTDecBinIf->decodeBinEP ( val ); 
+}
+
+Void TDecSbac::parseSAOBlkParam (SAOBlkParam& saoBlkParam
+                                , Bool* sliceEnabled
+                                , Bool leftMergeAvail
+                                , Bool aboveMergeAvail
+                                )
+{
+  UInt uiSymbol;
+
+  Bool isLeftMerge = false;
+  Bool isAboveMerge= false;
+
+  if(leftMergeAvail)
+  {
+    parseSaoMerge(uiSymbol); //sao_merge_left_flag
+    isLeftMerge = (uiSymbol?true:false);
+  }
+
+  if( aboveMergeAvail && !isLeftMerge)
+  {
+    parseSaoMerge(uiSymbol); //sao_merge_up_flag
+    isAboveMerge = (uiSymbol?true:false);
+  }
+
+  if(isLeftMerge || isAboveMerge) //merge mode
+  {
+    saoBlkParam[SAO_Y].modeIdc = saoBlkParam[SAO_Cb].modeIdc = saoBlkParam[SAO_Cr].modeIdc = SAO_MODE_MERGE;
+    saoBlkParam[SAO_Y].typeIdc = saoBlkParam[SAO_Cb].typeIdc = saoBlkParam[SAO_Cr].typeIdc = (isLeftMerge)?SAO_MERGE_LEFT:SAO_MERGE_ABOVE;
+  }
+  else //new or off mode
+  {    
+    for(Int compIdx=0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
+    {
+      SAOOffset& ctbParam = saoBlkParam[compIdx];
+
+      if(!sliceEnabled[compIdx])
+      {
+        //off
+        ctbParam.modeIdc = SAO_MODE_OFF;
+        continue;
+      }
+
+      //type
+      if(compIdx == SAO_Y || compIdx == SAO_Cb)
+      {
+        parseSaoTypeIdx(uiSymbol); //sao_type_idx_luma or sao_type_idx_chroma
+
+        assert(uiSymbol ==0 || uiSymbol ==1 || uiSymbol ==2);
+
+        if(uiSymbol ==0) //OFF
+        {
+          ctbParam.modeIdc = SAO_MODE_OFF;
+        }
+        else if(uiSymbol == 1) //BO
+        {
+          ctbParam.modeIdc = SAO_MODE_NEW;
+          ctbParam.typeIdc = SAO_TYPE_START_BO;
+        }
+        else //2, EO
+        {
+          ctbParam.modeIdc = SAO_MODE_NEW;
+          ctbParam.typeIdc = SAO_TYPE_START_EO;
+        }
+
+      }
+      else //Cr, follow Cb SAO type
+      {
+        ctbParam.modeIdc = saoBlkParam[SAO_Cb].modeIdc;
+        ctbParam.typeIdc = saoBlkParam[SAO_Cb].typeIdc;
+      }
+
+      if(ctbParam.modeIdc == SAO_MODE_NEW)
+      {
+        Int offset[4];
+        for(Int i=0; i< 4; i++)
+        {
+          parseSaoMaxUvlc(uiSymbol,  g_saoMaxOffsetQVal[compIdx] ); //sao_offset_abs
+          offset[i] = (Int)uiSymbol;
+        }
+
+        if(ctbParam.typeIdc == SAO_TYPE_START_BO)
+        {
+          for(Int i=0; i< 4; i++)
+          {
+            if(offset[i] != 0)
+            {
+              parseSaoSign(uiSymbol); //sao_offset_sign
+              if(uiSymbol)
+              {
+                offset[i] = -offset[i];
+              }
+            }
+          }
+          parseSaoUflc(NUM_SAO_BO_CLASSES_LOG2, uiSymbol ); //sao_band_position
+          ctbParam.typeAuxInfo = uiSymbol;
+        
+          for(Int i=0; i<4; i++)
+          {
+            ctbParam.offset[(ctbParam.typeAuxInfo+i)%MAX_NUM_SAO_CLASSES] = offset[i];
+          }      
+        
+        }
+        else //EO
+        {
+          ctbParam.typeAuxInfo = 0;
+
+          if(compIdx == SAO_Y || compIdx == SAO_Cb)
+          {
+            parseSaoUflc(NUM_SAO_EO_TYPES_LOG2, uiSymbol ); //sao_eo_class_luma or sao_eo_class_chroma
+            ctbParam.typeIdc += uiSymbol;
+          }
+          else
+          {
+            ctbParam.typeIdc = saoBlkParam[SAO_Cb].typeIdc;
+          }
+          ctbParam.offset[SAO_CLASS_EO_FULL_VALLEY] = offset[0];
+          ctbParam.offset[SAO_CLASS_EO_HALF_VALLEY] = offset[1];
+          ctbParam.offset[SAO_CLASS_EO_PLAIN      ] = 0;
+          ctbParam.offset[SAO_CLASS_EO_HALF_PEAK  ] = -offset[2];
+          ctbParam.offset[SAO_CLASS_EO_FULL_PEAK  ] = -offset[3];
+        }
+      }
+    }
+  }
+}
+
+#else
 
 inline Void copySaoOneLcuParam(SaoLcuParam* psDst,  SaoLcuParam* psSrc)
@@ -1559,4 +1705,6 @@
 }
 
+#endif
+
 /**
  - Initialize our contexts from the nominated source.
Index: branches/SHM-4.1-dev/source/Lib/TLibDecoder/TDecSbac.h
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibDecoder/TDecSbac.h	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibDecoder/TDecSbac.h	(revision 532)
@@ -90,6 +90,11 @@
   Void  parseSaoTypeIdx           ( UInt&  ruiVal  );
   Void  parseSaoUflc              ( UInt uiLength, UInt& ruiVal     );
+#if HM_CLEANUP_SAO
+  Void parseSAOBlkParam (SAOBlkParam& saoBlkParam, Bool* sliceEnabled, Bool leftMergeAvail, Bool aboveMergeAvail);
+  Void parseSaoSign(UInt& val);
+#else
   Void  parseSaoOneLcuInterleaving(Int rx, Int ry, SAOParam* pSaoParam, TComDataCU* pcCU, Int iCUAddrInSlice, Int iCUAddrUpInSlice, Int allowMergeLeft, Int allowMergeUp);
   Void  parseSaoOffset            (SaoLcuParam* psSaoLcuParam, UInt compIdx);
+#endif
 private:
   Void  xReadUnarySymbol    ( UInt& ruiSymbol, ContextModel* pcSCModel, Int iOffset );
Index: branches/SHM-4.1-dev/source/Lib/TLibDecoder/TDecSlice.cpp
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibDecoder/TDecSlice.cpp	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibDecoder/TDecSlice.cpp	(revision 532)
@@ -197,5 +197,4 @@
   UInt uiTileLCUX;
   Int iNumSubstreamsPerTile = 1; // if independent.
-
   Bool depSliceSegmentsEnabled = rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getPPS()->getDependentSliceSegmentsEnabledFlag();
   uiTileStartLCU = rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(iStartCUAddr))->getFirstCUAddr();
@@ -323,4 +322,41 @@
     g_bJustDoIt = g_bEncDecTraceEnable;
 #endif
+
+#if HM_CLEANUP_SAO
+    if ( pcSlice->getSPS()->getUseSAO() )
+    {
+      SAOBlkParam& saoblkParam = (rpcPic->getPicSym()->getSAOBlkParam())[iCUAddr];
+      if (pcSlice->getSaoEnabledFlag()||pcSlice->getSaoEnabledFlagChroma())
+      {
+        Bool sliceEnabled[NUM_SAO_COMPONENTS];
+        sliceEnabled[SAO_Y] = pcSlice->getSaoEnabledFlag();
+        sliceEnabled[SAO_Cb]= sliceEnabled[SAO_Cr]= pcSlice->getSaoEnabledFlagChroma();
+
+        Bool leftMergeAvail = false;
+        Bool aboveMergeAvail= false;
+
+        //merge left condition
+        Int rx = (iCUAddr % uiWidthInLCUs);
+        if(rx > 0)
+        {
+          leftMergeAvail = rpcPic->getSAOMergeAvailability(iCUAddr, iCUAddr-1);
+        }
+        //merge up condition
+        Int ry = (iCUAddr / uiWidthInLCUs);
+        if(ry > 0)
+        {
+          aboveMergeAvail = rpcPic->getSAOMergeAvailability(iCUAddr, iCUAddr-uiWidthInLCUs);
+        }
+
+        pcSbacDecoder->parseSAOBlkParam( saoblkParam, sliceEnabled, leftMergeAvail, aboveMergeAvail);
+      }
+      else 
+      {
+        saoblkParam[SAO_Y ].modeIdc = SAO_MODE_OFF;
+        saoblkParam[SAO_Cb].modeIdc = SAO_MODE_OFF;
+        saoblkParam[SAO_Cr].modeIdc = SAO_MODE_OFF;
+      }
+    }
+#else
     if ( pcSlice->getSPS()->getUseSAO() && (pcSlice->getSaoEnabledFlag()||pcSlice->getSaoEnabledFlagChroma()) )
     {
@@ -374,4 +410,6 @@
       }
     }
+#endif
+
     m_pcCuDecoder->decodeCU     ( pcCU, uiIsLast );
     m_pcCuDecoder->decompressCU ( pcCU );
Index: branches/SHM-4.1-dev/source/Lib/TLibDecoder/TDecTop.cpp
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibDecoder/TDecTop.cpp	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibDecoder/TDecTop.cpp	(revision 532)
@@ -371,6 +371,7 @@
 #endif
 #endif
-
+#if !HM_CLEANUP_SAO
     rpcPic->getPicSym()->allocSaoParam(&m_cSAO);
+#endif
     m_cListPic.pushBack( rpcPic );
     
@@ -452,5 +453,7 @@
 #endif
 #endif
+#if !HM_CLEANUP_SAO
   rpcPic->getPicSym()->allocSaoParam(&m_cSAO);
+#endif
 }
 
@@ -747,7 +750,23 @@
   m_cSAO.destroy();
 #if REPN_FORMAT_IN_VPS
+#if AUXILIARY_PICTURES
+#if HM_CLEANUP_SAO
+  m_cSAO.create( m_apcSlicePilot->getPicWidthInLumaSamples(), m_apcSlicePilot->getPicHeightInLumaSamples(), sps->getChromaFormatIdc(), sps->getMaxCUWidth(), sps->getMaxCUHeight(), sps->getMaxCUDepth() );
+#else
+  m_cSAO.create( m_apcSlicePilot->getPicWidthInLumaSamples(), m_apcSlicePilot->getPicHeightInLumaSamples(), sps->getChromaFormatIdc(), sps->getMaxCUWidth(), sps->getMaxCUHeight() );
+#endif
+#else
+#if HM_CLEANUP_SAO
+  m_cSAO.create( m_apcSlicePilot->getPicWidthInLumaSamples(), m_apcSlicePilot->getPicHeightInLumaSamples(), sps->getMaxCUWidth(), sps->getMaxCUHeight(), sps->getMaxCUDepth() );
+#else
   m_cSAO.create( m_apcSlicePilot->getPicWidthInLumaSamples(), m_apcSlicePilot->getPicHeightInLumaSamples(), sps->getMaxCUWidth(), sps->getMaxCUHeight() );
+#endif
+#endif
+#else
+#if HM_CLEANUP_SAO
+  m_cSAO.create( sps->getPicWidthInLumaSamples(), sps->getPicHeightInLumaSamples(), sps->getMaxCUWidth(), sps->getMaxCUHeight(), sps->getMaxCUDepth() );
 #else
   m_cSAO.create( sps->getPicWidthInLumaSamples(), sps->getPicHeightInLumaSamples(), sps->getMaxCUWidth(), sps->getMaxCUHeight() );
+#endif
 #endif
   m_cLoopFilter.create( sps->getMaxCUDepth() );
@@ -969,5 +988,5 @@
     // Check for TSA alignment
     if( m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_N ||
-        m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_TLA_R 
+        m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_R 
          )
     {
@@ -979,5 +998,5 @@
         {
           assert( m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_N ||
-                    m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_TLA_R );    // TSA pictures should be aligned among depenedent layers
+                    m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_R );    // TSA pictures should be aligned among depenedent layers
         } 
       }
@@ -1275,9 +1294,5 @@
     if (m_layerId == 0)
 #endif
-#if FIX1071
     pcSlice->setRefPicList( m_cListPic, true );
-#else
-    pcSlice->setRefPicList( m_cListPic );
-#endif
 
 #if SVC_EXTENSION
@@ -1524,5 +1539,4 @@
   {
     pcSlice->setScalingList ( pcSlice->getSPS()->getScalingList()  );
-
     if(pcSlice->getPPS()->getScalingListPresentFlag())
     {
@@ -1770,5 +1784,5 @@
     case NAL_UNIT_CODED_SLICE_TRAIL_R:
     case NAL_UNIT_CODED_SLICE_TRAIL_N:
-    case NAL_UNIT_CODED_SLICE_TLA_R:
+    case NAL_UNIT_CODED_SLICE_TSA_R:
     case NAL_UNIT_CODED_SLICE_TSA_N:
     case NAL_UNIT_CODED_SLICE_STSA_R:
@@ -1790,6 +1804,25 @@
 #endif
       break;
+      
+    case NAL_UNIT_EOS:
+      m_associatedIRAPType = NAL_UNIT_INVALID;
+      m_pocCRA = 0;
+      m_pocRandomAccess = MAX_INT;
+      m_prevPOC = MAX_INT;
+      m_bFirstSliceInPicture = true;
+      m_bFirstSliceInSequence = true;
+      m_prevSliceSkipped = false;
+      m_skippedPOC = 0;
+      return false;
+      
+    case NAL_UNIT_ACCESS_UNIT_DELIMITER:
+      // TODO: process AU delimiter
+      return false;
+      
+    case NAL_UNIT_EOB:
+      return false;
+      
     default:
-      assert (1);
+      assert (0);
   }
 
Index: branches/SHM-4.1-dev/source/Lib/TLibDecoder/TDecTop.h
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibDecoder/TDecTop.h	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibDecoder/TDecTop.h	(revision 532)
@@ -73,5 +73,4 @@
   TComList<TComPic*>      m_cListPic;         //  Dynamic buffer
   ParameterSetManagerDecoder m_parameterSetManagerDecoder;  // storage for parameter sets 
-
   TComSlice*              m_apcSlicePilot;
 
Index: branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncAnalyze.cpp
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncAnalyze.cpp	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncAnalyze.cpp	(revision 532)
@@ -58,3 +58,4 @@
 
 TEncAnalyze             m_gcAnalyzeAll_in;
+
 //! \}
Index: branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncAnalyze.h
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncAnalyze.h	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncAnalyze.h	(revision 532)
@@ -160,4 +160,5 @@
   }
   
+  
   Void    printSummary(Char ch)
   {
@@ -207,4 +208,5 @@
 
 extern TEncAnalyze             m_gcAnalyzeAll_in;
+
 //! \}
 
Index: branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncCavlc.cpp
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 532)
@@ -239,10 +239,6 @@
 
   WRITE_FLAG( pcPPS->getScalingListPresentFlag() ? 1 : 0,                          "pps_scaling_list_data_present_flag" ); 
-
   if( pcPPS->getScalingListPresentFlag() )
   {
-#if SCALING_LIST_OUTPUT_RESULT
-    printf("PPS\n");
-#endif
     codeScalingList( m_pcSlice->getScalingList() );
   }
@@ -521,5 +517,4 @@
   WRITE_UVLC( pcSPS->getQuadtreeTUMaxDepthIntra() - 1,                               "max_transform_hierarchy_depth_intra" );
   WRITE_FLAG( pcSPS->getScalingListFlag() ? 1 : 0,                                   "scaling_list_enabled_flag" ); 
-
   if(pcSPS->getScalingListFlag())
   {
@@ -543,7 +538,4 @@
     if(pcSPS->getScalingListPresentFlag())
     {
-#if SCALING_LIST_OUTPUT_RESULT
-    printf("SPS\n");
-#endif
       codeScalingList( m_pcSlice->getScalingList() );
     }
@@ -1427,5 +1419,4 @@
       TComReferencePictureSet* rps = pcSlice->getRPS();
       
-#if FIX1071
       // check for bitstream restriction stating that:
       // If the current picture is a BLA or CRA picture, the value of NumPocTotalCurr shall be equal to 0.
@@ -1441,5 +1432,4 @@
         }
       }
-#endif
 
       if(pcSlice->getRPSidx() < 0)
@@ -1595,18 +1585,22 @@
       if (pcSlice->getSPS()->getUseSAO())
       {
-         WRITE_FLAG( pcSlice->getSaoEnabledFlag(), "slice_sao_luma_flag" );
+         WRITE_FLAG( pcSlice->getSaoEnabledFlag(), "slice_sao_luma_flag" );         
+#if AUXILIARY_PICTURES
+         if (pcSlice->getChromaFormatIdc() != CHROMA_400)
          {
+#endif
+#if HM_CLEANUP_SAO
+         WRITE_FLAG( pcSlice->getSaoEnabledFlagChroma(), "slice_sao_chroma_flag" );
+#else
+         {
+           SAOParam *saoParam = pcSlice->getPic()->getPicSym()->getSaoParam();
+           WRITE_FLAG( saoParam->bSaoFlag[1], "slice_sao_chroma_flag" );
+         }
+#endif
 #if AUXILIARY_PICTURES
-           if (pcSlice->getChromaFormatIdc() != CHROMA_400)
-           {
-#endif
-           SAOParam *saoParam = pcSlice->getPic()->getPicSym()->getSaoParam();
-          WRITE_FLAG( saoParam->bSaoFlag[1], "slice_sao_chroma_flag" );
-#if AUXILIARY_PICTURES
-           }
-#endif
          }
-      }
-    }
+#endif
+      }
+    }   
 
     //check if numrefidxes match the defaults. If not, override
@@ -2154,11 +2148,4 @@
   Bool scalingListPredModeFlag;
 
-#if SCALING_LIST_OUTPUT_RESULT
-  Int startBit;
-  Int startTotalBit;
-  startBit = m_pcBitIf->getNumberOfWrittenBits();
-  startTotalBit = m_pcBitIf->getNumberOfWrittenBits();
-#endif
-
     //for each size
     for(sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
@@ -2166,7 +2153,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" );
@@ -2179,14 +2163,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;
 }
@@ -2203,5 +2179,4 @@
   Int data;
   Int *src = scalingList->getScalingListAddress(sizeId, listId);
-
   if( sizeId > SCALING_LIST_8x8 )
   {
Index: branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncCavlc.h
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncCavlc.h	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncCavlc.h	(revision 532)
@@ -109,4 +109,7 @@
   
   Void codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList );
+#if HM_CLEANUP_SAO
+  Void codeSAOBlkParam(SAOBlkParam& saoBlkParam, Bool* sliceEnabled, Bool leftMergeAvail, Bool aboveMergeAvail, Bool onlyEstMergeInfo = false){printf("only supported in CABAC"); assert(0); exit(-1);}
+#else
   Void codeSAOSign       ( UInt code   ) { printf("Not supported\n"); assert (0); }
   Void codeSaoMaxUvlc    ( UInt   code, UInt maxSymbol ){printf("Not supported\n"); assert (0);}
@@ -114,5 +117,5 @@
   Void codeSaoTypeIdx    ( UInt uiCode ){printf("Not supported\n"); assert (0);}
   Void codeSaoUflc       ( UInt uiLength, UInt   uiCode ){ assert(uiCode < 32); printf("Not supported\n"); assert (0);}
-
+#endif
   Void codeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx );
   Void codeSkipFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
Index: branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncCfg.h
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncCfg.h	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncCfg.h	(revision 532)
@@ -196,6 +196,7 @@
   Int       m_maxNumOffsetsPerPic;
   Bool      m_saoLcuBoundary;
+#if !HM_CLEANUP_SAO
   Bool      m_saoLcuBasedOptimization;
-
+#endif
   //====== Lossless ========
   Bool      m_useLossless;
@@ -328,21 +329,11 @@
   Int       m_TMVPModeId;
   Int       m_signHideFlag;
-#if RATE_CONTROL_LAMBDA_DOMAIN
   Bool      m_RCEnableRateControl;
   Int       m_RCTargetBitrate;
-#if M0036_RC_IMPROVEMENT
   Int       m_RCKeepHierarchicalBit;
-#else
-  Bool      m_RCKeepHierarchicalBit;
-#endif
   Bool      m_RCLCULevelRC;
   Bool      m_RCUseLCUSeparateModel;
   Int       m_RCInitialQP;
   Bool      m_RCForceIntraQP;
-#else
-  Bool      m_enableRateCtrl;                                ///< Flag for using rate control algorithm
-  Int       m_targetBitrate;                                 ///< target bitrate
-  Int       m_numLCUInUnit;                                  ///< Total number of LCUs in a frame should be divided by the NumLCUInUnit
-#endif
   Bool      m_TransquantBypassEnableFlag;                     ///< transquant_bypass_enable_flag setting in PPS.
   Bool      m_CUTransquantBypassFlagValue;                    ///< if transquant_bypass_enable_flag, the fixed value to use for the per-CU cu_transquant_bypass_flag.
@@ -638,6 +629,8 @@
   Void  setSaoLcuBoundary              (Bool val)      { m_saoLcuBoundary = val; }
   Bool  getSaoLcuBoundary              ()              { return m_saoLcuBoundary; }
+#if !HM_CLEANUP_SAO
   Void  setSaoLcuBasedOptimization               (Bool val)            { m_saoLcuBasedOptimization = val; }
   Bool  getSaoLcuBasedOptimization               ()                    { return m_saoLcuBasedOptimization; }
+#endif
   Void  setLFCrossTileBoundaryFlag               ( Bool   val  )       { m_loopFilterAcrossTilesEnabledFlag = val; }
   Bool  getLFCrossTileBoundaryFlag               ()                    { return m_loopFilterAcrossTilesEnabledFlag;   }
@@ -815,16 +808,10 @@
   Void      setSignHideFlag( Int signHideFlag ) { m_signHideFlag = signHideFlag; }
   Int       getSignHideFlag()                    { return m_signHideFlag; }
-#if RATE_CONTROL_LAMBDA_DOMAIN
   Bool      getUseRateCtrl         ()              { return m_RCEnableRateControl;   }
   Void      setUseRateCtrl         ( Bool b )      { m_RCEnableRateControl = b;      }
   Int       getTargetBitrate       ()              { return m_RCTargetBitrate;       }
   Void      setTargetBitrate       ( Int bitrate ) { m_RCTargetBitrate  = bitrate;   }
-#if M0036_RC_IMPROVEMENT
   Int       getKeepHierBit         ()              { return m_RCKeepHierarchicalBit; }
   Void      setKeepHierBit         ( Int i )       { m_RCKeepHierarchicalBit = i;    }
-#else
-  Bool      getKeepHierBit         ()              { return m_RCKeepHierarchicalBit; }
-  Void      setKeepHierBit         ( Bool b )      { m_RCKeepHierarchicalBit = b;    }
-#endif
   Bool      getLCULevelRC          ()              { return m_RCLCULevelRC; }
   Void      setLCULevelRC          ( Bool b )      { m_RCLCULevelRC = b; }
@@ -835,12 +822,4 @@
   Bool      getForceIntraQP        ()              { return m_RCForceIntraQP;        }
   Void      setForceIntraQP        ( Bool b )      { m_RCForceIntraQP = b;           }
-#else
-  Bool      getUseRateCtrl    ()                { return m_enableRateCtrl;    }
-  Void      setUseRateCtrl    (Bool flag)       { m_enableRateCtrl = flag;    }
-  Int       getTargetBitrate  ()                { return m_targetBitrate;     }
-  Void      setTargetBitrate  (Int target)      { m_targetBitrate  = target;  }
-  Int       getNumLCUInUnit   ()                { return m_numLCUInUnit;      }
-  Void      setNumLCUInUnit   (Int numLCUs)     { m_numLCUInUnit   = numLCUs; }
-#endif
   Bool      getTransquantBypassEnableFlag()           { return m_TransquantBypassEnableFlag; }
   Void      setTransquantBypassEnableFlag(Bool flag)  { m_TransquantBypassEnableFlag = flag; }
Index: branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncCu.cpp
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncCu.cpp	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncCu.cpp	(revision 532)
@@ -95,9 +95,4 @@
   
   m_bEncodeDQP = false;
-#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
-  m_LCUPredictionSAD = 0;
-  m_addSADDepth      = 0;
-  m_temporalSAD      = 0;
-#endif
 
   // initialize partition order.
@@ -243,10 +238,4 @@
   m_ppcBestCU[0]->initCU( rpcCU->getPic(), rpcCU->getAddr() );
   m_ppcTempCU[0]->initCU( rpcCU->getPic(), rpcCU->getAddr() );
-
-#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
-  m_addSADDepth      = 0;
-  m_LCUPredictionSAD = 0;
-  m_temporalSAD      = 0;
-#endif
 
 #if N0383_IL_CONSTRAINED_TILE_SETS_SEI
@@ -433,5 +422,4 @@
   }
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
   if ( m_pcEncCfg->getUseRateCtrl() )
   {
@@ -439,12 +427,4 @@
     iMaxQP = m_pcRateCtrl->getRCQP();
   }
-#else
-  if(m_pcEncCfg->getUseRateCtrl())
-  {
-    Int qp = m_pcRateCtrl->getUnitQP();
-    iMinQP  = Clip3( MIN_QP, MAX_QP, qp);
-    iMaxQP  = Clip3( MIN_QP, MAX_QP, qp);
-  }
-#endif
 
   // If slice start or slice end is within this cu...
@@ -538,12 +518,4 @@
       }
     }
-
-#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
-    if ( uiDepth <= m_addSADDepth )
-    {
-      m_LCUPredictionSAD += m_temporalSAD;
-      m_addSADDepth = uiDepth;
-    }
-#endif
 
     if(!earlyDetectionSkipMode)
@@ -796,7 +768,4 @@
   {
     bBoundary = true;
-#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
-    m_addSADDepth++;
-#endif
   }
 
@@ -842,5 +811,4 @@
     iMaxQP = iStartQP;
   }
-#if RATE_CONTROL_LAMBDA_DOMAIN
   if ( m_pcEncCfg->getUseRateCtrl() )
   {
@@ -848,12 +816,4 @@
     iMaxQP = m_pcRateCtrl->getRCQP();
   }
-#else
-  if(m_pcEncCfg->getUseRateCtrl())
-  {
-    Int qp = m_pcRateCtrl->getUnitQP();
-    iMinQP  = Clip3( MIN_QP, MAX_QP, qp);
-    iMaxQP  = Clip3( MIN_QP, MAX_QP, qp);
-  }
-#endif
   for (Int iQP=iMinQP; iQP<=iMaxQP; iQP++)
   {
@@ -1250,5 +1210,4 @@
 }
 
-#if RATE_CONTROL_INTRA
 Int xCalcHADs8x8_ISlice(Pel *piOrg, Int iStrideOrg) 
 {
@@ -1365,5 +1324,4 @@
   return(iSumHad);
 }
-#endif
 
 /** check RD costs for a CU block encoded with merge
@@ -1542,14 +1500,4 @@
 #endif
 
-#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
-  if ( m_pcEncCfg->getUseRateCtrl() && m_pcEncCfg->getLCULevelRC() && ePartSize == SIZE_2Nx2N && uhDepth <= m_addSADDepth )
-  {
-    UInt SAD = m_pcRdCost->getSADPart( g_bitDepthY, m_ppcPredYuvTemp[uhDepth]->getLumaAddr(), m_ppcPredYuvTemp[uhDepth]->getStride(),
-      m_ppcOrigYuv[uhDepth]->getLumaAddr(), m_ppcOrigYuv[uhDepth]->getStride(),
-      rpcTempCU->getWidth(0), rpcTempCU->getHeight(0) );
-    m_temporalSAD = (Int)SAD;
-  }
-#endif
-
   m_pcPredSearch->encodeResAndCalcRdInterCU( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcResiYuvBest[uhDepth], m_ppcRecoYuvTemp[uhDepth], false );
   rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
@@ -1582,5 +1530,4 @@
   
   m_pcEntropyCoder->resetBits();
-
   if ( rpcTempCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
   {
@@ -1636,5 +1583,4 @@
 
   m_pcEntropyCoder->resetBits();
-
   if ( rpcTempCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
   {
Index: branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncCu.h
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncCu.h	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncCu.h	(revision 532)
@@ -103,9 +103,5 @@
   Bool                    m_bUseSBACRD;
   TEncRateCtrl*           m_pcRateCtrl;
-#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
-  UInt                    m_LCUPredictionSAD;
-  Int                     m_addSADDepth;
-  Int                     m_temporalSAD;
-#endif
+
 #if N0383_IL_CONSTRAINED_TILE_SETS_SEI
   Bool                    m_disableILP;
@@ -128,11 +124,5 @@
   
   Void setBitCounter        ( TComBitCounter* pcBitCounter ) { m_pcBitCounter = pcBitCounter; }
-#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
-  UInt getLCUPredictionSAD() { return m_LCUPredictionSAD; }
-#endif
-#if RATE_CONTROL_INTRA
   Int   updateLCUDataISlice ( TComDataCU* pcCU, Int LCUIdx, Int width, Int height );
-#endif
-
 protected:
   Void  finishCU            ( TComDataCU*  pcCU, UInt uiAbsPartIdx,           UInt uiDepth        );
Index: branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncEntropy.cpp
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncEntropy.cpp	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncEntropy.cpp	(revision 532)
@@ -51,4 +51,5 @@
 Void TEncEntropy::encodeSliceHeader ( TComSlice* pcSlice )
 {
+#if !HM_CLEANUP_SAO
   if (pcSlice->getSPS()->getUseSAO())
   {
@@ -59,5 +60,5 @@
     }
   }
-
+#endif
   m_pcEntropyCoderIf->codeSliceHeader( pcSlice );
   return;
@@ -638,4 +639,5 @@
 }
 
+#if !HM_CLEANUP_SAO
 /** Encode SAO Offset
  * \param  saoLcuParam SAO LCU paramters
@@ -731,4 +733,6 @@
 }
 
+#endif
+
 Int TEncEntropy::countNonZeroCoeffs( TCoeff* pcCoef, UInt uiSize )
 {
Index: branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncEntropy.h
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncEntropy.h	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncEntropy.h	(revision 532)
@@ -105,4 +105,7 @@
   virtual Void codeCoeffNxN      ( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType ) = 0;
   virtual Void codeTransformSkipFlags ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, TextType eTType ) = 0;
+#if HM_CLEANUP_SAO
+  virtual Void codeSAOBlkParam(SAOBlkParam& saoBlkParam, Bool* sliceEnabled, Bool leftMergeAvail, Bool aboveMergeAvail, Bool onlyEstMergeInfo = false)    =0;
+#else
   virtual Void codeSAOSign          ( UInt code   ) = 0;
   virtual Void codeSaoMaxUvlc       ( UInt code, UInt maxSymbol ) = 0;
@@ -110,4 +113,5 @@
   virtual Void codeSaoTypeIdx      ( UInt   uiCode) = 0;
   virtual Void codeSaoUflc         ( UInt uiLength, UInt   uiCode ) = 0;
+#endif
   virtual Void estBit               (estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType) = 0;
   
@@ -188,6 +192,10 @@
   
   Void estimateBit             ( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType);
+#if HM_CLEANUP_SAO
+  Void encodeSAOBlkParam(SAOBlkParam& saoBlkParam, Bool* sliceEnabled, Bool leftMergeAvail, Bool aboveMergeAvail){m_pcEntropyCoderIf->codeSAOBlkParam(saoBlkParam, sliceEnabled, leftMergeAvail, aboveMergeAvail, false);}
+#else
   Void    encodeSaoOffset(SaoLcuParam* saoLcuParam, UInt compIdx);
   Void    encodeSaoUnitInterleaving(Int compIdx, Bool saoFlag, Int rx, Int ry, SaoLcuParam* saoLcuParam, Int cuAddrInSlice, Int cuAddrUpInSlice, Int allowMergeLeft, Int allowMergeUp);
+#endif
   static Int countNonZeroCoeffs( TCoeff* pcCoef, UInt uiSize );
 
Index: branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncGOP.cpp
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 532)
@@ -971,15 +971,8 @@
     pcSlice->getRPS()->setNumberOfLongtermPictures(0);
 
-#if FIX1071
     if ((pcSlice->checkThatAllRefPicsAreAvailable(rcListPic, pcSlice->getRPS(), false) != 0) || (pcSlice->isIRAP()))
     {
       pcSlice->createExplicitReferencePictureSetFromReference(rcListPic, pcSlice->getRPS(), pcSlice->isIRAP());
     }
-#else
-    if(pcSlice->checkThatAllRefPicsAreAvailable(rcListPic, pcSlice->getRPS(), false) != 0)
-    {
-      pcSlice->createExplicitReferencePictureSetFromReference(rcListPic, pcSlice->getRPS());
-    }
-#endif
     pcSlice->applyReferencePictureSet(rcListPic, pcSlice->getRPS());
 
@@ -999,5 +992,5 @@
             {
               if( ( lowerLayerPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_N ) ||
-                  ( lowerLayerPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_TLA_R ) 
+                  ( lowerLayerPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_R ) 
                 )
               {
@@ -1008,5 +1001,5 @@
                 else
                 {
-                  pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TLA_R );
+                  pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TSA_R );
                 }
                 oneRefLayerTSA = true;
@@ -1040,5 +1033,5 @@
             else
             {
-              pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TLA_R );
+              pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TSA_R );
             }
           }
@@ -1051,5 +1044,5 @@
         else
         {
-          pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TLA_R);
+          pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TSA_R);
         }
 #endif
@@ -1421,5 +1414,4 @@
     pcPic->getSlice(pcSlice->getSliceIdx())->setMvdL1ZeroFlag(pcSlice->getMvdL1ZeroFlag());
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
     Double lambda            = 0.0;
     Int actualHeadBits       = 0;
@@ -1454,15 +1446,9 @@
       else if ( frameLevel == 0 )   // intra case, but use the model
       {
-#if RATE_CONTROL_INTRA
         m_pcSliceEncoder->calCostSliceI(pcPic);
-#endif
         if ( m_pcCfg->getIntraPeriod() != 1 )   // do not refine allocated bits for all intra case
         {
           Int bits = m_pcRateCtrl->getRCSeq()->getLeftAverageBits();
-#if RATE_CONTROL_INTRA
           bits = m_pcRateCtrl->getRCPic()->getRefineBitsForIntra( bits );
-#else
-          bits = m_pcRateCtrl->getRCSeq()->getRefineBitsForIntra( bits );
-#endif
           if ( bits < 200 )
           {
@@ -1473,10 +1459,6 @@
 
         list<TEncRCPic*> listPreviousPicture = m_pcRateCtrl->getPicList();
-#if RATE_CONTROL_INTRA
         m_pcRateCtrl->getRCPic()->getLCUInitTargetBits();
         lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambda( listPreviousPicture, pcSlice->getSliceType());
-#else
-        lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambda( listPreviousPicture );
-#endif
         sliceQP = m_pcRateCtrl->getRCPic()->estimatePicQP( lambda, listPreviousPicture );
       }
@@ -1484,9 +1466,5 @@
       {
         list<TEncRCPic*> listPreviousPicture = m_pcRateCtrl->getPicList();
-#if RATE_CONTROL_INTRA
         lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambda( listPreviousPicture, pcSlice->getSliceType());
-#else
-        lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambda( listPreviousPicture );
-#endif
         sliceQP = m_pcRateCtrl->getRCPic()->estimatePicQP( lambda, listPreviousPicture );
       }
@@ -1501,5 +1479,4 @@
       m_pcSliceEncoder->resetQP( pcPic, sliceQP, lambda );
     }
-#endif
 
     UInt uiNumSlices = 1;
@@ -1712,4 +1689,10 @@
 
     // SAO parameter estimation using non-deblocked pixels for LCU bottom and right boundary areas
+#if HM_CLEANUP_SAO
+    if( pcSlice->getSPS()->getUseSAO() && m_pcCfg->getSaoLcuBoundary() )
+    {
+      m_pcSAO->getPreDBFStatistics(pcPic);
+    }
+#else
     if( m_pcCfg->getSaoLcuBasedOptimization() && m_pcCfg->getSaoLcuBoundary() )
     {
@@ -1717,5 +1700,5 @@
       m_pcSAO->calcSaoStatsCu_BeforeDblk( pcPic );
     }
-
+#endif    
     //-- Loop filter
     Bool bLFCrossTileBoundary = pcSlice->getPPS()->getLoopFilterAcrossTilesEnabledFlag();
@@ -1727,4 +1710,5 @@
     m_pcLoopFilter->loopFilterPic( pcPic );
 
+#if !HM_CLEANUP_SAO    
     pcSlice = pcPic->getSlice(0);
     if(pcSlice->getSPS()->getUseSAO())
@@ -1746,5 +1730,5 @@
       m_pcSAO->createPicSaoInfo(pcPic);
     }
-
+#endif
     /////////////////////////////////////////////////////////////////////////////////////////////////// File writing
     // Set entropy coder
@@ -1778,7 +1762,5 @@
       writeRBSPTrailingBits(nalu.m_Bitstream);
       accessUnit.push_back(new NALUnitEBSP(nalu));
-#if RATE_CONTROL_LAMBDA_DOMAIN
       actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
-#endif
 #if SVC_EXTENSION
       }
@@ -1821,7 +1803,5 @@
       writeRBSPTrailingBits(nalu.m_Bitstream);
       accessUnit.push_back(new NALUnitEBSP(nalu));
-#if RATE_CONTROL_LAMBDA_DOMAIN
       actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
-#endif
 
 #if SVC_EXTENSION
@@ -1837,7 +1817,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
 
       xCreateLeadingSEIMessages(accessUnit, pcSlice->getSPS());
@@ -2159,13 +2137,7 @@
           }
           m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
-#if RATE_CONTROL_LAMBDA_DOMAIN
           tmpBitsBeforeWriting = m_pcEntropyCoder->getNumberOfWrittenBits();
-#endif
-
           m_pcEntropyCoder->encodeSliceHeader(pcSlice);
-
-#if RATE_CONTROL_LAMBDA_DOMAIN
           actualHeadBits += ( m_pcEntropyCoder->getNumberOfWrittenBits() - tmpBitsBeforeWriting );
-#endif
 
           // is it needed?
@@ -2288,7 +2260,5 @@
           xAttachSliceDataToNalUnit(nalu, pcBitstreamRedirect);
           accessUnit.push_back(new NALUnitEBSP(nalu));
-#if RATE_CONTROL_LAMBDA_DOMAIN
           actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
-#endif
           bNALUAlignedWrittenToList = true; 
           uiOneBitstreamPerSliceLength += nalu.m_Bitstream.getNumberOfWrittenBits(); // length of bitstream after byte-alignment
@@ -2338,8 +2308,27 @@
               m_pcEntropyCoder->resetEntropy();
               m_pcEntropyCoder->setBitstream( m_pcBitCounter );
+#if HM_CLEANUP_SAO
+              Bool sliceEnabled[NUM_SAO_COMPONENTS];
+              m_pcSAO->initRDOCabacCoder(m_pcEncTop->getRDGoOnSbacCoder(), pcSlice);
+              m_pcSAO->SAOProcess(pcPic
+                , sliceEnabled
+                , pcPic->getSlice(0)->getLambdas()
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                , m_pcCfg->getSaoLcuBoundary()
+#endif
+              );
+              m_pcSAO->PCMLFDisableProcess(pcPic);   
+
+              //assign SAO slice header
+              for(Int s=0; s< uiNumSlices; s++)
+              {
+                pcPic->getSlice(s)->setSaoEnabledFlag(sliceEnabled[SAO_Y]);
+                assert(sliceEnabled[SAO_Cb] == sliceEnabled[SAO_Cr]);
+                pcPic->getSlice(s)->setSaoEnabledFlagChroma(sliceEnabled[SAO_Cb]);
+              }
+#else
               m_pcSAO->startSaoEnc(pcPic, m_pcEntropyCoder, m_pcEncTop->getRDSbacCoder(), m_pcEncTop->getRDGoOnSbacCoder());
               SAOParam& cSaoParam = *pcSlice->getPic()->getPicSym()->getSaoParam();
 
-#if SAO_CHROMA_LAMBDA
 #if SAO_ENCODING_CHOICE
               m_pcSAO->SAOProcess(&cSaoParam, pcPic->getSlice(0)->getLambdaLuma(), pcPic->getSlice(0)->getLambdaChroma(), pcPic->getSlice(0)->getDepth());
@@ -2347,14 +2336,15 @@
               m_pcSAO->SAOProcess(&cSaoParam, pcPic->getSlice(0)->getLambdaLuma(), pcPic->getSlice(0)->getLambdaChroma());
 #endif
-#else
-              m_pcSAO->SAOProcess(&cSaoParam, pcPic->getSlice(0)->getLambda());
-#endif
               m_pcSAO->endSaoEnc();
               m_pcSAO->PCMLFDisableProcess(pcPic);
+#endif
             }
+#if !HM_CLEANUP_SAO          
 #if SAO_RDO
             m_pcEntropyCoder->setEntropyCoder ( m_pcCavlcCoder, pcSlice );
 #endif
+#endif
             processingState = ENCODE_SLICE;
+#if !HM_CLEANUP_SAO
 #if HIGHER_LAYER_IRAP_SKIP_FLAG
             if ( ( m_pcEncTop->getSkipPictureAtArcSwitch() && m_pcEncTop->getAdaptiveResolutionChange() > 0 && pcSlice->getLayerId() == 1 && pcSlice->getPOC() == m_pcEncTop->getAdaptiveResolutionChange()) )
@@ -2371,4 +2361,5 @@
               }
             }
+#endif
           }
           break;
@@ -2381,5 +2372,5 @@
         }
       } // end iteration over slices
-
+#if !HM_CLEANUP_SAO    
       if(pcSlice->getSPS()->getUseSAO())
       {
@@ -2390,5 +2381,5 @@
         pcPic->destroyNonDBFilterInfo();
       }
-
+#endif
       pcPic->compressMotion(); 
       
@@ -2490,10 +2481,6 @@
         }
       }
-#if RATE_CONTROL_LAMBDA_DOMAIN
       if ( m_pcCfg->getUseRateCtrl() )
       {
-#if !M0036_RC_IMPROVEMENT
-        Double effectivePercentage = m_pcRateCtrl->getRCPic()->getEffectivePercentage();
-#endif
         Double avgQP     = m_pcRateCtrl->getRCPic()->calAverageQP();
         Double avgLambda = m_pcRateCtrl->getRCPic()->calAverageLambda();
@@ -2502,13 +2489,5 @@
           avgLambda = lambda;
         }
-#if M0036_RC_IMPROVEMENT
-#if RATE_CONTROL_INTRA
         m_pcRateCtrl->getRCPic()->updateAfterPicture( actualHeadBits, actualTotalBits, avgQP, avgLambda, pcSlice->getSliceType());
-#else
-        m_pcRateCtrl->getRCPic()->updateAfterPicture( actualHeadBits, actualTotalBits, avgQP, avgLambda );
-#endif
-#else
-        m_pcRateCtrl->getRCPic()->updateAfterPicture( actualHeadBits, actualTotalBits, avgQP, avgLambda, effectivePercentage );
-#endif
         m_pcRateCtrl->getRCPic()->addToPictureLsit( m_pcRateCtrl->getPicList() );
 
@@ -2523,11 +2502,4 @@
         }
       }
-#else
-      if(m_pcCfg->getUseRateCtrl())
-      {
-        UInt  frameBits = m_vRVM_RP[m_vRVM_RP.size()-1];
-        m_pcRateCtrl->updataRCFrameStatus((Int)frameBits, pcSlice->getSliceType());
-      }
-#endif
 
       if( ( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() ) &&
@@ -2714,10 +2686,4 @@
       delete[] pcSubstreamsOut;
   }
-#if !RATE_CONTROL_LAMBDA_DOMAIN
-  if(m_pcCfg->getUseRateCtrl())
-  {
-    m_pcRateCtrl->updateRCGOPStatus();
-  }
-#endif
   delete pcBitstreamRedirect;
 
@@ -2802,4 +2768,5 @@
   m_pcEntropyCoder->resetEntropy    ();
   m_pcEntropyCoder->setBitstream    ( m_pcBitCounter );
+#if !HM_CLEANUP_SAO
   pcSlice = pcPic->getSlice(0);
   if(pcSlice->getSPS()->getUseSAO())
@@ -2816,5 +2783,5 @@
     pcPic->destroyNonDBFilterInfo();
   }
-  
+#endif
   m_pcEntropyCoder->resetEntropy    ();
   ruiBits += m_pcEntropyCoder->getNumberOfWrittenBits();
@@ -2888,4 +2855,5 @@
       iterPicYuvRec--;
     }
+    
   }
   
@@ -2983,5 +2951,5 @@
     case NAL_UNIT_CODED_SLICE_TRAIL_R:    return "TRAIL_R";
     case NAL_UNIT_CODED_SLICE_TRAIL_N:    return "TRAIL_N";
-    case NAL_UNIT_CODED_SLICE_TLA_R:      return "TLA_R";
+    case NAL_UNIT_CODED_SLICE_TSA_R:      return "TSA_R";
     case NAL_UNIT_CODED_SLICE_TSA_N:      return "TSA_N";
     case NAL_UNIT_CODED_SLICE_STSA_R:     return "STSA_R";
@@ -3218,6 +3186,6 @@
     for (Int x = 0; x < width; x++)
     {
-      dst[x] = isTff ? (UChar) top[x] : (UChar) bottom[x];
-      dst[stride+x] = isTff ? (UChar) bottom[x] : (UChar) top[x];
+      dst[x] = isTff ? top[x] : bottom[x];
+      dst[stride+x] = isTff ? bottom[x] : top[x];
     }
     top += stride;
@@ -3376,4 +3344,6 @@
   delete pcRecInterlaced;
 }
+
+
 
 /** Function for deciding the nal_unit_type.
Index: branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncRateCtrl.cpp
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncRateCtrl.cpp	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncRateCtrl.cpp	(revision 532)
@@ -42,6 +42,4 @@
 using namespace std;
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
-
 //sequence level
 TEncRCSeq::TEncRCSeq()
@@ -67,8 +65,6 @@
   m_bitsLeft            = 0;
   m_useLCUSeparateModel = false;
-#if M0036_RC_IMPROVEMENT
   m_adaptiveBit         = 0;
   m_lastLambda          = 0.0;
-#endif
 }
 
@@ -78,9 +74,5 @@
 }
 
-#if M0036_RC_IMPROVEMENT
 Void TEncRCSeq::create( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Int numberOfLevel, Bool useLCUSeparateModel, Int adaptiveBit )
-#else
-Void TEncRCSeq::create( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Int numberOfLevel, Bool useLCUSeparateModel )
-#endif
 {
   destroy();
@@ -109,5 +101,4 @@
     m_betaUpdate  = 0.025;
   }
-#if M0036_RC_IMPROVEMENT
   else if ( m_seqTargetBpp < 0.2 )
   {
@@ -125,11 +116,4 @@
     m_betaUpdate  = 0.2;
   }
-#else
-  else
-  {
-    m_alphaUpdate = 0.1;
-    m_betaUpdate  = 0.05;
-  }
-#endif
   m_averageBits     = (Int)(m_targetBits / totalFrames);
   Int picWidthInBU  = ( m_picWidth  % m_LCUWidth  ) == 0 ? m_picWidth  / m_LCUWidth  : m_picWidth  / m_LCUWidth  + 1;
@@ -172,8 +156,6 @@
   m_framesLeft = m_totalFrames;
   m_bitsLeft   = m_targetBits;
-#if M0036_RC_IMPROVEMENT
   m_adaptiveBit = adaptiveBit;
   m_lastLambda = 0.0;
-#endif
 }
 
@@ -233,5 +215,4 @@
     for ( Int i=0; i<m_numberOfLevel; i++ )
     {
-#if RATE_CONTROL_INTRA
       if (i>0)
       {
@@ -244,8 +225,4 @@
         m_picPara[i].m_beta  = BETA2;
       }
-#else
-      m_picPara[i].m_alpha = 3.2003;
-      m_picPara[i].m_beta  = -1.367;
-#endif
     }
   }
@@ -271,11 +248,6 @@
       for ( Int j=0; j<m_numberOfLCU; j++)
       {
-#if RATE_CONTROL_INTRA
         m_LCUPara[i][j].m_alpha = m_picPara[i].m_alpha;
         m_LCUPara[i][j].m_beta  = m_picPara[i].m_beta;
-#else
-        m_LCUPara[i][j].m_alpha = 3.2003;
-        m_LCUPara[i][j].m_beta  = -1.367;
-#endif
       }
     }
@@ -299,21 +271,4 @@
 }
 
-#if !RATE_CONTROL_INTRA
-Int TEncRCSeq::getRefineBitsForIntra( Int orgBits )
-{
-  Double bpp = ( (Double)orgBits ) / m_picHeight / m_picHeight;
-  if ( bpp > 0.2 )
-  {
-    return orgBits * 5;
-  }
-  if ( bpp > 0.1 )
-  {
-    return orgBits * 7;
-  }
-  return orgBits * 10;
-}
-#endif
-
-#if M0036_RC_IMPROVEMENT
 Void TEncRCSeq::setAllBitRatio( Double basicLambda, Double* equaCoeffA, Double* equaCoeffB )
 {
@@ -326,5 +281,4 @@
   delete[] bitsRatio;
 }
-#endif
 
 //GOP level
@@ -349,5 +303,4 @@
   Int targetBits = xEstGOPTargetBits( encRCSeq, numPic );
 
-#if M0036_RC_IMPROVEMENT
   if ( encRCSeq->getAdaptiveBits() > 0 && encRCSeq->getLastLambda() > 0.1 )
   {
@@ -409,5 +362,4 @@
     delete []equaCoeffB;
   }
-#endif
 
   m_picTargetBitInGOP = new Int[numPic];
@@ -422,9 +374,5 @@
   {
     currPicRatio = encRCSeq->getBitRatio( i );
-#if M0036_RC_IMPROVEMENT
     m_picTargetBitInGOP[i] = (Int)( ((Double)targetBits) * currPicRatio / totalPicRatio );
-#else
-    m_picTargetBitInGOP[i] = targetBits * currPicRatio / totalPicRatio;
-#endif
   }
 
@@ -436,5 +384,4 @@
 }
 
-#if M0036_RC_IMPROVEMENT
 Void TEncRCGOP::xCalEquaCoeff( TEncRCSeq* encRCSeq, Double* lambdaRatio, Double* equaCoeffA, Double* equaCoeffB, Int GOPSize )
 {
@@ -482,5 +429,4 @@
   return solution;
 }
-#endif
 
 Void TEncRCGOP::destroy()
@@ -534,11 +480,5 @@
 
   m_LCUs         = NULL;
-#if !M0036_RC_IMPROVEMENT
-  m_lastPicture  = NULL;
-#endif
   m_picActualHeaderBits = 0;
-#if !M0036_RC_IMPROVEMENT
-  m_totalMAD            = 0.0;
-#endif
   m_picActualBits       = 0;
   m_picQP               = 0;
@@ -565,9 +505,5 @@
   }
 
-#if M0036_RC_IMPROVEMENT
   targetBits  = Int( ((Double)GOPbitsLeft) * currPicRatio / totalPicRatio );
-#else
-  targetBits  = Int( GOPbitsLeft * currPicRatio / totalPicRatio );
-#endif
 
   if ( targetBits < 100 )
@@ -665,9 +601,5 @@
       m_LCUs[LCUIdx].m_lambda     = 0.0;
       m_LCUs[LCUIdx].m_targetBits = 0;
-#if M0036_RC_IMPROVEMENT
       m_LCUs[LCUIdx].m_bitWeight  = 1.0;
-#else
-      m_LCUs[LCUIdx].m_MAD        = 0.0;
-#endif
       Int currWidth  = ( (i == picWidthInLCU -1) ? picWidth  - LCUWidth *(picWidthInLCU -1) : LCUWidth  );
       Int currHeight = ( (j == picHeightInLCU-1) ? picHeight - LCUHeight*(picHeightInLCU-1) : LCUHeight );
@@ -676,23 +608,7 @@
   }
   m_picActualHeaderBits = 0;
-#if !M0036_RC_IMPROVEMENT
-  m_totalMAD            = 0.0;
-#endif
   m_picActualBits       = 0;
   m_picQP               = 0;
   m_picLambda           = 0.0;
-
-#if !M0036_RC_IMPROVEMENT
-  m_lastPicture = NULL;
-  list<TEncRCPic*>::reverse_iterator it;
-  for ( it = listPreviousPictures.rbegin(); it != listPreviousPictures.rend(); it++ )
-  {
-    if ( (*it)->getFrameLevel() == m_frameLevel )
-    {
-      m_lastPicture = (*it);
-      break;
-    }
-  }
-#endif
 }
 
@@ -709,14 +625,9 @@
 
 
-#if RATE_CONTROL_INTRA
 Double TEncRCPic::estimatePicLambda( list<TEncRCPic*>& listPreviousPictures, SliceType eSliceType)
-#else
-Double TEncRCPic::estimatePicLambda( list<TEncRCPic*>& listPreviousPictures )
-#endif
 {
   Double alpha         = m_encRCSeq->getPicPara( m_frameLevel ).m_alpha;
   Double beta          = m_encRCSeq->getPicPara( m_frameLevel ).m_beta;
   Double bpp       = (Double)m_targetBits/(Double)m_numberOfPixel;
-#if RATE_CONTROL_INTRA
   Double estLambda;
   if (eSliceType == I_SLICE)
@@ -728,7 +639,4 @@
     estLambda = alpha * pow( bpp, beta );
   }
-#else
-  Double estLambda = alpha * pow( bpp, beta );
-#endif  
   
   Double lastLevelLambda = -1.0;
@@ -778,10 +686,8 @@
   m_estPicLambda = estLambda;
 
-#if M0036_RC_IMPROVEMENT
   Double totalWeight = 0.0;
   // initial BU bit allocation weight
   for ( Int i=0; i<m_numberOfLCU; i++ )
   {
-#if RC_FIX
     Double alphaLCU, betaLCU;
     if ( m_encRCSeq->getUseLCUSeparateModel() )
@@ -795,8 +701,4 @@
       betaLCU  = m_encRCSeq->getPicPara( m_frameLevel ).m_beta;
     }
-#else
-    Double alphaLCU = m_encRCSeq->getLCUPara( m_frameLevel, i ).m_alpha;
-    Double betaLCU  = m_encRCSeq->getLCUPara( m_frameLevel, i ).m_beta;
-#endif
 
     m_LCUs[i].m_bitWeight =  m_LCUs[i].m_numberOfPixel * pow( estLambda/alphaLCU, 1.0/betaLCU );
@@ -813,5 +715,4 @@
     m_LCUs[i].m_bitWeight = BUTargetBits;
   }
-#endif
 
   return estLambda;
@@ -856,20 +757,12 @@
 }
 
-#if RATE_CONTROL_INTRA
 Double TEncRCPic::getLCUTargetBpp(SliceType eSliceType)  
-#else 
-Double TEncRCPic::getLCUTargetBpp()
-#endif
 {
   Int   LCUIdx    = getLCUCoded();
   Double bpp      = -1.0;
   Int avgBits     = 0;
-#if !M0036_RC_IMPROVEMENT
-  Double totalMAD = -1.0;
-  Double MAD      = -1.0;
-#endif
-
-#if RATE_CONTROL_INTRA
-  if (eSliceType == I_SLICE){
+
+  if (eSliceType == I_SLICE)
+  {
     Int noOfLCUsLeft = m_numberOfLCU - LCUIdx + 1;
     Int bitrateWindow = min(4,noOfLCUsLeft);
@@ -889,6 +782,4 @@
   else
   {
-#endif
-#if M0036_RC_IMPROVEMENT
   Double totalWeight = 0;
   for ( Int i=LCUIdx; i<m_numberOfLCU; i++ )
@@ -898,31 +789,5 @@
   Int realInfluenceLCU = min( g_RCLCUSmoothWindowSize, getLCULeft() );
   avgBits = (Int)( m_LCUs[LCUIdx].m_bitWeight - ( totalWeight - m_bitsLeft ) / realInfluenceLCU + 0.5 );
-#else
-  if ( m_lastPicture == NULL )
-  {
-    avgBits = Int( m_bitsLeft / m_LCULeft );
-  }
-  else
-  {
-    MAD = m_lastPicture->getLCU(LCUIdx).m_MAD;
-    totalMAD = m_lastPicture->getTotalMAD();
-    for ( Int i=0; i<LCUIdx; i++ )
-    {
-      totalMAD -= m_lastPicture->getLCU(i).m_MAD;
-    }
-
-    if ( totalMAD > 0.1 )
-    {
-      avgBits = Int( m_bitsLeft * MAD / totalMAD );
-    }
-    else
-    {
-      avgBits = Int( m_bitsLeft / m_LCULeft );
-    }
-  }
-#endif
-#if RATE_CONTROL_INTRA
-  }
-#endif
+    }
 
   if ( avgBits < 1 )
@@ -1050,11 +915,6 @@
     beta  *= ( 1.0 - m_encRCSeq->getBetaUpdate() / 2.0 );
 
-#if M0036_RC_IMPROVEMENT
     alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha );
     beta  = Clip3( g_RCBetaMinValue,  g_RCBetaMaxValue,  beta  );
-#else
-    alpha = Clip3( 0.05, 20.0, alpha );
-    beta  = Clip3( -3.0, -0.1, beta  );
-#endif
 
     TRCParameter rcPara;
@@ -1069,18 +929,9 @@
   alpha += m_encRCSeq->getAlphaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * alpha;
   double lnbpp = log( bpp );
-#if M0036_RC_IMPROVEMENT
   lnbpp = Clip3( -5.0, -0.1, lnbpp );
-#else
-  lnbpp = Clip3( -5.0, 1.0, lnbpp );
-#endif
   beta  += m_encRCSeq->getBetaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * lnbpp;
 
-#if M0036_RC_IMPROVEMENT
   alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha );
   beta  = Clip3( g_RCBetaMinValue,  g_RCBetaMaxValue,  beta  );
-#else
-  alpha = Clip3( 0.05, 20.0, alpha );
-  beta  = Clip3( -3.0, -0.1, beta  );
-#endif
   TRCParameter rcPara;
   rcPara.m_alpha = alpha;
@@ -1090,24 +941,4 @@
 }
 
-#if !M0036_RC_IMPROVEMENT
-Double TEncRCPic::getEffectivePercentage()
-{
-  Int effectivePiexels = 0;
-  Int totalPixels = 0;
-
-  for ( Int i=0; i<m_numberOfLCU; i++ )
-  {
-    totalPixels += m_LCUs[i].m_numberOfPixel;
-    if ( m_LCUs[i].m_QP > 0 )
-    {
-      effectivePiexels += m_LCUs[i].m_numberOfPixel;
-    }
-  }
-
-  Double effectivePixelPercentage = (Double)effectivePiexels/(Double)totalPixels;
-  return effectivePixelPercentage;
-}
-#endif
-
 Double TEncRCPic::calAverageQP()
 {
@@ -1164,13 +995,5 @@
 }
 
-#if M0036_RC_IMPROVEMENT
-#if RATE_CONTROL_INTRA
 Void TEncRCPic::updateAfterPicture( Int actualHeaderBits, Int actualTotalBits, Double averageQP, Double averageLambda, SliceType eSliceType)
-#else
-Void TEncRCPic::updateAfterPicture( Int actualHeaderBits, Int actualTotalBits, Double averageQP, Double averageLambda )
-#endif
-#else
-Void TEncRCPic::updateAfterPicture( Int actualHeaderBits, Int actualTotalBits, Double averageQP, Double averageLambda, Double effectivePercentage )
-#endif
 {
   m_picActualHeaderBits = actualHeaderBits;
@@ -1185,14 +1008,7 @@
   }
   m_picLambda           = averageLambda;
-#if !M0036_RC_IMPROVEMENT
-  for ( Int i=0; i<m_numberOfLCU; i++ )
-  {
-    m_totalMAD += m_LCUs[i].m_MAD;
-  }
-#endif
 
   Double alpha = m_encRCSeq->getPicPara( m_frameLevel ).m_alpha;
   Double beta  = m_encRCSeq->getPicPara( m_frameLevel ).m_beta;
-#if RATE_CONTROL_INTRA
   if (eSliceType == I_SLICE)
   {
@@ -1201,5 +1017,4 @@
   else
   {
-#endif
   // update parameters
   Double picActualBits = ( Double )m_picActualBits;
@@ -1208,20 +1023,11 @@
   Double inputLambda   = m_picLambda;
 
-#if M0036_RC_IMPROVEMENT
   if ( inputLambda < 0.01 || calLambda < 0.01 || picActualBpp < 0.0001 )
-#else
-  if ( inputLambda < 0.01 || calLambda < 0.01 || picActualBpp < 0.0001 || effectivePercentage < 0.05 )
-#endif
   {
     alpha *= ( 1.0 - m_encRCSeq->getAlphaUpdate() / 2.0 );
     beta  *= ( 1.0 - m_encRCSeq->getBetaUpdate() / 2.0 );
 
-#if M0036_RC_IMPROVEMENT
     alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha );
     beta  = Clip3( g_RCBetaMinValue,  g_RCBetaMaxValue,  beta  );
-#else
-    alpha = Clip3( 0.05, 20.0, alpha );
-    beta  = Clip3( -3.0, -0.1, beta  );
-#endif
     TRCParameter rcPara;
     rcPara.m_alpha = alpha;
@@ -1235,21 +1041,10 @@
   alpha += m_encRCSeq->getAlphaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * alpha;
   double lnbpp = log( picActualBpp );
-#if M0036_RC_IMPROVEMENT
   lnbpp = Clip3( -5.0, -0.1, lnbpp );
-#else
-  lnbpp = Clip3( -5.0, 1.0, lnbpp );
-#endif
   beta  += m_encRCSeq->getBetaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * lnbpp;
 
-#if M0036_RC_IMPROVEMENT
   alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha );
   beta  = Clip3( g_RCBetaMinValue,  g_RCBetaMaxValue,  beta  );
-#else
-  alpha = Clip3( 0.05, 20.0, alpha );
-  beta  = Clip3( -3.0, -0.1, beta  );
-#endif
-#if RATE_CONTROL_INTRA
-  }
-#endif
+  }
 
   TRCParameter rcPara;
@@ -1259,5 +1054,4 @@
   m_encRCSeq->setPicPara( m_frameLevel, rcPara );
 
-#if M0036_RC_IMPROVEMENT
   if ( m_frameLevel == 1 )
   {
@@ -1266,8 +1060,6 @@
     m_encRCSeq->setLastLambda( updateLastLambda );
   }
-#endif
-}
-
-#if RATE_CONTROL_INTRA
+}
+
 Int TEncRCPic::getRefineBitsForIntra( Int orgBits )
 {
@@ -1358,5 +1150,4 @@
   return estLambda;
 }
-#endif
 
 TEncRateCtrl::TEncRateCtrl()
@@ -1392,9 +1183,5 @@
 }
 
-#if M0036_RC_IMPROVEMENT
 Void TEncRateCtrl::init( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Int keepHierBits, Bool useLCUSeparateModel, GOPEntry  GOPList[MAX_GOP] )
-#else
-Void TEncRateCtrl::init( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Bool keepHierBits, Bool useLCUSeparateModel, GOPEntry  GOPList[MAX_GOP] )
-#endif
 {
   destroy();
@@ -1411,10 +1198,6 @@
 
   Int numberOfLevel = 1;
-#if M0036_RC_IMPROVEMENT
   Int adaptiveBit = 0;
   if ( keepHierBits > 0 )
-#else
-  if ( keepHierBits )
-#endif
   {
     numberOfLevel = Int( log((Double)GOPSize)/log(2.0) + 0.5 ) + 1;
@@ -1439,9 +1222,5 @@
   }
 
-#if M0036_RC_IMPROVEMENT
   if ( keepHierBits > 0 )
-#else
-  if ( keepHierBits )
-#endif
   {
     Double bpp = (Double)( targetBitrate / (Double)( frameRate*picWidth*picHeight ) );
@@ -1476,10 +1255,8 @@
         bitsRatio[3] = 14;
       }
-#if M0036_RC_IMPROVEMENT
       if ( keepHierBits == 2 )
       {
         adaptiveBit = 1;
       }
-#endif
     }
     else if ( GOPSize == 8 && !isLowdelay )
@@ -1529,18 +1306,12 @@
         bitsRatio[7] = 1;
       }
-#if M0036_RC_IMPROVEMENT
       if ( keepHierBits == 2 )
       {
         adaptiveBit = 2;
       }
-#endif
     }
     else
     {
-#if M0036_RC_IMPROVEMENT
       printf( "\n hierarchical bit allocation is not support for the specified coding structure currently.\n" );
-#else
-      printf( "\n hierarchical bit allocation is not support for the specified coding structure currently." );
-#endif
     }
   }
@@ -1555,9 +1326,5 @@
     }
   }
-#if M0036_RC_IMPROVEMENT
   if ( keepHierBits > 0 )
-#else
-  if ( keepHierBits )
-#endif
   {
     if ( GOPSize == 4 && isLowdelay )
@@ -1594,9 +1361,5 @@
 
   m_encRCSeq = new TEncRCSeq;
-#if M0036_RC_IMPROVEMENT
   m_encRCSeq->create( totalFrames, targetBitrate, frameRate, GOPSize, picWidth, picHeight, LCUWidth, LCUHeight, numberOfLevel, useLCUSeparateModel, adaptiveBit );
-#else
-  m_encRCSeq->create( totalFrames, targetBitrate, frameRate, GOPSize, picWidth, picHeight, LCUWidth, LCUHeight, numberOfLevel, useLCUSeparateModel );
-#endif
   m_encRCSeq->initBitsRatio( bitsRatio );
   m_encRCSeq->initGOPID2Level( GOPID2Level );
@@ -1629,596 +1392,2 @@
 }
 
-#else
-
-#define ADJUSTMENT_FACTOR       0.60
-#define HIGH_QSTEP_THRESHOLD    9.5238
-#define HIGH_QSTEP_ALPHA        4.9371
-#define HIGH_QSTEP_BETA         0.0922
-#define LOW_QSTEP_ALPHA         16.7429
-#define LOW_QSTEP_BETA          -1.1494
-
-#define MAD_PRED_Y1             1.0
-#define MAD_PRED_Y2             0.0
-
-enum MAD_HISOTRY {
-  MAD_PPPrevious = 0,
-  MAD_PPrevious  = 1,
-  MAD_Previous   = 2
-};
-
-Void    MADLinearModel::initMADLinearModel()
-{
-  m_activeOn = false;
-  m_paramY1  = 1.0;
-  m_paramY2  = 0.0;
-  m_costMADs[0] = m_costMADs[1] = m_costMADs[2] = 0.0;
-}
-
-Double  MADLinearModel::getMAD()
-{
-  Double costPredMAD = m_paramY1 * m_costMADs[MAD_Previous] + m_paramY2;
-
-  if(costPredMAD < 0)
-  {
-    costPredMAD = m_costMADs[MAD_Previous];
-    m_paramY1   = MAD_PRED_Y1;
-    m_paramY2   = MAD_PRED_Y2;
-  } 
-  return costPredMAD;
-}
-
-Void    MADLinearModel::updateMADLiearModel()
-{
-  Double dNewY1 = ((m_costMADs[MAD_Previous] - m_costMADs[MAD_PPrevious]) / (m_costMADs[MAD_PPrevious] - m_costMADs[MAD_PPPrevious]));
-  Double dNewY2 =  (m_costMADs[MAD_Previous] - (dNewY1*m_costMADs[MAD_PPrevious]));
-  
-  m_paramY1 = 0.70+0.20*m_paramY1+ 0.10*dNewY1;
-  m_paramY2 =      0.20*m_paramY2+ 0.10*dNewY2;
-}
-
-Void    MADLinearModel::updateMADHistory(Double dMAD)
-{
-  m_costMADs[MAD_PPPrevious] = m_costMADs[MAD_PPrevious];
-  m_costMADs[MAD_PPrevious ] = m_costMADs[MAD_Previous ];
-  m_costMADs[MAD_Previous  ] = dMAD;
-  m_activeOn = (m_costMADs[MAD_Previous  ] && m_costMADs[MAD_PPrevious ] && m_costMADs[MAD_PPPrevious]);
-}
-
-
-Void    PixelBaseURQQuadraticModel::initPixelBaseQuadraticModel()
-{
-  m_paramHighX1 = HIGH_QSTEP_ALPHA;
-  m_paramHighX2 = HIGH_QSTEP_BETA;
-  m_paramLowX1  = LOW_QSTEP_ALPHA;
-  m_paramLowX2  = LOW_QSTEP_BETA;
-}
-
-Int     PixelBaseURQQuadraticModel::getQP(Int qp, Int targetBits, Int numberOfPixels, Double costPredMAD)
-{
-  Double qStep;
-  Double bppPerMAD = (Double)(targetBits/(numberOfPixels*costPredMAD));
-  
-  if(xConvertQP2QStep(qp) >= HIGH_QSTEP_THRESHOLD)
-  {
-    qStep = 1/( sqrt((bppPerMAD/m_paramHighX1)+((m_paramHighX2*m_paramHighX2)/(4*m_paramHighX1*m_paramHighX1))) - (m_paramHighX2/(2*m_paramHighX1)));
-  }
-  else
-  {
-    qStep = 1/( sqrt((bppPerMAD/m_paramLowX1)+((m_paramLowX2*m_paramLowX2)/(4*m_paramLowX1*m_paramLowX1))) - (m_paramLowX2/(2*m_paramLowX1)));
-  }
-  
-  return xConvertQStep2QP(qStep);
-}
-
-Void    PixelBaseURQQuadraticModel::updatePixelBasedURQQuadraticModel (Int qp, Int bits, Int numberOfPixels, Double costMAD)
-{
-  Double qStep     = xConvertQP2QStep(qp);
-  Double invqStep = (1/qStep);
-  Double paramNewX1, paramNewX2;
-  
-  if(qStep >= HIGH_QSTEP_THRESHOLD)
-  {
-    paramNewX2    = (((bits/(numberOfPixels*costMAD))-(23.3772*invqStep*invqStep))/((1-200*invqStep)*invqStep));
-    paramNewX1    = (23.3772-200*paramNewX2);
-    m_paramHighX1 = 0.70*HIGH_QSTEP_ALPHA + 0.20 * m_paramHighX1 + 0.10 * paramNewX1;
-    m_paramHighX2 = 0.70*HIGH_QSTEP_BETA  + 0.20 * m_paramHighX2 + 0.10 * paramNewX2;
-  }
-  else
-  {
-    paramNewX2   = (((bits/(numberOfPixels*costMAD))-(5.8091*invqStep*invqStep))/((1-9.5455*invqStep)*invqStep));
-    paramNewX1   = (5.8091-9.5455*paramNewX2);
-    m_paramLowX1 = 0.90*LOW_QSTEP_ALPHA + 0.09 * m_paramLowX1 + 0.01 * paramNewX1;
-    m_paramLowX2 = 0.90*LOW_QSTEP_BETA  + 0.09 * m_paramLowX2 + 0.01 * paramNewX2;
-  }
-}
-
-Bool    PixelBaseURQQuadraticModel::checkUpdateAvailable(Int qpReference )
-{ 
-  Double qStep = xConvertQP2QStep(qpReference);
-
-  if (qStep > xConvertQP2QStep(MAX_QP) 
-    ||qStep < xConvertQP2QStep(MIN_QP) )
-  {
-    return false;
-  }
-
-  return true;
-}
-
-Double  PixelBaseURQQuadraticModel::xConvertQP2QStep(Int qp )
-{
-  Int i;
-  Double qStep;
-  static const Double mapQP2QSTEP[6] = { 0.625, 0.703, 0.797, 0.891, 1.000, 1.125 };
-
-  qStep = mapQP2QSTEP[qp % 6];
-  for( i=0; i<(qp/6); i++)
-  {
-    qStep *= 2;
-  }
-
-  return qStep;
-}
-
-Int     PixelBaseURQQuadraticModel::xConvertQStep2QP(Double qStep )
-{
-  Int per = 0, rem = 0;
-
-  if( qStep < xConvertQP2QStep(MIN_QP))
-  {
-    return MIN_QP;
-  }
-  else if (qStep > xConvertQP2QStep(MAX_QP) )
-  {
-    return MAX_QP;
-  }
-
-  while( qStep > xConvertQP2QStep(5) )
-  {
-    qStep /= 2.0;
-    per++;
-  }
-
-  if (qStep <= 0.625)
-  {
-    rem = 0;
-  }
-  else if (qStep <= 0.703)
-  {
-    rem = 1;
-  }
-  else if (qStep <= 0.797)
-  {
-    rem = 2;
-  }
-  else if (qStep <= 0.891)
-  {
-    rem = 3;
-  }
-  else if (qStep <= 1.000)
-  {
-    rem = 4;
-  }
-  else
-  {
-    rem = 5;
-  }
-  return (per * 6 + rem);
-}
-
-
-Void  TEncRateCtrl::create(Int sizeIntraPeriod, Int sizeGOP, Int frameRate, Int targetKbps, Int qp, Int numLCUInBasicUnit, Int sourceWidth, Int sourceHeight, Int maxCUWidth, Int maxCUHeight)
-{
-  Int leftInHeight, leftInWidth;
-
-  m_sourceWidthInLCU         = (sourceWidth  / maxCUWidth  ) + (( sourceWidth  %  maxCUWidth ) ? 1 : 0);
-  m_sourceHeightInLCU        = (sourceHeight / maxCUHeight) + (( sourceHeight %  maxCUHeight) ? 1 : 0);  
-  m_isLowdelay               = (sizeIntraPeriod == -1) ? true : false;
-  m_prevBitrate              = ( targetKbps << 10 );  // in units of 1,024 bps
-  m_currBitrate              = ( targetKbps << 10 );
-  m_frameRate                = frameRate;
-  m_refFrameNum              = m_isLowdelay ? (sizeGOP) : (sizeGOP>>1);
-  m_nonRefFrameNum           = sizeGOP-m_refFrameNum;
-  m_sizeGOP                  = sizeGOP;
-  m_numOfPixels              = ((sourceWidth*sourceHeight*3)>>1);
-  m_indexGOP                 = 0;
-  m_indexFrame               = 0;
-  m_indexLCU                 = 0;
-  m_indexUnit                = 0;
-  m_indexRefFrame            = 0;
-  m_indexNonRefFrame         = 0;
-  m_occupancyVB              = 0;
-  m_initialOVB               = 0;
-  m_targetBufLevel           = 0;
-  m_initialTBL               = 0;
-  m_occupancyVBInFrame       = 0;
-  m_remainingBitsInGOP       = (m_currBitrate*sizeGOP/m_frameRate);
-  m_remainingBitsInFrame     = 0;
-  m_numUnitInFrame           = m_sourceWidthInLCU*m_sourceHeightInLCU;
-  m_cMADLinearModel.        initMADLinearModel();
-  m_cPixelURQQuadraticModel.initPixelBaseQuadraticModel();
-
-  m_costRefAvgWeighting      = 0.0;
-  m_costNonRefAvgWeighting   = 0.0;
-  m_costAvgbpp               = 0.0;  
-  m_activeUnitLevelOn        = false;
-
-  m_pcFrameData              = new FrameData   [sizeGOP+1];         initFrameData(qp);
-  m_pcLCUData                = new LCUData     [m_numUnitInFrame];  initUnitData (qp);
-
-  for(Int i = 0, addressUnit = 0; i < m_sourceHeightInLCU*maxCUHeight; i += maxCUHeight)  
-  {
-    leftInHeight = sourceHeight - i;
-    leftInHeight = min(leftInHeight, maxCUHeight);
-    for(Int j = 0; j < m_sourceWidthInLCU*maxCUWidth; j += maxCUWidth, addressUnit++)
-    {
-      leftInWidth = sourceWidth - j;
-      leftInWidth = min(leftInWidth, maxCUWidth);
-      m_pcLCUData[addressUnit].m_widthInPixel = leftInWidth;
-      m_pcLCUData[addressUnit].m_heightInPixel= leftInHeight;
-      m_pcLCUData[addressUnit].m_pixels       = ((leftInHeight*leftInWidth*3)>>1);
-    }
-  }
-}
-
-Void  TEncRateCtrl::destroy()
-{
-  if(m_pcFrameData)
-  {
-    delete [] m_pcFrameData;
-    m_pcFrameData = NULL;
-  }
-  if(m_pcLCUData)
-  {
-    delete [] m_pcLCUData;
-    m_pcLCUData = NULL;
-  }
-}
-
-Void  TEncRateCtrl::initFrameData   (Int qp)
-{
-  for(Int i = 0 ; i <= m_sizeGOP; i++)
-  {
-    m_pcFrameData[i].m_isReferenced = false;
-    m_pcFrameData[i].m_costMAD      = 0.0;
-    m_pcFrameData[i].m_bits         = 0;
-    m_pcFrameData[i].m_qp           = qp;
-  }
-}
-
-Void  TEncRateCtrl::initUnitData    (Int qp)
-{
-  for(Int i = 1 ; i < m_numUnitInFrame; i++)
-  {
-    m_pcLCUData[i].m_qp            = qp;
-    m_pcLCUData[i].m_bits          = 0;
-    m_pcLCUData[i].m_pixels        = 0;
-    m_pcLCUData[i].m_widthInPixel  = 0;
-    m_pcLCUData[i].m_heightInPixel = 0;
-    m_pcLCUData[i].m_costMAD       = 0.0;
-  }
-}
-
-Int  TEncRateCtrl::getFrameQP(Bool isReferenced, Int POC)
-{
-  Int numofReferenced = 0;
-  Int finalQP = 0;
-  FrameData* pcFrameData;
-
-  m_indexPOCInGOP = (POC%m_sizeGOP) == 0 ? m_sizeGOP : (POC%m_sizeGOP);
-  pcFrameData     = &m_pcFrameData[m_indexPOCInGOP];
-    
-  if(m_indexFrame != 0)
-  {
-    if(isReferenced)
-    {
-      Double gamma = m_isLowdelay ? 0.5 : 0.25;
-      Double beta  = m_isLowdelay ? 0.9 : 0.6;
-      Int    numRemainingRefFrames  = m_refFrameNum    - m_indexRefFrame;
-      Int    numRemainingNRefFrames = m_nonRefFrameNum - m_indexNonRefFrame;
-      
-      Double targetBitsOccupancy  = (m_currBitrate/(Double)m_frameRate) + gamma*(m_targetBufLevel-m_occupancyVB - (m_initialOVB/(Double)m_frameRate));
-      Double targetBitsLeftBudget = ((m_costRefAvgWeighting*m_remainingBitsInGOP)/((m_costRefAvgWeighting*numRemainingRefFrames)+(m_costNonRefAvgWeighting*numRemainingNRefFrames)));
-
-      m_targetBits = (Int)(beta * targetBitsLeftBudget + (1-beta) * targetBitsOccupancy);
-  
-      if(m_targetBits <= 0 || m_remainingBitsInGOP <= 0)
-      {
-        finalQP = m_pcFrameData[m_indexPrevPOCInGOP].m_qp + 2;
-      }
-      else
-      {
-        Double costPredMAD   = m_cMADLinearModel.getMAD();
-        Int    qpLowerBound = m_pcFrameData[m_indexPrevPOCInGOP].m_qp-2;
-        Int    qpUpperBound = m_pcFrameData[m_indexPrevPOCInGOP].m_qp+2;
-        finalQP = m_cPixelURQQuadraticModel.getQP(m_pcFrameData[m_indexPrevPOCInGOP].m_qp, m_targetBits, m_numOfPixels, costPredMAD);
-        finalQP = max(qpLowerBound, min(qpUpperBound, finalQP));
-        m_activeUnitLevelOn    = true;
-        m_remainingBitsInFrame = m_targetBits;
-        m_costAvgbpp           = (m_targetBits/(Double)m_numOfPixels);
-      }
-
-      m_indexRefFrame++;
-    }
-    else
-    {
-      Int bwdQP = m_pcFrameData[m_indexPOCInGOP-1].m_qp;
-      Int fwdQP = m_pcFrameData[m_indexPOCInGOP+1].m_qp;
-       
-      if( (fwdQP+bwdQP) == m_pcFrameData[m_indexPOCInGOP-1].m_qp
-        ||(fwdQP+bwdQP) == m_pcFrameData[m_indexPOCInGOP+1].m_qp)
-      {
-        finalQP = (fwdQP+bwdQP);
-      }
-      else if(bwdQP != fwdQP)
-      {
-        finalQP = ((bwdQP+fwdQP+2)>>1);
-      }
-      else
-      {
-        finalQP = bwdQP+2;
-      }
-      m_indexNonRefFrame++;
-    }
-  }
-  else
-  {
-    Int lastQPminus2 = m_pcFrameData[0].m_qp - 2;
-    Int lastQPplus2  = m_pcFrameData[0].m_qp + 2;
-
-    for(Int idx = 1; idx <= m_sizeGOP; idx++)
-    {
-      if(m_pcFrameData[idx].m_isReferenced)
-      {
-        finalQP += m_pcFrameData[idx].m_qp;
-        numofReferenced++;
-      }
-    }
-    
-    finalQP = (numofReferenced == 0) ? m_pcFrameData[0].m_qp : ((finalQP + (1<<(numofReferenced>>1)))/numofReferenced);
-    finalQP = max( lastQPminus2, min( lastQPplus2, finalQP));
-
-    Double costAvgFrameBits = m_remainingBitsInGOP/(Double)m_sizeGOP;
-    Int    bufLevel  = m_occupancyVB + m_initialOVB;
-
-    if(abs(bufLevel) > costAvgFrameBits)
-    {
-      if(bufLevel < 0)
-      {
-        finalQP -= 2;
-      }
-      else
-      {
-        finalQP += 2;
-      }
-    }
-    m_indexRefFrame++;
-  }
-  finalQP = max(MIN_QP, min(MAX_QP, finalQP));
-
-  for(Int indexLCU = 0 ; indexLCU < m_numUnitInFrame; indexLCU++)
-  {
-    m_pcLCUData[indexLCU].m_qp = finalQP;
-  }
-
-  pcFrameData->m_isReferenced = isReferenced;
-  pcFrameData->m_qp           = finalQP;
-
-  return finalQP;
-}
-
-Bool  TEncRateCtrl::calculateUnitQP ()
-{
-  if(!m_activeUnitLevelOn || m_indexLCU == 0)
-  {
-    return false;
-  }
-  Int upperQPBound, lowerQPBound, finalQP;
-  Int    colQP        = m_pcLCUData[m_indexLCU].m_qp;
-  Double colMAD       = m_pcLCUData[m_indexLCU].m_costMAD;
-  Double budgetInUnit = m_pcLCUData[m_indexLCU].m_pixels*m_costAvgbpp;
-
-
-  Int targetBitsOccupancy = (Int)(budgetInUnit - (m_occupancyVBInFrame/(m_numUnitInFrame-m_indexUnit)));
-  Int targetBitsLeftBudget= (Int)((m_remainingBitsInFrame*m_pcLCUData[m_indexLCU].m_pixels)/(Double)(m_numOfPixels-m_codedPixels));
-  Int targetBits = (targetBitsLeftBudget>>1) + (targetBitsOccupancy>>1);
-  
-
-  if( m_indexLCU >= m_sourceWidthInLCU)
-  {
-    upperQPBound = ( (m_pcLCUData[m_indexLCU-1].m_qp + m_pcLCUData[m_indexLCU - m_sourceWidthInLCU].m_qp)>>1) + MAX_DELTA_QP;
-    lowerQPBound = ( (m_pcLCUData[m_indexLCU-1].m_qp + m_pcLCUData[m_indexLCU - m_sourceWidthInLCU].m_qp)>>1) - MAX_DELTA_QP;
-  }
-  else
-  {
-    upperQPBound = m_pcLCUData[m_indexLCU-1].m_qp + MAX_DELTA_QP;
-    lowerQPBound = m_pcLCUData[m_indexLCU-1].m_qp - MAX_DELTA_QP;
-  }
-
-  if(targetBits < 0)
-  {
-    finalQP = m_pcLCUData[m_indexLCU-1].m_qp + 1;
-  }
-  else
-  {
-    finalQP = m_cPixelURQQuadraticModel.getQP(colQP, targetBits, m_pcLCUData[m_indexLCU].m_pixels, colMAD);
-  }
-  
-  finalQP = max(lowerQPBound, min(upperQPBound, finalQP));
-  m_pcLCUData[m_indexLCU].m_qp = max(MIN_QP, min(MAX_QP, finalQP));
-  
-  return true;
-}
-
-Void  TEncRateCtrl::updateRCGOPStatus()
-{
-  m_remainingBitsInGOP = ((m_currBitrate/m_frameRate)*m_sizeGOP) - m_occupancyVB;
-  
-  FrameData cFrameData = m_pcFrameData[m_sizeGOP];
-  initFrameData();
-
-  m_pcFrameData[0]   = cFrameData;
-  m_indexGOP++;
-  m_indexFrame       = 0;
-  m_indexRefFrame    = 0;
-  m_indexNonRefFrame = 0;
-}
-
-Void  TEncRateCtrl::updataRCFrameStatus(Int frameBits, SliceType eSliceType)
-{
-  FrameData* pcFrameData = &m_pcFrameData[m_indexPOCInGOP];
-  Int occupancyBits;
-  Double adjustmentBits;
-
-  m_remainingBitsInGOP = m_remainingBitsInGOP + ( ((m_currBitrate-m_prevBitrate)/m_frameRate)*(m_sizeGOP-m_indexFrame) ) - frameBits;
-  occupancyBits        = (Int)((Double)frameBits - (m_currBitrate/(Double)m_frameRate));
-  
-  if( (occupancyBits < 0) && (m_initialOVB > 0) )
-  {
-    adjustmentBits = xAdjustmentBits(occupancyBits, m_initialOVB );
-
-    if(m_initialOVB < 0)
-    {
-      adjustmentBits = m_initialOVB;
-      occupancyBits += (Int)adjustmentBits;
-      m_initialOVB   =  0;
-    }
-  }
-  else if( (occupancyBits > 0) && (m_initialOVB < 0) )
-  {
-    adjustmentBits = xAdjustmentBits(m_initialOVB, occupancyBits );
-    
-    if(occupancyBits < 0)
-    {
-      adjustmentBits = occupancyBits;
-      m_initialOVB  += (Int)adjustmentBits;
-      occupancyBits  =  0;
-    }
-  }
-
-  if(m_indexGOP == 0)
-  {
-    m_initialOVB = occupancyBits;
-  }
-  else
-  {
-    m_occupancyVB= m_occupancyVB + occupancyBits;
-  }
-
-  if(pcFrameData->m_isReferenced)
-  {
-    m_costRefAvgWeighting  = ((pcFrameData->m_bits*pcFrameData->m_qp)/8.0) + (7.0*(m_costRefAvgWeighting)/8.0);
-
-    if(m_indexFrame == 0)
-    {
-      m_initialTBL = m_targetBufLevel  = (frameBits - (m_currBitrate/m_frameRate));
-    }
-    else
-    {
-      Int distance = (m_costNonRefAvgWeighting == 0) ? 0 : 1;
-      m_targetBufLevel =  m_targetBufLevel 
-                            - (m_initialTBL/(m_refFrameNum-1)) 
-                            + (Int)((m_costRefAvgWeighting*(distance+1)*m_currBitrate)/(m_frameRate*(m_costRefAvgWeighting+(m_costNonRefAvgWeighting*distance)))) 
-                            - (m_currBitrate/m_frameRate);
-    }
-
-    if(m_cMADLinearModel.IsUpdateAvailable())
-    {
-      m_cMADLinearModel.updateMADLiearModel();
-    }
-
-    if(eSliceType != I_SLICE &&
-       m_cPixelURQQuadraticModel.checkUpdateAvailable(pcFrameData->m_qp))
-    {
-      m_cPixelURQQuadraticModel.updatePixelBasedURQQuadraticModel(pcFrameData->m_qp, pcFrameData->m_bits, m_numOfPixels, pcFrameData->m_costMAD);
-    }
-  }
-  else
-  {
-    m_costNonRefAvgWeighting = ((pcFrameData->m_bits*pcFrameData->m_qp)/8.0) + (7.0*(m_costNonRefAvgWeighting)/8.0);
-  }
-
-  m_indexFrame++;
-  m_indexLCU             = 0;
-  m_indexUnit            = 0;
-  m_occupancyVBInFrame   = 0;
-  m_remainingBitsInFrame = 0;
-  m_codedPixels          = 0;
-  m_activeUnitLevelOn    = false;
-  m_costAvgbpp           = 0.0;
-}
-Void  TEncRateCtrl::updataRCUnitStatus ()
-{
-  if(!m_activeUnitLevelOn || m_indexLCU == 0)
-  {
-    return;
-  }
-
-  m_codedPixels  += m_pcLCUData[m_indexLCU-1].m_pixels;
-  m_remainingBitsInFrame = m_remainingBitsInFrame - m_pcLCUData[m_indexLCU-1].m_bits;
-  m_occupancyVBInFrame   = (Int)(m_occupancyVBInFrame + m_pcLCUData[m_indexLCU-1].m_bits - m_pcLCUData[m_indexLCU-1].m_pixels*m_costAvgbpp);
-
-  if( m_cPixelURQQuadraticModel.checkUpdateAvailable(m_pcLCUData[m_indexLCU-1].m_qp) )
-  {
-    m_cPixelURQQuadraticModel.updatePixelBasedURQQuadraticModel(m_pcLCUData[m_indexLCU-1].m_qp, m_pcLCUData[m_indexLCU-1].m_bits, m_pcLCUData[m_indexLCU-1].m_pixels, m_pcLCUData[m_indexLCU-1].m_costMAD);
-  }
-
-  m_indexUnit++;
-}
-
-Void  TEncRateCtrl::updateFrameData(UInt64 actualFrameBits)
-{
-  Double costMAD = 0.0;
-  
-  for(Int i = 0; i < m_numUnitInFrame; i++)
-  {
-    costMAD    += m_pcLCUData[i].m_costMAD;
-  }
-  
-  m_pcFrameData[m_indexPOCInGOP].m_costMAD = (costMAD/(Double)m_numUnitInFrame);
-  m_pcFrameData[m_indexPOCInGOP].m_bits    = (Int)actualFrameBits;
-  
-  if(m_pcFrameData[m_indexPOCInGOP].m_isReferenced)
-  {
-    m_indexPrevPOCInGOP = m_indexPOCInGOP;
-    m_cMADLinearModel.updateMADHistory(m_pcFrameData[m_indexPOCInGOP].m_costMAD);
-  }
-}
-
-Void  TEncRateCtrl::updateLCUData(TComDataCU* pcCU, UInt64 actualLCUBits, Int qp)
-{
-  Int     x, y;
-  Double  costMAD = 0.0;
-
-  Pel*  pOrg   = pcCU->getPic()->getPicYuvOrg()->getLumaAddr(pcCU->getAddr(), 0);
-  Pel*  pRec   = pcCU->getPic()->getPicYuvRec()->getLumaAddr(pcCU->getAddr(), 0);
-  Int   stride = pcCU->getPic()->getStride();
-
-  Int   width  = m_pcLCUData[m_indexLCU].m_widthInPixel;
-  Int   height = m_pcLCUData[m_indexLCU].m_heightInPixel;
-
-  for( y = 0; y < height; y++ )
-  {
-    for( x = 0; x < width; x++ )
-    {
-      costMAD += abs( pOrg[x] - pRec[x] );
-    }
-    pOrg += stride;
-    pRec += stride;
-  }
-  m_pcLCUData[m_indexLCU  ].m_qp      = qp;
-  m_pcLCUData[m_indexLCU  ].m_costMAD = (costMAD /(Double)(width*height));
-  m_pcLCUData[m_indexLCU++].m_bits    = (Int)actualLCUBits;
-}
-
-Double TEncRateCtrl::xAdjustmentBits(Int& reductionBits, Int& compensationBits)
-{
-  Double adjustment  = ADJUSTMENT_FACTOR*reductionBits;
-  reductionBits     -= (Int)adjustment;
-  compensationBits  += (Int)adjustment;
-
-  return adjustment;
-}
-
-#endif
-
Index: branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncRateCtrl.h
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncRateCtrl.h	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncRateCtrl.h	(revision 532)
@@ -55,5 +55,4 @@
 //! \{
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
 #include "../TLibEncoder/TEncCfg.h"
 #include <list>
@@ -65,5 +64,4 @@
 const Double g_RCWeightPicTargetBitInGOP    = 0.9;
 const Double g_RCWeightPicRargetBitInBuffer = 1.0 - g_RCWeightPicTargetBitInGOP;
-#if M0036_RC_IMPROVEMENT
 const Int g_RCIterationNum = 20;
 const Double g_RCWeightHistoryLambda = 0.5;
@@ -74,11 +72,8 @@
 const Double g_RCBetaMinValue  = -3.0;
 const Double g_RCBetaMaxValue  = -0.1;
-#endif
-
-#if RATE_CONTROL_INTRA
+
 #define ALPHA     6.7542;
 #define BETA1     1.2517
 #define BETA2     1.7860
-#endif
 
 struct TRCLCU
@@ -88,14 +83,8 @@
   Int m_targetBits;
   Double m_lambda;
-#if M0036_RC_IMPROVEMENT
   Double m_bitWeight;
-#else
-  Double m_MAD;
-#endif
   Int m_numberOfPixel;
-#if RATE_CONTROL_INTRA
   Double m_costIntra;
   Int m_targetBitsLeft;
-#endif
 };
 
@@ -113,9 +102,5 @@
 
 public:
-#if M0036_RC_IMPROVEMENT
   Void create( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Int numberOfLevel, Bool useLCUSeparateModel, Int adaptiveBit );
-#else
-  Void create( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Int numberOfLevel, Bool useLCUSeparateModel );
-#endif
   Void destroy();
   Void initBitsRatio( Int bitsRatio[] );
@@ -124,10 +109,5 @@
   Void initLCUPara( TRCParameter** LCUPara = NULL );    // NULL to initial with default value
   Void updateAfterPic ( Int bits );
-#if !RATE_CONTROL_INTRA
-  Int  getRefineBitsForIntra( Int orgBits );
-#endif
-#if M0036_RC_IMPROVEMENT
   Void setAllBitRatio( Double basicLambda, Double* equaCoeffA, Double* equaCoeffB );
-#endif
 
 public:
@@ -167,9 +147,7 @@
   Double getBetaUpdate()                { return m_betaUpdate; }
 
-#if M0036_RC_IMPROVEMENT
   Int    getAdaptiveBits()              { return m_adaptiveBit;  }
   Double getLastLambda()                { return m_lastLambda;   }
   Void   setLastLambda( Double lamdba ) { m_lastLambda = lamdba; }
-#endif
 
 private:
@@ -200,8 +178,6 @@
   Bool m_useLCUSeparateModel;
 
-#if M0036_RC_IMPROVEMENT
   Int m_adaptiveBit;
   Double m_lastLambda;
-#endif
 };
 
@@ -219,8 +195,6 @@
 private:
   Int  xEstGOPTargetBits( TEncRCSeq* encRCSeq, Int GOPSize );
-#if M0036_RC_IMPROVEMENT
   Void   xCalEquaCoeff( TEncRCSeq* encRCSeq, Double* lambdaRatio, Double* equaCoeffA, Double* equaCoeffB, Int GOPSize );
   Double xSolveEqua( Double targetBpp, Double* equaCoeffA, Double* equaCoeffB, Int GOPSize );
-#endif
 
 public:
@@ -251,9 +225,5 @@
   Void destroy();
 
-#if !RATE_CONTROL_INTRA
-  Double estimatePicLambda( list<TEncRCPic*>& listPreviousPictures );
-#endif
   Int    estimatePicQP    ( Double lambda, list<TEncRCPic*>& listPreviousPictures );
-#if RATE_CONTROL_INTRA
   Int    getRefineBitsForIntra(Int orgBits);
   Double calculateLambdaIntra(double alpha, double beta, double MADPerPixel, double bitsPerPixel);
@@ -264,25 +234,11 @@
   Double getLCUTargetBpp(SliceType eSliceType);
   Double getLCUEstLambdaAndQP(Double bpp, Int clipPicQP, Int *estQP);
-#else
-  Double getLCUTargetBpp();
-#endif
   Double getLCUEstLambda( Double bpp );
   Int    getLCUEstQP( Double lambda, Int clipPicQP );
 
   Void updateAfterLCU( Int LCUIdx, Int bits, Int QP, Double lambda, Bool updateLCUParameter = true );
-#if M0036_RC_IMPROVEMENT
-#if RATE_CONTROL_INTRA
   Void updateAfterPicture( Int actualHeaderBits, Int actualTotalBits, Double averageQP, Double averageLambda, SliceType eSliceType);
-#else
-  Void updateAfterPicture( Int actualHeaderBits, Int actualTotalBits, Double averageQP, Double averageLambda );
-#endif
-#else
-  Void updateAfterPicture( Int actualHeaderBits, Int actualTotalBits, Double averageQP, Double averageLambda, Double effectivePercentage );
-#endif
 
   Void addToPictureLsit( list<TEncRCPic*>& listPreviousPictures );
-#if !M0036_RC_IMPROVEMENT
-  Double getEffectivePercentage();
-#endif
   Double calAverageQP();
   Double calAverageLambda();
@@ -300,7 +256,4 @@
   Int  getNumberOfLCU()                                   { return m_numberOfLCU; }
   Int  getTargetBits()                                    { return m_targetBits; }
-#if !RATE_CONTROL_INTRA 
-  Void setTargetBits( Int bits )                          { m_targetBits = bits; }
-#endif
   Int  getEstHeaderBits()                                 { return m_estHeaderBits; }
   Int  getLCULeft()                                       { return m_LCULeft; }
@@ -312,13 +265,7 @@
   TRCLCU& getLCU( Int LCUIdx )                            { return m_LCUs[LCUIdx]; }
   Int  getPicActualHeaderBits()                           { return m_picActualHeaderBits; }
-#if !M0036_RC_IMPROVEMENT
-  Double getTotalMAD()                                    { return m_totalMAD; }
-  Void   setTotalMAD( Double MAD )                        { m_totalMAD = MAD; }
-#endif
-#if RATE_CONTROL_INTRA
   Void setTargetBits( Int bits )                          { m_targetBits = bits; m_bitsLeft = bits;}
   Void setTotalIntraCost(Double cost)                     { m_totalCostIntra = cost; }
   Void getLCUInitTargetBits();
-#endif
 
   Int  getPicActualBits()                                 { return m_picActualBits; }
@@ -348,17 +295,9 @@
   TRCLCU* m_LCUs;
   Int m_picActualHeaderBits;    // only SH and potential APS
-#if !M0036_RC_IMPROVEMENT
-  Double m_totalMAD;
-#endif
-#if RATE_CONTROL_INTRA
   Double m_totalCostIntra; 
   Double m_remainingCostIntra;
-#endif
   Int m_picActualBits;          // the whole picture, including header
   Int m_picQP;                  // in integer form
   Double m_picLambda;
-#if !M0036_RC_IMPROVEMENT
-  TEncRCPic* m_lastPicture;
-#endif
 };
 
@@ -370,9 +309,5 @@
 
 public:
-#if M0036_RC_IMPROVEMENT
   Void init( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Int keepHierBits, Bool useLCUSeparateModel, GOPEntry GOPList[MAX_GOP] );
-#else
-  Void init( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Bool keepHierBits, Bool useLCUSeparateModel, GOPEntry GOPList[MAX_GOP] );
-#endif
   Void destroy();
   Void initRCPic( Int frameLevel );
@@ -396,133 +331,5 @@
 };
 
-#else
-
-// ====================================================================================================================
-// Class definition
-// ====================================================================================================================
-#define MAX_DELTA_QP    2
-#define MAX_CUDQP_DEPTH 0 
-
-typedef struct FrameData
-{
-  Bool       m_isReferenced;
-  Int        m_qp;
-  Int        m_bits;
-  Double     m_costMAD;
-}FrameData;
-
-typedef struct LCUData
-{
-  Int     m_qp;                ///<  coded QP
-  Int     m_bits;              ///<  actually generated bits
-  Int     m_pixels;            ///<  number of pixels for a unit
-  Int     m_widthInPixel;      ///<  number of pixels for width
-  Int     m_heightInPixel;     ///<  number of pixels for height
-  Double  m_costMAD;           ///<  texture complexity for a unit
-}LCUData;
-
-class MADLinearModel
-{
-private:
-  Bool   m_activeOn;
-  Double m_paramY1;
-  Double m_paramY2;
-  Double m_costMADs[3];
-
-public:
-  MADLinearModel ()   {};
-  ~MADLinearModel()   {};
-  
-  Void    initMADLinearModel      ();
-  Double  getMAD                  ();
-  Void    updateMADLiearModel     ();
-  Void    updateMADHistory        (Double costMAD);
-  Bool    IsUpdateAvailable       ()              { return m_activeOn; }
-};
-
-class PixelBaseURQQuadraticModel
-{
-private:
-  Double m_paramHighX1;
-  Double m_paramHighX2;
-  Double m_paramLowX1;
-  Double m_paramLowX2;
-public:
-  PixelBaseURQQuadraticModel () {};
-  ~PixelBaseURQQuadraticModel() {};
-
-  Void    initPixelBaseQuadraticModel       ();
-  Int     getQP                             (Int qp, Int targetBits, Int numberOfPixels, Double costPredMAD);
-  Void    updatePixelBasedURQQuadraticModel (Int qp, Int bits, Int numberOfPixels, Double costMAD);
-  Bool    checkUpdateAvailable              (Int qpReference );
-  Double  xConvertQP2QStep                  (Int qp );
-  Int     xConvertQStep2QP                  (Double qStep );
-};
-
-class TEncRateCtrl
-{
-private:
-  Bool            m_isLowdelay;
-  Int             m_prevBitrate;
-  Int             m_currBitrate;
-  Int             m_frameRate;
-  Int             m_refFrameNum;
-  Int             m_nonRefFrameNum;
-  Int             m_numOfPixels;
-  Int             m_sourceWidthInLCU;
-  Int             m_sourceHeightInLCU;      
-  Int             m_sizeGOP;
-  Int             m_indexGOP;
-  Int             m_indexFrame;
-  Int             m_indexLCU;
-  Int             m_indexUnit;
-  Int             m_indexRefFrame;
-  Int             m_indexNonRefFrame;
-  Int             m_indexPOCInGOP;
-  Int             m_indexPrevPOCInGOP;
-  Int             m_occupancyVB;
-  Int             m_initialOVB;
-  Int             m_targetBufLevel;
-  Int             m_initialTBL;
-  Int             m_remainingBitsInGOP;
-  Int             m_remainingBitsInFrame;
-  Int             m_occupancyVBInFrame;
-  Int             m_targetBits;
-  Int             m_numUnitInFrame;
-  Int             m_codedPixels;
-  Bool            m_activeUnitLevelOn;
-  Double          m_costNonRefAvgWeighting;
-  Double          m_costRefAvgWeighting;
-  Double          m_costAvgbpp;         
-  
-  FrameData*      m_pcFrameData;
-  LCUData*        m_pcLCUData;
-
-  MADLinearModel              m_cMADLinearModel;
-  PixelBaseURQQuadraticModel  m_cPixelURQQuadraticModel;
-  
-public:
-  TEncRateCtrl         () {};
-  virtual ~TEncRateCtrl() {};
-
-  Void          create                (Int sizeIntraPeriod, Int sizeGOP, Int frameRate, Int targetKbps, Int qp, Int numLCUInBasicUnit, Int sourceWidth, Int sourceHeight, Int maxCUWidth, Int maxCUHeight);
-  Void          destroy               ();
-
-  Void          initFrameData         (Int qp = 0);
-  Void          initUnitData          (Int qp = 0);
-  Int           getFrameQP            (Bool isReferenced, Int POC);
-  Bool          calculateUnitQP       ();
-  Int           getUnitQP             ()                                          { return m_pcLCUData[m_indexLCU].m_qp;  }
-  Void          updateRCGOPStatus     ();
-  Void          updataRCFrameStatus   (Int frameBits, SliceType eSliceType);
-  Void          updataRCUnitStatus    ();
-  Void          updateLCUData         (TComDataCU* pcCU, UInt64 actualLCUBits, Int qp);
-  Void          updateFrameData       (UInt64 actualFrameBits);
-  Double        xAdjustmentBits       (Int& reductionBits, Int& compensationBits);
-  Int           getGOPId              ()                                          { return m_indexFrame; }
-};
 #endif
 
-#endif
-
-
+
Index: branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp	(revision 532)
@@ -45,4 +45,1267 @@
 //! \{
 
+
+#if HM_CLEANUP_SAO
+
+/** rounding with IBDI
+ * \param  x
+ */
+inline Double xRoundIbdi2(Int bitDepth, Double x)
+{
+  return ((x)>0) ? (Int)(((Int)(x)+(1<<(bitDepth-8-1)))/(1<<(bitDepth-8))) : ((Int)(((Int)(x)-(1<<(bitDepth-8-1)))/(1<<(bitDepth-8))));
+}
+
+inline Double xRoundIbdi(Int bitDepth, Double x)
+{
+  return (bitDepth > 8 ? xRoundIbdi2(bitDepth, (x)) : ((x)>=0 ? ((Int)((x)+0.5)) : ((Int)((x)-0.5)))) ;
+}
+
+
+TEncSampleAdaptiveOffset::TEncSampleAdaptiveOffset()
+{
+  m_pppcRDSbacCoder = NULL;           
+  m_pcRDGoOnSbacCoder = NULL;
+  m_pppcBinCoderCABAC = NULL;    
+  m_statData = NULL;
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  m_preDBFstatData = NULL;
+#endif
+}
+
+TEncSampleAdaptiveOffset::~TEncSampleAdaptiveOffset()
+{
+  destroyEncData();
+}
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+Void TEncSampleAdaptiveOffset::createEncData(Bool isPreDBFSamplesUsed)
+#else
+Void TEncSampleAdaptiveOffset::createEncData()
+#endif
+{
+
+  //cabac coder for RDO
+  m_pppcRDSbacCoder = new TEncSbac* [NUM_SAO_CABACSTATE_LABELS];
+  m_pppcBinCoderCABAC = new TEncBinCABACCounter* [NUM_SAO_CABACSTATE_LABELS];
+
+  for(Int cs=0; cs < NUM_SAO_CABACSTATE_LABELS; cs++)
+  {
+    m_pppcRDSbacCoder[cs] = new TEncSbac;
+    m_pppcBinCoderCABAC[cs] = new TEncBinCABACCounter;
+    m_pppcRDSbacCoder   [cs]->init( m_pppcBinCoderCABAC [cs] );
+  }
+
+
+  //statistics
+  m_statData = new SAOStatData**[m_numCTUsPic];
+  for(Int i=0; i< m_numCTUsPic; i++)
+  {
+    m_statData[i] = new SAOStatData*[NUM_SAO_COMPONENTS];
+    for(Int compIdx=0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
+    {
+      m_statData[i][compIdx] = new SAOStatData[NUM_SAO_NEW_TYPES];
+    }
+  }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  if(isPreDBFSamplesUsed)
+  {
+    m_preDBFstatData = new SAOStatData**[m_numCTUsPic];
+    for(Int i=0; i< m_numCTUsPic; i++)
+    {
+      m_preDBFstatData[i] = new SAOStatData*[NUM_SAO_COMPONENTS];
+      for(Int compIdx=0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
+      {
+        m_preDBFstatData[i][compIdx] = new SAOStatData[NUM_SAO_NEW_TYPES];
+      }
+    }
+
+  }
+#endif
+
+#if SAO_ENCODING_CHOICE
+  ::memset(m_saoDisabledRate, 0, sizeof(m_saoDisabledRate));
+#endif
+
+  for(Int typeIdc=0; typeIdc < NUM_SAO_NEW_TYPES; typeIdc++)
+  {
+    m_skipLinesR[SAO_Y ][typeIdc]= 5;
+    m_skipLinesR[SAO_Cb][typeIdc]= m_skipLinesR[SAO_Cr][typeIdc]= 3;
+
+    m_skipLinesB[SAO_Y ][typeIdc]= 4;
+    m_skipLinesB[SAO_Cb][typeIdc]= m_skipLinesB[SAO_Cr][typeIdc]= 2;
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+    if(isPreDBFSamplesUsed)
+    {
+      switch(typeIdc)
+      {
+      case SAO_TYPE_EO_0:
+        {
+          m_skipLinesR[SAO_Y ][typeIdc]= 5;
+          m_skipLinesR[SAO_Cb][typeIdc]= m_skipLinesR[SAO_Cr][typeIdc]= 3;
+
+          m_skipLinesB[SAO_Y ][typeIdc]= 3;
+          m_skipLinesB[SAO_Cb][typeIdc]= m_skipLinesB[SAO_Cr][typeIdc]= 1;
+        }
+        break;
+      case SAO_TYPE_EO_90:
+        {
+          m_skipLinesR[SAO_Y ][typeIdc]= 4;
+          m_skipLinesR[SAO_Cb][typeIdc]= m_skipLinesR[SAO_Cr][typeIdc]= 2;
+
+          m_skipLinesB[SAO_Y ][typeIdc]= 4;
+          m_skipLinesB[SAO_Cb][typeIdc]= m_skipLinesB[SAO_Cr][typeIdc]= 2;
+        }
+        break;
+      case SAO_TYPE_EO_135:
+      case SAO_TYPE_EO_45:
+        {
+          m_skipLinesR[SAO_Y ][typeIdc]= 5;
+          m_skipLinesR[SAO_Cb][typeIdc]= m_skipLinesR[SAO_Cr][typeIdc]= 3;
+
+          m_skipLinesB[SAO_Y ][typeIdc]= 4;
+          m_skipLinesB[SAO_Cb][typeIdc]= m_skipLinesB[SAO_Cr][typeIdc]= 2;
+        }
+        break;
+      case SAO_TYPE_BO:
+        {
+          m_skipLinesR[SAO_Y ][typeIdc]= 4;
+          m_skipLinesR[SAO_Cb][typeIdc]= m_skipLinesR[SAO_Cr][typeIdc]= 2;
+
+          m_skipLinesB[SAO_Y ][typeIdc]= 3;
+          m_skipLinesB[SAO_Cb][typeIdc]= m_skipLinesB[SAO_Cr][typeIdc]= 1;
+        }
+        break;
+      default:
+        {
+          printf("Not a supported type");
+          assert(0);
+          exit(-1);
+        }
+      }
+    }
+#endif    
+  }
+
+}
+
+Void TEncSampleAdaptiveOffset::destroyEncData()
+{
+  if(m_pppcRDSbacCoder != NULL)
+  {
+    for (Int cs = 0; cs < NUM_SAO_CABACSTATE_LABELS; cs ++ )
+    {
+      delete m_pppcRDSbacCoder[cs];
+    }
+    delete[] m_pppcRDSbacCoder; m_pppcRDSbacCoder = NULL;
+  }
+
+  if(m_pppcBinCoderCABAC != NULL)
+  {
+    for (Int cs = 0; cs < NUM_SAO_CABACSTATE_LABELS; cs ++ )
+    {
+      delete m_pppcBinCoderCABAC[cs];
+    }
+    delete[] m_pppcBinCoderCABAC; m_pppcBinCoderCABAC = NULL;
+  }
+
+  if(m_statData != NULL)
+  {
+    for(Int i=0; i< m_numCTUsPic; i++)
+    {
+      for(Int compIdx=0; compIdx< NUM_SAO_COMPONENTS; compIdx++)
+      {
+        delete[] m_statData[i][compIdx];
+      }
+      delete[] m_statData[i];
+    }
+    delete[] m_statData; m_statData = NULL;
+  }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  if(m_preDBFstatData != NULL)
+  {
+    for(Int i=0; i< m_numCTUsPic; i++)
+    {
+      for(Int compIdx=0; compIdx< NUM_SAO_COMPONENTS; compIdx++)
+      {
+        delete[] m_preDBFstatData[i][compIdx];
+      }
+      delete[] m_preDBFstatData[i];
+    }
+    delete[] m_preDBFstatData; m_preDBFstatData = NULL;
+  }
+
+#endif
+}
+
+Void TEncSampleAdaptiveOffset::initRDOCabacCoder(TEncSbac* pcRDGoOnSbacCoder, TComSlice* pcSlice) 
+{
+  m_pcRDGoOnSbacCoder = pcRDGoOnSbacCoder;
+  m_pcRDGoOnSbacCoder->setSlice(pcSlice);
+  m_pcRDGoOnSbacCoder->resetEntropy();
+  m_pcRDGoOnSbacCoder->resetBits();
+
+  m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[SAO_CABACSTATE_PIC_INIT]);
+}
+
+
+
+Void TEncSampleAdaptiveOffset::SAOProcess(TComPic* pPic, Bool* sliceEnabled, const Double *lambdas
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                                         , Bool isPreDBFSamplesUsed
+#endif
+                                          )
+{
+  TComPicYuv* orgYuv= pPic->getPicYuvOrg();
+  TComPicYuv* resYuv= pPic->getPicYuvRec();
+  m_labmda[SAO_Y]= lambdas[0]; m_labmda[SAO_Cb]= lambdas[1]; m_labmda[SAO_Cr]= lambdas[2];
+  TComPicYuv* srcYuv = m_tempPicYuv;
+  resYuv->copyToPic(srcYuv);
+  srcYuv->setBorderExtension(false);
+  srcYuv->extendPicBorder();
+
+  //collect statistics
+  getStatistics(m_statData, orgYuv, srcYuv, pPic);
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  if(isPreDBFSamplesUsed)
+  {
+    addPreDBFStatistics(m_statData);
+  }
+#endif
+  //slice on/off 
+  decidePicParams(sliceEnabled, pPic->getSlice(0)->getDepth()); 
+
+  //block on/off 
+  SAOBlkParam* reconParams = new SAOBlkParam[m_numCTUsPic]; //temporary parameter buffer for storing reconstructed SAO parameters
+  decideBlkParams(pPic, sliceEnabled, m_statData, srcYuv, resYuv, reconParams, pPic->getPicSym()->getSAOBlkParam());
+  delete[] reconParams;
+
+}
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+Void TEncSampleAdaptiveOffset::getPreDBFStatistics(TComPic* pPic)
+{
+  getStatistics(m_preDBFstatData, pPic->getPicYuvOrg(), pPic->getPicYuvRec(), pPic, true);
+}
+
+Void TEncSampleAdaptiveOffset::addPreDBFStatistics(SAOStatData*** blkStats)
+{
+  for(Int n=0; n< m_numCTUsPic; n++)
+  {
+    for(Int compIdx=0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
+    {
+      for(Int typeIdc=0; typeIdc < NUM_SAO_NEW_TYPES; typeIdc++)
+      {
+        blkStats[n][compIdx][typeIdc] += m_preDBFstatData[n][compIdx][typeIdc];
+      }
+    }
+  }
+}
+
+#endif
+
+Void TEncSampleAdaptiveOffset::getStatistics(SAOStatData*** blkStats, TComPicYuv* orgYuv, TComPicYuv* srcYuv, TComPic* pPic
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                          , Bool isCalculatePreDeblockSamples
+#endif
+                          )
+{
+  Bool isLeftAvail,isRightAvail,isAboveAvail,isBelowAvail,isAboveLeftAvail,isAboveRightAvail,isBelowLeftAvail,isBelowRightAvail;
+
+  for(Int ctu= 0; ctu < m_numCTUsPic; ctu++)
+  {
+    Int yPos   = (ctu / m_numCTUInWidth)*m_maxCUHeight;
+    Int xPos   = (ctu % m_numCTUInWidth)*m_maxCUWidth;
+    Int height = (yPos + m_maxCUHeight > m_picHeight)?(m_picHeight- yPos):m_maxCUHeight;
+    Int width  = (xPos + m_maxCUWidth  > m_picWidth )?(m_picWidth - xPos):m_maxCUWidth;
+
+    pPic->getPicSym()->deriveLoopFilterBoundaryAvailibility(ctu, isLeftAvail,isRightAvail,isAboveAvail,isBelowAvail,isAboveLeftAvail,isAboveRightAvail,isBelowLeftAvail,isBelowRightAvail);
+
+    //NOTE: The number of skipped lines during gathering CTU statistics depends on the slice boundary availabilities.
+    //For simplicity, here only picture boundaries are considered.
+
+    isRightAvail      = (xPos + m_maxCUWidth  < m_picWidth );
+    isBelowAvail      = (yPos + m_maxCUHeight < m_picHeight);
+    isBelowRightAvail = (isRightAvail && isBelowAvail);
+    isBelowLeftAvail  = ((xPos > 0) && (isBelowAvail));
+    isAboveRightAvail = ((yPos > 0) && (isRightAvail));
+
+    for(Int compIdx=0; compIdx< NUM_SAO_COMPONENTS; compIdx++)
+    {
+      Bool isLuma     = (compIdx == SAO_Y);
+      Int  formatShift= isLuma?0:1;
+
+      Int  srcStride = isLuma?srcYuv->getStride():srcYuv->getCStride();
+      Pel* srcBlk    = getPicBuf(srcYuv, compIdx)+ (yPos >> formatShift)*srcStride+ (xPos >> formatShift);
+
+      Int  orgStride  = isLuma?orgYuv->getStride():orgYuv->getCStride();
+      Pel* orgBlk     = getPicBuf(orgYuv, compIdx)+ (yPos >> formatShift)*orgStride+ (xPos >> formatShift);
+
+      getBlkStats(compIdx, blkStats[ctu][compIdx]  
+                , srcBlk, orgBlk, srcStride, orgStride, (width  >> formatShift), (height >> formatShift)
+                , isLeftAvail,  isRightAvail, isAboveAvail, isBelowAvail, isAboveLeftAvail, isAboveRightAvail, isBelowLeftAvail, isBelowRightAvail
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                , isCalculatePreDeblockSamples
+#endif
+                );
+
+    }
+  }
+}
+
+Void TEncSampleAdaptiveOffset::decidePicParams(Bool* sliceEnabled, Int picTempLayer)
+{
+  //decide sliceEnabled[compIdx]
+  for (Int compIdx=0; compIdx<NUM_SAO_COMPONENTS; compIdx++)
+  {
+    // reset flags & counters
+    sliceEnabled[compIdx] = true;
+
+#if SAO_ENCODING_CHOICE
+#if SAO_ENCODING_CHOICE_CHROMA
+    // decide slice-level on/off based on previous results
+    if( (picTempLayer > 0) 
+      && (m_saoDisabledRate[compIdx][picTempLayer-1] > ((compIdx==SAO_Y) ? SAO_ENCODING_RATE : SAO_ENCODING_RATE_CHROMA)) )
+    {
+      sliceEnabled[compIdx] = false;
+    }
+#else
+    // decide slice-level on/off based on previous results
+    if( (picTempLayer > 0) 
+      && (m_saoDisabledRate[SAO_Y][0] > SAO_ENCODING_RATE) )
+    {
+      sliceEnabled[compIdx] = false;
+    }
+#endif
+#endif
+  }
+}
+
+Int64 TEncSampleAdaptiveOffset::getDistortion(Int ctu, Int compIdx, Int typeIdc, Int typeAuxInfo, Int* invQuantOffset, SAOStatData& statData)
+{
+  Int64 dist=0;
+  Int inputBitDepth    = (compIdx == SAO_Y) ? g_bitDepthY : g_bitDepthC ;
+  Int shift = 2 * DISTORTION_PRECISION_ADJUSTMENT(inputBitDepth-8);
+
+  switch(typeIdc)
+  {
+    case SAO_TYPE_EO_0:
+    case SAO_TYPE_EO_90:
+    case SAO_TYPE_EO_135:
+    case SAO_TYPE_EO_45:
+      {
+        for (Int offsetIdx=0; offsetIdx<NUM_SAO_EO_CLASSES; offsetIdx++)
+        {
+          dist += estSaoDist( statData.count[offsetIdx], invQuantOffset[offsetIdx], statData.diff[offsetIdx], shift);
+        }        
+      }
+      break;
+    case SAO_TYPE_BO:
+      {
+        for (Int offsetIdx=typeAuxInfo; offsetIdx<typeAuxInfo+4; offsetIdx++)
+        {
+          Int bandIdx = offsetIdx % NUM_SAO_BO_CLASSES ; 
+          dist += estSaoDist( statData.count[bandIdx], invQuantOffset[bandIdx], statData.diff[bandIdx], shift);
+        }
+      }
+      break;
+    default:
+      {
+        printf("Not a supported type");
+        assert(0);
+        exit(-1);
+      }
+  }
+
+  return dist;
+}
+
+inline Int64 TEncSampleAdaptiveOffset::estSaoDist(Int64 count, Int64 offset, Int64 diffSum, Int shift)
+{
+  return (( count*offset*offset-diffSum*offset*2 ) >> shift);
+}
+
+
+inline Int TEncSampleAdaptiveOffset::estIterOffset(Int typeIdx, Int classIdx, Double lambda, Int offsetInput, Int64 count, Int64 diffSum, Int shift, Int bitIncrease, Int64& bestDist, Double& bestCost, Int offsetTh )
+{
+  Int iterOffset, tempOffset;
+  Int64 tempDist, tempRate;
+  Double tempCost, tempMinCost;
+  Int offsetOutput = 0;
+  iterOffset = offsetInput;
+  // Assuming sending quantized value 0 results in zero offset and sending the value zero needs 1 bit. entropy coder can be used to measure the exact rate here. 
+  tempMinCost = lambda; 
+  while (iterOffset != 0)
+  {
+    // Calculate the bits required for signaling the offset
+    tempRate = (typeIdx == SAO_TYPE_BO) ? (abs((Int)iterOffset)+2) : (abs((Int)iterOffset)+1); 
+    if (abs((Int)iterOffset)==offsetTh) //inclusive 
+    {  
+      tempRate --;
+    }
+    // Do the dequantization before distortion calculation
+    tempOffset  = iterOffset << bitIncrease;
+    tempDist    = estSaoDist( count, tempOffset, diffSum, shift);
+    tempCost    = ((Double)tempDist + lambda * (Double) tempRate);
+    if(tempCost < tempMinCost)
+    {
+      tempMinCost = tempCost;
+      offsetOutput = iterOffset;
+      bestDist = tempDist;
+      bestCost = tempCost;
+    }
+    iterOffset = (iterOffset > 0) ? (iterOffset-1):(iterOffset+1);
+  }
+  return offsetOutput;
+}
+
+
+Void TEncSampleAdaptiveOffset::deriveOffsets(Int ctu, Int compIdx, Int typeIdc, SAOStatData& statData, Int* quantOffsets, Int& typeAuxInfo)
+{
+  Int bitDepth = (compIdx== SAO_Y) ? g_bitDepthY : g_bitDepthC;
+  Int shift = 2 * DISTORTION_PRECISION_ADJUSTMENT(bitDepth-8);
+  Int offsetTh = g_saoMaxOffsetQVal[compIdx];  //inclusive
+
+  ::memset(quantOffsets, 0, sizeof(Int)*MAX_NUM_SAO_CLASSES);
+
+  //derive initial offsets 
+  Int numClasses = (typeIdc == SAO_TYPE_BO)?((Int)NUM_SAO_BO_CLASSES):((Int)NUM_SAO_EO_CLASSES);
+  for(Int classIdx=0; classIdx< numClasses; classIdx++)
+  {
+    if( (typeIdc != SAO_TYPE_BO) && (classIdx==SAO_CLASS_EO_PLAIN)  ) 
+    {
+      continue; //offset will be zero
+    }
+
+    if(statData.count[classIdx] == 0)
+    {
+      continue; //offset will be zero
+    }
+
+    quantOffsets[classIdx] = (Int) xRoundIbdi(bitDepth, (Double)( statData.diff[classIdx]<<(bitDepth-8)) 
+                                                                  / 
+                                                          (Double)( statData.count[classIdx]<< m_offsetStepLog2[compIdx])
+                                               );
+    quantOffsets[classIdx] = Clip3(-offsetTh, offsetTh, quantOffsets[classIdx]);
+  }
+
+  // adjust offsets
+  switch(typeIdc)
+  {
+    case SAO_TYPE_EO_0:
+    case SAO_TYPE_EO_90:
+    case SAO_TYPE_EO_135:
+    case SAO_TYPE_EO_45:
+      {
+        Int64 classDist;
+        Double classCost;
+        for(Int classIdx=0; classIdx<NUM_SAO_EO_CLASSES; classIdx++)  
+        {         
+          if(classIdx==SAO_CLASS_EO_FULL_VALLEY && quantOffsets[classIdx] < 0) quantOffsets[classIdx] =0;
+          if(classIdx==SAO_CLASS_EO_HALF_VALLEY && quantOffsets[classIdx] < 0) quantOffsets[classIdx] =0;
+          if(classIdx==SAO_CLASS_EO_HALF_PEAK   && quantOffsets[classIdx] > 0) quantOffsets[classIdx] =0;
+          if(classIdx==SAO_CLASS_EO_FULL_PEAK   && quantOffsets[classIdx] > 0) quantOffsets[classIdx] =0;
+
+          if( quantOffsets[classIdx] != 0 ) //iterative adjustment only when derived offset is not zero
+          {
+            quantOffsets[classIdx] = estIterOffset( typeIdc, classIdx, m_labmda[compIdx], quantOffsets[classIdx], statData.count[classIdx], statData.diff[classIdx], shift, m_offsetStepLog2[compIdx], classDist , classCost , offsetTh );
+          }
+        }
+      
+        typeAuxInfo =0;
+      }
+      break;
+    case SAO_TYPE_BO:
+      {
+        Int64  distBOClasses[NUM_SAO_BO_CLASSES];
+        Double costBOClasses[NUM_SAO_BO_CLASSES];
+        ::memset(distBOClasses, 0, sizeof(Int64)*NUM_SAO_BO_CLASSES);
+        for(Int classIdx=0; classIdx< NUM_SAO_BO_CLASSES; classIdx++)
+        {         
+          costBOClasses[classIdx]= m_labmda[compIdx];
+          if( quantOffsets[classIdx] != 0 ) //iterative adjustment only when derived offset is not zero
+          {
+            quantOffsets[classIdx] = estIterOffset( typeIdc, classIdx, m_labmda[compIdx], quantOffsets[classIdx], statData.count[classIdx], statData.diff[classIdx], shift, m_offsetStepLog2[compIdx], distBOClasses[classIdx], costBOClasses[classIdx], offsetTh );
+          }
+        }
+
+        //decide the starting band index
+        Double minCost = MAX_DOUBLE, cost;
+        for(Int band=0; band< NUM_SAO_BO_CLASSES- 4+ 1; band++) 
+        {
+          cost  = costBOClasses[band  ];
+          cost += costBOClasses[band+1];
+          cost += costBOClasses[band+2];
+          cost += costBOClasses[band+3];
+
+          if(cost < minCost)
+          {
+            minCost = cost;
+            typeAuxInfo = band;
+          }
+        }
+        //clear those unused classes
+        Int clearQuantOffset[NUM_SAO_BO_CLASSES];
+        ::memset(clearQuantOffset, 0, sizeof(Int)*NUM_SAO_BO_CLASSES);
+        for(Int i=0; i< 4; i++) 
+        {
+          Int band = (typeAuxInfo+i)%NUM_SAO_BO_CLASSES;
+          clearQuantOffset[band] = quantOffsets[band];
+        }
+        ::memcpy(quantOffsets, clearQuantOffset, sizeof(Int)*NUM_SAO_BO_CLASSES);        
+      }
+      break;
+    default:
+      {
+        printf("Not a supported type");
+        assert(0);
+        exit(-1);
+      }
+
+  }
+
+
+}
+
+
+Void TEncSampleAdaptiveOffset::deriveModeNewRDO(Int ctu, std::vector<SAOBlkParam*>& mergeList, Bool* sliceEnabled, SAOStatData*** blkStats, SAOBlkParam& modeParam, Double& modeNormCost, TEncSbac** cabacCoderRDO, Int inCabacLabel)
+{
+  Double minCost, cost;
+  Int rate, minRate;
+  Int64 dist[NUM_SAO_COMPONENTS], modeDist[NUM_SAO_COMPONENTS];
+  SAOOffset testOffset[NUM_SAO_COMPONENTS];
+  Int compIdx;
+  Int invQuantOffset[MAX_NUM_SAO_CLASSES];
+
+  modeDist[SAO_Y]= modeDist[SAO_Cb] = modeDist[SAO_Cr] = 0;
+
+  //pre-encode merge flags
+  modeParam[SAO_Y ].modeIdc = SAO_MODE_OFF;
+  m_pcRDGoOnSbacCoder->load(cabacCoderRDO[inCabacLabel]);
+  m_pcRDGoOnSbacCoder->codeSAOBlkParam(modeParam, sliceEnabled, (mergeList[SAO_MERGE_LEFT]!= NULL), (mergeList[SAO_MERGE_ABOVE]!= NULL), true);
+  m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
+
+  //------ luma --------//
+  compIdx = SAO_Y;
+  //"off" case as initial cost
+  modeParam[compIdx].modeIdc = SAO_MODE_OFF;
+  m_pcRDGoOnSbacCoder->resetBits();
+  m_pcRDGoOnSbacCoder->codeSAOOffsetParam(compIdx, modeParam[compIdx], sliceEnabled[compIdx]);
+  minRate= m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
+  modeDist[compIdx] = 0;
+  minCost= m_labmda[compIdx]*((Double)minRate);
+  m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
+  if(sliceEnabled[compIdx])
+  {
+    for(Int typeIdc=0; typeIdc< NUM_SAO_NEW_TYPES; typeIdc++)
+    {
+      testOffset[compIdx].modeIdc = SAO_MODE_NEW;
+      testOffset[compIdx].typeIdc = typeIdc;
+
+      //derive coded offset
+      deriveOffsets(ctu, compIdx, typeIdc, blkStats[ctu][compIdx][typeIdc], testOffset[compIdx].offset, testOffset[compIdx].typeAuxInfo);
+
+      //inversed quantized offsets
+      invertQuantOffsets(compIdx, typeIdc, testOffset[compIdx].typeAuxInfo, invQuantOffset, testOffset[compIdx].offset);
+
+      //get distortion
+      dist[compIdx] = getDistortion(ctu, compIdx, testOffset[compIdx].typeIdc, testOffset[compIdx].typeAuxInfo, invQuantOffset, blkStats[ctu][compIdx][typeIdc]);
+
+      //get rate
+      m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
+      m_pcRDGoOnSbacCoder->resetBits();
+      m_pcRDGoOnSbacCoder->codeSAOOffsetParam(compIdx, testOffset[compIdx], sliceEnabled[compIdx]);
+      rate = m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
+      cost = (Double)dist[compIdx] + m_labmda[compIdx]*((Double)rate);
+      if(cost < minCost)
+      {
+        minCost = cost;
+        minRate = rate;
+        modeDist[compIdx] = dist[compIdx];
+        modeParam[compIdx]= testOffset[compIdx];
+        m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
+      }
+    }
+  }
+  m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
+  m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
+
+  //------ chroma --------//
+  assert(m_labmda[SAO_Cb] == m_labmda[SAO_Cr]);
+  Double chromaLambda = m_labmda[SAO_Cb];
+  //"off" case as initial cost
+  m_pcRDGoOnSbacCoder->resetBits();
+  modeParam[SAO_Cb].modeIdc = SAO_MODE_OFF; 
+  m_pcRDGoOnSbacCoder->codeSAOOffsetParam(SAO_Cb, modeParam[SAO_Cb], sliceEnabled[SAO_Cb]);
+  modeParam[SAO_Cr].modeIdc = SAO_MODE_OFF; 
+  m_pcRDGoOnSbacCoder->codeSAOOffsetParam(SAO_Cr, modeParam[SAO_Cr], sliceEnabled[SAO_Cr]);
+  minRate= m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
+  modeDist[SAO_Cb] = modeDist[SAO_Cr]= 0;
+  minCost= chromaLambda*((Double)minRate); 
+
+  //doesn't need to store cabac status here since the whole CTU parameters will be re-encoded at the end of this function
+
+  for(Int typeIdc=0; typeIdc< NUM_SAO_NEW_TYPES; typeIdc++)
+  {
+    for(compIdx= SAO_Cb; compIdx< NUM_SAO_COMPONENTS; compIdx++)
+    {
+      if(!sliceEnabled[compIdx])
+      {
+        testOffset[compIdx].modeIdc = SAO_MODE_OFF;
+        dist[compIdx]= 0;
+        continue;
+      }
+      testOffset[compIdx].modeIdc = SAO_MODE_NEW;
+      testOffset[compIdx].typeIdc = typeIdc;
+
+      //derive offset & get distortion
+      deriveOffsets(ctu, compIdx, typeIdc, blkStats[ctu][compIdx][typeIdc], testOffset[compIdx].offset, testOffset[compIdx].typeAuxInfo);
+      invertQuantOffsets(compIdx, typeIdc, testOffset[compIdx].typeAuxInfo, invQuantOffset, testOffset[compIdx].offset);
+      dist[compIdx]= getDistortion(ctu, compIdx, typeIdc, testOffset[compIdx].typeAuxInfo, invQuantOffset, blkStats[ctu][compIdx][typeIdc]);
+    }
+
+    //get rate
+    m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
+    m_pcRDGoOnSbacCoder->resetBits();
+    m_pcRDGoOnSbacCoder->codeSAOOffsetParam(SAO_Cb, testOffset[SAO_Cb], sliceEnabled[SAO_Cb]);
+    m_pcRDGoOnSbacCoder->codeSAOOffsetParam(SAO_Cr, testOffset[SAO_Cr], sliceEnabled[SAO_Cr]);
+    rate = m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
+
+    cost = (Double)(dist[SAO_Cb]+ dist[SAO_Cr]) + chromaLambda*((Double)rate);
+    if(cost < minCost)
+    {
+      minCost = cost;
+      minRate = rate;
+      modeDist[SAO_Cb] = dist[SAO_Cb];
+      modeDist[SAO_Cr] = dist[SAO_Cr];
+      modeParam[SAO_Cb]= testOffset[SAO_Cb];
+      modeParam[SAO_Cr]= testOffset[SAO_Cr];
+    }
+  }
+
+
+  //----- re-gen rate & normalized cost----//
+  modeNormCost  = (Double)modeDist[SAO_Y]/m_labmda[SAO_Y];
+  modeNormCost += (Double)(modeDist[SAO_Cb]+ modeDist[SAO_Cr])/chromaLambda; 
+  m_pcRDGoOnSbacCoder->load(cabacCoderRDO[inCabacLabel]);
+  m_pcRDGoOnSbacCoder->resetBits();
+  m_pcRDGoOnSbacCoder->codeSAOBlkParam(modeParam, sliceEnabled, (mergeList[SAO_MERGE_LEFT]!= NULL), (mergeList[SAO_MERGE_ABOVE]!= NULL), false);
+  modeNormCost += (Double)m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
+
+}
+
+Void TEncSampleAdaptiveOffset::deriveModeMergeRDO(Int ctu, std::vector<SAOBlkParam*>& mergeList, Bool* sliceEnabled, SAOStatData*** blkStats, SAOBlkParam& modeParam, Double& modeNormCost, TEncSbac** cabacCoderRDO, Int inCabacLabel)
+{
+  Int mergeListSize = (Int)mergeList.size();
+  modeNormCost = MAX_DOUBLE;
+
+  Double cost;
+  SAOBlkParam testBlkParam;
+
+  for(Int mergeType=0; mergeType< mergeListSize; mergeType++)
+  {
+    if(mergeList[mergeType] == NULL)
+    {
+      continue;
+    }
+
+    testBlkParam = *(mergeList[mergeType]);
+    //normalized distortion
+    Double normDist=0;
+    for(Int compIdx=0; compIdx< NUM_SAO_COMPONENTS; compIdx++)
+    {
+      testBlkParam[compIdx].modeIdc = SAO_MODE_MERGE;
+      testBlkParam[compIdx].typeIdc = mergeType;
+
+      SAOOffset& mergedOffsetParam = (*(mergeList[mergeType]))[compIdx];
+
+      if( mergedOffsetParam.modeIdc != SAO_MODE_OFF)
+      {
+        //offsets have been reconstructed. Don't call inversed quantization function.
+        normDist += (((Double)getDistortion(ctu, compIdx, mergedOffsetParam.typeIdc, mergedOffsetParam.typeAuxInfo, mergedOffsetParam.offset, blkStats[ctu][compIdx][mergedOffsetParam.typeIdc]))
+                       /m_labmda[compIdx]
+                    );
+      }
+
+    }
+
+    //rate
+    m_pcRDGoOnSbacCoder->load(cabacCoderRDO[inCabacLabel]);
+    m_pcRDGoOnSbacCoder->resetBits();
+    m_pcRDGoOnSbacCoder->codeSAOBlkParam(testBlkParam, sliceEnabled, (mergeList[SAO_MERGE_LEFT]!= NULL), (mergeList[SAO_MERGE_ABOVE]!= NULL), false);
+    Int rate = m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
+
+    cost = normDist+(Double)rate;
+
+    if(cost < modeNormCost)
+    {
+      modeNormCost = cost;
+      modeParam    = testBlkParam;
+      m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
+    }
+  }
+
+  m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
+
+
+}
+
+Void TEncSampleAdaptiveOffset::decideBlkParams(TComPic* pic, Bool* sliceEnabled, SAOStatData*** blkStats, TComPicYuv* srcYuv, TComPicYuv* resYuv, SAOBlkParam* reconParams, SAOBlkParam* codedParams)
+{
+  Bool isAllBlksDisabled = false;
+  if(!sliceEnabled[SAO_Y] && !sliceEnabled[SAO_Cb] && !sliceEnabled[SAO_Cr])
+  {
+    isAllBlksDisabled = true;
+  }
+
+  m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[ SAO_CABACSTATE_PIC_INIT ]);
+
+  SAOBlkParam modeParam;
+  Double minCost, modeCost;
+
+  for(Int ctu=0; ctu< m_numCTUsPic; ctu++)
+  {
+    if(isAllBlksDisabled)
+    {
+      codedParams[ctu].reset();
+      continue;
+    }
+
+    m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[ SAO_CABACSTATE_BLK_CUR ]);
+
+    //get merge list
+    std::vector<SAOBlkParam*> mergeList;
+    getMergeList(pic, ctu, reconParams, mergeList);
+
+    minCost = MAX_DOUBLE;
+    for(Int mode=0; mode < NUM_SAO_MODES; mode++)
+    {
+      switch(mode)
+      {
+      case SAO_MODE_OFF:
+        {
+          continue; //not necessary, since all-off case will be tested in SAO_MODE_NEW case.
+        }
+        break;
+      case SAO_MODE_NEW:
+        {
+          deriveModeNewRDO(ctu, mergeList, sliceEnabled, blkStats, modeParam, modeCost, m_pppcRDSbacCoder, SAO_CABACSTATE_BLK_CUR);
+
+        }
+        break;
+      case SAO_MODE_MERGE:
+        {
+          deriveModeMergeRDO(ctu, mergeList, sliceEnabled, blkStats , modeParam, modeCost, m_pppcRDSbacCoder, SAO_CABACSTATE_BLK_CUR);
+        }
+        break;
+      default:
+        {
+          printf("Not a supported SAO mode\n");
+          assert(0);
+          exit(-1);
+        }
+      }
+
+      if(modeCost < minCost)
+      {
+        minCost = modeCost;
+        codedParams[ctu] = modeParam;
+        m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[ SAO_CABACSTATE_BLK_NEXT ]);
+
+      }
+    } //mode
+    m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[ SAO_CABACSTATE_BLK_NEXT ]);
+
+    //apply reconstructed offsets
+    reconParams[ctu] = codedParams[ctu];
+    reconstructBlkSAOParam(reconParams[ctu], mergeList);
+    offsetCTU(ctu, srcYuv, resYuv, reconParams[ctu], pic);
+  } //ctu
+
+#if SAO_ENCODING_CHOICE 
+  Int picTempLayer = pic->getSlice(0)->getDepth();
+  Int numLcusForSAOOff[NUM_SAO_COMPONENTS];
+  numLcusForSAOOff[SAO_Y ] = numLcusForSAOOff[SAO_Cb]= numLcusForSAOOff[SAO_Cr]= 0;
+
+  for (Int compIdx=0; compIdx<NUM_SAO_COMPONENTS; compIdx++)
+  {
+    for(Int ctu=0; ctu< m_numCTUsPic; ctu++)
+    {
+      if( reconParams[ctu][compIdx].modeIdc == SAO_MODE_OFF)
+      {
+        numLcusForSAOOff[compIdx]++;
+      }
+    }
+  }
+#if SAO_ENCODING_CHOICE_CHROMA
+  for (Int compIdx=0; compIdx<NUM_SAO_COMPONENTS; compIdx++)
+  {
+    m_saoDisabledRate[compIdx][picTempLayer] = (Double)numLcusForSAOOff[compIdx]/(Double)m_numCTUsPic;
+  }
+#else
+  if (picTempLayer == 0)
+  {
+    m_saoDisabledRate[SAO_Y][0] = (Double)(numLcusForSAOOff[SAO_Y]+numLcusForSAOOff[SAO_Cb]+numLcusForSAOOff[SAO_Cr])/(Double)(m_numCTUsPic*3);
+  }
+#endif                                              
+#endif
+}
+
+
+Void TEncSampleAdaptiveOffset::getBlkStats(Int compIdx, SAOStatData* statsDataTypes  
+                        , Pel* srcBlk, Pel* orgBlk, Int srcStride, Int orgStride, Int width, Int height
+                        , Bool isLeftAvail,  Bool isRightAvail, Bool isAboveAvail, Bool isBelowAvail, Bool isAboveLeftAvail, Bool isAboveRightAvail, Bool isBelowLeftAvail, Bool isBelowRightAvail
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                        , Bool isCalculatePreDeblockSamples
+#endif
+                        )
+{
+  if(m_lineBufWidth != m_maxCUWidth)
+  {
+    m_lineBufWidth = m_maxCUWidth;
+
+    if (m_signLineBuf1) delete[] m_signLineBuf1; m_signLineBuf1 = NULL;
+    m_signLineBuf1 = new Char[m_lineBufWidth+1]; 
+
+    if (m_signLineBuf2) delete[] m_signLineBuf2; m_signLineBuf2 = NULL;
+    m_signLineBuf2 = new Char[m_lineBufWidth+1];
+  }
+
+  Int x,y, startX, startY, endX, endY, edgeType, firstLineStartX, firstLineEndX;
+  Char signLeft, signRight, signDown;
+  Int64 *diff, *count;
+  Pel *srcLine, *orgLine;
+  Int* skipLinesR = m_skipLinesR[compIdx];
+  Int* skipLinesB = m_skipLinesB[compIdx];
+
+  for(Int typeIdx=0; typeIdx< NUM_SAO_NEW_TYPES; typeIdx++)
+  {
+    SAOStatData& statsData= statsDataTypes[typeIdx];
+    statsData.reset();
+
+    srcLine = srcBlk;
+    orgLine = orgBlk;
+    diff    = statsData.diff;
+    count   = statsData.count;
+    switch(typeIdx)
+    {
+    case SAO_TYPE_EO_0:
+      {
+        diff +=2;
+        count+=2;
+        endY   = (isBelowAvail) ? (height - skipLinesB[typeIdx]) : height;
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        startX = (!isCalculatePreDeblockSamples) ? (isLeftAvail  ? 0 : 1)
+                                                 : (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
+                                                 ;
+#else
+        startX = isLeftAvail ? 0 : 1;
+#endif
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        endX   = (!isCalculatePreDeblockSamples) ? (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
+                                                 : (isRightAvail ? width : (width - 1))
+                                                 ;
+#else
+        endX   = isRightAvail ? (width - skipLinesR[typeIdx]): (width - 1);
+#endif
+        for (y=0; y<endY; y++)
+        {
+          signLeft = (Char)m_sign[srcLine[startX] - srcLine[startX-1]];
+          for (x=startX; x<endX; x++)
+          {
+            signRight =  (Char)m_sign[srcLine[x] - srcLine[x+1]]; 
+            edgeType  =  signRight + signLeft;
+            signLeft  = -signRight;
+
+            diff [edgeType] += (orgLine[x] - srcLine[x]);
+            count[edgeType] ++;
+          }
+          srcLine  += srcStride;
+          orgLine  += orgStride;
+        }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        if(isCalculatePreDeblockSamples)
+        {
+          if(isBelowAvail)
+          {
+            startX = isLeftAvail  ? 0 : 1;
+            endX   = isRightAvail ? width : (width -1);
+
+            for(y=0; y<skipLinesB[typeIdx]; y++)
+            {
+              signLeft = (Char)m_sign[srcLine[startX] - srcLine[startX-1]];
+              for (x=startX; x<endX; x++)
+              {
+                signRight =  (Char)m_sign[srcLine[x] - srcLine[x+1]]; 
+                edgeType  =  signRight + signLeft;
+                signLeft  = -signRight;
+
+                diff [edgeType] += (orgLine[x] - srcLine[x]);
+                count[edgeType] ++;
+              }
+              srcLine  += srcStride;
+              orgLine  += orgStride;
+            }
+          }
+        }
+#endif
+      }
+      break;
+    case SAO_TYPE_EO_90:
+      {
+        diff +=2;
+        count+=2;
+        Char *signUpLine = m_signLineBuf1;
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        startX = (!isCalculatePreDeblockSamples) ? 0
+                                                 : (isRightAvail ? (width - skipLinesR[typeIdx]) : width)
+                                                 ;
+#endif
+        startY = isAboveAvail ? 0 : 1;
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        endX   = (!isCalculatePreDeblockSamples) ? (isRightAvail ? (width - skipLinesR[typeIdx]) : width) 
+                                                 : width
+                                                 ;
+#else
+        endX   = isRightAvail ? (width - skipLinesR[typeIdx]) : width ;
+#endif
+        endY   = isBelowAvail ? (height - skipLinesB[typeIdx]) : (height - 1);
+        if (!isAboveAvail)
+        {
+          srcLine += srcStride;
+          orgLine += orgStride;
+        }
+
+        Pel* srcLineAbove = srcLine - srcStride;
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        for (x=startX; x<endX; x++) 
+#else
+        for (x=0; x< endX; x++) 
+#endif
+        {
+          signUpLine[x] = (Char)m_sign[srcLine[x] - srcLineAbove[x]];
+        }
+
+        Pel* srcLineBelow;
+        for (y=startY; y<endY; y++)
+        {
+          srcLineBelow = srcLine + srcStride;
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+          for (x=startX; x<endX; x++)
+#else
+          for (x=0; x<endX; x++)
+#endif
+          {
+            signDown  = (Char)m_sign[srcLine[x] - srcLineBelow[x]]; 
+            edgeType  = signDown + signUpLine[x];
+            signUpLine[x]= -signDown;
+
+            diff [edgeType] += (orgLine[x] - srcLine[x]);
+            count[edgeType] ++;
+          }
+          srcLine += srcStride;
+          orgLine += orgStride;
+        }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        if(isCalculatePreDeblockSamples)
+        {
+          if(isBelowAvail)
+          {
+            startX = 0;
+            endX   = width;
+
+            for(y=0; y<skipLinesB[typeIdx]; y++)
+            {
+              srcLineBelow = srcLine + srcStride;
+              srcLineAbove = srcLine - srcStride;
+
+              for (x=startX; x<endX; x++)
+              {
+                edgeType = m_sign[srcLine[x] - srcLineBelow[x]] + m_sign[srcLine[x] - srcLineAbove[x]];
+                diff [edgeType] += (orgLine[x] - srcLine[x]);
+                count[edgeType] ++;
+              }
+              srcLine  += srcStride;
+              orgLine  += orgStride;
+            }
+          }
+        }
+#endif
+
+      }
+      break;
+    case SAO_TYPE_EO_135:
+      {
+        diff +=2;
+        count+=2;
+        Char *signUpLine, *signDownLine, *signTmpLine;
+
+        signUpLine  = m_signLineBuf1;
+        signDownLine= m_signLineBuf2;
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        startX = (!isCalculatePreDeblockSamples) ? (isLeftAvail  ? 0 : 1)
+                                                 : (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
+                                                 ;
+#else
+        startX = isLeftAvail ? 0 : 1 ;
+#endif
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        endX   = (!isCalculatePreDeblockSamples) ? (isRightAvail ? (width - skipLinesR[typeIdx]): (width - 1))
+                                                 : (isRightAvail ? width : (width - 1))
+                                                 ;
+#else
+        endX   = isRightAvail ? (width - skipLinesR[typeIdx]): (width - 1);
+#endif
+        endY   = isBelowAvail ? (height - skipLinesB[typeIdx]) : (height - 1);
+
+        //prepare 2nd line's upper sign
+        Pel* srcLineBelow = srcLine + srcStride;
+        for (x=startX; x<endX+1; x++)
+        {
+          signUpLine[x] = (Char)m_sign[srcLineBelow[x] - srcLine[x-1]];
+        }
+
+        //1st line
+        Pel* srcLineAbove = srcLine - srcStride;
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        firstLineStartX = (!isCalculatePreDeblockSamples) ? (isAboveLeftAvail ? 0    : 1) : startX;
+        firstLineEndX   = (!isCalculatePreDeblockSamples) ? (isAboveAvail     ? endX : 1) : endX;
+#else
+        firstLineStartX = isAboveLeftAvail ? 0    : 1;
+        firstLineEndX   = isAboveAvail     ? endX : 1;
+#endif
+        for(x=firstLineStartX; x<firstLineEndX; x++)
+        {
+          edgeType = m_sign[srcLine[x] - srcLineAbove[x-1]] - signUpLine[x+1];
+          diff [edgeType] += (orgLine[x] - srcLine[x]);
+          count[edgeType] ++;
+        }
+        srcLine  += srcStride;
+        orgLine  += orgStride;
+
+
+        //middle lines
+        for (y=1; y<endY; y++)
+        {
+          srcLineBelow = srcLine + srcStride;
+
+          for (x=startX; x<endX; x++)
+          {
+            signDown = (Char)m_sign[srcLine[x] - srcLineBelow[x+1]] ;
+            edgeType = signDown + signUpLine[x];
+            diff [edgeType] += (orgLine[x] - srcLine[x]);
+            count[edgeType] ++;
+
+            signDownLine[x+1] = -signDown; 
+          }
+          signDownLine[startX] = (Char)m_sign[srcLineBelow[startX] - srcLine[startX-1]];
+
+          signTmpLine  = signUpLine;
+          signUpLine   = signDownLine;
+          signDownLine = signTmpLine;
+
+          srcLine += srcStride;
+          orgLine += orgStride;
+        }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        if(isCalculatePreDeblockSamples)
+        {
+          if(isBelowAvail)
+          {
+            startX = isLeftAvail  ? 0     : 1 ;
+            endX   = isRightAvail ? width : (width -1);
+
+            for(y=0; y<skipLinesB[typeIdx]; y++)
+            {
+              srcLineBelow = srcLine + srcStride;
+              srcLineAbove = srcLine - srcStride;
+
+              for (x=startX; x< endX; x++)
+              {
+                edgeType = m_sign[srcLine[x] - srcLineBelow[x+1]] + m_sign[srcLine[x] - srcLineAbove[x-1]];
+                diff [edgeType] += (orgLine[x] - srcLine[x]);
+                count[edgeType] ++;
+              }
+              srcLine  += srcStride;
+              orgLine  += orgStride;
+            }
+          }
+        }
+#endif
+      }
+      break;
+    case SAO_TYPE_EO_45:
+      {
+        diff +=2;
+        count+=2;
+        Char *signUpLine = m_signLineBuf1+1;
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        startX = (!isCalculatePreDeblockSamples) ? (isLeftAvail  ? 0 : 1)
+                                                 : (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
+                                                 ;
+#else
+        startX = isLeftAvail ? 0 : 1;
+#endif
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        endX   = (!isCalculatePreDeblockSamples) ? (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
+                                                 : (isRightAvail ? width : (width - 1))
+                                                 ;
+#else
+        endX   = isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1);
+#endif
+        endY   = isBelowAvail ? (height - skipLinesB[typeIdx]) : (height - 1);
+
+        //prepare 2nd line upper sign
+        Pel* srcLineBelow = srcLine + srcStride;
+        for (x=startX-1; x<endX; x++)
+        {
+          signUpLine[x] = (Char)m_sign[srcLineBelow[x] - srcLine[x+1]];
+        }
+
+
+        //first line
+        Pel* srcLineAbove = srcLine - srcStride;
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        firstLineStartX = (!isCalculatePreDeblockSamples) ? (isAboveAvail ? startX : endX)
+                                                          : startX
+                                                          ;
+        firstLineEndX   = (!isCalculatePreDeblockSamples) ? ((!isRightAvail && isAboveRightAvail) ? width : endX)
+                                                          : endX
+                                                          ;
+#else
+        firstLineStartX = isAboveAvail ? startX : endX;
+        firstLineEndX   = (!isRightAvail && isAboveRightAvail) ? width : endX;
+#endif
+        for(x=firstLineStartX; x<firstLineEndX; x++)
+        {
+          edgeType = m_sign[srcLine[x] - srcLineAbove[x+1]] - signUpLine[x-1];
+          diff [edgeType] += (orgLine[x] - srcLine[x]);
+          count[edgeType] ++;
+        }
+
+        srcLine += srcStride;
+        orgLine += orgStride;
+
+        //middle lines
+        for (y=1; y<endY; y++)
+        {
+          srcLineBelow = srcLine + srcStride;
+
+          for(x=startX; x<endX; x++)
+          {
+            signDown = (Char)m_sign[srcLine[x] - srcLineBelow[x-1]] ;
+            edgeType = signDown + signUpLine[x];
+
+            diff [edgeType] += (orgLine[x] - srcLine[x]);
+            count[edgeType] ++;
+
+            signUpLine[x-1] = -signDown; 
+          }
+          signUpLine[endX-1] = (Char)m_sign[srcLineBelow[endX-1] - srcLine[endX]];
+          srcLine  += srcStride;
+          orgLine  += orgStride;
+        }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        if(isCalculatePreDeblockSamples)
+        {
+          if(isBelowAvail)
+          {
+            startX = isLeftAvail  ? 0     : 1 ;
+            endX   = isRightAvail ? width : (width -1);
+
+            for(y=0; y<skipLinesB[typeIdx]; y++)
+            {
+              srcLineBelow = srcLine + srcStride;
+              srcLineAbove = srcLine - srcStride;
+
+              for (x=startX; x<endX; x++)
+              {
+                edgeType = m_sign[srcLine[x] - srcLineBelow[x-1]] + m_sign[srcLine[x] - srcLineAbove[x+1]];
+                diff [edgeType] += (orgLine[x] - srcLine[x]);
+                count[edgeType] ++;
+              }
+              srcLine  += srcStride;
+              orgLine  += orgStride;
+            }
+          }
+        }
+#endif
+      }
+      break;
+    case SAO_TYPE_BO:
+      {
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        startX = (!isCalculatePreDeblockSamples)?0
+                                                :( isRightAvail?(width- skipLinesR[typeIdx]):width)
+                                                ;
+        endX   = (!isCalculatePreDeblockSamples)?(isRightAvail ? (width - skipLinesR[typeIdx]) : width )
+                                                :width
+                                                ;
+#else
+        endX = isRightAvail ? (width- skipLinesR[typeIdx]) : width;
+#endif
+        endY = isBelowAvail ? (height- skipLinesB[typeIdx]) : height;
+        Int shiftBits = ((compIdx == SAO_Y)?g_bitDepthY:g_bitDepthC)- NUM_SAO_BO_CLASSES_LOG2;
+        for (y=0; y< endY; y++)
+        {
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+          for (x=startX; x< endX; x++)
+#else
+          for (x=0; x< endX; x++)
+#endif
+          {
+
+            Int bandIdx= srcLine[x] >> shiftBits; 
+            diff [bandIdx] += (orgLine[x] - srcLine[x]);
+            count[bandIdx] ++;
+          }
+          srcLine += srcStride;
+          orgLine += orgStride;
+        }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        if(isCalculatePreDeblockSamples)
+        {
+          if(isBelowAvail)
+          {
+            startX = 0;
+            endX   = width;
+
+            for(y= 0; y< skipLinesB[typeIdx]; y++)
+            {
+              for (x=startX; x< endX; x++)
+              {
+                Int bandIdx= srcLine[x] >> shiftBits; 
+                diff [bandIdx] += (orgLine[x] - srcLine[x]);
+                count[bandIdx] ++;
+              }
+              srcLine  += srcStride;
+              orgLine  += orgStride;
+
+            }
+
+          }
+        }
+#endif
+      }
+      break;
+    default:
+      {
+        printf("Not a supported SAO types\n");
+        assert(0);
+        exit(-1);
+      }
+    }
+  }
+}
+
+#else
+
+
+
 TEncSampleAdaptiveOffset::TEncSampleAdaptiveOffset()
 {
@@ -1661,5 +2924,4 @@
 }
 
-#if SAO_CHROMA_LAMBDA 
 /** Sample adaptive offset process
  * \param pcSaoParam
@@ -1671,10 +2933,4 @@
 #else
 Void TEncSampleAdaptiveOffset::SAOProcess(SAOParam *pcSaoParam, Double dLambdaLuma, Double dLambdaChroma)
-#endif
-#else
-/** Sample adaptive offset process
- * \param dLambda
- */
-Void TEncSampleAdaptiveOffset::SAOProcess(SAOParam *pcSaoParam, Double dLambda)
 #endif
 {
@@ -2501,3 +3757,5 @@
 }
 
+#endif
+
 //! \}
Index: branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h	(revision 532)
@@ -53,4 +53,112 @@
 // Class definition
 // ====================================================================================================================
+
+#if HM_CLEANUP_SAO
+enum SAOCabacStateLablesRDO //CABAC state labels
+{
+  SAO_CABACSTATE_PIC_INIT =0,
+  SAO_CABACSTATE_BLK_CUR,
+  SAO_CABACSTATE_BLK_NEXT,
+  SAO_CABACSTATE_BLK_MID,
+  SAO_CABACSTATE_BLK_TEMP,
+  NUM_SAO_CABACSTATE_LABELS
+};
+
+struct SAOStatData //data structure for SAO statistics
+{
+  Int64 diff[MAX_NUM_SAO_CLASSES];
+  Int64 count[MAX_NUM_SAO_CLASSES];
+
+  SAOStatData(){}
+  ~SAOStatData(){}
+  Void reset()
+  {
+    ::memset(diff, 0, sizeof(Int64)*MAX_NUM_SAO_CLASSES);
+    ::memset(count, 0, sizeof(Int64)*MAX_NUM_SAO_CLASSES);
+  }
+  const SAOStatData& operator=(const SAOStatData& src)
+  {
+    ::memcpy(diff, src.diff, sizeof(Int64)*MAX_NUM_SAO_CLASSES);
+    ::memcpy(count, src.count, sizeof(Int64)*MAX_NUM_SAO_CLASSES);
+    return *this;
+  }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  const SAOStatData& operator+= (const SAOStatData& src)
+  {
+    for(Int i=0; i< MAX_NUM_SAO_CLASSES; i++)
+    {
+      diff[i] += src.diff[i];
+      count[i] += src.count[i];
+    }
+    return *this;
+  }
+#endif
+};
+
+class TEncSampleAdaptiveOffset : public TComSampleAdaptiveOffset
+{
+public:
+  TEncSampleAdaptiveOffset();
+  virtual ~TEncSampleAdaptiveOffset();
+
+  //interface
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  Void createEncData(Bool isPreDBFSamplesUsed);
+#else
+  Void createEncData();
+#endif
+  Void destroyEncData();
+  Void initRDOCabacCoder(TEncSbac* pcRDGoOnSbacCoder, TComSlice* pcSlice) ;
+  Void SAOProcess(TComPic* pPic, Bool* sliceEnabled, const Double *lambdas
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                , Bool isPreDBFSamplesUsed
+#endif
+                ); 
+public: //methods
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  Void getPreDBFStatistics(TComPic* pPic); 
+#endif
+private: //methods
+  Void getStatistics(SAOStatData*** blkStats, TComPicYuv* orgYuv, TComPicYuv* srcYuv,TComPic* pPic
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                   , Bool isCalculatePreDeblockSamples = false
+#endif
+                   );
+  Void decidePicParams(Bool* sliceEnabled, Int picTempLayer);
+  Void decideBlkParams(TComPic* pic, Bool* sliceEnabled, SAOStatData*** blkStats, TComPicYuv* srcYuv, TComPicYuv* resYuv, SAOBlkParam* reconParams, SAOBlkParam* codedParams);
+  Void getBlkStats(Int compIdx, SAOStatData* statsDataTypes, Pel* srcBlk, Pel* orgBlk, Int srcStride, Int orgStride, Int width, Int height, Bool isLeftAvail,  Bool isRightAvail, Bool isAboveAvail, Bool isBelowAvail, Bool isAboveLeftAvail, Bool isAboveRightAvail, Bool isBelowLeftAvail, Bool isBelowRightAvail
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                  , Bool isCalculatePreDeblockSamples
+#endif
+                  );
+  Void deriveModeNewRDO(Int ctu, std::vector<SAOBlkParam*>& mergeList, Bool* sliceEnabled, SAOStatData*** blkStats, SAOBlkParam& modeParam, Double& modeNormCost, TEncSbac** cabacCoderRDO, Int inCabacLabel);
+  Void deriveModeMergeRDO(Int ctu, std::vector<SAOBlkParam*>& mergeList, Bool* sliceEnabled, SAOStatData*** blkStats, SAOBlkParam& modeParam, Double& modeNormCost, TEncSbac** cabacCoderRDO, Int inCabacLabel);
+  Int64 getDistortion(Int ctu, Int compIdx, Int typeIdc, Int typeAuxInfo, Int* offsetVal, SAOStatData& statData);
+  Void deriveOffsets(Int ctu, Int compIdx, Int typeIdc, SAOStatData& statData, Int* quantOffsets, Int& typeAuxInfo);
+  inline Int64 estSaoDist(Int64 count, Int64 offset, Int64 diffSum, Int shift);
+  inline Int estIterOffset(Int typeIdx, Int classIdx, Double lambda, Int offsetInput, Int64 count, Int64 diffSum, Int shift, Int bitIncrease, Int64& bestDist, Double& bestCost, Int offsetTh );
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  Void addPreDBFStatistics(SAOStatData*** blkStats);
+#endif
+private: //members
+  //for RDO
+  TEncSbac**             m_pppcRDSbacCoder;           
+  TEncSbac*              m_pcRDGoOnSbacCoder;
+  TEncBinCABACCounter**  m_pppcBinCoderCABAC;    
+  Double                 m_labmda[NUM_SAO_COMPONENTS];
+
+  //statistics
+  SAOStatData***         m_statData; //[ctu][comp][classes]
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  SAOStatData***         m_preDBFstatData;
+#endif
+#if SAO_ENCODING_CHOICE
+  Double                 m_saoDisabledRate[NUM_SAO_COMPONENTS][MAX_TLAYER];
+#endif
+  Int                    m_skipLinesR[NUM_SAO_COMPONENTS][NUM_SAO_NEW_TYPES];
+  Int                    m_skipLinesB[NUM_SAO_COMPONENTS][NUM_SAO_NEW_TYPES];
+};
+#else
+
 
 class TEncSampleAdaptiveOffset : public TComSampleAdaptiveOffset
@@ -95,12 +203,8 @@
   Void endSaoEnc();
   Void resetStats();
-#if SAO_CHROMA_LAMBDA
 #if SAO_ENCODING_CHOICE
   Void SAOProcess(SAOParam *pcSaoParam, Double dLambda, Double dLambdaChroma, Int depth);
 #else
   Void SAOProcess(SAOParam *pcSaoParam, Double dLambda, Double dLambdaChroma);
-#endif
-#else
-  Void SAOProcess(SAOParam *pcSaoParam, Double dLambda);
 #endif
 
@@ -131,5 +235,5 @@
   Int  getMaxNumOffsetsPerPic() {return m_maxNumOffsetsPerPic; }
 };
-
+#endif
 //! \}
 
Index: branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncSbac.cpp
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncSbac.cpp	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncSbac.cpp	(revision 532)
@@ -416,5 +416,4 @@
 {
   PartSize eSize         = pcCU->getPartitionSize( uiAbsPartIdx );
-
   if ( pcCU->isIntra( uiAbsPartIdx ) )
   {
@@ -1394,5 +1393,9 @@
   {
     m_pcBinIf->encodeBin( 1, m_cSaoTypeIdxSCModel.get( 0, 0, 0 ) );
+#if HM_CLEANUP_SAO
+    m_pcBinIf->encodeBinEP( uiCode == 1 ? 0 : 1 );
+#else
     m_pcBinIf->encodeBinEP( uiCode <= 4 ? 1 : 0 );
+#endif
   }
 }
@@ -1597,3 +1600,118 @@
 }
 
+#if HM_CLEANUP_SAO
+Void TEncSbac::codeSAOOffsetParam(Int compIdx, SAOOffset& ctbParam, Bool sliceEnabled)
+{
+  UInt uiSymbol;
+  if(!sliceEnabled)
+  {
+    assert(ctbParam.modeIdc == SAO_MODE_OFF);
+    return;
+  }
+
+  //type
+  if(compIdx == SAO_Y || compIdx == SAO_Cb)
+  {
+    //sao_type_idx_luma or sao_type_idx_chroma
+    if(ctbParam.modeIdc == SAO_MODE_OFF)
+    {
+      uiSymbol =0;
+    }
+    else if(ctbParam.typeIdc == SAO_TYPE_BO) //BO
+    {
+      uiSymbol = 1;
+    }
+    else
+    {
+      assert(ctbParam.typeIdc < SAO_TYPE_START_BO); //EO
+      uiSymbol = 2;
+    }
+    codeSaoTypeIdx(uiSymbol); 
+  }
+
+  if(ctbParam.modeIdc == SAO_MODE_NEW)
+  {
+    Int numClasses = (ctbParam.typeIdc == SAO_TYPE_BO)?4:NUM_SAO_EO_CLASSES; 
+    Int offset[4];
+    Int k=0;
+    for(Int i=0; i< numClasses; i++)
+    {
+      if(ctbParam.typeIdc != SAO_TYPE_BO && i == SAO_CLASS_EO_PLAIN)
+      {
+        continue;
+      }
+      Int classIdx = (ctbParam.typeIdc == SAO_TYPE_BO)?(  (ctbParam.typeAuxInfo+i)% NUM_SAO_BO_CLASSES   ):i;
+      offset[k] = ctbParam.offset[classIdx];
+      k++;
+    }
+
+    for(Int i=0; i< 4; i++)
+    {
+      codeSaoMaxUvlc((offset[i]<0)?(-offset[i]):(offset[i]),  g_saoMaxOffsetQVal[compIdx] ); //sao_offset_abs
+    }
+
+
+    if(ctbParam.typeIdc == SAO_TYPE_BO)
+    {
+      for(Int i=0; i< 4; i++)
+      {
+        if(offset[i] != 0)
+        {
+          codeSAOSign((offset[i]< 0)?1:0);
+        }
+      }
+
+      codeSaoUflc(NUM_SAO_BO_CLASSES_LOG2, ctbParam.typeAuxInfo ); //sao_band_position
+    }
+    else //EO
+    {
+      if(compIdx == SAO_Y || compIdx == SAO_Cb)
+      {
+        assert(ctbParam.typeIdc - SAO_TYPE_START_EO >=0);
+        codeSaoUflc(NUM_SAO_EO_TYPES_LOG2, ctbParam.typeIdc - SAO_TYPE_START_EO ); //sao_eo_class_luma or sao_eo_class_chroma
+      }
+    }
+
+  }
+}
+
+
+Void TEncSbac::codeSAOBlkParam(SAOBlkParam& saoBlkParam
+                              , Bool* sliceEnabled
+                              , Bool leftMergeAvail
+                              , Bool aboveMergeAvail
+                              , Bool onlyEstMergeInfo // = false
+                              )
+{
+
+  Bool isLeftMerge = false;
+  Bool isAboveMerge= false;
+
+  if(leftMergeAvail)
+  {
+    isLeftMerge = ((saoBlkParam[SAO_Y].modeIdc == SAO_MODE_MERGE) && (saoBlkParam[SAO_Y].typeIdc == SAO_MERGE_LEFT));
+    codeSaoMerge( isLeftMerge?1:0  ); //sao_merge_left_flag
+  }
+
+  if( aboveMergeAvail && !isLeftMerge)
+  {
+    isAboveMerge = ((saoBlkParam[SAO_Y].modeIdc == SAO_MODE_MERGE) && (saoBlkParam[SAO_Y].typeIdc == SAO_MERGE_ABOVE)); 
+    codeSaoMerge( isAboveMerge?1:0  ); //sao_merge_left_flag
+  }
+
+  if(onlyEstMergeInfo)
+  {
+    return; //only for RDO
+  }
+
+  if(!isLeftMerge && !isAboveMerge) //not merge mode
+  {
+    for(Int compIdx=0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
+    {
+      codeSAOOffsetParam(compIdx, saoBlkParam[compIdx], sliceEnabled[compIdx]);
+    }
+  }
+}
+#endif
+
 //! \}
Index: branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncSbac.h
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncSbac.h	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncSbac.h	(revision 532)
@@ -103,4 +103,14 @@
   Void  codeSAOSign       ( UInt  uiCode);  //<! code SAO offset sign
   Void  codeScalingList      ( TComScalingList* /*scalingList*/     ){ assert (0);  return;};
+
+#if HM_CLEANUP_SAO
+  Void codeSAOOffsetParam(Int compIdx, SAOOffset& ctbParam, Bool sliceEnabled);
+  Void codeSAOBlkParam(SAOBlkParam& saoBlkParam
+                    , Bool* sliceEnabled
+                    , Bool leftMergeAvail
+                    , Bool aboveMergeAvail
+                    , Bool onlyEstMergeInfo = false
+                    );
+#endif
 
 private:
Index: branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncSearch.cpp
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncSearch.cpp	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncSearch.cpp	(revision 532)
@@ -720,9 +720,5 @@
   Pel*  piRefPos;
   Int iRefStride = m_filteredBlock[0][0].getStride();
-#if NS_HAD
-  m_pcRdCost->setDistParam( pcPatternKey, m_filteredBlock[0][0].getLumaAddr(), iRefStride, 1, m_cDistParam, m_pcEncCfg->getUseHADME(), m_pcEncCfg->getUseNSQT() );
-#else
   m_pcRdCost->setDistParam( pcPatternKey, m_filteredBlock[0][0].getLumaAddr(), iRefStride, 1, m_cDistParam, m_pcEncCfg->getUseHADME() );
-#endif
   
   const TComMv* pcMvRefine = (iFrac == 2 ? s_acMvRefineH : s_acMvRefineQ);
@@ -737,7 +733,11 @@
     piRefPos = m_filteredBlock[ verVal & 3 ][ horVal & 3 ].getLumaAddr();
     if ( horVal == 2 && ( verVal & 1 ) == 0 )
+    {
       piRefPos += 1;
+    }
     if ( ( horVal & 1 ) == 0 && verVal == 2 )
+    {
       piRefPos += iRefStride;
+    }
     cMvTest = pcMvRefine[i];
     cMvTest += rcMvFrac;
@@ -774,28 +774,26 @@
   UInt  uiLog2TrafoSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth()] + 2 - uiFullDepth;
 
-  {
-    if( pcCU->getPredictionMode(0) == MODE_INTRA && pcCU->getPartitionSize(0) == SIZE_NxN && uiTrDepth == 0 )
-    {
-      assert( uiSubdiv );
-    }
-    else if( uiLog2TrafoSize > pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() )
-    {
-      assert( uiSubdiv );
-    }
-    else if( uiLog2TrafoSize == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
-    {
-      assert( !uiSubdiv );
-    }
-    else if( uiLog2TrafoSize == pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
-    {
-      assert( !uiSubdiv );
-    }
-    else
-    {
-      assert( uiLog2TrafoSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) );
-      if( bLuma )
-      {
-        m_pcEntropyCoder->encodeTransformSubdivFlag( uiSubdiv, 5 - uiLog2TrafoSize );
-      }
+  if( pcCU->getPredictionMode(0) == MODE_INTRA && pcCU->getPartitionSize(0) == SIZE_NxN && uiTrDepth == 0 )
+  {
+    assert( uiSubdiv );
+  }
+  else if( uiLog2TrafoSize > pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() )
+  {
+    assert( uiSubdiv );
+  }
+  else if( uiLog2TrafoSize == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+  {
+    assert( !uiSubdiv );
+  }
+  else if( uiLog2TrafoSize == pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
+  {
+    assert( !uiSubdiv );
+  }
+  else
+  {
+    assert( uiLog2TrafoSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) );
+    if( bLuma )
+    {
+      m_pcEntropyCoder->encodeTransformSubdivFlag( uiSubdiv, 5 - uiLog2TrafoSize );
     }
   }
@@ -806,7 +804,11 @@
     {
       if( uiTrDepth==0 || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth-1 ) )
+      {
         m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth );
+      }
       if( uiTrDepth==0 || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth-1 ) )
+      {
         m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth );
+      }
     }
   }
@@ -822,10 +824,8 @@
   }
   
-  {
-    //===== Cbfs =====
-    if( bLuma )
-    {
-      m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
-    }
+  //===== Cbfs =====
+  if( bLuma )
+  {
+    m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
   }
 }
@@ -944,5 +944,4 @@
     }
   }
-
   if( bChroma )
   {
@@ -1306,5 +1305,5 @@
 
 #if RDOQ_CHROMA_LAMBDA 
-    m_pcTrQuant->selectLambda      (TEXT_CHROMA);  
+    m_pcTrQuant->selectLambda(eText);
 #endif
     m_pcTrQuant->transformNxN      ( pcCU, piResi, uiStride, pcCoeff, 
@@ -1358,9 +1357,5 @@
   
   //===== update distortion =====
-#if WEIGHTED_CHROMA_DISTORTION
   ruiDist += m_pcRdCost->getDistPart(g_bitDepthC, piReco, uiStride, piOrg, uiStride, uiWidth, uiHeight, eText );
-#else
-  ruiDist += m_pcRdCost->getDistPart(g_bitDepthC, piReco, uiStride, piOrg, uiStride, uiWidth, uiHeight );
-#endif
 }
 
@@ -2539,5 +2534,4 @@
       
       for( Int j=0; j < numCand; j++)
-
       {
         Bool mostProbableModeIncluded = false;
@@ -3039,9 +3033,5 @@
                             pcYuvOrg->getLumaAddr( uiAbsPartIdx ), pcYuvOrg->getStride(), 
                             m_tmpYuvPred .getLumaAddr( uiAbsPartIdx ), m_tmpYuvPred .getStride(), 
-#if NS_HAD
-                            iWidth, iHeight, m_pcEncCfg->getUseHADME(), m_pcEncCfg->getUseNSQT() );
-#else
                             iWidth, iHeight, m_pcEncCfg->getUseHADME() );
-#endif
   ruiErr = cDistParam.DistFunc( &cDistParam );
 }
@@ -3246,5 +3236,8 @@
 
     UInt          uiCostTempL0[MAX_NUM_REF];
-    for (Int iNumRef=0; iNumRef < MAX_NUM_REF; iNumRef++) uiCostTempL0[iNumRef] = MAX_UINT;
+    for (Int iNumRef=0; iNumRef < MAX_NUM_REF; iNumRef++)
+    {
+      uiCostTempL0[iNumRef] = MAX_UINT;
+    }
     UInt          uiBitsTempL0[MAX_NUM_REF];
 
@@ -3716,18 +3709,14 @@
     {
       uiLastMode = 2;
-      {
-            pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMv( cMvBi[0], ePartSize, uiPartAddr, 0, iPartIdx );
-            pcCU->getCUMvField(REF_PIC_LIST_0)->setAllRefIdx( iRefIdxBi[0], ePartSize, uiPartAddr, 0, iPartIdx );
-            pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMv( cMvBi[1], ePartSize, uiPartAddr, 0, iPartIdx );
-            pcCU->getCUMvField(REF_PIC_LIST_1)->setAllRefIdx( iRefIdxBi[1], ePartSize, uiPartAddr, 0, iPartIdx );
-      }
-      {
-        TempMv = cMvBi[0] - cMvPredBi[0][iRefIdxBi[0]];
-            pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
-      }
-      {
-        TempMv = cMvBi[1] - cMvPredBi[1][iRefIdxBi[1]];
-            pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
-      }
+      pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMv( cMvBi[0], ePartSize, uiPartAddr, 0, iPartIdx );
+      pcCU->getCUMvField(REF_PIC_LIST_0)->setAllRefIdx( iRefIdxBi[0], ePartSize, uiPartAddr, 0, iPartIdx );
+      pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMv( cMvBi[1], ePartSize, uiPartAddr, 0, iPartIdx );
+      pcCU->getCUMvField(REF_PIC_LIST_1)->setAllRefIdx( iRefIdxBi[1], ePartSize, uiPartAddr, 0, iPartIdx );
+      
+      TempMv = cMvBi[0] - cMvPredBi[0][iRefIdxBi[0]];
+      pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
+      
+      TempMv = cMvBi[1] - cMvPredBi[1][iRefIdxBi[1]];
+      pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
       
       pcCU->setInterDirSubParts( 3, uiPartAddr, iPartIdx, pcCU->getDepth(0) );
@@ -3743,10 +3732,8 @@
     {
       uiLastMode = 0;
-          pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMv( cMv[0], ePartSize, uiPartAddr, 0, iPartIdx );
-          pcCU->getCUMvField(REF_PIC_LIST_0)->setAllRefIdx( iRefIdx[0], ePartSize, uiPartAddr, 0, iPartIdx );
-      {
-        TempMv = cMv[0] - cMvPred[0][iRefIdx[0]];
-            pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
-      }
+      pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMv( cMv[0], ePartSize, uiPartAddr, 0, iPartIdx );
+      pcCU->getCUMvField(REF_PIC_LIST_0)->setAllRefIdx( iRefIdx[0], ePartSize, uiPartAddr, 0, iPartIdx );
+      TempMv = cMv[0] - cMvPred[0][iRefIdx[0]];
+      pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
       pcCU->setInterDirSubParts( 1, uiPartAddr, iPartIdx, pcCU->getDepth(0) );
       
@@ -3759,10 +3746,8 @@
     {
       uiLastMode = 1;
-          pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMv( cMv[1], ePartSize, uiPartAddr, 0, iPartIdx );
-          pcCU->getCUMvField(REF_PIC_LIST_1)->setAllRefIdx( iRefIdx[1], ePartSize, uiPartAddr, 0, iPartIdx );
-      {
-        TempMv = cMv[1] - cMvPred[1][iRefIdx[1]];
-            pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
-      }
+      pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMv( cMv[1], ePartSize, uiPartAddr, 0, iPartIdx );
+      pcCU->getCUMvField(REF_PIC_LIST_1)->setAllRefIdx( iRefIdx[1], ePartSize, uiPartAddr, 0, iPartIdx );
+      TempMv = cMv[1] - cMvPred[1][iRefIdx[1]];
+      pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
       pcCU->setInterDirSubParts( 2, uiPartAddr, iPartIdx, pcCU->getDepth(0) );
       
@@ -3816,8 +3801,6 @@
         pcCU->setMergeIndexSubParts( uiMRGIndex,    uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
         pcCU->setInterDirSubParts  ( uiMRGInterDir, uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
-        {
-          pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( cMRGMvField[0], ePartSize, uiPartAddr, 0, iPartIdx );
-          pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMRGMvField[1], ePartSize, uiPartAddr, 0, iPartIdx );
-        }
+        pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( cMRGMvField[0], ePartSize, uiPartAddr, 0, iPartIdx );
+        pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMRGMvField[1], ePartSize, uiPartAddr, 0, iPartIdx );
 
         pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvd    ( cMvZero,            ePartSize, uiPartAddr, 0, iPartIdx );
@@ -3834,8 +3817,6 @@
         pcCU->setMergeFlagSubParts( false,        uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
         pcCU->setInterDirSubParts ( uiMEInterDir, uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
-        {
-          pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( cMEMvField[0], ePartSize, uiPartAddr, 0, iPartIdx );
-          pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMEMvField[1], ePartSize, uiPartAddr, 0, iPartIdx );
-        }
+        pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( cMEMvField[0], ePartSize, uiPartAddr, 0, iPartIdx );
+        pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMEMvField[1], ePartSize, uiPartAddr, 0, iPartIdx );
       }
     }
@@ -3944,5 +3925,7 @@
   
   if (iNum == 1)
+  {
     return 0;
+  }
   
   UInt uiLength = 1;
@@ -4123,17 +4106,9 @@
                             pcOrgYuv->getLumaAddr(uiPartAddr), pcOrgYuv->getStride(), 
                             pcTemplateCand->getLumaAddr(uiPartAddr), pcTemplateCand->getStride(), 
-#if NS_HAD
-                            iSizeX, iSizeY, m_pcEncCfg->getUseHADME(), m_pcEncCfg->getUseNSQT() );
-#else
                             iSizeX, iSizeY, m_pcEncCfg->getUseHADME() );
-#endif
   ruiDist = cDistParam.DistFunc( &cDistParam );
   uiCost = ruiDist + m_pcRdCost->getCost( m_auiMVPIdxCost[iMVPIdx][iMVPNum] );
 #else
-#if WEIGHTED_CHROMA_DISTORTION
   uiCost = m_pcRdCost->getDistPart(g_bitDepthY, pcTemplateCand->getLumaAddr(uiPartAddr), pcTemplateCand->getStride(), pcOrgYuv->getLumaAddr(uiPartAddr), pcOrgYuv->getStride(), iSizeX, iSizeY, TEXT_LUMA, DF_SAD );
-#else
-  uiCost = m_pcRdCost->getDistPart(g_bitDepthY, pcTemplateCand->getLumaAddr(uiPartAddr), pcTemplateCand->getStride(), pcOrgYuv->getLumaAddr(uiPartAddr), pcOrgYuv->getStride(), iSizeX, iSizeY, DF_SAD );
-#endif
   uiCost = (UInt) m_pcRdCost->calcRdCost( m_auiMVPIdxCost[iMVPIdx][iMVPNum], uiCost, false, DF_SAD );
 #endif
@@ -4228,24 +4203,18 @@
   m_pcRdCost->getMotionCost( 1, 0 );
   m_pcRdCost->setCostScale ( 1 );
-  
-  {
+
 #if REF_IDX_ME_ZEROMV
-    if( pcCU->getSlice()->getRefPic( eRefPicList, iRefIdxPred )->isILR(pcCU->getLayerId()))  //ILR reference pic
-    {
-      xPatternSearchFracDIFMv0( pcCU, pcPatternKey, piRefY, iRefStride, &rcMv, cMvHalf, cMvQter, ruiCost, bBi );
-    }
-    else    //non ILR reference pic
-    {
-      xPatternSearchFracDIF( pcCU, pcPatternKey, piRefY, iRefStride, &rcMv, cMvHalf, cMvQter, ruiCost, bBi );
-    }
+  if( pcCU->getSlice()->getRefPic( eRefPicList, iRefIdxPred )->isILR(pcCU->getLayerId()))  //ILR reference pic
+  {
+    xPatternSearchFracDIFMv0( pcCU, pcPatternKey, piRefY, iRefStride, &rcMv, cMvHalf, cMvQter, ruiCost, bBi );
+  }
+  else    //non ILR reference pic
+  {
+    xPatternSearchFracDIF( pcCU, pcPatternKey, piRefY, iRefStride, &rcMv, cMvHalf, cMvQter, ruiCost, bBi );
+  }
 #else
-    xPatternSearchFracDIF( pcCU, pcPatternKey, piRefY, iRefStride, &rcMv, cMvHalf, cMvQter, ruiCost
-                          ,bBi
-                          );
-#endif
-  }
-  
-  
-  
+  xPatternSearchFracDIF( pcCU, pcPatternKey, piRefY, iRefStride, &rcMv, cMvHalf, cMvQter, ruiCost,bBi );
+#endif
+
   m_pcRdCost->setCostScale( 0 );
   rcMv <<= 2;
@@ -4601,16 +4570,12 @@
     pcYuvPred->copyToPartYuv( rpcYuvRec, 0 );
     
-#if WEIGHTED_CHROMA_DISTORTION
     uiDistortion = m_pcRdCost->getDistPart(g_bitDepthY, rpcYuvRec->getLumaAddr(), rpcYuvRec->getStride(),  pcYuvOrg->getLumaAddr(), pcYuvOrg->getStride(),  uiWidth,      uiHeight      )
     + m_pcRdCost->getDistPart(g_bitDepthC, rpcYuvRec->getCbAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCbAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1, TEXT_CHROMA_U )
     + m_pcRdCost->getDistPart(g_bitDepthC, rpcYuvRec->getCrAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCrAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1, TEXT_CHROMA_V );
-#else
-    uiDistortion = m_pcRdCost->getDistPart(g_bitDepthY, rpcYuvRec->getLumaAddr(), rpcYuvRec->getStride(),  pcYuvOrg->getLumaAddr(), pcYuvOrg->getStride(),  uiWidth,      uiHeight      )
-    + m_pcRdCost->getDistPart(g_bitDepthC, rpcYuvRec->getCbAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCbAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1 )
-    + m_pcRdCost->getDistPart(g_bitDepthC, rpcYuvRec->getCrAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCrAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1 );
-#endif
 
     if( m_bUseSBACRD )
+    {
       m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_CURR_BEST]);
+    }
     
     m_pcEntropyCoder->resetBits();
@@ -4628,5 +4593,7 @@
     
     if( m_bUseSBACRD )
+    {
       m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_TEMP_BEST]);
+    }
     
     pcCU->setCbfSubParts( 0, 0, 0, 0, pcCU->getDepth( 0 ) );
@@ -4799,13 +4766,7 @@
   
   // update with clipped distortion and cost (qp estimation loop uses unclipped values)
-#if WEIGHTED_CHROMA_DISTORTION
     uiDistortionBest = m_pcRdCost->getDistPart(g_bitDepthY, rpcYuvRec->getLumaAddr(), rpcYuvRec->getStride(),  pcYuvOrg->getLumaAddr(), pcYuvOrg->getStride(),  uiWidth,      uiHeight      )
     + m_pcRdCost->getDistPart(g_bitDepthC, rpcYuvRec->getCbAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCbAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1, TEXT_CHROMA_U )
     + m_pcRdCost->getDistPart(g_bitDepthC, rpcYuvRec->getCrAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCrAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1, TEXT_CHROMA_V );
-#else
-  uiDistortionBest = m_pcRdCost->getDistPart(g_bitDepthY, rpcYuvRec->getLumaAddr(), rpcYuvRec->getStride(),  pcYuvOrg->getLumaAddr(), pcYuvOrg->getStride(),  uiWidth,      uiHeight      )
-  + m_pcRdCost->getDistPart(g_bitDepthC, rpcYuvRec->getCbAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCbAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1 )
-  + m_pcRdCost->getDistPart(g_bitDepthC, rpcYuvRec->getCrAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCrAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1 );
-#endif
   dCostBest = m_pcRdCost->calcRdCost( uiBitsBest, uiDistortionBest );
   
@@ -4832,7 +4793,11 @@
   Bool bCheckFull;
   if ( SplitFlag && uiDepth == pcCU->getDepth(uiAbsPartIdx) && ( uiLog2TrSize >  pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) ) )
+  {
      bCheckFull = false;
+  }
   else
+  {
      bCheckFull =  ( uiLog2TrSize <= pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() );
+  }
 
   const Bool bCheckSplit  = ( uiLog2TrSize >  pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) );
@@ -4932,5 +4897,5 @@
 
 #if RDOQ_CHROMA_LAMBDA 
-      m_pcTrQuant->selectLambda(TEXT_CHROMA); 
+      m_pcTrQuant->selectLambda(TEXT_CHROMA_U);
 #endif
 
@@ -4943,4 +4908,9 @@
       curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCrQpOffset() + pcCU->getSlice()->getSliceQpDeltaCr();
       m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
+      
+#if RDOQ_CHROMA_LAMBDA
+      m_pcTrQuant->selectLambda(TEXT_CHROMA_V);
+#endif
+
       m_pcTrQuant->transformNxN( pcCU, pcResi->getCrAddr(absTUPartIdxC), pcResi->getCStride(), pcCoeffCurrV, 
 #if ADAPTIVE_QP_SELECTION
@@ -4955,8 +4925,6 @@
     m_pcEntropyCoder->resetBits();
     
-    {
-      m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
-    }
-    
+    m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
+
     m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrY, uiAbsPartIdx,  trWidth,  trHeight,    uiDepth, TEXT_LUMA );
     const UInt uiSingleBitsY = m_pcEntropyCoder->getNumberOfWrittenBits();
@@ -4966,13 +4934,9 @@
     if( bCodeChroma )
     {
-      {
-        m_pcEntropyCoder->encodeQtCbf   ( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrMode );
-      }
+      m_pcEntropyCoder->encodeQtCbf   ( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrMode );
       m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrU, uiAbsPartIdx, trWidthC, trHeightC, uiDepth, TEXT_CHROMA_U );
       uiSingleBitsU = m_pcEntropyCoder->getNumberOfWrittenBits() - uiSingleBitsY;
       
-      {
-        m_pcEntropyCoder->encodeQtCbf   ( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrMode );
-      }
+      m_pcEntropyCoder->encodeQtCbf   ( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrMode );
       m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrV, uiAbsPartIdx, trWidthC, trHeightC, uiDepth, TEXT_CHROMA_V );
       uiSingleBitsV = m_pcEntropyCoder->getNumberOfWrittenBits() - ( uiSingleBitsY + uiSingleBitsU );
@@ -5003,4 +4967,5 @@
       assert(scalingListType < 6);     
       m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_LUMA,REG_DCT, pcResiCurrY, m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(),  pcCoeffCurrY, trWidth, trHeight, scalingListType );//this is for inter mode only
+      
       const UInt uiNonzeroDistY = m_pcRdCost->getDistPart(g_bitDepthY, m_pcQTTempTComYuv[uiQTTempAccessLayer].getLumaAddr( absTUPartIdx ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(),
       pcResi->getLumaAddr( absTUPartIdx ), pcResi->getStride(), trWidth,trHeight );
@@ -5059,7 +5024,5 @@
     {
       uiDistU = m_pcRdCost->getDistPart(g_bitDepthC, m_pTempPel, trWidthC, pcResi->getCbAddr( absTUPartIdxC ), pcResi->getCStride(), trWidthC, trHeightC
-#if WEIGHTED_CHROMA_DISTORTION
                                         , TEXT_CHROMA_U
-#endif
                                         ); // initialized with zero residual destortion
       if ( puiZeroDist )
@@ -5080,7 +5043,5 @@
         const UInt uiNonzeroDistU = m_pcRdCost->getDistPart(g_bitDepthC, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCbAddr( absTUPartIdxC), m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(),
                                                             pcResi->getCbAddr( absTUPartIdxC), pcResi->getCStride(), trWidthC, trHeightC
-#if WEIGHTED_CHROMA_DISTORTION
                                                             , TEXT_CHROMA_U
-#endif
                                                             );
 
@@ -5118,5 +5079,5 @@
       {
         m_pcEntropyCoder->resetBits();
-        m_pcEntropyCoder->encodeQtCbfZero( pcCU, TEXT_CHROMA_U, uiTrModeC );
+        m_pcEntropyCoder->encodeQtCbfZero( pcCU, TEXT_CHROMA_U, uiTrMode );
         const UInt uiNullBitsU = m_pcEntropyCoder->getNumberOfWrittenBits();
         minCostU = m_pcRdCost->calcRdCost( uiNullBitsU, uiDistU );
@@ -5134,7 +5095,5 @@
       
       uiDistV = m_pcRdCost->getDistPart(g_bitDepthC, m_pTempPel, trWidthC, pcResi->getCrAddr( absTUPartIdxC), pcResi->getCStride(), trWidthC, trHeightC
-#if WEIGHTED_CHROMA_DISTORTION
                                         , TEXT_CHROMA_V
-#endif
                                         ); // initialized with zero residual destortion
       if ( puiZeroDist )
@@ -5154,7 +5113,5 @@
         const UInt uiNonzeroDistV = m_pcRdCost->getDistPart(g_bitDepthC, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCrAddr( absTUPartIdxC ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(),
                                                             pcResi->getCrAddr( absTUPartIdxC ), pcResi->getCStride(), trWidthC, trHeightC
-#if WEIGHTED_CHROMA_DISTORTION
                                                             , TEXT_CHROMA_V
-#endif
                                                             );
         if (pcCU->isLosslessCoded(0)) 
@@ -5191,5 +5148,5 @@
       {
         m_pcEntropyCoder->resetBits();
-        m_pcEntropyCoder->encodeQtCbfZero( pcCU, TEXT_CHROMA_V, uiTrModeC );
+        m_pcEntropyCoder->encodeQtCbfZero( pcCU, TEXT_CHROMA_V, uiTrMode );
         const UInt uiNullBitsV = m_pcEntropyCoder->getNumberOfWrittenBits();
         minCostV = m_pcRdCost->calcRdCost( uiNullBitsV, uiDistV );
@@ -5352,5 +5309,5 @@
 
 #if RDOQ_CHROMA_LAMBDA 
-      m_pcTrQuant->selectLambda(TEXT_CHROMA); 
+      m_pcTrQuant->selectLambda(TEXT_CHROMA_U);
 #endif
 
@@ -5362,4 +5319,7 @@
       curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCrQpOffset() + pcCU->getSlice()->getSliceQpDeltaCr();
       m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
+#if RDOQ_CHROMA_LAMBDA
+      m_pcTrQuant->selectLambda(TEXT_CHROMA_V);
+#endif
       m_pcTrQuant->transformNxN( pcCU, pcResi->getCrAddr(absTUPartIdxC), pcResi->getCStride(), pcCoeffCurrV, 
 #if ADAPTIVE_QP_SELECTION
@@ -5391,7 +5351,5 @@
         uiNonzeroDistU = m_pcRdCost->getDistPart(g_bitDepthC, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCbAddr( absTUPartIdxC), m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(),
                                                  pcResi->getCbAddr( absTUPartIdxC), pcResi->getCStride(), trWidthC, trHeightC
-#if WEIGHTED_CHROMA_DISTORTION
                                                  , TEXT_CHROMA_U
-#endif
                                                  );
 
@@ -5435,7 +5393,5 @@
         uiNonzeroDistV = m_pcRdCost->getDistPart(g_bitDepthC, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCrAddr( absTUPartIdxC ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(),
                                                  pcResi->getCrAddr( absTUPartIdxC ), pcResi->getCStride(), trWidthC, trHeightC
-#if WEIGHTED_CHROMA_DISTORTION
                                                  , TEXT_CHROMA_V
-#endif
                                                  );
 
@@ -5474,20 +5430,16 @@
     m_pcEntropyCoder->resetBits();
 
-    {
-      if( uiLog2TrSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
-      {
-        m_pcEntropyCoder->encodeTransformSubdivFlag( 0, 5 - uiLog2TrSize );
-      }
-    }
-
-    {
-      if( bCodeChroma )
-      {
-        m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrMode );
-        m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrMode );
-      }
-
-      m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
-    }
+    if( uiLog2TrSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
+    {
+      m_pcEntropyCoder->encodeTransformSubdivFlag( 0, 5 - uiLog2TrSize );
+    }
+
+    if( bCodeChroma )
+    {
+      m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrMode );
+      m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrMode );
+    }
+
+    m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
 
     m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrY, uiAbsPartIdx, trWidth, trHeight,    uiDepth, TEXT_LUMA );
@@ -5546,11 +5498,9 @@
     m_pcEntropyCoder->resetBits();
     
-    {
-      xEncodeResidualQT( pcCU, uiAbsPartIdx, uiDepth, true,  TEXT_LUMA );
-      xEncodeResidualQT( pcCU, uiAbsPartIdx, uiDepth, false, TEXT_LUMA );
-      xEncodeResidualQT( pcCU, uiAbsPartIdx, uiDepth, false, TEXT_CHROMA_U );
-      xEncodeResidualQT( pcCU, uiAbsPartIdx, uiDepth, false, TEXT_CHROMA_V );
-    }
-    
+    xEncodeResidualQT( pcCU, uiAbsPartIdx, uiDepth, true,  TEXT_LUMA );
+    xEncodeResidualQT( pcCU, uiAbsPartIdx, uiDepth, false, TEXT_LUMA );
+    xEncodeResidualQT( pcCU, uiAbsPartIdx, uiDepth, false, TEXT_CHROMA_U );
+    xEncodeResidualQT( pcCU, uiAbsPartIdx, uiDepth, false, TEXT_CHROMA_V );
+
     uiSubdivBits = m_pcEntropyCoder->getNumberOfWrittenBits();
     dSubdivCost  = m_pcRdCost->calcRdCost( uiSubdivBits, uiSubdivDist );
@@ -5602,13 +5552,10 @@
   const UInt uiLog2TrSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiDepth]+2;
 
-  {
-    if( bSubdivAndCbf && uiLog2TrSize <= pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() && uiLog2TrSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
-    {
-      m_pcEntropyCoder->encodeTransformSubdivFlag( bSubdiv, 5 - uiLog2TrSize );
-    }
-  }
-
-  {
-    assert( pcCU->getPredictionMode(uiAbsPartIdx) != MODE_INTRA );
+  if( bSubdivAndCbf && uiLog2TrSize <= pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() && uiLog2TrSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
+  {
+    m_pcEntropyCoder->encodeTransformSubdivFlag( bSubdiv, 5 - uiLog2TrSize );
+  }
+
+  assert( pcCU->getPredictionMode(uiAbsPartIdx) != MODE_INTRA );
     if( bSubdivAndCbf )
     {
@@ -5631,5 +5578,4 @@
       }
     }
-  }
   
   if( !bSubdiv )
@@ -5655,7 +5601,5 @@
     if( bSubdivAndCbf )
     {
-      {
-        m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
-      }
+      m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
     }
     else
@@ -5725,7 +5669,5 @@
       if( bCodeChroma )
       {
-        {
-          m_pcQTTempTComYuv[uiQTTempAccessLayer].copyPartToPartChroma( pcResi, uiAbsPartIdx, 1 << uiLog2TrSizeC, 1 << uiLog2TrSizeC );
-        }
+        m_pcQTTempTComYuv[uiQTTempAccessLayer].copyPartToPartChroma( pcResi, uiAbsPartIdx, 1 << uiLog2TrSizeC, 1 << uiLog2TrSizeC );
       }
     }
@@ -5847,5 +5789,4 @@
     m_pcEntropyCoder->encodePartSize( pcCU, 0, pcCU->getDepth(0), true );
     m_pcEntropyCoder->encodePredInfo( pcCU, 0, true );
-
     Bool bDummy = false;
     m_pcEntropyCoder->encodeCoeff   ( pcCU, 0, pcCU->getDepth(0), pcCU->getWidth(0), pcCU->getHeight(0), bDummy );
Index: branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncSearch.h
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncSearch.h	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncSearch.h	(revision 532)
@@ -194,4 +194,5 @@
                                   UInt        uiPreCalcDistC );
   
+  
   /// encoder estimation - inter prediction (non-skip)
   Void predInterSearch          ( TComDataCU* pcCU,
Index: branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncSlice.cpp
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 532)
@@ -295,10 +295,4 @@
     dQP += pdQPs[ rpcSlice->getPOC() ];
   }
-#if !RATE_CONTROL_LAMBDA_DOMAIN
-  if ( m_pcCfg->getUseRateCtrl())
-  {
-    dQP = m_pcRateCtrl->getFrameQP(rpcSlice->isReferenced(), rpcSlice->getPOC());
-  }
-#endif
   // ------------------------------------------------------------------------------------------------------------------
   // Lambda computation
@@ -386,8 +380,7 @@
   // store lambda
   m_pcRdCost ->setLambda( dLambda );
-#if WEIGHTED_CHROMA_DISTORTION
 // for RDO
   // in RdCost there is only one lambda because the luma and chroma bits are not separated, instead we weight the distortion of chroma.
-  Double weight = 1.0;
+  Double weight[2] = { 1.0, 1.0 };
   Int qpc;
   Int chromaQPOffset;
@@ -395,33 +388,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
-#if JCTVC_M0259_LAMBDAREFINEMENT
-  if( rpcSlice->getLayerId() > 0 && m_ppcTEncTop[layerId]->getNumActiveRefLayers() && m_pcCfg->getGOPSize() >= 8 && rpcSlice->isIntra() == false && depth == 0 )
-  {
-    dLambda *= 1.1;
-    weight *= 1.15;
-  }
-#endif
-  m_pcRdCost->setCrDistortionWeight(weight);
-#endif
-
+  weight[1] = 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
@@ -500,5 +483,4 @@
 
   pcPic->setTLayer( m_pcCfg->getGOPEntry(iGOPid).m_temporalId );
-
   if(eSliceType==I_SLICE)
   {
@@ -552,5 +534,4 @@
 }
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
 Void TEncSlice::resetQP( TComPic* pic, Int sliceQP, Double lambda )
 {
@@ -561,8 +542,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;
@@ -570,136 +550,24 @@
   chromaQPOffset = slice->getPPS()->getChromaCbQpOffset() + slice->getSliceQpDeltaCb();
   qpc = Clip3( 0, 57, sliceQP + chromaQPOffset);
-  weight = pow( 2.0, (sliceQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
-  m_pcRdCost->setCbDistortionWeight(weight);
+  weight[0] = pow( 2.0, (sliceQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+  m_pcRdCost->setCbDistortionWeight(weight[0]);
 
   chromaQPOffset = slice->getPPS()->getChromaCrQpOffset() + slice->getSliceQpDeltaCr();
   qpc = Clip3( 0, 57, sliceQP + chromaQPOffset);
-  weight = pow( 2.0, (sliceQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
-  m_pcRdCost->setCrDistortionWeight(weight);
-#endif
+  weight[1] = pow( 2.0, (sliceQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+  m_pcRdCost->setCrDistortionWeight(weight[1]);
+
+  const Double lambdaArray[3] = {lambda, (lambda / weight[0]), (lambda / weight[1])};
 
 #if RDOQ_CHROMA_LAMBDA
   // for RDOQ
-  m_pcTrQuant->setLambda( lambda, lambda / weight );
+  m_pcTrQuant->setLambdas( lambdaArray );
 #else
   m_pcTrQuant->setLambda( lambda );
 #endif
 
-#if SAO_CHROMA_LAMBDA
   // For SAO
-  slice   ->setLambda( lambda, lambda / weight );
-#else
-  slice   ->setLambda( lambda );
-#endif
+  slice->setLambdas( lambdaArray );
 }
-#else
-/**
- - lambda re-computation based on rate control QP
- */
-Void TEncSlice::xLamdaRecalculation(Int changeQP, Int idGOP, Int depth, SliceType eSliceType, TComSPS* pcSPS, TComSlice* pcSlice)
-{
-  Int qp;
-  Double recalQP= (Double)changeQP;
-  Double origQP = (Double)recalQP;
-  Double lambda;
-
-  // pre-compute lambda and QP values for all possible QP candidates
-  for ( Int deltqQpIdx = 0; deltqQpIdx < 2 * m_pcCfg->getDeltaQpRD() + 1; deltqQpIdx++ )
-  {
-    // compute QP value
-    recalQP = origQP + ((deltqQpIdx+1)>>1)*(deltqQpIdx%2 ? -1 : 1);
-
-    // compute lambda value
-    Int    NumberBFrames = ( m_pcCfg->getGOPSize() - 1 );
-    Int    SHIFT_QP = 12;
-    Double dLambda_scale = 1.0 - Clip3( 0.0, 0.5, 0.05*(Double)NumberBFrames );
-#if FULL_NBIT
-    Int    bitdepth_luma_qp_scale = 6 * (g_bitDepth - 8);
-#else
-    Int    bitdepth_luma_qp_scale = 0;
-#endif
-    Double qp_temp = (Double) recalQP + bitdepth_luma_qp_scale - SHIFT_QP;
-#if FULL_NBIT
-    Double qp_temp_orig = (Double) recalQP - SHIFT_QP;
-#endif
-    // Case #1: I or P-slices (key-frame)
-    Double dQPFactor = m_pcCfg->getGOPEntry(idGOP).m_QPFactor;
-    if ( eSliceType==I_SLICE )
-    {
-      dQPFactor=0.57*dLambda_scale;
-    }
-    lambda = dQPFactor*pow( 2.0, qp_temp/3.0 );
-
-    if ( depth>0 )
-    {
-#if FULL_NBIT
-      lambda *= Clip3( 2.00, 4.00, (qp_temp_orig / 6.0) ); // (j == B_SLICE && p_cur_frm->layer != 0 )
-#else
-      lambda *= Clip3( 2.00, 4.00, (qp_temp / 6.0) ); // (j == B_SLICE && p_cur_frm->layer != 0 )
-#endif
-    }
-
-    // if hadamard is used in ME process
-    if ( !m_pcCfg->getUseHADME() )
-    {
-      lambda *= 0.95;
-    }
-
-#if REPN_FORMAT_IN_VPS
-    qp = max( -pcSlice->getQpBDOffsetY(), min( MAX_QP, (Int) floor( recalQP + 0.5 ) ) );
-#else
-    qp = max( -pcSPS->getQpBDOffsetY(), min( MAX_QP, (Int) floor( recalQP + 0.5 ) ) );
-#endif
-
-    m_pdRdPicLambda[deltqQpIdx] = lambda;
-    m_pdRdPicQp    [deltqQpIdx] = recalQP;
-    m_piRdPicQp    [deltqQpIdx] = qp;
-  }
-
-  // obtain dQP = 0 case
-  lambda  = m_pdRdPicLambda[0];
-  recalQP = m_pdRdPicQp    [0];
-  qp      = m_piRdPicQp    [0];
-
-  if( pcSlice->getSliceType( ) != I_SLICE )
-  {
-    lambda *= m_pcCfg->getLambdaModifier( depth );
-  }
-
-  // store lambda
-  m_pcRdCost ->setLambda( lambda );
-#if WEIGHTED_CHROMA_DISTORTION
-  // for RDO
-  // in RdCost there is only one lambda because the luma and chroma bits are not separated, instead we weight the distortion of chroma.
-  Double weight = 1.0;
-  Int qpc;
-  Int chromaQPOffset;
-
-  chromaQPOffset = pcSlice->getPPS()->getChromaCbQpOffset() + pcSlice->getSliceQpDeltaCb();
-  qpc = Clip3( 0, 57, qp + chromaQPOffset);
-  weight = pow( 2.0, (qp-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
-  m_pcRdCost->setCbDistortionWeight(weight);
-
-  chromaQPOffset = pcSlice->getPPS()->getChromaCrQpOffset() + pcSlice->getSliceQpDeltaCr();
-  qpc = Clip3( 0, 57, qp + chromaQPOffset);
-  weight = pow( 2.0, (qp-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
-  m_pcRdCost->setCrDistortionWeight(weight);
-#endif
-
-#if RDOQ_CHROMA_LAMBDA
-  // for RDOQ
-  m_pcTrQuant->setLambda( lambda, lambda / weight );
-#else
-  m_pcTrQuant->setLambda( lambda );
-#endif
-
-#if SAO_CHROMA_LAMBDA
-  // For SAO
-  pcSlice   ->setLambda( lambda, lambda / weight );
-#else
-  pcSlice   ->setLambda( lambda );
-#endif
-}
-#endif
 // ====================================================================================================================
 // Public member functions
@@ -741,5 +609,4 @@
   }
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
   if ( m_pcCfg->getUseRateCtrl() )
   {
@@ -747,5 +614,4 @@
     assert(0);
   }
-#endif
 
   TComSlice* pcSlice        = rpcPic->getSlice(getSliceIdx());
@@ -779,9 +645,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;
@@ -789,25 +654,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
@@ -836,8 +697,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;
@@ -845,30 +705,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)
 {
@@ -909,5 +764,4 @@
   m_pcRateCtrl->getRCPic()->setTotalIntraCost(iSumHadSlice);
 }
-#endif
 
 Void TEncSlice::compressSlice( TComPic*& rpcPic )
@@ -1037,5 +891,4 @@
   UInt uiTileStartLCU = 0;
   UInt uiTileLCUX     = 0;
-
   Bool depSliceSegmentsEnabled = pcSlice->getPPS()->getDependentSliceSegmentsEnabledFlag();
   uiCUAddr = rpcPic->getPicSym()->getCUOrderMap( uiStartCUAddr /rpcPic->getNumPartInCU());
@@ -1086,13 +939,4 @@
     pcCU->initCU( rpcPic, uiCUAddr );
 
-#if !RATE_CONTROL_LAMBDA_DOMAIN
-    if(m_pcCfg->getUseRateCtrl())
-    {
-      if(m_pcRateCtrl->calculateUnitQP())
-      {
-        xLamdaRecalculation(m_pcRateCtrl->getUnitQP(), m_pcRateCtrl->getGOPId(), pcSlice->getDepth(), pcSlice->getSliceType(), pcSlice->getSPS(), pcSlice );
-      }
-    }
-#endif
     // inherit from TR if necessary, select substream to use.
     if( m_pcCfg->getUseSBACRD() )
@@ -1169,5 +1013,4 @@
       ((TEncBinCABAC*)m_pcRDGoOnSbacCoder->getEncBinIf())->setBinCountingEnableFlag(true);
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
       Double oldLambda = m_pcRdCost->getLambda();
       if ( m_pcCfg->getUseRateCtrl() )
@@ -1177,9 +1020,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();
@@ -1187,5 +1026,4 @@
         else
         {
-#if RATE_CONTROL_INTRA
           bpp = m_pcRateCtrl->getRCPic()->getLCUTargetBpp(pcSlice->getSliceType());
           if ( rpcPic->getSlice( 0 )->getSliceType() == I_SLICE)
@@ -1198,9 +1036,4 @@
             estQP     = m_pcRateCtrl->getRCPic()->getLCUEstQP    ( estLambda, pcSlice->getSliceQp() );
           }
-#else
-          bpp       = m_pcRateCtrl->getRCPic()->getLCUTargetBpp();
-          estLambda = m_pcRateCtrl->getRCPic()->getLCUEstLambda( bpp );
-          estQP     = m_pcRateCtrl->getRCPic()->getLCUEstQP    ( estLambda, pcSlice->getSliceQp() );
-#endif
 
 #if REPN_FORMAT_IN_VPS
@@ -1211,12 +1044,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
         }
@@ -1225,58 +1057,7 @@
         pcCU->getSlice()->setSliceQpBase( estQP );
       }
-#endif
 
       // run CU encoder
       m_pcCuEncoder->compressCU( pcCU );
-
-#if !TICKET_1090_FIX
-#if RATE_CONTROL_LAMBDA_DOMAIN
-      if ( m_pcCfg->getUseRateCtrl() )
-      {
-#if !M0036_RC_IMPROVEMENT
-        UInt SAD    = m_pcCuEncoder->getLCUPredictionSAD();
-#if REPN_FORMAT_IN_VPS
-        Int height  = min( pcSlice->getSPS()->getMaxCUHeight(),pcSlice->getPicHeightInLumaSamples() - uiCUAddr / rpcPic->getFrameWidthInCU() * pcSlice->getSPS()->getMaxCUHeight() );
-        Int width   = min( pcSlice->getSPS()->getMaxCUWidth(),pcSlice->>getPicWidthInLumaSamples() - uiCUAddr % rpcPic->getFrameWidthInCU() * pcSlice->getSPS()->getMaxCUWidth() );
-#else
-        Int height  = min( pcSlice->getSPS()->getMaxCUHeight(),pcSlice->getSPS()->getPicHeightInLumaSamples() - uiCUAddr / rpcPic->getFrameWidthInCU() * pcSlice->getSPS()->getMaxCUHeight() );
-        Int width   = min( pcSlice->getSPS()->getMaxCUWidth(),pcSlice->getSPS()->getPicWidthInLumaSamples() - uiCUAddr % rpcPic->getFrameWidthInCU() * pcSlice->getSPS()->getMaxCUWidth() );
-#endif
-        Double MAD = (Double)SAD / (Double)(height * width);
-        MAD = MAD * MAD;
-        ( m_pcRateCtrl->getRCPic()->getLCU(uiCUAddr) ).m_MAD = MAD;
-#endif
-
-        Int actualQP        = g_RCInvalidQPValue;
-        Double actualLambda = m_pcRdCost->getLambda();
-        Int actualBits      = pcCU->getTotalBits();
-        Int numberOfEffectivePixels    = 0;
-        for ( Int idx = 0; idx < rpcPic->getNumPartInCU(); idx++ )
-        {
-          if ( pcCU->getPredictionMode( idx ) != MODE_NONE && ( !pcCU->isSkipped( idx ) ) )
-          {
-            numberOfEffectivePixels = numberOfEffectivePixels + 16;
-            break;
-          }
-        }
-
-        if ( numberOfEffectivePixels == 0 )
-        {
-          actualQP = g_RCInvalidQPValue;
-        }
-        else
-        {
-          actualQP = pcCU->getQP( 0 );
-        }
-        m_pcRdCost->setLambda(oldLambda);
-#if RATE_CONTROL_INTRA
-        m_pcRateCtrl->getRCPic()->updateAfterLCU( m_pcRateCtrl->getRCPic()->getLCUCoded(), actualBits, actualQP, actualLambda,
-          pcCU->getSlice()->getSliceType() == I_SLICE ? 0 : m_pcCfg->getLCULevelRC() );
-#else
-        m_pcRateCtrl->getRCPic()->updateAfterLCU( m_pcRateCtrl->getRCPic()->getLCUCoded(), actualBits, actualQP, actualLambda, m_pcCfg->getLCULevelRC() );
-#endif
-      }
-#endif
-#endif
 
       // restore entropy coder to an initial stage
@@ -1312,21 +1093,6 @@
       }
 
-#if TICKET_1090_FIX
-#if RATE_CONTROL_LAMBDA_DOMAIN
       if ( m_pcCfg->getUseRateCtrl() )
       {
-#if !M0036_RC_IMPROVEMENT
-        UInt SAD    = m_pcCuEncoder->getLCUPredictionSAD();
-#if REPN_FORMAT_IN_VPS
-        Int height  = min( pcSlice->getSPS()->getMaxCUHeight(),pcSlice->getPicHeightInLumaSamples() - uiCUAddr / rpcPic->getFrameWidthInCU() * pcSlice->getSPS()->getMaxCUHeight() );
-        Int width   = min( pcSlice->getSPS()->getMaxCUWidth(),pcSlice->getPicWidthInLumaSamples() - uiCUAddr % rpcPic->getFrameWidthInCU() * pcSlice->getSPS()->getMaxCUWidth() );
-#else
-        Int height  = min( pcSlice->getSPS()->getMaxCUHeight(),pcSlice->getSPS()->getPicHeightInLumaSamples() - uiCUAddr / rpcPic->getFrameWidthInCU() * pcSlice->getSPS()->getMaxCUHeight() );
-        Int width   = min( pcSlice->getSPS()->getMaxCUWidth(),pcSlice->getSPS()->getPicWidthInLumaSamples() - uiCUAddr % rpcPic->getFrameWidthInCU() * pcSlice->getSPS()->getMaxCUWidth() );
-#endif
-        Double MAD = (Double)SAD / (Double)(height * width);
-        MAD = MAD * MAD;
-        ( m_pcRateCtrl->getRCPic()->getLCU(uiCUAddr) ).m_MAD = MAD;
-#endif
 
         Int actualQP        = g_RCInvalidQPValue;
@@ -1353,13 +1119,7 @@
         m_pcRdCost->setLambda(oldLambda);
 
-#if RATE_CONTROL_INTRA
         m_pcRateCtrl->getRCPic()->updateAfterLCU( m_pcRateCtrl->getRCPic()->getLCUCoded(), actualBits, actualQP, actualLambda,
           pcCU->getSlice()->getSliceType() == I_SLICE ? 0 : m_pcCfg->getLCULevelRC() );
-#else
-        m_pcRateCtrl->getRCPic()->updateAfterLCU( m_pcRateCtrl->getRCPic()->getLCUCoded(), actualBits, actualQP, actualLambda, m_pcCfg->getLCULevelRC() );
-#endif
-      }
-#endif
-#endif
+      }
     }
     // other case: encodeCU is not called
@@ -1383,11 +1143,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)
@@ -1404,10 +1157,4 @@
   }
   xRestoreWPparam( pcSlice );
-#if !RATE_CONTROL_LAMBDA_DOMAIN
-  if(m_pcCfg->getUseRateCtrl())
-  {
-    m_pcRateCtrl->updateFrameData(m_uiPicTotalBits);
-  }
-#endif
 }
 
@@ -1609,4 +1356,34 @@
 
     TComDataCU*& pcCU = rpcPic->getCU( uiCUAddr );
+#if HM_CLEANUP_SAO
+    if ( pcSlice->getSPS()->getUseSAO() )
+    {
+      if (pcSlice->getSaoEnabledFlag()||pcSlice->getSaoEnabledFlagChroma())
+      {
+        SAOBlkParam& saoblkParam = (rpcPic->getPicSym()->getSAOBlkParam())[uiCUAddr];
+        Bool sliceEnabled[NUM_SAO_COMPONENTS];
+        sliceEnabled[SAO_Y] = pcSlice->getSaoEnabledFlag();
+        sliceEnabled[SAO_Cb]= sliceEnabled[SAO_Cr]= pcSlice->getSaoEnabledFlagChroma();
+
+        Bool leftMergeAvail = false;
+        Bool aboveMergeAvail= false;
+        //merge left condition
+        Int rx = (uiCUAddr % uiWidthInLCUs);
+        if(rx > 0)
+        {
+          leftMergeAvail = rpcPic->getSAOMergeAvailability(uiCUAddr, uiCUAddr-1);
+        }
+
+        //merge up condition
+        Int ry = (uiCUAddr / uiWidthInLCUs);
+        if(ry > 0)
+        {
+          aboveMergeAvail = rpcPic->getSAOMergeAvailability(uiCUAddr, uiCUAddr-uiWidthInLCUs);
+        }
+
+        m_pcEntropyCoder->encodeSAOBlkParam(saoblkParam,sliceEnabled, leftMergeAvail, aboveMergeAvail);
+      }
+    }
+#else
     if ( pcSlice->getSPS()->getUseSAO() && (pcSlice->getSaoEnabledFlag()||pcSlice->getSaoEnabledFlagChroma()) )
     {
@@ -1691,4 +1468,6 @@
       }
     }
+#endif
+
 #if ENC_DEC_TRACE
     g_bJustDoIt = g_bEncDecTraceEnable;
Index: branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncSlice.h
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncSlice.h	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncSlice.h	(revision 532)
@@ -131,15 +131,9 @@
 #endif
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
   Void    resetQP             ( TComPic* pic, Int sliceQP, Double lambda );
-#else
-  Void    xLamdaRecalculation ( Int changeQP, Int idGOP, Int depth, SliceType eSliceType, TComSPS* pcSPS, TComSlice* pcSlice);
-#endif
   // compress and encode slice
   Void    precompressSlice    ( TComPic*& rpcPic                                );      ///< precompress slice for multi-loop opt.
   Void    compressSlice       ( TComPic*& rpcPic                                );      ///< analysis stage of slice
-#if RATE_CONTROL_INTRA
   Void    calCostSliceI       ( TComPic*& rpcPic );
-#endif
   Void    encodeSlice         ( TComPic*& rpcPic, TComOutputBitstream* pcSubstreams  );
   
Index: branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncTop.cpp
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncTop.cpp	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncTop.cpp	(revision 532)
@@ -129,4 +129,16 @@
   if (m_bUseSAO)
   {
+#if HM_CLEANUP_SAO
+#if AUXILIARY_PICTURES
+    m_cEncSAO.create( getSourceWidth(), getSourceHeight(), m_chromaFormatIDC, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+#else
+    m_cEncSAO.create( getSourceWidth(), getSourceHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+#endif
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+    m_cEncSAO.createEncData(getSaoLcuBoundary());
+#else
+    m_cEncSAO.createEncData();
+#endif
+#else
     m_cEncSAO.setSaoLcuBoundary(getSaoLcuBoundary());
     m_cEncSAO.setSaoLcuBasedOptimization(getSaoLcuBasedOptimization());
@@ -134,4 +146,5 @@
     m_cEncSAO.create( getSourceWidth(), getSourceHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight );
     m_cEncSAO.createEncBuffer();
+#endif
   }
 #if ADAPTIVE_QP_SELECTION
@@ -143,5 +156,4 @@
   m_cLoopFilter.        create( g_uiMaxCUDepth );
   
-#if RATE_CONTROL_LAMBDA_DOMAIN
   if ( m_RCEnableRateControl )
   {
@@ -149,7 +161,4 @@
                       g_uiMaxCUWidth, g_uiMaxCUHeight, m_RCKeepHierarchicalBit, m_RCUseLCUSeparateModel, m_GOPList );
   }
-#else
-  m_cRateCtrl.create(getIntraPeriod(), getGOPSize(), getFrameRate(), getTargetBitrate(), getQP(), getNumLCUInUnit(), getSourceWidth(), getSourceHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight);
-#endif
   // if SBAC-based RD optimization is used
   if( m_bUseSBACRD )
@@ -250,6 +259,11 @@
   if (m_cSPS.getUseSAO())
   {
+#if HM_CLEANUP_SAO
+    m_cEncSAO.destroyEncData();
+    m_cEncSAO.destroy();
+#else
     m_cEncSAO.destroy();
     m_cEncSAO.destroyEncBuffer();
+#endif
   }
   m_cLoopFilter.        destroy();
@@ -401,5 +415,4 @@
 {
   // compress GOP
-#if RATE_CONTROL_LAMBDA_DOMAIN
 #if !RC_SHVC_HARMONIZATION
   if ( m_RCEnableRateControl )
@@ -408,10 +421,8 @@
   }
 #endif
-#endif
 
   // compress GOP
   m_cGOPEncoder.compressGOP(iPicIdInGOP, m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, false, false);
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
 #if !RC_SHVC_HARMONIZATION
   if ( m_RCEnableRateControl )
@@ -419,5 +430,4 @@
     m_cRateCtrl.destroyRCGOP();
   }
-#endif
 #endif
   
@@ -463,10 +473,8 @@
   }
   
-#if RATE_CONTROL_LAMBDA_DOMAIN
   if ( m_RCEnableRateControl )
   {
     m_cRateCtrl.initRCGOP( m_iNumPicRcvd );
   }
-#endif
 
   // compress GOP
@@ -474,10 +482,8 @@
   m_cGOPEncoder.compressGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, false, false);
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
   if ( m_RCEnableRateControl )
   {
     m_cRateCtrl.destroyRCGOP();
   }
-#endif
   
   iNumEncoded         = m_iNumPicRcvd;
@@ -519,5 +525,7 @@
     TComPic *pcTopField;
     xGetNewPicBuffer( pcTopField );
+#if !HM_CLEANUP_SAO
     pcTopField->getPicSym()->allocSaoParam(&m_cEncSAO);
+#endif
     pcTopField->setReconMark (false);
     
@@ -540,11 +548,11 @@
     Pel * pcTopFieldU =  pcTopField->getPicYuvOrg()->getCbAddr();
     Pel * pcTopFieldV =  pcTopField->getPicYuvOrg()->getCrAddr();
-    
+
     // compute image characteristics
     if ( getUseAdaptiveQP() )
     {
       m_cPreanalyzer.xPreanalyze( dynamic_cast<TEncPic*>( pcTopField ) );
-    }
-    
+    }    
+
     /* -- Defield -- */
     
@@ -560,5 +568,7 @@
     TComPic* pcBottomField;
     xGetNewPicBuffer( pcBottomField );
+#if !HM_CLEANUP_SAO
     pcBottomField->getPicSym()->allocSaoParam(&m_cEncSAO);
+#endif
     pcBottomField->setReconMark (false);
    
@@ -581,11 +591,11 @@
     Pel * pcBottomFieldU =  pcBottomField->getPicYuvOrg()->getCbAddr();
     Pel * pcBottomFieldV =  pcBottomField->getPicYuvOrg()->getCrAddr();
-    
-    // Compute image characteristics
+
+    // compute image characteristics
     if ( getUseAdaptiveQP() )
     {
       m_cPreanalyzer.xPreanalyze( dynamic_cast<TEncPic*>( pcBottomField ) );
-    }
-    
+    }       
+
     /* -- Defield -- */
     
@@ -642,5 +652,7 @@
     TComPic *pcTopField;
     xGetNewPicBuffer( pcTopField );
+#if !HM_CLEANUP_SAO
     pcTopField->getPicSym()->allocSaoParam(&m_cEncSAO);
+#endif
     pcTopField->setReconMark (false);
     
@@ -694,8 +706,10 @@
     TComPic* pcBottomField;
     xGetNewPicBuffer( pcBottomField );
+#if !HM_CLEANUP_SAO
     pcBottomField->getPicSym()->allocSaoParam(&m_cEncSAO);
+#endif
     pcBottomField->setReconMark (false);
     
-    TComPicYuv* rpcPicYuvRec = new TComPicYuv;
+    TComPicYuv* rpcPicYuvRec;
     if ( rcListPicYuvRecOut.size() == (UInt)m_iGOPSize )
     {
@@ -704,4 +718,5 @@
     else
     {
+      rpcPicYuvRec = new TComPicYuv;
       rpcPicYuvRec->create( m_iSourceWidth, m_iSourceHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
     }
@@ -897,9 +912,10 @@
 #endif
     }
-
+#if !HM_CLEANUP_SAO
     if (getUseSAO())
     {
       rpcPic->getPicSym()->allocSaoParam(&m_cEncSAO);
     }
+#endif
     m_cListPic.pushBack( rpcPic );
   }
@@ -1147,5 +1163,4 @@
   }
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
   if ( m_RCEnableRateControl )
   {
@@ -1154,5 +1169,4 @@
     m_cPPS.setMinCuDQPSize( m_cPPS.getSPS()->getMaxCUWidth() >> ( m_cPPS.getMaxCuDQPDepth()) );
   } 
-#endif
 
   m_cPPS.setChromaCbQpOffset( m_chromaCbQpOffset );
Index: branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncTop.h
===================================================================
--- branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncTop.h	(revision 531)
+++ branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncTop.h	(revision 532)
@@ -83,5 +83,5 @@
   // encoder search
   TEncSearch              m_cSearch;                      ///< encoder search class
-  TEncEntropy*            m_pcEntropyCoder;                     ///< entropy encoder 
+  //TEncEntropy*            m_pcEntropyCoder;                     ///< entropy encoder
   TEncCavlc*              m_pcCavlcCoder;                       ///< CAVLC encoder  
   // coding tool
