Index: trunk/source/Lib/TLibEncoder/TEncAnalyze.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncAnalyze.cpp	(revision 494)
+++ trunk/source/Lib/TLibEncoder/TEncAnalyze.cpp	(revision 540)
@@ -58,3 +58,4 @@
 
 TEncAnalyze             m_gcAnalyzeAll_in;
+
 //! \}
Index: trunk/source/Lib/TLibEncoder/TEncAnalyze.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncAnalyze.h	(revision 494)
+++ trunk/source/Lib/TLibEncoder/TEncAnalyze.h	(revision 540)
@@ -160,4 +160,5 @@
   }
   
+  
   Void    printSummary(Char ch)
   {
@@ -207,4 +208,5 @@
 
 extern TEncAnalyze             m_gcAnalyzeAll_in;
+
 //! \}
 
Index: trunk/source/Lib/TLibEncoder/TEncCavlc.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 494)
+++ trunk/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 540)
@@ -220,61 +220,32 @@
     }
   }
+
+#if SCALINGLIST_INFERRING
+  if( pcPPS->getLayerId() > 0 )
+  {
+    WRITE_FLAG( pcPPS->getInferScalingListFlag() ? 1 : 0, "pps_infer_scaling_list_flag" );
+  }
+
+  if( pcPPS->getInferScalingListFlag() )
+  {
+    // The value of pps_scaling_list_ref_layer_id shall be in the range of 0 to 62, inclusive
+    assert( pcPPS->getScalingListRefLayerId() <= 62 );
+
+    WRITE_UVLC( pcPPS->getScalingListRefLayerId(), "pps_scaling_list_ref_layer_id" );
+  }
+  else
+  {
+#endif
+
   WRITE_FLAG( pcPPS->getScalingListPresentFlag() ? 1 : 0,                          "pps_scaling_list_data_present_flag" ); 
-
-#if IL_SL_SIGNALLING_N0371
-  pcPPS->setPPS( pcPPS->getLayerId(), pcPPS );  
-#endif
-
   if( pcPPS->getScalingListPresentFlag() )
   {
-#if SCALING_LIST_OUTPUT_RESULT
-    printf("PPS\n");
-#endif
-
-#if IL_SL_SIGNALLING_N0371
-    m_pcSlice->getScalingList()->setLayerId( pcPPS->getLayerId() );
-
-    if( pcPPS->getLayerId() > 0 )
-    {
-      WRITE_FLAG( pcPPS->getPredScalingListFlag() ? 1 : 0,                          "pps_pred_scaling_list_flag" );
-      m_pcSlice->getScalingList()->setPredScalingListFlag( pcPPS->getPredScalingListFlag() );
-
-      if( pcPPS->getPredScalingListFlag() )
-      {
-        // The value of pps_scaling_list_ref_layer_id shall be in the range of 0 to 62, inclusive
-        assert( /*pcPPS->getScalingListRefLayerId() >= 0 &&*/ pcPPS->getScalingListRefLayerId() <= 62 );
-
-        // When avc_base_layer_flag is equal to 1, it is a requirement of bitstream conformance that the value of pps_scaling_list_ref_layer_id shall be greater than 0
-        if( pcPPS->getSPS()->getVPS()->getAvcBaseLayerFlag() )
-        {
-          assert( pcPPS->getScalingListRefLayerId() > 0 );
-        }
-
-        // It is a requirement of bitstream conformance that, when a PPS with nuh_layer_id equal to nuhLayerIdA is active for a layer with nuh_layer_id equal to nuhLayerIdB and 
-        // pps_infer_scaling_list_flag in the PPS is equal to 1, pps_infer_scaling_list_flag shall be equal to 0 for the PPS that is active for the layer with nuh_layer_id equal to pps_scaling_list_ref_layer_id
-        assert( pcPPS->getPPS( pcPPS->getScalingListRefLayerId() )->getPredScalingListFlag() == false );
-
-        // It is a requirement of bitstream conformance that, when a PPS with nuh_layer_id equal to nuhLayerIdA is active for a layer with nuh_layer_id equal to nuhLayerIdB, 
-        // the layer with nuh_layer_id equal to pps_scaling_list_ref_layer_id shall be a direct or indirect reference layer of the layer with nuh_layer_id equal to nuhLayerIdB
-        assert( pcPPS->getSPS()->getVPS()->getScalingListLayerDependency( pcPPS->getLayerId(), pcPPS->getScalingListRefLayerId() ) == true );
-        
-        WRITE_UVLC( pcPPS->getScalingListRefLayerId(),                            "scaling_list_pps_ref_layer_id" );
-        m_pcSlice->getScalingList()->setScalingListRefLayerId( pcPPS->getScalingListRefLayerId() );
-        codeScalingList( m_pcSlice->getScalingList() );
-      }
-      else
-      {
-        codeScalingList( m_pcSlice->getScalingList() );
-      }
-    }
-    else
-    {
-      codeScalingList( m_pcSlice->getScalingList() );
-    }
-#else
     codeScalingList( m_pcSlice->getScalingList() );
-#endif
-
-  }
+  }
+
+#if SCALINGLIST_INFERRING
+  }
+#endif
+
   WRITE_FLAG( pcPPS->getListsModificationPresentFlag(), "lists_modification_present_flag");
   WRITE_UVLC( pcPPS->getLog2ParallelMergeLevelMinus2(), "log2_parallel_merge_level_minus2");
@@ -471,5 +442,9 @@
     WRITE_FLAG( pcSPS->getUpdateRepFormatFlag(), "update_rep_format_flag" );
   }
+#if O0096_REP_FORMAT_INDEX
+  if( pcSPS->getLayerId() == 0 ) 
+#else
   if( pcSPS->getLayerId() == 0 || pcSPS->getUpdateRepFormatFlag() ) 
+#endif
   {
 #endif
@@ -486,4 +461,10 @@
 #if REPN_FORMAT_IN_VPS
   }
+#if O0096_REP_FORMAT_INDEX
+  else if (pcSPS->getUpdateRepFormatFlag())
+  {
+    WRITE_CODE( pcSPS->getUpdateRepFormatIndex(), 8,   "update_rep_format_index");
+  }
+#endif
 #endif
   Window conf = pcSPS->getConformanceWindow();
@@ -499,5 +480,9 @@
 
 #if REPN_FORMAT_IN_VPS
+#if O0096_REP_FORMAT_INDEX
+  if( pcSPS->getLayerId() == 0 ) 
+#else
   if( pcSPS->getLayerId() == 0 || pcSPS->getUpdateRepFormatFlag() ) 
+#endif  
   {
     assert( pcSPS->getBitDepthY() >= 8 );
@@ -532,64 +517,30 @@
   WRITE_UVLC( pcSPS->getQuadtreeTUMaxDepthIntra() - 1,                               "max_transform_hierarchy_depth_intra" );
   WRITE_FLAG( pcSPS->getScalingListFlag() ? 1 : 0,                                   "scaling_list_enabled_flag" ); 
-
-#if IL_SL_SIGNALLING_N0371
-  pcSPS->setSPS( pcSPS->getLayerId(), pcSPS );
-#endif
-
   if(pcSPS->getScalingListFlag())
   {
+#if SCALINGLIST_INFERRING
+    if( pcSPS->getLayerId() > 0 )
+    {
+      WRITE_FLAG( pcSPS->getInferScalingListFlag() ? 1 : 0, "sps_infer_scaling_list_flag" );
+    }
+
+    if( pcSPS->getInferScalingListFlag() )
+    {
+      // The value of pps_scaling_list_ref_layer_id shall be in the range of 0 to 62, inclusive
+      assert( pcSPS->getScalingListRefLayerId() <= 62 );
+
+      WRITE_UVLC( pcSPS->getScalingListRefLayerId(), "sps_scaling_list_ref_layer_id" );
+    }
+    else
+    {
+#endif
     WRITE_FLAG( pcSPS->getScalingListPresentFlag() ? 1 : 0,                          "sps_scaling_list_data_present_flag" ); 
     if(pcSPS->getScalingListPresentFlag())
     {
-#if SCALING_LIST_OUTPUT_RESULT
-    printf("SPS\n");
-#endif
-
-#if IL_SL_SIGNALLING_N0371
-    m_pcSlice->getScalingList()->setLayerId( pcSPS->getLayerId() );
-
-    if( pcSPS->getLayerId() > 0 )
-    {
-      WRITE_FLAG( pcSPS->getPredScalingListFlag() ? 1 : 0,                          "sps_pred_scaling_list_flag" );
-      m_pcSlice->getScalingList()->setPredScalingListFlag( pcSPS->getPredScalingListFlag() );
-
-      if( pcSPS->getPredScalingListFlag() )
-      {
-
-        // The value of sps_scaling_list_ref_layer_id shall be in the range of 0 to 62, inclusive
-        assert( /*pcSPS->getScalingListRefLayerId() >= 0 &&*/ pcSPS->getScalingListRefLayerId() <= 62 );
-        
-        // When avc_base_layer_flag is equal to 1, it is a requirement of bitstream conformance that the value of sps_scaling_list_ref_layer_id shall be greater than 0
-        if( pcSPS->getVPS()->getAvcBaseLayerFlag() )
-        {
-          assert( pcSPS->getScalingListRefLayerId() > 0 );
-        }
-
-        // It is a requirement of bitstream conformance that, when an SPS with nuh_layer_id equal to nuhLayerIdA is active for a layer with nuh_layer_id equal to nuhLayerIdB and 
-        // sps_infer_scaling_list_flag in the SPS is equal to 1, sps_infer_scaling_list_flag shall be equal to 0 for the SPS that is active for the layer with nuh_layer_id equal to sps_scaling_list_ref_layer_id
-        assert( pcSPS->getSPS( pcSPS->getScalingListRefLayerId() )->getPredScalingListFlag() == false );
-
-        // It is a requirement of bitstream conformance that, when an SPS with nuh_layer_id equal to nuhLayerIdA is active for a layer with nuh_layer_id equal to nuhLayerIdB, 
-        // the layer with nuh_layer_id equal to sps_scaling_list_ref_layer_id shall be a direct or indirect reference layer of the layer with nuh_layer_id equal to nuhLayerIdB
-        assert( pcSPS->getVPS()->getScalingListLayerDependency( pcSPS->getLayerId(), pcSPS->getScalingListRefLayerId() ) == true );
-
-        WRITE_UVLC( pcSPS->getScalingListRefLayerId(),                            "scaling_list_sps_ref_layer_id" );
-        m_pcSlice->getScalingList()->setScalingListRefLayerId( pcSPS->getScalingListRefLayerId() );
-        codeScalingList( m_pcSlice->getScalingList() );
-      }
-      else
-      {
-        codeScalingList( m_pcSlice->getScalingList() );
-      }
-    }
-    else
-    {
       codeScalingList( m_pcSlice->getScalingList() );
     }
-#else
-      codeScalingList( m_pcSlice->getScalingList() );
-#endif
-
-    }
+#if SCALINGLIST_INFERRING
+    }
+#endif
   }
   WRITE_FLAG( pcSPS->getUseAMP() ? 1 : 0,                                            "amp_enabled_flag" );
@@ -648,6 +599,18 @@
   if( 1 )   // if( sps_extension_flag )
   {
+#if O0142_CONDITIONAL_SPS_EXTENSION
+    UInt spsExtensionTypeFlag[8] = { 0, 1, 0, 0, 0, 0, 0, 0 };
+    for (UInt i = 0; i < 8; i++)
+    {
+      WRITE_FLAG( spsExtensionTypeFlag[i], "sps_extension_type_flag" );
+    }
+    if (spsExtensionTypeFlag[1])
+    {
+      codeSPSExtension( pcSPS );
+    }
+#else
     codeSPSExtension( pcSPS );
     WRITE_FLAG( 0, "sps_extension2_flag" );
+#endif
   }
 #else
@@ -670,4 +633,7 @@
     {
       Window scaledWindow = pcSPS->getScaledRefLayerWindow(i);
+#if O0098_SCALED_REF_LAYER_ID
+      WRITE_CODE( pcSPS->getScaledRefLayerId(i), 6,          "scaled_ref_layer_id" );
+#endif
       WRITE_SVLC( scaledWindow.getWindowLeftOffset()   >> 1, "scaled_ref_layer_left_offset" );
       WRITE_SVLC( scaledWindow.getWindowTopOffset()    >> 1, "scaled_ref_layer_top_offset" );
@@ -891,4 +857,14 @@
     }
   }
+#endif
+#if VPS_TSLAYERS
+    WRITE_FLAG( vps->getMaxTSLayersPresentFlag(), "vps_sub_layers_max_minus1_present_flag");
+    if (vps->getMaxTSLayersPresentFlag())
+    {
+        for( i = 0; i < vps->getMaxLayers() - 1; i++)
+        {
+            WRITE_CODE(vps->getMaxTSLayersMinus1(i), 3, "sub_layers_vps_max_minus1[i]" );
+        }
+    }
 #endif
 #if JCTVC_M0203_INTERLAYER_PRED_IDC
@@ -982,4 +958,11 @@
   }
 
+#if O0153_ALT_OUTPUT_LAYER_FLAG
+  if( vps->getMaxLayers() > 1 )
+  {
+    WRITE_FLAG( vps->getAltOuputLayerFlag(), "alt_output_layer_flag" );   
+  }
+#endif
+
 #if REPN_FORMAT_IN_VPS
   WRITE_FLAG( vps->getRepFormatIdxPresentFlag(), "rep_format_idx_present_flag"); 
@@ -987,5 +970,9 @@
   if( vps->getRepFormatIdxPresentFlag() )
   {
+#if O0096_REP_FORMAT_INDEX
+    WRITE_CODE( vps->getVpsNumRepFormats() - 1, 8, "vps_num_rep_formats_minus1" );
+#else
     WRITE_CODE( vps->getVpsNumRepFormats() - 1, 4, "vps_num_rep_formats_minus1" );
+#endif
   }
   for(i = 0; i < vps->getVpsNumRepFormats(); i++)
@@ -1001,5 +988,9 @@
       if( vps->getVpsNumRepFormats() > 1 )
       {
+#if O0096_REP_FORMAT_INDEX
+        WRITE_CODE( vps->getVpsRepFormatIdx(i), 8, "vps_rep_format_idx[i]" );
+#else
         WRITE_CODE( vps->getVpsRepFormatIdx(i), 4, "vps_rep_format_idx[i]" );
+#endif
       }
     }
@@ -1025,6 +1016,48 @@
   WRITE_FLAG(vps->getCrossLayerIrapAlignFlag(), "cross_layer_irap_aligned_flag");
 #endif 
+#if VPS_DPB_SIZE_TABLE
+  for(i = 1; i < vps->getNumOutputLayerSets(); i++)
+  {
+    WRITE_FLAG( vps->getSubLayerFlagInfoPresentFlag( i ), "sub_layer_flag_info_present_flag[i]");  
+    for(j = 0; j < vps->getMaxTLayers(); j++)
+    {
+      if( j > 0 && vps->getSubLayerFlagInfoPresentFlag(i) )
+      {
+        WRITE_FLAG( vps->getSubLayerDpbInfoPresentFlag( i, j), "sub_layer_dpb_info_present_flag[i]");  
+      }
+      if( vps->getSubLayerDpbInfoPresentFlag(i, j) )
+      {
+        for(Int k = 0; k < vps->getNumSubDpbs(i); k++)
+        {
+          WRITE_UVLC( vps->getMaxVpsDecPicBufferingMinus1( i, k, j), "max_vps_dec_pic_buffering_minus1[i][k][j]" ); 
+        }
+        WRITE_UVLC( vps->getMaxVpsNumReorderPics( i, j), "max_vps_num_reorder_pics[i][j]" );              
+        WRITE_UVLC( vps->getMaxVpsLatencyIncreasePlus1( i, j), "max_vps_latency_increase_plus1[i][j]" );        
+      }
+    }
+  }
+#endif
 #if VPS_EXTN_DIRECT_REF_LAYERS && M0457_PREDICTION_INDICATIONS
   WRITE_UVLC( vps->getDirectDepTypeLen()-2,                           "direct_dep_type_len_minus2");
+#if O0096_DEFAULT_DEPENDENCY_TYPE
+  WRITE_FLAG(vps->getDefaultDirectDependencyTypeFlag(), "default_direct_dependency_flag");
+  if (vps->getDefaultDirectDependencyTypeFlag())
+  {
+    WRITE_CODE( vps->getDefaultDirectDependencyType(), vps->getDirectDepTypeLen(), "default_direct_dependency_type" );
+  }
+  else
+  {
+    for(i = 1; i < vps->getMaxLayers(); i++)
+    {
+      for(j = 0; j < i; j++)
+      {
+        if (vps->getDirectDependencyFlag(i, j))
+        {
+          WRITE_CODE( vps->getDirectDependencyType(i, j), vps->getDirectDepTypeLen(), "direct_dependency_type[i][j]" );
+        }
+      }
+    }
+  }
+#else
   for(i = 1; i < vps->getMaxLayers(); i++)
   {
@@ -1037,19 +1070,12 @@
     }
   }
-
-#if IL_SL_SIGNALLING_N0371
-  for(i = 1; i < vps->getMaxLayers(); i++)
-  {
-    for(j = 0; j < i; j++)
-    {
-      vps->setScalingListLayerDependency( i, j, vps->checkLayerDependency( i,j ) );
-    }
-  }
-#endif
-
+#endif
 #endif
 #if M0040_ADAPTIVE_RESOLUTION_CHANGE
   WRITE_FLAG(vps->getSingleLayerForNonIrapFlag(), "single_layer_for_non_irap_flag" );
 #endif
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+  WRITE_FLAG(vps->getHigherLayerIrapSkipFlag(), "higher_layer_irap_skip_flag" );
+#endif
 
 #if !VPS_VUI
@@ -1071,4 +1097,25 @@
 Void  TEncCavlc::codeRepFormat      ( RepFormat *repFormat )
 {
+#if REPN_FORMAT_CONTROL_FLAG
+   WRITE_FLAG ( repFormat->getChromaAndBitDepthVpsPresentFlag(), "chroma_and_bit_depth_vps_presenet_flag"); 
+
+   WRITE_CODE ( repFormat->getPicWidthVpsInLumaSamples (), 16, "pic_width_in_luma_samples" );    
+   WRITE_CODE ( repFormat->getPicHeightVpsInLumaSamples(), 16, "pic_height_in_luma_samples" );  
+
+   if ( repFormat->getChromaAndBitDepthVpsPresentFlag() )
+   {
+     WRITE_CODE( repFormat->getChromaFormatVpsIdc(), 2, "chroma_format_idc" );   
+
+     if( repFormat->getChromaFormatVpsIdc() == 3 )
+     {
+       WRITE_FLAG( repFormat->getSeparateColourPlaneVpsFlag(), "separate_colour_plane_flag");      
+     }
+
+     assert( repFormat->getBitDepthVpsLuma() >= 8 );
+     assert( repFormat->getBitDepthVpsChroma() >= 8 );
+     WRITE_CODE( repFormat->getBitDepthVpsLuma() - 8,   4, "bit_depth_luma_minus8" );           
+     WRITE_CODE( repFormat->getBitDepthVpsChroma() - 8, 4, "bit_depth_chroma_minus8" );
+   }
+#else 
   WRITE_CODE( repFormat->getChromaFormatVpsIdc(), 2, "chroma_format_idc" );    
   
@@ -1084,5 +1131,6 @@
   assert( repFormat->getBitDepthVpsChroma() >= 8 );
   WRITE_CODE( repFormat->getBitDepthVpsLuma() - 8,   4, "bit_depth_luma_minus8" );           
-  WRITE_CODE( repFormat->getBitDepthVpsChroma() - 8, 4, "bit_depth_chroma_minus8" );         
+  WRITE_CODE( repFormat->getBitDepthVpsChroma() - 8, 4, "bit_depth_chroma_minus8" );
+#endif 
 
 }
@@ -1092,7 +1140,15 @@
 {
   Int i,j;
+#if O0223_PICTURE_TYPES_ALIGN_FLAG
+  WRITE_FLAG(vps->getCrossLayerPictureTypeAlignFlag(), "cross_layer_pic_type_aligned_flag");
+  if (!vps->getCrossLayerPictureTypeAlignFlag())
+  {
+#endif 
 #if IRAP_ALIGN_FLAG_IN_VPS_VUI
-      WRITE_FLAG(vps->getCrossLayerIrapAlignFlag(), "cross_layer_irap_aligned_flag");
+    WRITE_FLAG(vps->getCrossLayerIrapAlignFlag(), "cross_layer_irap_aligned_flag");
 #endif 
+#if O0223_PICTURE_TYPES_ALIGN_FLAG
+  }
+#endif
 #if VPS_VUI_BITRATE_PICRATE
   WRITE_FLAG( vps->getBitRatePresentVpsFlag(),        "bit_rate_present_vps_flag" );
@@ -1127,13 +1183,47 @@
   }
 #endif
+#if VPS_VUI_TILES_NOT_IN_USE__FLAG
+  UInt layerIdx;
+  WRITE_FLAG( vps->getTilesNotInUseFlag() ? 1 : 0 , "tiles_not_in_use_flag" );
+  if (!vps->getTilesNotInUseFlag())
+  {
+    for(i = 0; i < vps->getMaxLayers(); i++)
+    {
+      WRITE_FLAG( vps->getTilesInUseFlag(i) ? 1 : 0 , "tiles_in_use_flag[ i ]" );
+      if (vps->getTilesInUseFlag(i))
+      {
+        WRITE_FLAG( vps->getLoopFilterNotAcrossTilesFlag(i) ? 1 : 0 , "loop_filter_not_across_tiles_flag[ i ]" );
+      }
+    }
+#endif
 #if TILE_BOUNDARY_ALIGNED_FLAG
-  for(i = 1; i < vps->getMaxLayers(); i++)
-  {
-    for(j = 0; j < vps->getNumDirectRefLayers(vps->getLayerIdInNuh(i)); j++)
-    {
-      WRITE_FLAG( vps->getTileBoundariesAlignedFlag(i,j) ? 1 : 0 , "tile_boundaries_aligned_flag[i][j]" );
-    }
-  }  
-#endif 
+    for(i = 1; i < vps->getMaxLayers(); i++)
+    {
+      for(j = 0; j < vps->getNumDirectRefLayers(vps->getLayerIdInNuh(i)); j++)
+      {
+#if VPS_VUI_TILES_NOT_IN_USE__FLAG
+        layerIdx = vps->getLayerIdInVps(vps->getRefLayerId(vps->getLayerIdInNuh(i), j));
+        if (vps->getTilesInUseFlag(i) && vps->getTilesInUseFlag(layerIdx)) {
+          WRITE_FLAG( vps->getTileBoundariesAlignedFlag(i,j) ? 1 : 0 , "tile_boundaries_aligned_flag[i][j]" );
+        }
+#else
+        WRITE_FLAG( vps->getTileBoundariesAlignedFlag(i,j) ? 1 : 0 , "tile_boundaries_aligned_flag[i][j]" );
+#endif
+      }
+    }  
+#endif
+#if VPS_VUI_TILES_NOT_IN_USE__FLAG
+  }
+#endif
+#if VPS_VUI_WPP_NOT_IN_USE__FLAG
+  WRITE_FLAG( vps->getWppNotInUseFlag() ? 1 : 0 , "wpp_not_in_use_flag" );
+  if (!vps->getWppNotInUseFlag())
+  {
+    for(i = 0; i < vps->getMaxLayers(); i++)
+    {
+      WRITE_FLAG( vps->getWppInUseFlag(i) ? 1 : 0 , "wpp_in_use_flag[ i ]" );
+    }
+  }
+#endif
 #if N0160_VUI_EXT_ILP_REF
   WRITE_FLAG( vps->getNumIlpRestrictedRefLayers() ? 1 : 0 , "num_ilp_restricted_ref_layers" );    
@@ -1159,4 +1249,26 @@
   }
 #endif 
+#if VPS_VUI_VIDEO_SIGNAL
+    WRITE_FLAG( vps->getVideoSigPresentVpsFlag(), "video_signal_info_idx_present_flag" );
+    if (vps->getVideoSigPresentVpsFlag())
+    {
+        WRITE_CODE(vps->getNumVideoSignalInfo()-1, 4, "vps_num_video_signal_info_minus1" );
+    }
+    
+    for(i = 0; i < vps->getNumVideoSignalInfo(); i++)
+    {
+        WRITE_CODE(vps->getVideoVPSFormat(i), 3, "video_vps_format" );
+        WRITE_FLAG(vps->getVideoFullRangeVpsFlag(i), "video_full_range_vps_flag" );
+        WRITE_CODE(vps->getColorPrimaries(i), 8, "color_primaries_vps" );
+        WRITE_CODE(vps->getTransCharacter(i), 8, "transfer_characteristics_vps" );
+        WRITE_CODE(vps->getMaxtrixCoeff(i), 8, "matrix_coeffs_vps" );
+    }
+    
+    if (vps->getVideoSigPresentVpsFlag() && vps->getNumVideoSignalInfo() > 1 )
+    {
+        for (i=1; i < vps->getMaxLayers(); i++)
+            WRITE_CODE(vps->getVideoSignalInfoIdx(i), 4, "vps_video_signal_info_idx" );
+    }
+#endif
 }
 #endif
@@ -1221,4 +1333,12 @@
       iBits++;
     }
+#if O0149_CROSS_LAYER_BLA_FLAG
+    if( pcSlice->getPPS()->getNumExtraSliceHeaderBits() > iBits )
+    {
+      assert(!!"cross_layer_bla_flag");
+      WRITE_FLAG(pcSlice->getCrossLayerBLAFlag(), "cross_layer_bla_flag");
+      iBits++;
+    }
+#endif
     for ( ; iBits < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); iBits++)
     {
@@ -1299,5 +1419,4 @@
       TComReferencePictureSet* rps = pcSlice->getRPS();
       
-#if FIX1071
       // check for bitstream restriction stating that:
       // If the current picture is a BLA or CRA picture, the value of NumPocTotalCurr shall be equal to 0.
@@ -1313,5 +1432,4 @@
         }
       }
-#endif
 
       if(pcSlice->getRPSidx() < 0)
@@ -1467,18 +1585,22 @@
       if (pcSlice->getSPS()->getUseSAO())
       {
-         WRITE_FLAG( pcSlice->getSaoEnabledFlag(), "slice_sao_luma_flag" );
+         WRITE_FLAG( pcSlice->getSaoEnabledFlag(), "slice_sao_luma_flag" );         
+#if AUXILIARY_PICTURES
+         if (pcSlice->getChromaFormatIdc() != CHROMA_400)
          {
+#endif
+#if HM_CLEANUP_SAO
+         WRITE_FLAG( pcSlice->getSaoEnabledFlagChroma(), "slice_sao_chroma_flag" );
+#else
+         {
+           SAOParam *saoParam = pcSlice->getPic()->getPicSym()->getSaoParam();
+           WRITE_FLAG( saoParam->bSaoFlag[1], "slice_sao_chroma_flag" );
+         }
+#endif
 #if AUXILIARY_PICTURES
-           if (pcSlice->getChromaFormatIdc() != CHROMA_400)
-           {
-#endif
-           SAOParam *saoParam = pcSlice->getPic()->getPicSym()->getSaoParam();
-          WRITE_FLAG( saoParam->bSaoFlag[1], "slice_sao_chroma_flag" );
-#if AUXILIARY_PICTURES
-           }
-#endif
          }
-      }
-    }
+#endif
+      }
+    }   
 
     //check if numrefidxes match the defaults. If not, override
@@ -2026,11 +2148,4 @@
   Bool scalingListPredModeFlag;
 
-#if SCALING_LIST_OUTPUT_RESULT
-  Int startBit;
-  Int startTotalBit;
-  startBit = m_pcBitIf->getNumberOfWrittenBits();
-  startTotalBit = m_pcBitIf->getNumberOfWrittenBits();
-#endif
-
     //for each size
     for(sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
@@ -2038,36 +2153,4 @@
       for(listId = 0; listId < g_scalingListNum[sizeId]; listId++)
       {
-#if SCALING_LIST_OUTPUT_RESULT
-        startBit = m_pcBitIf->getNumberOfWrittenBits();
-#endif
-
-#if IL_SL_SIGNALLING_N0371
-        if( scalingList->getLayerId() > 0 && scalingList->getPredScalingListFlag() )
-        {
-          scalingListPredModeFlag = scalingList->checkPredMode( sizeId, listId );
-          WRITE_FLAG( scalingListPredModeFlag, "scaling_list_pred_mode_flag" );
-          if(!scalingListPredModeFlag)// Copy Mode
-          {
-            WRITE_UVLC( (Int)listId - (Int)scalingList->getRefMatrixId (sizeId,listId), "scaling_list_pred_matrix_id_delta");
-          }
-          else// DPCM Mode
-          {
-            xCodeScalingList(scalingList, sizeId, listId);
-          }
-        }
-        else
-        {
-          scalingListPredModeFlag = scalingList->checkPredMode( sizeId, listId );
-          WRITE_FLAG( scalingListPredModeFlag, "scaling_list_pred_mode_flag" );
-          if(!scalingListPredModeFlag)// Copy Mode
-          {
-            WRITE_UVLC( (Int)listId - (Int)scalingList->getRefMatrixId (sizeId,listId), "scaling_list_pred_matrix_id_delta");
-          }
-          else// DPCM Mode
-          {
-            xCodeScalingList(scalingList, sizeId, listId);
-          }
-        }
-#else
         scalingListPredModeFlag = scalingList->checkPredMode( sizeId, listId );
         WRITE_FLAG( scalingListPredModeFlag, "scaling_list_pred_mode_flag" );
@@ -2080,15 +2163,6 @@
           xCodeScalingList(scalingList, sizeId, listId);
         }
-#endif
-
-#if SCALING_LIST_OUTPUT_RESULT
-        printf("Matrix [%d][%d] Bit %d\n",sizeId,listId,m_pcBitIf->getNumberOfWrittenBits() - startBit);
-#endif
-
-      }
-    }
-#if SCALING_LIST_OUTPUT_RESULT
-  printf("Total Bit %d\n",m_pcBitIf->getNumberOfWrittenBits()-startTotalBit);
-#endif
+      }
+    }
   return;
 }
@@ -2105,63 +2179,24 @@
   Int data;
   Int *src = scalingList->getScalingListAddress(sizeId, listId);
-
-    if( sizeId > SCALING_LIST_8x8 )
-    {
-#if IL_SL_SIGNALLING_N0371
-      if( scalingList->getLayerId() > 0 && scalingList->getPredScalingListFlag() )
-      {
-        ref_scalingListDC[scalingList->getLayerId()][sizeId][listId] = scalingList->getScalingListDC(sizeId,listId);
-        scalingList->setScalingListDC(sizeId,listId,ref_scalingListDC[scalingList->getScalingListRefLayerId()][sizeId][listId]);
-      }
-      else
-      {
-        WRITE_SVLC( scalingList->getScalingListDC(sizeId,listId) - 8, "scaling_list_dc_coef_minus8");
-        nextCoef = scalingList->getScalingListDC(sizeId,listId);
-        ref_scalingListDC[scalingList->getLayerId()][sizeId][listId] = scalingList->getScalingListDC(sizeId,listId);
-      }
-#else
-      WRITE_SVLC( scalingList->getScalingListDC(sizeId,listId) - 8, "scaling_list_dc_coef_minus8");
-      nextCoef = scalingList->getScalingListDC(sizeId,listId);
-#endif
-    }
-    for(Int i=0;i<coefNum;i++)
-    {
-#if IL_SL_SIGNALLING_N0371
-      if( scalingList->getLayerId() > 0 && scalingList->getPredScalingListFlag() )
-      {
-        ref_scalingListCoef[scalingList->getLayerId()][sizeId][listId][i] = src[scan[i]];
-        src[scan[i]] = ref_scalingListCoef[scalingList->getScalingListRefLayerId()][sizeId][listId][i];
-      }
-      else
-      {
-        data = src[scan[i]] - nextCoef;
-        ref_scalingListCoef[scalingList->getLayerId()][sizeId][listId][i] = src[scan[i]];
-        nextCoef = src[scan[i]];
-        if(data > 127)
-        {
-          data = data - 256;
-        }
-        if(data < -128)
-        {
-          data = data + 256;
-        }
-
-        WRITE_SVLC( data,  "scaling_list_delta_coef");
-      }
-#else
-      data = src[scan[i]] - nextCoef;
-      nextCoef = src[scan[i]];
-      if(data > 127)
-      {
-        data = data - 256;
-      }
-      if(data < -128)
-      {
-        data = data + 256;
-      }
-
-      WRITE_SVLC( data,  "scaling_list_delta_coef");
-#endif
-    }
+  if( sizeId > SCALING_LIST_8x8 )
+  {
+    WRITE_SVLC( scalingList->getScalingListDC(sizeId,listId) - 8, "scaling_list_dc_coef_minus8");
+    nextCoef = scalingList->getScalingListDC(sizeId,listId);
+  }
+  for(Int i=0;i<coefNum;i++)
+  {
+    data = src[scan[i]] - nextCoef;
+    nextCoef = src[scan[i]];
+    if(data > 127)
+    {
+      data = data - 256;
+    }
+    if(data < -128)
+    {
+      data = data + 256;
+    }
+
+    WRITE_SVLC( data,  "scaling_list_delta_coef");
+  }
 }
 Bool TEncCavlc::findMatchingLTRP ( TComSlice* pcSlice, UInt *ltrpsIndex, Int ltrpPOC, Bool usedFlag )
Index: trunk/source/Lib/TLibEncoder/TEncCavlc.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncCavlc.h	(revision 494)
+++ trunk/source/Lib/TLibEncoder/TEncCavlc.h	(revision 540)
@@ -109,4 +109,7 @@
   
   Void codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList );
+#if HM_CLEANUP_SAO
+  Void codeSAOBlkParam(SAOBlkParam& saoBlkParam, Bool* sliceEnabled, Bool leftMergeAvail, Bool aboveMergeAvail, Bool onlyEstMergeInfo = false){printf("only supported in CABAC"); assert(0); exit(-1);}
+#else
   Void codeSAOSign       ( UInt code   ) { printf("Not supported\n"); assert (0); }
   Void codeSaoMaxUvlc    ( UInt   code, UInt maxSymbol ){printf("Not supported\n"); assert (0);}
@@ -114,5 +117,5 @@
   Void codeSaoTypeIdx    ( UInt uiCode ){printf("Not supported\n"); assert (0);}
   Void codeSaoUflc       ( UInt uiLength, UInt   uiCode ){ assert(uiCode < 32); printf("Not supported\n"); assert (0);}
-
+#endif
   Void codeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx );
   Void codeSkipFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
Index: trunk/source/Lib/TLibEncoder/TEncCfg.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncCfg.h	(revision 494)
+++ trunk/source/Lib/TLibEncoder/TEncCfg.h	(revision 540)
@@ -196,6 +196,7 @@
   Int       m_maxNumOffsetsPerPic;
   Bool      m_saoLcuBoundary;
+#if !HM_CLEANUP_SAO
   Bool      m_saoLcuBasedOptimization;
-
+#endif
   //====== Lossless ========
   Bool      m_useLossless;
@@ -328,21 +329,11 @@
   Int       m_TMVPModeId;
   Int       m_signHideFlag;
-#if RATE_CONTROL_LAMBDA_DOMAIN
   Bool      m_RCEnableRateControl;
   Int       m_RCTargetBitrate;
-#if M0036_RC_IMPROVEMENT
   Int       m_RCKeepHierarchicalBit;
-#else
-  Bool      m_RCKeepHierarchicalBit;
-#endif
   Bool      m_RCLCULevelRC;
   Bool      m_RCUseLCUSeparateModel;
   Int       m_RCInitialQP;
   Bool      m_RCForceIntraQP;
-#else
-  Bool      m_enableRateCtrl;                                ///< Flag for using rate control algorithm
-  Int       m_targetBitrate;                                 ///< target bitrate
-  Int       m_numLCUInUnit;                                  ///< Total number of LCUs in a frame should be divided by the NumLCUInUnit
-#endif
   Bool      m_TransquantBypassEnableFlag;                     ///< transquant_bypass_enable_flag setting in PPS.
   Bool      m_CUTransquantBypassFlagValue;                    ///< if transquant_bypass_enable_flag, the fixed value to use for the per-CU cu_transquant_bypass_flag.
@@ -393,4 +384,13 @@
   Int       m_adaptiveResolutionChange;
 #endif
+#if O0153_ALT_OUTPUT_LAYER_FLAG
+  Bool      m_altOutputLayerFlag;
+#endif
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+  Int       m_skipPictureAtArcSwitch;
+#endif
+#if O0149_CROSS_LAYER_BLA_FLAG
+  Bool      m_crossLayerBLAFlag;
+#endif
 #endif
 
@@ -629,6 +629,8 @@
   Void  setSaoLcuBoundary              (Bool val)      { m_saoLcuBoundary = val; }
   Bool  getSaoLcuBoundary              ()              { return m_saoLcuBoundary; }
+#if !HM_CLEANUP_SAO
   Void  setSaoLcuBasedOptimization               (Bool val)            { m_saoLcuBasedOptimization = val; }
   Bool  getSaoLcuBasedOptimization               ()                    { return m_saoLcuBasedOptimization; }
+#endif
   Void  setLFCrossTileBoundaryFlag               ( Bool   val  )       { m_loopFilterAcrossTilesEnabledFlag = val; }
   Bool  getLFCrossTileBoundaryFlag               ()                    { return m_loopFilterAcrossTilesEnabledFlag;   }
@@ -806,16 +808,10 @@
   Void      setSignHideFlag( Int signHideFlag ) { m_signHideFlag = signHideFlag; }
   Int       getSignHideFlag()                    { return m_signHideFlag; }
-#if RATE_CONTROL_LAMBDA_DOMAIN
   Bool      getUseRateCtrl         ()              { return m_RCEnableRateControl;   }
   Void      setUseRateCtrl         ( Bool b )      { m_RCEnableRateControl = b;      }
   Int       getTargetBitrate       ()              { return m_RCTargetBitrate;       }
   Void      setTargetBitrate       ( Int bitrate ) { m_RCTargetBitrate  = bitrate;   }
-#if M0036_RC_IMPROVEMENT
   Int       getKeepHierBit         ()              { return m_RCKeepHierarchicalBit; }
   Void      setKeepHierBit         ( Int i )       { m_RCKeepHierarchicalBit = i;    }
-#else
-  Bool      getKeepHierBit         ()              { return m_RCKeepHierarchicalBit; }
-  Void      setKeepHierBit         ( Bool b )      { m_RCKeepHierarchicalBit = b;    }
-#endif
   Bool      getLCULevelRC          ()              { return m_RCLCULevelRC; }
   Void      setLCULevelRC          ( Bool b )      { m_RCLCULevelRC = b; }
@@ -826,12 +822,4 @@
   Bool      getForceIntraQP        ()              { return m_RCForceIntraQP;        }
   Void      setForceIntraQP        ( Bool b )      { m_RCForceIntraQP = b;           }
-#else
-  Bool      getUseRateCtrl    ()                { return m_enableRateCtrl;    }
-  Void      setUseRateCtrl    (Bool flag)       { m_enableRateCtrl = flag;    }
-  Int       getTargetBitrate  ()                { return m_targetBitrate;     }
-  Void      setTargetBitrate  (Int target)      { m_targetBitrate  = target;  }
-  Int       getNumLCUInUnit   ()                { return m_numLCUInUnit;      }
-  Void      setNumLCUInUnit   (Int numLCUs)     { m_numLCUInUnit   = numLCUs; }
-#endif
   Bool      getTransquantBypassEnableFlag()           { return m_TransquantBypassEnableFlag; }
   Void      setTransquantBypassEnableFlag(Bool flag)  { m_TransquantBypassEnableFlag = flag; }
@@ -934,8 +922,20 @@
   Int       getAdaptiveResolutionChange()      { return m_adaptiveResolutionChange; }
 #endif
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+  Void      setSkipPictureAtArcSwitch(Int x) { m_skipPictureAtArcSwitch = x;    }
+  Int       getSkipPictureAtArcSwitch()      { return m_skipPictureAtArcSwitch; }
+#endif
 #if AUXILIARY_PICTURES
   Void         setChromaFormatIDC(ChromaFormat x) { m_chromaFormatIDC = x;    }
   ChromaFormat getChromaFormatIDC()               { return m_chromaFormatIDC; }
 #endif
+#if O0153_ALT_OUTPUT_LAYER_FLAG
+  Bool      getAltOuputLayerFlag() const { return m_altOutputLayerFlag; }
+  Void      setAltOuputLayerFlag(Bool b) { m_altOutputLayerFlag = b;    }
+#endif
+#if O0149_CROSS_LAYER_BLA_FLAG
+  Bool      getCrossLayerBLAFlag() const { return m_crossLayerBLAFlag; }
+  Void      setCrossLayerBLAFlag(Bool b) { m_crossLayerBLAFlag = b;    }
+#endif
 #endif
 };
Index: trunk/source/Lib/TLibEncoder/TEncCu.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncCu.cpp	(revision 494)
+++ trunk/source/Lib/TLibEncoder/TEncCu.cpp	(revision 540)
@@ -95,9 +95,4 @@
   
   m_bEncodeDQP = false;
-#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
-  m_LCUPredictionSAD = 0;
-  m_addSADDepth      = 0;
-  m_temporalSAD      = 0;
-#endif
 
   // initialize partition order.
@@ -243,10 +238,4 @@
   m_ppcBestCU[0]->initCU( rpcCU->getPic(), rpcCU->getAddr() );
   m_ppcTempCU[0]->initCU( rpcCU->getPic(), rpcCU->getAddr() );
-
-#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
-  m_addSADDepth      = 0;
-  m_LCUPredictionSAD = 0;
-  m_temporalSAD      = 0;
-#endif
 
 #if N0383_IL_CONSTRAINED_TILE_SETS_SEI
@@ -433,5 +422,4 @@
   }
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
   if ( m_pcEncCfg->getUseRateCtrl() )
   {
@@ -439,12 +427,4 @@
     iMaxQP = m_pcRateCtrl->getRCQP();
   }
-#else
-  if(m_pcEncCfg->getUseRateCtrl())
-  {
-    Int qp = m_pcRateCtrl->getUnitQP();
-    iMinQP  = Clip3( MIN_QP, MAX_QP, qp);
-    iMaxQP  = Clip3( MIN_QP, MAX_QP, qp);
-  }
-#endif
 
   // If slice start or slice end is within this cu...
@@ -460,4 +440,14 @@
   if(!bSliceEnd && !bSliceStart && bInsidePicture )
   {
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+    if (m_pcEncCfg->getSkipPictureAtArcSwitch() && m_pcEncCfg->getAdaptiveResolutionChange() > 0 && pcSlice->getLayerId() == 1 && pcSlice->getPOC() == m_pcEncCfg->getAdaptiveResolutionChange())
+    {
+      rpcTempCU->initEstData( uiDepth, iBaseQP );
+      
+      xCheckRDCostMerge2Nx2N( rpcBestCU, rpcTempCU, &earlyDetectionSkipMode, true );
+    }
+    else
+    {
+#endif
 #if (ENCODER_FAST_MODE)
     Bool testInter = true;
@@ -528,12 +518,4 @@
       }
     }
-
-#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
-    if ( uiDepth <= m_addSADDepth )
-    {
-      m_LCUPredictionSAD += m_temporalSAD;
-      m_addSADDepth = uiDepth;
-    }
-#endif
 
     if(!earlyDetectionSkipMode)
@@ -779,11 +761,11 @@
       bSubBranch = true;
     }
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+    }
+#endif
   }
   else if(!(bSliceEnd && bInsidePicture))
   {
     bBoundary = true;
-#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
-    m_addSADDepth++;
-#endif
   }
 
@@ -829,5 +811,4 @@
     iMaxQP = iStartQP;
   }
-#if RATE_CONTROL_LAMBDA_DOMAIN
   if ( m_pcEncCfg->getUseRateCtrl() )
   {
@@ -835,12 +816,4 @@
     iMaxQP = m_pcRateCtrl->getRCQP();
   }
-#else
-  if(m_pcEncCfg->getUseRateCtrl())
-  {
-    Int qp = m_pcRateCtrl->getUnitQP();
-    iMinQP  = Clip3( MIN_QP, MAX_QP, qp);
-    iMaxQP  = Clip3( MIN_QP, MAX_QP, qp);
-  }
-#endif
   for (Int iQP=iMinQP; iQP<=iMaxQP; iQP++)
   {
@@ -1143,4 +1116,10 @@
   
   TComSlice * pcSlice = pcCU->getPic()->getSlice(pcCU->getPic()->getCurrSliceIdx());
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+  if (m_pcEncCfg->getSkipPictureAtArcSwitch() && m_pcEncCfg->getAdaptiveResolutionChange() > 0 && pcSlice->getLayerId() == 1 && pcSlice->getPOC() == m_pcEncCfg->getAdaptiveResolutionChange())
+  {
+    pcCU->setSkipFlagSubParts(true, uiAbsPartIdx, uiDepth);
+  }
+#endif
   // If slice start is within this cu...
   Bool bSliceStart = pcSlice->getSliceSegmentCurStartCUAddr() > pcPic->getPicSym()->getInverseCUOrderMap(pcCU->getAddr())*pcCU->getPic()->getNumPartInCU()+uiAbsPartIdx && 
@@ -1231,5 +1210,4 @@
 }
 
-#if RATE_CONTROL_INTRA
 Int xCalcHADs8x8_ISlice(Pel *piOrg, Int iStrideOrg) 
 {
@@ -1346,5 +1324,4 @@
   return(iSumHad);
 }
-#endif
 
 /** check RD costs for a CU block encoded with merge
@@ -1353,5 +1330,9 @@
  * \returns Void
  */
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+Void TEncCu::xCheckRDCostMerge2Nx2N( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, Bool *earlyDetectionSkipMode, Bool bUseSkip )
+#else
 Void TEncCu::xCheckRDCostMerge2Nx2N( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, Bool *earlyDetectionSkipMode )
+#endif
 {
   assert( rpcTempCU->getSlice()->getSliceType() != I_SLICE );
@@ -1387,5 +1368,9 @@
   }
 
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+  for( UInt uiNoResidual = bUseSkip?1:0; uiNoResidual < iteration; ++uiNoResidual )
+#else
   for( UInt uiNoResidual = 0; uiNoResidual < iteration; ++uiNoResidual )
+#endif
   {
     for( UInt uiMergeCand = 0; uiMergeCand < numValidMergeCand; ++uiMergeCand )
@@ -1515,14 +1500,4 @@
 #endif
 
-#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
-  if ( m_pcEncCfg->getUseRateCtrl() && m_pcEncCfg->getLCULevelRC() && ePartSize == SIZE_2Nx2N && uhDepth <= m_addSADDepth )
-  {
-    UInt SAD = m_pcRdCost->getSADPart( g_bitDepthY, m_ppcPredYuvTemp[uhDepth]->getLumaAddr(), m_ppcPredYuvTemp[uhDepth]->getStride(),
-      m_ppcOrigYuv[uhDepth]->getLumaAddr(), m_ppcOrigYuv[uhDepth]->getStride(),
-      rpcTempCU->getWidth(0), rpcTempCU->getHeight(0) );
-    m_temporalSAD = (Int)SAD;
-  }
-#endif
-
   m_pcPredSearch->encodeResAndCalcRdInterCU( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcResiYuvBest[uhDepth], m_ppcRecoYuvTemp[uhDepth], false );
   rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
@@ -1555,5 +1530,4 @@
   
   m_pcEntropyCoder->resetBits();
-
   if ( rpcTempCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
   {
@@ -1609,5 +1583,4 @@
 
   m_pcEntropyCoder->resetBits();
-
   if ( rpcTempCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
   {
Index: trunk/source/Lib/TLibEncoder/TEncCu.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncCu.h	(revision 494)
+++ trunk/source/Lib/TLibEncoder/TEncCu.h	(revision 540)
@@ -103,9 +103,5 @@
   Bool                    m_bUseSBACRD;
   TEncRateCtrl*           m_pcRateCtrl;
-#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
-  UInt                    m_LCUPredictionSAD;
-  Int                     m_addSADDepth;
-  Int                     m_temporalSAD;
-#endif
+
 #if N0383_IL_CONSTRAINED_TILE_SETS_SEI
   Bool                    m_disableILP;
@@ -128,11 +124,5 @@
   
   Void setBitCounter        ( TComBitCounter* pcBitCounter ) { m_pcBitCounter = pcBitCounter; }
-#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
-  UInt getLCUPredictionSAD() { return m_LCUPredictionSAD; }
-#endif
-#if RATE_CONTROL_INTRA
   Int   updateLCUDataISlice ( TComDataCU* pcCU, Int LCUIdx, Int width, Int height );
-#endif
-
 protected:
   Void  finishCU            ( TComDataCU*  pcCU, UInt uiAbsPartIdx,           UInt uiDepth        );
@@ -146,6 +136,9 @@
   Int   xComputeQP          ( TComDataCU* pcCU, UInt uiDepth );
   Void  xCheckBestMode      ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UInt uiDepth        );
-  
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+  Void  xCheckRDCostMerge2Nx2N( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, Bool *earlyDetectionSkipMode, Bool bUseSkip=false);
+#else  
   Void  xCheckRDCostMerge2Nx2N( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, Bool *earlyDetectionSkipMode);
+#endif
 
 #if AMP_MRG
Index: trunk/source/Lib/TLibEncoder/TEncEntropy.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncEntropy.cpp	(revision 494)
+++ trunk/source/Lib/TLibEncoder/TEncEntropy.cpp	(revision 540)
@@ -51,4 +51,5 @@
 Void TEncEntropy::encodeSliceHeader ( TComSlice* pcSlice )
 {
+#if !HM_CLEANUP_SAO
   if (pcSlice->getSPS()->getUseSAO())
   {
@@ -59,5 +60,5 @@
     }
   }
-
+#endif
   m_pcEntropyCoderIf->codeSliceHeader( pcSlice );
   return;
@@ -638,4 +639,5 @@
 }
 
+#if !HM_CLEANUP_SAO
 /** Encode SAO Offset
  * \param  saoLcuParam SAO LCU paramters
@@ -731,4 +733,6 @@
 }
 
+#endif
+
 Int TEncEntropy::countNonZeroCoeffs( TCoeff* pcCoef, UInt uiSize )
 {
Index: trunk/source/Lib/TLibEncoder/TEncEntropy.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncEntropy.h	(revision 494)
+++ trunk/source/Lib/TLibEncoder/TEncEntropy.h	(revision 540)
@@ -105,4 +105,7 @@
   virtual Void codeCoeffNxN      ( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType ) = 0;
   virtual Void codeTransformSkipFlags ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, TextType eTType ) = 0;
+#if HM_CLEANUP_SAO
+  virtual Void codeSAOBlkParam(SAOBlkParam& saoBlkParam, Bool* sliceEnabled, Bool leftMergeAvail, Bool aboveMergeAvail, Bool onlyEstMergeInfo = false)    =0;
+#else
   virtual Void codeSAOSign          ( UInt code   ) = 0;
   virtual Void codeSaoMaxUvlc       ( UInt code, UInt maxSymbol ) = 0;
@@ -110,4 +113,5 @@
   virtual Void codeSaoTypeIdx      ( UInt   uiCode) = 0;
   virtual Void codeSaoUflc         ( UInt uiLength, UInt   uiCode ) = 0;
+#endif
   virtual Void estBit               (estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType) = 0;
   
@@ -188,6 +192,10 @@
   
   Void estimateBit             ( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType);
+#if HM_CLEANUP_SAO
+  Void encodeSAOBlkParam(SAOBlkParam& saoBlkParam, Bool* sliceEnabled, Bool leftMergeAvail, Bool aboveMergeAvail){m_pcEntropyCoderIf->codeSAOBlkParam(saoBlkParam, sliceEnabled, leftMergeAvail, aboveMergeAvail, false);}
+#else
   Void    encodeSaoOffset(SaoLcuParam* saoLcuParam, UInt compIdx);
   Void    encodeSaoUnitInterleaving(Int compIdx, Bool saoFlag, Int rx, Int ry, SaoLcuParam* saoLcuParam, Int cuAddrInSlice, Int cuAddrUpInSlice, Int allowMergeLeft, Int allowMergeUp);
+#endif
   static Int countNonZeroCoeffs( TCoeff* pcCoef, UInt uiSize );
 
Index: trunk/source/Lib/TLibEncoder/TEncGOP.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 494)
+++ trunk/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 540)
@@ -635,4 +635,54 @@
     }
 #endif
+#if O0149_CROSS_LAYER_BLA_FLAG
+    if( m_layerId == 0 && (getNalUnitType(pocCurr, m_iLastIDR) == NAL_UNIT_CODED_SLICE_IDR_W_RADL || getNalUnitType(pocCurr, m_iLastIDR) == NAL_UNIT_CODED_SLICE_IDR_N_LP) )
+    {
+      pcSlice->setCrossLayerBLAFlag(m_pcEncTop->getCrossLayerBLAFlag());
+    }
+    else
+    {
+      pcSlice->setCrossLayerBLAFlag(false);
+    }
+#endif
+#if NO_CLRAS_OUTPUT_FLAG
+    if (m_layerId == 0 &&
+        (pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA))
+    {
+      if (m_bFirst)
+      {
+        m_pcEncTop->setNoClrasOutputFlag(true);
+      }
+      else if (pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
+            || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
+            || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP)
+      {
+        m_pcEncTop->setNoClrasOutputFlag(true);
+      }
+#if O0149_CROSS_LAYER_BLA_FLAG
+      else if ((pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP) &&
+               pcSlice->getCrossLayerBLAFlag())
+      {
+        m_pcEncTop->setNoClrasOutputFlag(true);
+      }
+#endif
+      else
+      {
+        m_pcEncTop->setNoClrasOutputFlag(false);
+      }
+      if (m_pcEncTop->getNoClrasOutputFlag())
+      {
+        for (UInt i = 0; i < m_pcCfg->getNumLayer(); i++)
+        {
+          m_ppcTEncTop[i]->setLayerInitializedFlag(false);
+          m_ppcTEncTop[i]->setFirstPicInLayerDecodedFlag(false);
+        }
+      }
+    }
+#endif
 #if M0040_ADAPTIVE_RESOLUTION_CHANGE
     if (m_pcEncTop->getAdaptiveResolutionChange() > 0 && m_layerId == 1 && pocCurr > m_pcEncTop->getAdaptiveResolutionChange())
@@ -661,8 +711,4 @@
 #endif
 
-#if IL_SL_SIGNALLING_N0371
-    m_pcEncTop->getScalingList()->setLayerId( m_layerId );
-#endif
-
     pcSlice->setLastIDR(m_iLastIDR);
     pcSlice->setSliceIdx(0);
@@ -672,9 +718,5 @@
     if(m_pcEncTop->getUseScalingListId() == SCALING_LIST_OFF)
     {
-#if IL_SL_SIGNALLING_N0371
-      m_pcEncTop->getTrQuant()->setFlatScalingList( m_layerId );
-#else
       m_pcEncTop->getTrQuant()->setFlatScalingList();
-#endif
       m_pcEncTop->getTrQuant()->setUseScalingList(false);
       m_pcEncTop->getSPS()->setScalingListPresentFlag(false);
@@ -683,16 +725,29 @@
     else if(m_pcEncTop->getUseScalingListId() == SCALING_LIST_DEFAULT)
     {
-#if IL_SL_SIGNALLING_N0371
-      pcSlice->getScalingList()->setLayerId( m_layerId );
-#endif
-
-#if IL_SL_SIGNALLING_N0371
-      pcSlice->setDefaultScalingList ( m_layerId );
-#else
+#if SCALINGLIST_INFERRING
+      // inferring of the scaling list can be moved to the config file
+      UInt refLayerId = 0;
+      if( m_layerId > 0 && !m_pcEncTop->getVPS()->getAvcBaseLayerFlag() && m_pcEncTop->getVPS()->getRecursiveRefLayerFlag( m_layerId, refLayerId ) )
+      {
+        m_pcEncTop->getSPS()->setInferScalingListFlag( true );
+        m_pcEncTop->getSPS()->setScalingListRefLayerId( refLayerId );
+        m_pcEncTop->getSPS()->setScalingListPresentFlag( false );
+        m_pcEncTop->getPPS()->setInferScalingListFlag( false );
+        m_pcEncTop->getPPS()->setScalingListPresentFlag( false );
+
+        // infer the scaling list from the reference layer
+        pcSlice->setScalingList ( m_ppcTEncTop[refLayerId]->getScalingList() );
+      }
+      else
+      {
+#endif
       pcSlice->setDefaultScalingList ();
-#endif
-
       m_pcEncTop->getSPS()->setScalingListPresentFlag(false);
       m_pcEncTop->getPPS()->setScalingListPresentFlag(false);
+
+#if SCALINGLIST_INFERRING
+      }
+#endif
+
       m_pcEncTop->getTrQuant()->setScalingList(pcSlice->getScalingList());
       m_pcEncTop->getTrQuant()->setUseScalingList(true);
@@ -700,39 +755,33 @@
     else if(m_pcEncTop->getUseScalingListId() == SCALING_LIST_FILE_READ)
     {
-#if IL_SL_SIGNALLING_N0371
-      pcSlice->getScalingList()->setLayerId( m_layerId );
+#if SCALINGLIST_INFERRING
+      // inferring of the scaling list can be moved to the config file
+      UInt refLayerId = 0;
+      if( m_layerId > 0 && !m_pcEncTop->getVPS()->getAvcBaseLayerFlag() && m_pcEncTop->getVPS()->getRecursiveRefLayerFlag( m_layerId, refLayerId ) )
+      {
+        m_pcEncTop->getSPS()->setInferScalingListFlag( true );
+        m_pcEncTop->getSPS()->setScalingListRefLayerId( refLayerId );
+        m_pcEncTop->getSPS()->setScalingListPresentFlag( false );
+        m_pcEncTop->getPPS()->setInferScalingListFlag( false );
+        m_pcEncTop->getPPS()->setScalingListPresentFlag( false );
+
+        // infer the scaling list from the reference layer
+        pcSlice->setScalingList ( m_ppcTEncTop[refLayerId]->getScalingList() );
+      }
+      else
+      {
 #endif
 
       if(pcSlice->getScalingList()->xParseScalingList(m_pcCfg->getScalingListFile()))
       {
-#if IL_SL_SIGNALLING_N0371
-        pcSlice->setDefaultScalingList ( m_layerId );
-#else
         pcSlice->setDefaultScalingList ();
-#endif
-      }
-#if IL_SL_SIGNALLING_N0371
-      pcSlice->getScalingList()->checkDcOfMatrix( m_layerId );
-#else
+      }
+
       pcSlice->getScalingList()->checkDcOfMatrix();
-#endif
       m_pcEncTop->getSPS()->setScalingListPresentFlag(pcSlice->checkDefaultScalingList());
-
-#if IL_SL_SIGNALLING_N0371
-      if( m_layerId > 0 )
-      {
-        m_pcEncTop->getSPS()->setPredScalingListFlag  (true); 
-        m_pcEncTop->getSPS()->setScalingListRefLayerId( 0 ); 
-      }
-#endif
-
       m_pcEncTop->getPPS()->setScalingListPresentFlag(false);
 
-#if IL_SL_SIGNALLING_N0371
-      if( m_layerId > 0 )
-      {
-        m_pcEncTop->getPPS()->setPredScalingListFlag  (false); 
-        m_pcEncTop->getPPS()->setScalingListRefLayerId( 0   ); 
-      }
+#if SCALINGLIST_INFERRING
+    }
 #endif
 
@@ -783,5 +832,9 @@
         }
 
+#if O0098_SCALED_REF_LAYER_ID
+        const Window &scalEL = m_pcEncTop->getScaledRefLayerWindowForLayer(pcSlice->getVPS()->getRefLayerId(m_layerId, refLayerIdc));
+#else
         const Window &scalEL = m_pcEncTop->getScaledRefLayerWindow(refLayerIdc);
+#endif
 
         Int widthBL   = pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec()->getWidth();
@@ -800,15 +853,20 @@
         if( pcPic->isSpatialEnhLayer(refLayerIdc))
         {
+/*#if O0098_SCALED_REF_LAYER_ID
+          Window scalEL = pcSlice->getSPS()->getScaledRefLayerWindowForLayer(pcSlice->getVPS()->getRefLayerId(m_layerId, refLayerIdc));
+#else
+          Window scalEL = pcSlice->getSPS()->getScaledRefLayerWindow(refLayerIdc);
+#endif*/
 #if O0215_PHASE_ALIGNMENT
 #if O0194_JOINT_US_BITSHIFT
-          m_pcPredSearch->upsampleBasePic( pcSlice, refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(), pcPic->getPicYuvRec(), pcSlice->getSPS()->getScaledRefLayerWindow(refLayerIdc), pcSlice->getVPS()->getPhaseAlignFlag() );
-#else
-          m_pcPredSearch->upsampleBasePic( refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(), pcPic->getPicYuvRec(), pcSlice->getSPS()->getScaledRefLayerWindow(refLayerIdc), pcSlice->getVPS()->getPhaseAlignFlag() );
+          m_pcPredSearch->upsampleBasePic( pcSlice, refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(), pcPic->getPicYuvRec(), scalEL, pcSlice->getVPS()->getPhaseAlignFlag() );
+#else
+          m_pcPredSearch->upsampleBasePic( refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(), pcPic->getPicYuvRec(), scalEL, pcSlice->getVPS()->getPhaseAlignFlag() );
 #endif
 #else
 #if O0194_JOINT_US_BITSHIFT
-          m_pcPredSearch->upsampleBasePic( pcSlice, refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(), pcPic->getPicYuvRec(), pcSlice->getSPS()->getScaledRefLayerWindow(refLayerIdc) );
-#else
-          m_pcPredSearch->upsampleBasePic( refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(), pcPic->getPicYuvRec(), pcSlice->getSPS()->getScaledRefLayerWindow(refLayerIdc) );
+          m_pcPredSearch->upsampleBasePic( pcSlice, refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(), pcPic->getPicYuvRec(), scalEL );
+#else
+          m_pcPredSearch->upsampleBasePic( refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(), pcPic->getPicYuvRec(), scalEL );
 #endif
 #endif
@@ -827,5 +885,8 @@
         pcSlice->setInterLayerPredLayerIdc( interLayerPredLayerIdcTmp[i], i );
       }
+
+#if !O0225_TID_BASED_IL_RPS_DERIV
       pcSlice->setActiveNumILRRefIdx( activeNumILRRefIdxTmp );
+#endif 
       if ( pcSlice->getActiveNumILRRefIdx() == 0 )
       {
@@ -902,19 +963,16 @@
 
     // Do decoding refresh marking if any 
+#if NO_CLRAS_OUTPUT_FLAG
+    pcSlice->decodingRefreshMarking(m_pocCRA, m_bRefreshPending, rcListPic, m_pcEncTop->getNoClrasOutputFlag());
+#else
     pcSlice->decodingRefreshMarking(m_pocCRA, m_bRefreshPending, rcListPic);
+#endif
     m_pcEncTop->selectReferencePictureSet(pcSlice, pocCurr, iGOPid);
     pcSlice->getRPS()->setNumberOfLongtermPictures(0);
 
-#if FIX1071
     if ((pcSlice->checkThatAllRefPicsAreAvailable(rcListPic, pcSlice->getRPS(), false) != 0) || (pcSlice->isIRAP()))
     {
       pcSlice->createExplicitReferencePictureSetFromReference(rcListPic, pcSlice->getRPS(), pcSlice->isIRAP());
     }
-#else
-    if(pcSlice->checkThatAllRefPicsAreAvailable(rcListPic, pcSlice->getRPS(), false) != 0)
-    {
-      pcSlice->createExplicitReferencePictureSetFromReference(rcListPic, pcSlice->getRPS());
-    }
-#endif
     pcSlice->applyReferencePictureSet(rcListPic, pcSlice->getRPS());
 
@@ -934,5 +992,5 @@
             {
               if( ( lowerLayerPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_N ) ||
-                  ( lowerLayerPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_TLA_R ) 
+                  ( lowerLayerPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_R ) 
                 )
               {
@@ -943,5 +1001,5 @@
                 else
                 {
-                  pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TLA_R );
+                  pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TSA_R );
                 }
                 oneRefLayerTSA = true;
@@ -975,5 +1033,5 @@
             else
             {
-              pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TLA_R );
+              pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TSA_R );
             }
           }
@@ -986,5 +1044,5 @@
         else
         {
-          pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TLA_R);
+          pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TSA_R);
         }
 #endif
@@ -1356,5 +1414,4 @@
     pcPic->getSlice(pcSlice->getSliceIdx())->setMvdL1ZeroFlag(pcSlice->getMvdL1ZeroFlag());
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
     Double lambda            = 0.0;
     Int actualHeadBits       = 0;
@@ -1389,15 +1446,9 @@
       else if ( frameLevel == 0 )   // intra case, but use the model
       {
-#if RATE_CONTROL_INTRA
         m_pcSliceEncoder->calCostSliceI(pcPic);
-#endif
         if ( m_pcCfg->getIntraPeriod() != 1 )   // do not refine allocated bits for all intra case
         {
           Int bits = m_pcRateCtrl->getRCSeq()->getLeftAverageBits();
-#if RATE_CONTROL_INTRA
           bits = m_pcRateCtrl->getRCPic()->getRefineBitsForIntra( bits );
-#else
-          bits = m_pcRateCtrl->getRCSeq()->getRefineBitsForIntra( bits );
-#endif
           if ( bits < 200 )
           {
@@ -1408,10 +1459,6 @@
 
         list<TEncRCPic*> listPreviousPicture = m_pcRateCtrl->getPicList();
-#if RATE_CONTROL_INTRA
         m_pcRateCtrl->getRCPic()->getLCUInitTargetBits();
         lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambda( listPreviousPicture, pcSlice->getSliceType());
-#else
-        lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambda( listPreviousPicture );
-#endif
         sliceQP = m_pcRateCtrl->getRCPic()->estimatePicQP( lambda, listPreviousPicture );
       }
@@ -1419,9 +1466,5 @@
       {
         list<TEncRCPic*> listPreviousPicture = m_pcRateCtrl->getPicList();
-#if RATE_CONTROL_INTRA
         lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambda( listPreviousPicture, pcSlice->getSliceType());
-#else
-        lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambda( listPreviousPicture );
-#endif
         sliceQP = m_pcRateCtrl->getRCPic()->estimatePicQP( lambda, listPreviousPicture );
       }
@@ -1436,5 +1479,4 @@
       m_pcSliceEncoder->resetQP( pcPic, sliceQP, lambda );
     }
-#endif
 
     UInt uiNumSlices = 1;
@@ -1647,4 +1689,10 @@
 
     // SAO parameter estimation using non-deblocked pixels for LCU bottom and right boundary areas
+#if HM_CLEANUP_SAO
+    if( pcSlice->getSPS()->getUseSAO() && m_pcCfg->getSaoLcuBoundary() )
+    {
+      m_pcSAO->getPreDBFStatistics(pcPic);
+    }
+#else
     if( m_pcCfg->getSaoLcuBasedOptimization() && m_pcCfg->getSaoLcuBoundary() )
     {
@@ -1652,5 +1700,5 @@
       m_pcSAO->calcSaoStatsCu_BeforeDblk( pcPic );
     }
-
+#endif    
     //-- Loop filter
     Bool bLFCrossTileBoundary = pcSlice->getPPS()->getLoopFilterAcrossTilesEnabledFlag();
@@ -1662,4 +1710,5 @@
     m_pcLoopFilter->loopFilterPic( pcPic );
 
+#if !HM_CLEANUP_SAO    
     pcSlice = pcPic->getSlice(0);
     if(pcSlice->getSPS()->getUseSAO())
@@ -1681,5 +1730,5 @@
       m_pcSAO->createPicSaoInfo(pcPic);
     }
-
+#endif
     /////////////////////////////////////////////////////////////////////////////////////////////////// File writing
     // Set entropy coder
@@ -1713,7 +1762,5 @@
       writeRBSPTrailingBits(nalu.m_Bitstream);
       accessUnit.push_back(new NALUnitEBSP(nalu));
-#if RATE_CONTROL_LAMBDA_DOMAIN
       actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
-#endif
 #if SVC_EXTENSION
       }
@@ -1722,7 +1769,4 @@
 #if SVC_EXTENSION
       nalu = NALUnit(NAL_UNIT_SPS, 0, m_layerId);
-#if IL_SL_SIGNALLING_N0371
-      pcSlice->getSPS()->setVPS( pcSlice->getVPS() );
-#endif
 #else
       nalu = NALUnit(NAL_UNIT_SPS);
@@ -1753,10 +1797,11 @@
         pcSlice->getSPS()->getVuiParameters()->setHrdParametersPresentFlag( true );
       }
+#if O0092_0094_DEPENDENCY_CONSTRAINT
+      assert( pcSlice->getSPS()->getLayerId() == 0 || pcSlice->getSPS()->getLayerId() == m_layerId || m_pcEncTop->getVPS()->getRecursiveRefLayerFlag(m_layerId, pcSlice->getSPS()->getLayerId()) );
+#endif
       m_pcEntropyCoder->encodeSPS(pcSlice->getSPS());
       writeRBSPTrailingBits(nalu.m_Bitstream);
       accessUnit.push_back(new NALUnitEBSP(nalu));
-#if RATE_CONTROL_LAMBDA_DOMAIN
       actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
-#endif
 
 #if SVC_EXTENSION
@@ -1766,10 +1811,11 @@
 #endif
       m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+#if O0092_0094_DEPENDENCY_CONSTRAINT
+      assert( pcSlice->getPPS()->getPPSId() == 0 || pcSlice->getPPS()->getPPSId() == m_layerId || m_pcEncTop->getVPS()->getRecursiveRefLayerFlag(m_layerId, pcSlice->getPPS()->getPPSId()) );
+#endif
       m_pcEntropyCoder->encodePPS(pcSlice->getPPS());
       writeRBSPTrailingBits(nalu.m_Bitstream);
       accessUnit.push_back(new NALUnitEBSP(nalu));
-#if RATE_CONTROL_LAMBDA_DOMAIN
       actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
-#endif
 
       xCreateLeadingSEIMessages(accessUnit, pcSlice->getSPS());
@@ -2091,13 +2137,7 @@
           }
           m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
-#if RATE_CONTROL_LAMBDA_DOMAIN
           tmpBitsBeforeWriting = m_pcEntropyCoder->getNumberOfWrittenBits();
-#endif
-
           m_pcEntropyCoder->encodeSliceHeader(pcSlice);
-
-#if RATE_CONTROL_LAMBDA_DOMAIN
           actualHeadBits += ( m_pcEntropyCoder->getNumberOfWrittenBits() - tmpBitsBeforeWriting );
-#endif
 
           // is it needed?
@@ -2220,7 +2260,5 @@
           xAttachSliceDataToNalUnit(nalu, pcBitstreamRedirect);
           accessUnit.push_back(new NALUnitEBSP(nalu));
-#if RATE_CONTROL_LAMBDA_DOMAIN
           actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
-#endif
           bNALUAlignedWrittenToList = true; 
           uiOneBitstreamPerSliceLength += nalu.m_Bitstream.getNumberOfWrittenBits(); // length of bitstream after byte-alignment
@@ -2262,28 +2300,58 @@
             // set entropy coder for RD
             m_pcEntropyCoder->setEntropyCoder ( m_pcSbacCoder, pcSlice );
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+            if ( pcSlice->getSPS()->getUseSAO() && !( m_pcEncTop->getSkipPictureAtArcSwitch() && m_pcEncTop->getAdaptiveResolutionChange() > 0 && pcSlice->getLayerId() == 1 && pcSlice->getPOC() == m_pcEncTop->getAdaptiveResolutionChange()) )
+#else
             if ( pcSlice->getSPS()->getUseSAO() )
+#endif
             {
               m_pcEntropyCoder->resetEntropy();
               m_pcEntropyCoder->setBitstream( m_pcBitCounter );
+#if HM_CLEANUP_SAO
+              Bool sliceEnabled[NUM_SAO_COMPONENTS];
+              m_pcSAO->initRDOCabacCoder(m_pcEncTop->getRDGoOnSbacCoder(), pcSlice);
+              m_pcSAO->SAOProcess(pcPic
+                , sliceEnabled
+                , pcPic->getSlice(0)->getLambdas()
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                , m_pcCfg->getSaoLcuBoundary()
+#endif
+              );
+              m_pcSAO->PCMLFDisableProcess(pcPic);   
+
+              //assign SAO slice header
+              for(Int s=0; s< uiNumSlices; s++)
+              {
+                pcPic->getSlice(s)->setSaoEnabledFlag(sliceEnabled[SAO_Y]);
+                assert(sliceEnabled[SAO_Cb] == sliceEnabled[SAO_Cr]);
+                pcPic->getSlice(s)->setSaoEnabledFlagChroma(sliceEnabled[SAO_Cb]);
+              }
+#else
               m_pcSAO->startSaoEnc(pcPic, m_pcEntropyCoder, m_pcEncTop->getRDSbacCoder(), m_pcEncTop->getRDGoOnSbacCoder());
               SAOParam& cSaoParam = *pcSlice->getPic()->getPicSym()->getSaoParam();
 
-#if SAO_CHROMA_LAMBDA
 #if SAO_ENCODING_CHOICE
-              m_pcSAO->SAOProcess(&cSaoParam, pcPic->getSlice(0)->getLambdaLuma(), pcPic->getSlice(0)->getLambdaChroma(), pcPic->getSlice(0)->getDepth());
+              m_pcSAO->SAOProcess(&cSaoParam, pcPic->getSlice(0)->getLambdas()[TEXT_LUMA], pcPic->getSlice(0)->getLambdas()[TEXT_CHROMA], pcPic->getSlice(0)->getDepth());
 #else
               m_pcSAO->SAOProcess(&cSaoParam, pcPic->getSlice(0)->getLambdaLuma(), pcPic->getSlice(0)->getLambdaChroma());
-#endif
-#else
-              m_pcSAO->SAOProcess(&cSaoParam, pcPic->getSlice(0)->getLambda());
 #endif
               m_pcSAO->endSaoEnc();
               m_pcSAO->PCMLFDisableProcess(pcPic);
+#endif
             }
+#if !HM_CLEANUP_SAO          
 #if SAO_RDO
             m_pcEntropyCoder->setEntropyCoder ( m_pcCavlcCoder, pcSlice );
 #endif
+#endif
             processingState = ENCODE_SLICE;
-
+#if !HM_CLEANUP_SAO
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+            if ( ( m_pcEncTop->getSkipPictureAtArcSwitch() && m_pcEncTop->getAdaptiveResolutionChange() > 0 && pcSlice->getLayerId() == 1 && pcSlice->getPOC() == m_pcEncTop->getAdaptiveResolutionChange()) )
+            {
+              pcSlice->getPic()->getPicSym()->getSaoParam()->bSaoFlag[0]=0;
+              pcSlice->getPic()->getPicSym()->getSaoParam()->bSaoFlag[1]=0;
+            }
+#endif
             for(Int s=0; s< uiNumSlices; s++)
             {
@@ -2293,4 +2361,5 @@
               }
             }
+#endif
           }
           break;
@@ -2303,5 +2372,5 @@
         }
       } // end iteration over slices
-
+#if !HM_CLEANUP_SAO    
       if(pcSlice->getSPS()->getUseSAO())
       {
@@ -2312,5 +2381,5 @@
         pcPic->destroyNonDBFilterInfo();
       }
-
+#endif
       pcPic->compressMotion(); 
       
@@ -2412,10 +2481,6 @@
         }
       }
-#if RATE_CONTROL_LAMBDA_DOMAIN
       if ( m_pcCfg->getUseRateCtrl() )
       {
-#if !M0036_RC_IMPROVEMENT
-        Double effectivePercentage = m_pcRateCtrl->getRCPic()->getEffectivePercentage();
-#endif
         Double avgQP     = m_pcRateCtrl->getRCPic()->calAverageQP();
         Double avgLambda = m_pcRateCtrl->getRCPic()->calAverageLambda();
@@ -2424,13 +2489,5 @@
           avgLambda = lambda;
         }
-#if M0036_RC_IMPROVEMENT
-#if RATE_CONTROL_INTRA
         m_pcRateCtrl->getRCPic()->updateAfterPicture( actualHeadBits, actualTotalBits, avgQP, avgLambda, pcSlice->getSliceType());
-#else
-        m_pcRateCtrl->getRCPic()->updateAfterPicture( actualHeadBits, actualTotalBits, avgQP, avgLambda );
-#endif
-#else
-        m_pcRateCtrl->getRCPic()->updateAfterPicture( actualHeadBits, actualTotalBits, avgQP, avgLambda, effectivePercentage );
-#endif
         m_pcRateCtrl->getRCPic()->addToPictureLsit( m_pcRateCtrl->getPicList() );
 
@@ -2445,11 +2502,4 @@
         }
       }
-#else
-      if(m_pcCfg->getUseRateCtrl())
-      {
-        UInt  frameBits = m_vRVM_RP[m_vRVM_RP.size()-1];
-        m_pcRateCtrl->updataRCFrameStatus((Int)frameBits, pcSlice->getSliceType());
-      }
-#endif
 
       if( ( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() ) &&
@@ -2636,10 +2686,4 @@
       delete[] pcSubstreamsOut;
   }
-#if !RATE_CONTROL_LAMBDA_DOMAIN
-  if(m_pcCfg->getUseRateCtrl())
-  {
-    m_pcRateCtrl->updateRCGOPStatus();
-  }
-#endif
   delete pcBitstreamRedirect;
 
@@ -2724,4 +2768,5 @@
   m_pcEntropyCoder->resetEntropy    ();
   m_pcEntropyCoder->setBitstream    ( m_pcBitCounter );
+#if !HM_CLEANUP_SAO
   pcSlice = pcPic->getSlice(0);
   if(pcSlice->getSPS()->getUseSAO())
@@ -2738,5 +2783,5 @@
     pcPic->destroyNonDBFilterInfo();
   }
-  
+#endif
   m_pcEntropyCoder->resetEntropy    ();
   ruiBits += m_pcEntropyCoder->getNumberOfWrittenBits();
@@ -2810,4 +2855,5 @@
       iterPicYuvRec--;
     }
+    
   }
   
@@ -2905,5 +2951,5 @@
     case NAL_UNIT_CODED_SLICE_TRAIL_R:    return "TRAIL_R";
     case NAL_UNIT_CODED_SLICE_TRAIL_N:    return "TRAIL_N";
-    case NAL_UNIT_CODED_SLICE_TLA_R:      return "TLA_R";
+    case NAL_UNIT_CODED_SLICE_TSA_R:      return "TSA_R";
     case NAL_UNIT_CODED_SLICE_TSA_N:      return "TSA_N";
     case NAL_UNIT_CODED_SLICE_STSA_R:     return "STSA_R";
@@ -3140,6 +3186,6 @@
     for (Int x = 0; x < width; x++)
     {
-      dst[x] = isTff ? (UChar) top[x] : (UChar) bottom[x];
-      dst[stride+x] = isTff ? (UChar) bottom[x] : (UChar) top[x];
+      dst[x] = isTff ? top[x] : bottom[x];
+      dst[stride+x] = isTff ? bottom[x] : top[x];
     }
     top += stride;
@@ -3298,4 +3344,6 @@
   delete pcRecInterlaced;
 }
+
+
 
 /** Function for deciding the nal_unit_type.
Index: trunk/source/Lib/TLibEncoder/TEncRateCtrl.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncRateCtrl.cpp	(revision 494)
+++ trunk/source/Lib/TLibEncoder/TEncRateCtrl.cpp	(revision 540)
@@ -42,6 +42,4 @@
 using namespace std;
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
-
 //sequence level
 TEncRCSeq::TEncRCSeq()
@@ -67,8 +65,6 @@
   m_bitsLeft            = 0;
   m_useLCUSeparateModel = false;
-#if M0036_RC_IMPROVEMENT
   m_adaptiveBit         = 0;
   m_lastLambda          = 0.0;
-#endif
 }
 
@@ -78,9 +74,5 @@
 }
 
-#if M0036_RC_IMPROVEMENT
 Void TEncRCSeq::create( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Int numberOfLevel, Bool useLCUSeparateModel, Int adaptiveBit )
-#else
-Void TEncRCSeq::create( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Int numberOfLevel, Bool useLCUSeparateModel )
-#endif
 {
   destroy();
@@ -109,5 +101,4 @@
     m_betaUpdate  = 0.025;
   }
-#if M0036_RC_IMPROVEMENT
   else if ( m_seqTargetBpp < 0.2 )
   {
@@ -125,11 +116,4 @@
     m_betaUpdate  = 0.2;
   }
-#else
-  else
-  {
-    m_alphaUpdate = 0.1;
-    m_betaUpdate  = 0.05;
-  }
-#endif
   m_averageBits     = (Int)(m_targetBits / totalFrames);
   Int picWidthInBU  = ( m_picWidth  % m_LCUWidth  ) == 0 ? m_picWidth  / m_LCUWidth  : m_picWidth  / m_LCUWidth  + 1;
@@ -172,8 +156,6 @@
   m_framesLeft = m_totalFrames;
   m_bitsLeft   = m_targetBits;
-#if M0036_RC_IMPROVEMENT
   m_adaptiveBit = adaptiveBit;
   m_lastLambda = 0.0;
-#endif
 }
 
@@ -233,5 +215,4 @@
     for ( Int i=0; i<m_numberOfLevel; i++ )
     {
-#if RATE_CONTROL_INTRA
       if (i>0)
       {
@@ -244,8 +225,4 @@
         m_picPara[i].m_beta  = BETA2;
       }
-#else
-      m_picPara[i].m_alpha = 3.2003;
-      m_picPara[i].m_beta  = -1.367;
-#endif
     }
   }
@@ -271,11 +248,6 @@
       for ( Int j=0; j<m_numberOfLCU; j++)
       {
-#if RATE_CONTROL_INTRA
         m_LCUPara[i][j].m_alpha = m_picPara[i].m_alpha;
         m_LCUPara[i][j].m_beta  = m_picPara[i].m_beta;
-#else
-        m_LCUPara[i][j].m_alpha = 3.2003;
-        m_LCUPara[i][j].m_beta  = -1.367;
-#endif
       }
     }
@@ -299,21 +271,4 @@
 }
 
-#if !RATE_CONTROL_INTRA
-Int TEncRCSeq::getRefineBitsForIntra( Int orgBits )
-{
-  Double bpp = ( (Double)orgBits ) / m_picHeight / m_picHeight;
-  if ( bpp > 0.2 )
-  {
-    return orgBits * 5;
-  }
-  if ( bpp > 0.1 )
-  {
-    return orgBits * 7;
-  }
-  return orgBits * 10;
-}
-#endif
-
-#if M0036_RC_IMPROVEMENT
 Void TEncRCSeq::setAllBitRatio( Double basicLambda, Double* equaCoeffA, Double* equaCoeffB )
 {
@@ -326,5 +281,4 @@
   delete[] bitsRatio;
 }
-#endif
 
 //GOP level
@@ -349,5 +303,4 @@
   Int targetBits = xEstGOPTargetBits( encRCSeq, numPic );
 
-#if M0036_RC_IMPROVEMENT
   if ( encRCSeq->getAdaptiveBits() > 0 && encRCSeq->getLastLambda() > 0.1 )
   {
@@ -409,5 +362,4 @@
     delete []equaCoeffB;
   }
-#endif
 
   m_picTargetBitInGOP = new Int[numPic];
@@ -422,9 +374,5 @@
   {
     currPicRatio = encRCSeq->getBitRatio( i );
-#if M0036_RC_IMPROVEMENT
     m_picTargetBitInGOP[i] = (Int)( ((Double)targetBits) * currPicRatio / totalPicRatio );
-#else
-    m_picTargetBitInGOP[i] = targetBits * currPicRatio / totalPicRatio;
-#endif
   }
 
@@ -436,5 +384,4 @@
 }
 
-#if M0036_RC_IMPROVEMENT
 Void TEncRCGOP::xCalEquaCoeff( TEncRCSeq* encRCSeq, Double* lambdaRatio, Double* equaCoeffA, Double* equaCoeffB, Int GOPSize )
 {
@@ -482,5 +429,4 @@
   return solution;
 }
-#endif
 
 Void TEncRCGOP::destroy()
@@ -534,11 +480,5 @@
 
   m_LCUs         = NULL;
-#if !M0036_RC_IMPROVEMENT
-  m_lastPicture  = NULL;
-#endif
   m_picActualHeaderBits = 0;
-#if !M0036_RC_IMPROVEMENT
-  m_totalMAD            = 0.0;
-#endif
   m_picActualBits       = 0;
   m_picQP               = 0;
@@ -565,9 +505,5 @@
   }
 
-#if M0036_RC_IMPROVEMENT
   targetBits  = Int( ((Double)GOPbitsLeft) * currPicRatio / totalPicRatio );
-#else
-  targetBits  = Int( GOPbitsLeft * currPicRatio / totalPicRatio );
-#endif
 
   if ( targetBits < 100 )
@@ -665,9 +601,5 @@
       m_LCUs[LCUIdx].m_lambda     = 0.0;
       m_LCUs[LCUIdx].m_targetBits = 0;
-#if M0036_RC_IMPROVEMENT
       m_LCUs[LCUIdx].m_bitWeight  = 1.0;
-#else
-      m_LCUs[LCUIdx].m_MAD        = 0.0;
-#endif
       Int currWidth  = ( (i == picWidthInLCU -1) ? picWidth  - LCUWidth *(picWidthInLCU -1) : LCUWidth  );
       Int currHeight = ( (j == picHeightInLCU-1) ? picHeight - LCUHeight*(picHeightInLCU-1) : LCUHeight );
@@ -676,23 +608,7 @@
   }
   m_picActualHeaderBits = 0;
-#if !M0036_RC_IMPROVEMENT
-  m_totalMAD            = 0.0;
-#endif
   m_picActualBits       = 0;
   m_picQP               = 0;
   m_picLambda           = 0.0;
-
-#if !M0036_RC_IMPROVEMENT
-  m_lastPicture = NULL;
-  list<TEncRCPic*>::reverse_iterator it;
-  for ( it = listPreviousPictures.rbegin(); it != listPreviousPictures.rend(); it++ )
-  {
-    if ( (*it)->getFrameLevel() == m_frameLevel )
-    {
-      m_lastPicture = (*it);
-      break;
-    }
-  }
-#endif
 }
 
@@ -709,14 +625,9 @@
 
 
-#if RATE_CONTROL_INTRA
 Double TEncRCPic::estimatePicLambda( list<TEncRCPic*>& listPreviousPictures, SliceType eSliceType)
-#else
-Double TEncRCPic::estimatePicLambda( list<TEncRCPic*>& listPreviousPictures )
-#endif
 {
   Double alpha         = m_encRCSeq->getPicPara( m_frameLevel ).m_alpha;
   Double beta          = m_encRCSeq->getPicPara( m_frameLevel ).m_beta;
   Double bpp       = (Double)m_targetBits/(Double)m_numberOfPixel;
-#if RATE_CONTROL_INTRA
   Double estLambda;
   if (eSliceType == I_SLICE)
@@ -728,7 +639,4 @@
     estLambda = alpha * pow( bpp, beta );
   }
-#else
-  Double estLambda = alpha * pow( bpp, beta );
-#endif  
   
   Double lastLevelLambda = -1.0;
@@ -778,10 +686,8 @@
   m_estPicLambda = estLambda;
 
-#if M0036_RC_IMPROVEMENT
   Double totalWeight = 0.0;
   // initial BU bit allocation weight
   for ( Int i=0; i<m_numberOfLCU; i++ )
   {
-#if RC_FIX
     Double alphaLCU, betaLCU;
     if ( m_encRCSeq->getUseLCUSeparateModel() )
@@ -795,8 +701,4 @@
       betaLCU  = m_encRCSeq->getPicPara( m_frameLevel ).m_beta;
     }
-#else
-    Double alphaLCU = m_encRCSeq->getLCUPara( m_frameLevel, i ).m_alpha;
-    Double betaLCU  = m_encRCSeq->getLCUPara( m_frameLevel, i ).m_beta;
-#endif
 
     m_LCUs[i].m_bitWeight =  m_LCUs[i].m_numberOfPixel * pow( estLambda/alphaLCU, 1.0/betaLCU );
@@ -813,5 +715,4 @@
     m_LCUs[i].m_bitWeight = BUTargetBits;
   }
-#endif
 
   return estLambda;
@@ -856,20 +757,12 @@
 }
 
-#if RATE_CONTROL_INTRA
 Double TEncRCPic::getLCUTargetBpp(SliceType eSliceType)  
-#else 
-Double TEncRCPic::getLCUTargetBpp()
-#endif
 {
   Int   LCUIdx    = getLCUCoded();
   Double bpp      = -1.0;
   Int avgBits     = 0;
-#if !M0036_RC_IMPROVEMENT
-  Double totalMAD = -1.0;
-  Double MAD      = -1.0;
-#endif
-
-#if RATE_CONTROL_INTRA
-  if (eSliceType == I_SLICE){
+
+  if (eSliceType == I_SLICE)
+  {
     Int noOfLCUsLeft = m_numberOfLCU - LCUIdx + 1;
     Int bitrateWindow = min(4,noOfLCUsLeft);
@@ -889,6 +782,4 @@
   else
   {
-#endif
-#if M0036_RC_IMPROVEMENT
   Double totalWeight = 0;
   for ( Int i=LCUIdx; i<m_numberOfLCU; i++ )
@@ -898,31 +789,5 @@
   Int realInfluenceLCU = min( g_RCLCUSmoothWindowSize, getLCULeft() );
   avgBits = (Int)( m_LCUs[LCUIdx].m_bitWeight - ( totalWeight - m_bitsLeft ) / realInfluenceLCU + 0.5 );
-#else
-  if ( m_lastPicture == NULL )
-  {
-    avgBits = Int( m_bitsLeft / m_LCULeft );
-  }
-  else
-  {
-    MAD = m_lastPicture->getLCU(LCUIdx).m_MAD;
-    totalMAD = m_lastPicture->getTotalMAD();
-    for ( Int i=0; i<LCUIdx; i++ )
-    {
-      totalMAD -= m_lastPicture->getLCU(i).m_MAD;
-    }
-
-    if ( totalMAD > 0.1 )
-    {
-      avgBits = Int( m_bitsLeft * MAD / totalMAD );
-    }
-    else
-    {
-      avgBits = Int( m_bitsLeft / m_LCULeft );
-    }
-  }
-#endif
-#if RATE_CONTROL_INTRA
-  }
-#endif
+    }
 
   if ( avgBits < 1 )
@@ -1050,11 +915,6 @@
     beta  *= ( 1.0 - m_encRCSeq->getBetaUpdate() / 2.0 );
 
-#if M0036_RC_IMPROVEMENT
     alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha );
     beta  = Clip3( g_RCBetaMinValue,  g_RCBetaMaxValue,  beta  );
-#else
-    alpha = Clip3( 0.05, 20.0, alpha );
-    beta  = Clip3( -3.0, -0.1, beta  );
-#endif
 
     TRCParameter rcPara;
@@ -1069,18 +929,9 @@
   alpha += m_encRCSeq->getAlphaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * alpha;
   double lnbpp = log( bpp );
-#if M0036_RC_IMPROVEMENT
   lnbpp = Clip3( -5.0, -0.1, lnbpp );
-#else
-  lnbpp = Clip3( -5.0, 1.0, lnbpp );
-#endif
   beta  += m_encRCSeq->getBetaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * lnbpp;
 
-#if M0036_RC_IMPROVEMENT
   alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha );
   beta  = Clip3( g_RCBetaMinValue,  g_RCBetaMaxValue,  beta  );
-#else
-  alpha = Clip3( 0.05, 20.0, alpha );
-  beta  = Clip3( -3.0, -0.1, beta  );
-#endif
   TRCParameter rcPara;
   rcPara.m_alpha = alpha;
@@ -1090,24 +941,4 @@
 }
 
-#if !M0036_RC_IMPROVEMENT
-Double TEncRCPic::getEffectivePercentage()
-{
-  Int effectivePiexels = 0;
-  Int totalPixels = 0;
-
-  for ( Int i=0; i<m_numberOfLCU; i++ )
-  {
-    totalPixels += m_LCUs[i].m_numberOfPixel;
-    if ( m_LCUs[i].m_QP > 0 )
-    {
-      effectivePiexels += m_LCUs[i].m_numberOfPixel;
-    }
-  }
-
-  Double effectivePixelPercentage = (Double)effectivePiexels/(Double)totalPixels;
-  return effectivePixelPercentage;
-}
-#endif
-
 Double TEncRCPic::calAverageQP()
 {
@@ -1164,13 +995,5 @@
 }
 
-#if M0036_RC_IMPROVEMENT
-#if RATE_CONTROL_INTRA
 Void TEncRCPic::updateAfterPicture( Int actualHeaderBits, Int actualTotalBits, Double averageQP, Double averageLambda, SliceType eSliceType)
-#else
-Void TEncRCPic::updateAfterPicture( Int actualHeaderBits, Int actualTotalBits, Double averageQP, Double averageLambda )
-#endif
-#else
-Void TEncRCPic::updateAfterPicture( Int actualHeaderBits, Int actualTotalBits, Double averageQP, Double averageLambda, Double effectivePercentage )
-#endif
 {
   m_picActualHeaderBits = actualHeaderBits;
@@ -1185,14 +1008,7 @@
   }
   m_picLambda           = averageLambda;
-#if !M0036_RC_IMPROVEMENT
-  for ( Int i=0; i<m_numberOfLCU; i++ )
-  {
-    m_totalMAD += m_LCUs[i].m_MAD;
-  }
-#endif
 
   Double alpha = m_encRCSeq->getPicPara( m_frameLevel ).m_alpha;
   Double beta  = m_encRCSeq->getPicPara( m_frameLevel ).m_beta;
-#if RATE_CONTROL_INTRA
   if (eSliceType == I_SLICE)
   {
@@ -1201,5 +1017,4 @@
   else
   {
-#endif
   // update parameters
   Double picActualBits = ( Double )m_picActualBits;
@@ -1208,20 +1023,11 @@
   Double inputLambda   = m_picLambda;
 
-#if M0036_RC_IMPROVEMENT
   if ( inputLambda < 0.01 || calLambda < 0.01 || picActualBpp < 0.0001 )
-#else
-  if ( inputLambda < 0.01 || calLambda < 0.01 || picActualBpp < 0.0001 || effectivePercentage < 0.05 )
-#endif
   {
     alpha *= ( 1.0 - m_encRCSeq->getAlphaUpdate() / 2.0 );
     beta  *= ( 1.0 - m_encRCSeq->getBetaUpdate() / 2.0 );
 
-#if M0036_RC_IMPROVEMENT
     alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha );
     beta  = Clip3( g_RCBetaMinValue,  g_RCBetaMaxValue,  beta  );
-#else
-    alpha = Clip3( 0.05, 20.0, alpha );
-    beta  = Clip3( -3.0, -0.1, beta  );
-#endif
     TRCParameter rcPara;
     rcPara.m_alpha = alpha;
@@ -1235,21 +1041,10 @@
   alpha += m_encRCSeq->getAlphaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * alpha;
   double lnbpp = log( picActualBpp );
-#if M0036_RC_IMPROVEMENT
   lnbpp = Clip3( -5.0, -0.1, lnbpp );
-#else
-  lnbpp = Clip3( -5.0, 1.0, lnbpp );
-#endif
   beta  += m_encRCSeq->getBetaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * lnbpp;
 
-#if M0036_RC_IMPROVEMENT
   alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha );
   beta  = Clip3( g_RCBetaMinValue,  g_RCBetaMaxValue,  beta  );
-#else
-  alpha = Clip3( 0.05, 20.0, alpha );
-  beta  = Clip3( -3.0, -0.1, beta  );
-#endif
-#if RATE_CONTROL_INTRA
-  }
-#endif
+  }
 
   TRCParameter rcPara;
@@ -1259,5 +1054,4 @@
   m_encRCSeq->setPicPara( m_frameLevel, rcPara );
 
-#if M0036_RC_IMPROVEMENT
   if ( m_frameLevel == 1 )
   {
@@ -1266,8 +1060,6 @@
     m_encRCSeq->setLastLambda( updateLastLambda );
   }
-#endif
-}
-
-#if RATE_CONTROL_INTRA
+}
+
 Int TEncRCPic::getRefineBitsForIntra( Int orgBits )
 {
@@ -1358,5 +1150,4 @@
   return estLambda;
 }
-#endif
 
 TEncRateCtrl::TEncRateCtrl()
@@ -1392,9 +1183,5 @@
 }
 
-#if M0036_RC_IMPROVEMENT
 Void TEncRateCtrl::init( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Int keepHierBits, Bool useLCUSeparateModel, GOPEntry  GOPList[MAX_GOP] )
-#else
-Void TEncRateCtrl::init( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Bool keepHierBits, Bool useLCUSeparateModel, GOPEntry  GOPList[MAX_GOP] )
-#endif
 {
   destroy();
@@ -1411,10 +1198,6 @@
 
   Int numberOfLevel = 1;
-#if M0036_RC_IMPROVEMENT
   Int adaptiveBit = 0;
   if ( keepHierBits > 0 )
-#else
-  if ( keepHierBits )
-#endif
   {
     numberOfLevel = Int( log((Double)GOPSize)/log(2.0) + 0.5 ) + 1;
@@ -1439,9 +1222,5 @@
   }
 
-#if M0036_RC_IMPROVEMENT
   if ( keepHierBits > 0 )
-#else
-  if ( keepHierBits )
-#endif
   {
     Double bpp = (Double)( targetBitrate / (Double)( frameRate*picWidth*picHeight ) );
@@ -1476,10 +1255,8 @@
         bitsRatio[3] = 14;
       }
-#if M0036_RC_IMPROVEMENT
       if ( keepHierBits == 2 )
       {
         adaptiveBit = 1;
       }
-#endif
     }
     else if ( GOPSize == 8 && !isLowdelay )
@@ -1529,18 +1306,12 @@
         bitsRatio[7] = 1;
       }
-#if M0036_RC_IMPROVEMENT
       if ( keepHierBits == 2 )
       {
         adaptiveBit = 2;
       }
-#endif
     }
     else
     {
-#if M0036_RC_IMPROVEMENT
       printf( "\n hierarchical bit allocation is not support for the specified coding structure currently.\n" );
-#else
-      printf( "\n hierarchical bit allocation is not support for the specified coding structure currently." );
-#endif
     }
   }
@@ -1555,9 +1326,5 @@
     }
   }
-#if M0036_RC_IMPROVEMENT
   if ( keepHierBits > 0 )
-#else
-  if ( keepHierBits )
-#endif
   {
     if ( GOPSize == 4 && isLowdelay )
@@ -1594,9 +1361,5 @@
 
   m_encRCSeq = new TEncRCSeq;
-#if M0036_RC_IMPROVEMENT
   m_encRCSeq->create( totalFrames, targetBitrate, frameRate, GOPSize, picWidth, picHeight, LCUWidth, LCUHeight, numberOfLevel, useLCUSeparateModel, adaptiveBit );
-#else
-  m_encRCSeq->create( totalFrames, targetBitrate, frameRate, GOPSize, picWidth, picHeight, LCUWidth, LCUHeight, numberOfLevel, useLCUSeparateModel );
-#endif
   m_encRCSeq->initBitsRatio( bitsRatio );
   m_encRCSeq->initGOPID2Level( GOPID2Level );
@@ -1629,596 +1392,2 @@
 }
 
-#else
-
-#define ADJUSTMENT_FACTOR       0.60
-#define HIGH_QSTEP_THRESHOLD    9.5238
-#define HIGH_QSTEP_ALPHA        4.9371
-#define HIGH_QSTEP_BETA         0.0922
-#define LOW_QSTEP_ALPHA         16.7429
-#define LOW_QSTEP_BETA          -1.1494
-
-#define MAD_PRED_Y1             1.0
-#define MAD_PRED_Y2             0.0
-
-enum MAD_HISOTRY {
-  MAD_PPPrevious = 0,
-  MAD_PPrevious  = 1,
-  MAD_Previous   = 2
-};
-
-Void    MADLinearModel::initMADLinearModel()
-{
-  m_activeOn = false;
-  m_paramY1  = 1.0;
-  m_paramY2  = 0.0;
-  m_costMADs[0] = m_costMADs[1] = m_costMADs[2] = 0.0;
-}
-
-Double  MADLinearModel::getMAD()
-{
-  Double costPredMAD = m_paramY1 * m_costMADs[MAD_Previous] + m_paramY2;
-
-  if(costPredMAD < 0)
-  {
-    costPredMAD = m_costMADs[MAD_Previous];
-    m_paramY1   = MAD_PRED_Y1;
-    m_paramY2   = MAD_PRED_Y2;
-  } 
-  return costPredMAD;
-}
-
-Void    MADLinearModel::updateMADLiearModel()
-{
-  Double dNewY1 = ((m_costMADs[MAD_Previous] - m_costMADs[MAD_PPrevious]) / (m_costMADs[MAD_PPrevious] - m_costMADs[MAD_PPPrevious]));
-  Double dNewY2 =  (m_costMADs[MAD_Previous] - (dNewY1*m_costMADs[MAD_PPrevious]));
-  
-  m_paramY1 = 0.70+0.20*m_paramY1+ 0.10*dNewY1;
-  m_paramY2 =      0.20*m_paramY2+ 0.10*dNewY2;
-}
-
-Void    MADLinearModel::updateMADHistory(Double dMAD)
-{
-  m_costMADs[MAD_PPPrevious] = m_costMADs[MAD_PPrevious];
-  m_costMADs[MAD_PPrevious ] = m_costMADs[MAD_Previous ];
-  m_costMADs[MAD_Previous  ] = dMAD;
-  m_activeOn = (m_costMADs[MAD_Previous  ] && m_costMADs[MAD_PPrevious ] && m_costMADs[MAD_PPPrevious]);
-}
-
-
-Void    PixelBaseURQQuadraticModel::initPixelBaseQuadraticModel()
-{
-  m_paramHighX1 = HIGH_QSTEP_ALPHA;
-  m_paramHighX2 = HIGH_QSTEP_BETA;
-  m_paramLowX1  = LOW_QSTEP_ALPHA;
-  m_paramLowX2  = LOW_QSTEP_BETA;
-}
-
-Int     PixelBaseURQQuadraticModel::getQP(Int qp, Int targetBits, Int numberOfPixels, Double costPredMAD)
-{
-  Double qStep;
-  Double bppPerMAD = (Double)(targetBits/(numberOfPixels*costPredMAD));
-  
-  if(xConvertQP2QStep(qp) >= HIGH_QSTEP_THRESHOLD)
-  {
-    qStep = 1/( sqrt((bppPerMAD/m_paramHighX1)+((m_paramHighX2*m_paramHighX2)/(4*m_paramHighX1*m_paramHighX1))) - (m_paramHighX2/(2*m_paramHighX1)));
-  }
-  else
-  {
-    qStep = 1/( sqrt((bppPerMAD/m_paramLowX1)+((m_paramLowX2*m_paramLowX2)/(4*m_paramLowX1*m_paramLowX1))) - (m_paramLowX2/(2*m_paramLowX1)));
-  }
-  
-  return xConvertQStep2QP(qStep);
-}
-
-Void    PixelBaseURQQuadraticModel::updatePixelBasedURQQuadraticModel (Int qp, Int bits, Int numberOfPixels, Double costMAD)
-{
-  Double qStep     = xConvertQP2QStep(qp);
-  Double invqStep = (1/qStep);
-  Double paramNewX1, paramNewX2;
-  
-  if(qStep >= HIGH_QSTEP_THRESHOLD)
-  {
-    paramNewX2    = (((bits/(numberOfPixels*costMAD))-(23.3772*invqStep*invqStep))/((1-200*invqStep)*invqStep));
-    paramNewX1    = (23.3772-200*paramNewX2);
-    m_paramHighX1 = 0.70*HIGH_QSTEP_ALPHA + 0.20 * m_paramHighX1 + 0.10 * paramNewX1;
-    m_paramHighX2 = 0.70*HIGH_QSTEP_BETA  + 0.20 * m_paramHighX2 + 0.10 * paramNewX2;
-  }
-  else
-  {
-    paramNewX2   = (((bits/(numberOfPixels*costMAD))-(5.8091*invqStep*invqStep))/((1-9.5455*invqStep)*invqStep));
-    paramNewX1   = (5.8091-9.5455*paramNewX2);
-    m_paramLowX1 = 0.90*LOW_QSTEP_ALPHA + 0.09 * m_paramLowX1 + 0.01 * paramNewX1;
-    m_paramLowX2 = 0.90*LOW_QSTEP_BETA  + 0.09 * m_paramLowX2 + 0.01 * paramNewX2;
-  }
-}
-
-Bool    PixelBaseURQQuadraticModel::checkUpdateAvailable(Int qpReference )
-{ 
-  Double qStep = xConvertQP2QStep(qpReference);
-
-  if (qStep > xConvertQP2QStep(MAX_QP) 
-    ||qStep < xConvertQP2QStep(MIN_QP) )
-  {
-    return false;
-  }
-
-  return true;
-}
-
-Double  PixelBaseURQQuadraticModel::xConvertQP2QStep(Int qp )
-{
-  Int i;
-  Double qStep;
-  static const Double mapQP2QSTEP[6] = { 0.625, 0.703, 0.797, 0.891, 1.000, 1.125 };
-
-  qStep = mapQP2QSTEP[qp % 6];
-  for( i=0; i<(qp/6); i++)
-  {
-    qStep *= 2;
-  }
-
-  return qStep;
-}
-
-Int     PixelBaseURQQuadraticModel::xConvertQStep2QP(Double qStep )
-{
-  Int per = 0, rem = 0;
-
-  if( qStep < xConvertQP2QStep(MIN_QP))
-  {
-    return MIN_QP;
-  }
-  else if (qStep > xConvertQP2QStep(MAX_QP) )
-  {
-    return MAX_QP;
-  }
-
-  while( qStep > xConvertQP2QStep(5) )
-  {
-    qStep /= 2.0;
-    per++;
-  }
-
-  if (qStep <= 0.625)
-  {
-    rem = 0;
-  }
-  else if (qStep <= 0.703)
-  {
-    rem = 1;
-  }
-  else if (qStep <= 0.797)
-  {
-    rem = 2;
-  }
-  else if (qStep <= 0.891)
-  {
-    rem = 3;
-  }
-  else if (qStep <= 1.000)
-  {
-    rem = 4;
-  }
-  else
-  {
-    rem = 5;
-  }
-  return (per * 6 + rem);
-}
-
-
-Void  TEncRateCtrl::create(Int sizeIntraPeriod, Int sizeGOP, Int frameRate, Int targetKbps, Int qp, Int numLCUInBasicUnit, Int sourceWidth, Int sourceHeight, Int maxCUWidth, Int maxCUHeight)
-{
-  Int leftInHeight, leftInWidth;
-
-  m_sourceWidthInLCU         = (sourceWidth  / maxCUWidth  ) + (( sourceWidth  %  maxCUWidth ) ? 1 : 0);
-  m_sourceHeightInLCU        = (sourceHeight / maxCUHeight) + (( sourceHeight %  maxCUHeight) ? 1 : 0);  
-  m_isLowdelay               = (sizeIntraPeriod == -1) ? true : false;
-  m_prevBitrate              = ( targetKbps << 10 );  // in units of 1,024 bps
-  m_currBitrate              = ( targetKbps << 10 );
-  m_frameRate                = frameRate;
-  m_refFrameNum              = m_isLowdelay ? (sizeGOP) : (sizeGOP>>1);
-  m_nonRefFrameNum           = sizeGOP-m_refFrameNum;
-  m_sizeGOP                  = sizeGOP;
-  m_numOfPixels              = ((sourceWidth*sourceHeight*3)>>1);
-  m_indexGOP                 = 0;
-  m_indexFrame               = 0;
-  m_indexLCU                 = 0;
-  m_indexUnit                = 0;
-  m_indexRefFrame            = 0;
-  m_indexNonRefFrame         = 0;
-  m_occupancyVB              = 0;
-  m_initialOVB               = 0;
-  m_targetBufLevel           = 0;
-  m_initialTBL               = 0;
-  m_occupancyVBInFrame       = 0;
-  m_remainingBitsInGOP       = (m_currBitrate*sizeGOP/m_frameRate);
-  m_remainingBitsInFrame     = 0;
-  m_numUnitInFrame           = m_sourceWidthInLCU*m_sourceHeightInLCU;
-  m_cMADLinearModel.        initMADLinearModel();
-  m_cPixelURQQuadraticModel.initPixelBaseQuadraticModel();
-
-  m_costRefAvgWeighting      = 0.0;
-  m_costNonRefAvgWeighting   = 0.0;
-  m_costAvgbpp               = 0.0;  
-  m_activeUnitLevelOn        = false;
-
-  m_pcFrameData              = new FrameData   [sizeGOP+1];         initFrameData(qp);
-  m_pcLCUData                = new LCUData     [m_numUnitInFrame];  initUnitData (qp);
-
-  for(Int i = 0, addressUnit = 0; i < m_sourceHeightInLCU*maxCUHeight; i += maxCUHeight)  
-  {
-    leftInHeight = sourceHeight - i;
-    leftInHeight = min(leftInHeight, maxCUHeight);
-    for(Int j = 0; j < m_sourceWidthInLCU*maxCUWidth; j += maxCUWidth, addressUnit++)
-    {
-      leftInWidth = sourceWidth - j;
-      leftInWidth = min(leftInWidth, maxCUWidth);
-      m_pcLCUData[addressUnit].m_widthInPixel = leftInWidth;
-      m_pcLCUData[addressUnit].m_heightInPixel= leftInHeight;
-      m_pcLCUData[addressUnit].m_pixels       = ((leftInHeight*leftInWidth*3)>>1);
-    }
-  }
-}
-
-Void  TEncRateCtrl::destroy()
-{
-  if(m_pcFrameData)
-  {
-    delete [] m_pcFrameData;
-    m_pcFrameData = NULL;
-  }
-  if(m_pcLCUData)
-  {
-    delete [] m_pcLCUData;
-    m_pcLCUData = NULL;
-  }
-}
-
-Void  TEncRateCtrl::initFrameData   (Int qp)
-{
-  for(Int i = 0 ; i <= m_sizeGOP; i++)
-  {
-    m_pcFrameData[i].m_isReferenced = false;
-    m_pcFrameData[i].m_costMAD      = 0.0;
-    m_pcFrameData[i].m_bits         = 0;
-    m_pcFrameData[i].m_qp           = qp;
-  }
-}
-
-Void  TEncRateCtrl::initUnitData    (Int qp)
-{
-  for(Int i = 1 ; i < m_numUnitInFrame; i++)
-  {
-    m_pcLCUData[i].m_qp            = qp;
-    m_pcLCUData[i].m_bits          = 0;
-    m_pcLCUData[i].m_pixels        = 0;
-    m_pcLCUData[i].m_widthInPixel  = 0;
-    m_pcLCUData[i].m_heightInPixel = 0;
-    m_pcLCUData[i].m_costMAD       = 0.0;
-  }
-}
-
-Int  TEncRateCtrl::getFrameQP(Bool isReferenced, Int POC)
-{
-  Int numofReferenced = 0;
-  Int finalQP = 0;
-  FrameData* pcFrameData;
-
-  m_indexPOCInGOP = (POC%m_sizeGOP) == 0 ? m_sizeGOP : (POC%m_sizeGOP);
-  pcFrameData     = &m_pcFrameData[m_indexPOCInGOP];
-    
-  if(m_indexFrame != 0)
-  {
-    if(isReferenced)
-    {
-      Double gamma = m_isLowdelay ? 0.5 : 0.25;
-      Double beta  = m_isLowdelay ? 0.9 : 0.6;
-      Int    numRemainingRefFrames  = m_refFrameNum    - m_indexRefFrame;
-      Int    numRemainingNRefFrames = m_nonRefFrameNum - m_indexNonRefFrame;
-      
-      Double targetBitsOccupancy  = (m_currBitrate/(Double)m_frameRate) + gamma*(m_targetBufLevel-m_occupancyVB - (m_initialOVB/(Double)m_frameRate));
-      Double targetBitsLeftBudget = ((m_costRefAvgWeighting*m_remainingBitsInGOP)/((m_costRefAvgWeighting*numRemainingRefFrames)+(m_costNonRefAvgWeighting*numRemainingNRefFrames)));
-
-      m_targetBits = (Int)(beta * targetBitsLeftBudget + (1-beta) * targetBitsOccupancy);
-  
-      if(m_targetBits <= 0 || m_remainingBitsInGOP <= 0)
-      {
-        finalQP = m_pcFrameData[m_indexPrevPOCInGOP].m_qp + 2;
-      }
-      else
-      {
-        Double costPredMAD   = m_cMADLinearModel.getMAD();
-        Int    qpLowerBound = m_pcFrameData[m_indexPrevPOCInGOP].m_qp-2;
-        Int    qpUpperBound = m_pcFrameData[m_indexPrevPOCInGOP].m_qp+2;
-        finalQP = m_cPixelURQQuadraticModel.getQP(m_pcFrameData[m_indexPrevPOCInGOP].m_qp, m_targetBits, m_numOfPixels, costPredMAD);
-        finalQP = max(qpLowerBound, min(qpUpperBound, finalQP));
-        m_activeUnitLevelOn    = true;
-        m_remainingBitsInFrame = m_targetBits;
-        m_costAvgbpp           = (m_targetBits/(Double)m_numOfPixels);
-      }
-
-      m_indexRefFrame++;
-    }
-    else
-    {
-      Int bwdQP = m_pcFrameData[m_indexPOCInGOP-1].m_qp;
-      Int fwdQP = m_pcFrameData[m_indexPOCInGOP+1].m_qp;
-       
-      if( (fwdQP+bwdQP) == m_pcFrameData[m_indexPOCInGOP-1].m_qp
-        ||(fwdQP+bwdQP) == m_pcFrameData[m_indexPOCInGOP+1].m_qp)
-      {
-        finalQP = (fwdQP+bwdQP);
-      }
-      else if(bwdQP != fwdQP)
-      {
-        finalQP = ((bwdQP+fwdQP+2)>>1);
-      }
-      else
-      {
-        finalQP = bwdQP+2;
-      }
-      m_indexNonRefFrame++;
-    }
-  }
-  else
-  {
-    Int lastQPminus2 = m_pcFrameData[0].m_qp - 2;
-    Int lastQPplus2  = m_pcFrameData[0].m_qp + 2;
-
-    for(Int idx = 1; idx <= m_sizeGOP; idx++)
-    {
-      if(m_pcFrameData[idx].m_isReferenced)
-      {
-        finalQP += m_pcFrameData[idx].m_qp;
-        numofReferenced++;
-      }
-    }
-    
-    finalQP = (numofReferenced == 0) ? m_pcFrameData[0].m_qp : ((finalQP + (1<<(numofReferenced>>1)))/numofReferenced);
-    finalQP = max( lastQPminus2, min( lastQPplus2, finalQP));
-
-    Double costAvgFrameBits = m_remainingBitsInGOP/(Double)m_sizeGOP;
-    Int    bufLevel  = m_occupancyVB + m_initialOVB;
-
-    if(abs(bufLevel) > costAvgFrameBits)
-    {
-      if(bufLevel < 0)
-      {
-        finalQP -= 2;
-      }
-      else
-      {
-        finalQP += 2;
-      }
-    }
-    m_indexRefFrame++;
-  }
-  finalQP = max(MIN_QP, min(MAX_QP, finalQP));
-
-  for(Int indexLCU = 0 ; indexLCU < m_numUnitInFrame; indexLCU++)
-  {
-    m_pcLCUData[indexLCU].m_qp = finalQP;
-  }
-
-  pcFrameData->m_isReferenced = isReferenced;
-  pcFrameData->m_qp           = finalQP;
-
-  return finalQP;
-}
-
-Bool  TEncRateCtrl::calculateUnitQP ()
-{
-  if(!m_activeUnitLevelOn || m_indexLCU == 0)
-  {
-    return false;
-  }
-  Int upperQPBound, lowerQPBound, finalQP;
-  Int    colQP        = m_pcLCUData[m_indexLCU].m_qp;
-  Double colMAD       = m_pcLCUData[m_indexLCU].m_costMAD;
-  Double budgetInUnit = m_pcLCUData[m_indexLCU].m_pixels*m_costAvgbpp;
-
-
-  Int targetBitsOccupancy = (Int)(budgetInUnit - (m_occupancyVBInFrame/(m_numUnitInFrame-m_indexUnit)));
-  Int targetBitsLeftBudget= (Int)((m_remainingBitsInFrame*m_pcLCUData[m_indexLCU].m_pixels)/(Double)(m_numOfPixels-m_codedPixels));
-  Int targetBits = (targetBitsLeftBudget>>1) + (targetBitsOccupancy>>1);
-  
-
-  if( m_indexLCU >= m_sourceWidthInLCU)
-  {
-    upperQPBound = ( (m_pcLCUData[m_indexLCU-1].m_qp + m_pcLCUData[m_indexLCU - m_sourceWidthInLCU].m_qp)>>1) + MAX_DELTA_QP;
-    lowerQPBound = ( (m_pcLCUData[m_indexLCU-1].m_qp + m_pcLCUData[m_indexLCU - m_sourceWidthInLCU].m_qp)>>1) - MAX_DELTA_QP;
-  }
-  else
-  {
-    upperQPBound = m_pcLCUData[m_indexLCU-1].m_qp + MAX_DELTA_QP;
-    lowerQPBound = m_pcLCUData[m_indexLCU-1].m_qp - MAX_DELTA_QP;
-  }
-
-  if(targetBits < 0)
-  {
-    finalQP = m_pcLCUData[m_indexLCU-1].m_qp + 1;
-  }
-  else
-  {
-    finalQP = m_cPixelURQQuadraticModel.getQP(colQP, targetBits, m_pcLCUData[m_indexLCU].m_pixels, colMAD);
-  }
-  
-  finalQP = max(lowerQPBound, min(upperQPBound, finalQP));
-  m_pcLCUData[m_indexLCU].m_qp = max(MIN_QP, min(MAX_QP, finalQP));
-  
-  return true;
-}
-
-Void  TEncRateCtrl::updateRCGOPStatus()
-{
-  m_remainingBitsInGOP = ((m_currBitrate/m_frameRate)*m_sizeGOP) - m_occupancyVB;
-  
-  FrameData cFrameData = m_pcFrameData[m_sizeGOP];
-  initFrameData();
-
-  m_pcFrameData[0]   = cFrameData;
-  m_indexGOP++;
-  m_indexFrame       = 0;
-  m_indexRefFrame    = 0;
-  m_indexNonRefFrame = 0;
-}
-
-Void  TEncRateCtrl::updataRCFrameStatus(Int frameBits, SliceType eSliceType)
-{
-  FrameData* pcFrameData = &m_pcFrameData[m_indexPOCInGOP];
-  Int occupancyBits;
-  Double adjustmentBits;
-
-  m_remainingBitsInGOP = m_remainingBitsInGOP + ( ((m_currBitrate-m_prevBitrate)/m_frameRate)*(m_sizeGOP-m_indexFrame) ) - frameBits;
-  occupancyBits        = (Int)((Double)frameBits - (m_currBitrate/(Double)m_frameRate));
-  
-  if( (occupancyBits < 0) && (m_initialOVB > 0) )
-  {
-    adjustmentBits = xAdjustmentBits(occupancyBits, m_initialOVB );
-
-    if(m_initialOVB < 0)
-    {
-      adjustmentBits = m_initialOVB;
-      occupancyBits += (Int)adjustmentBits;
-      m_initialOVB   =  0;
-    }
-  }
-  else if( (occupancyBits > 0) && (m_initialOVB < 0) )
-  {
-    adjustmentBits = xAdjustmentBits(m_initialOVB, occupancyBits );
-    
-    if(occupancyBits < 0)
-    {
-      adjustmentBits = occupancyBits;
-      m_initialOVB  += (Int)adjustmentBits;
-      occupancyBits  =  0;
-    }
-  }
-
-  if(m_indexGOP == 0)
-  {
-    m_initialOVB = occupancyBits;
-  }
-  else
-  {
-    m_occupancyVB= m_occupancyVB + occupancyBits;
-  }
-
-  if(pcFrameData->m_isReferenced)
-  {
-    m_costRefAvgWeighting  = ((pcFrameData->m_bits*pcFrameData->m_qp)/8.0) + (7.0*(m_costRefAvgWeighting)/8.0);
-
-    if(m_indexFrame == 0)
-    {
-      m_initialTBL = m_targetBufLevel  = (frameBits - (m_currBitrate/m_frameRate));
-    }
-    else
-    {
-      Int distance = (m_costNonRefAvgWeighting == 0) ? 0 : 1;
-      m_targetBufLevel =  m_targetBufLevel 
-                            - (m_initialTBL/(m_refFrameNum-1)) 
-                            + (Int)((m_costRefAvgWeighting*(distance+1)*m_currBitrate)/(m_frameRate*(m_costRefAvgWeighting+(m_costNonRefAvgWeighting*distance)))) 
-                            - (m_currBitrate/m_frameRate);
-    }
-
-    if(m_cMADLinearModel.IsUpdateAvailable())
-    {
-      m_cMADLinearModel.updateMADLiearModel();
-    }
-
-    if(eSliceType != I_SLICE &&
-       m_cPixelURQQuadraticModel.checkUpdateAvailable(pcFrameData->m_qp))
-    {
-      m_cPixelURQQuadraticModel.updatePixelBasedURQQuadraticModel(pcFrameData->m_qp, pcFrameData->m_bits, m_numOfPixels, pcFrameData->m_costMAD);
-    }
-  }
-  else
-  {
-    m_costNonRefAvgWeighting = ((pcFrameData->m_bits*pcFrameData->m_qp)/8.0) + (7.0*(m_costNonRefAvgWeighting)/8.0);
-  }
-
-  m_indexFrame++;
-  m_indexLCU             = 0;
-  m_indexUnit            = 0;
-  m_occupancyVBInFrame   = 0;
-  m_remainingBitsInFrame = 0;
-  m_codedPixels          = 0;
-  m_activeUnitLevelOn    = false;
-  m_costAvgbpp           = 0.0;
-}
-Void  TEncRateCtrl::updataRCUnitStatus ()
-{
-  if(!m_activeUnitLevelOn || m_indexLCU == 0)
-  {
-    return;
-  }
-
-  m_codedPixels  += m_pcLCUData[m_indexLCU-1].m_pixels;
-  m_remainingBitsInFrame = m_remainingBitsInFrame - m_pcLCUData[m_indexLCU-1].m_bits;
-  m_occupancyVBInFrame   = (Int)(m_occupancyVBInFrame + m_pcLCUData[m_indexLCU-1].m_bits - m_pcLCUData[m_indexLCU-1].m_pixels*m_costAvgbpp);
-
-  if( m_cPixelURQQuadraticModel.checkUpdateAvailable(m_pcLCUData[m_indexLCU-1].m_qp) )
-  {
-    m_cPixelURQQuadraticModel.updatePixelBasedURQQuadraticModel(m_pcLCUData[m_indexLCU-1].m_qp, m_pcLCUData[m_indexLCU-1].m_bits, m_pcLCUData[m_indexLCU-1].m_pixels, m_pcLCUData[m_indexLCU-1].m_costMAD);
-  }
-
-  m_indexUnit++;
-}
-
-Void  TEncRateCtrl::updateFrameData(UInt64 actualFrameBits)
-{
-  Double costMAD = 0.0;
-  
-  for(Int i = 0; i < m_numUnitInFrame; i++)
-  {
-    costMAD    += m_pcLCUData[i].m_costMAD;
-  }
-  
-  m_pcFrameData[m_indexPOCInGOP].m_costMAD = (costMAD/(Double)m_numUnitInFrame);
-  m_pcFrameData[m_indexPOCInGOP].m_bits    = (Int)actualFrameBits;
-  
-  if(m_pcFrameData[m_indexPOCInGOP].m_isReferenced)
-  {
-    m_indexPrevPOCInGOP = m_indexPOCInGOP;
-    m_cMADLinearModel.updateMADHistory(m_pcFrameData[m_indexPOCInGOP].m_costMAD);
-  }
-}
-
-Void  TEncRateCtrl::updateLCUData(TComDataCU* pcCU, UInt64 actualLCUBits, Int qp)
-{
-  Int     x, y;
-  Double  costMAD = 0.0;
-
-  Pel*  pOrg   = pcCU->getPic()->getPicYuvOrg()->getLumaAddr(pcCU->getAddr(), 0);
-  Pel*  pRec   = pcCU->getPic()->getPicYuvRec()->getLumaAddr(pcCU->getAddr(), 0);
-  Int   stride = pcCU->getPic()->getStride();
-
-  Int   width  = m_pcLCUData[m_indexLCU].m_widthInPixel;
-  Int   height = m_pcLCUData[m_indexLCU].m_heightInPixel;
-
-  for( y = 0; y < height; y++ )
-  {
-    for( x = 0; x < width; x++ )
-    {
-      costMAD += abs( pOrg[x] - pRec[x] );
-    }
-    pOrg += stride;
-    pRec += stride;
-  }
-  m_pcLCUData[m_indexLCU  ].m_qp      = qp;
-  m_pcLCUData[m_indexLCU  ].m_costMAD = (costMAD /(Double)(width*height));
-  m_pcLCUData[m_indexLCU++].m_bits    = (Int)actualLCUBits;
-}
-
-Double TEncRateCtrl::xAdjustmentBits(Int& reductionBits, Int& compensationBits)
-{
-  Double adjustment  = ADJUSTMENT_FACTOR*reductionBits;
-  reductionBits     -= (Int)adjustment;
-  compensationBits  += (Int)adjustment;
-
-  return adjustment;
-}
-
-#endif
-
Index: trunk/source/Lib/TLibEncoder/TEncRateCtrl.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncRateCtrl.h	(revision 494)
+++ trunk/source/Lib/TLibEncoder/TEncRateCtrl.h	(revision 540)
@@ -55,5 +55,4 @@
 //! \{
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
 #include "../TLibEncoder/TEncCfg.h"
 #include <list>
@@ -65,5 +64,4 @@
 const Double g_RCWeightPicTargetBitInGOP    = 0.9;
 const Double g_RCWeightPicRargetBitInBuffer = 1.0 - g_RCWeightPicTargetBitInGOP;
-#if M0036_RC_IMPROVEMENT
 const Int g_RCIterationNum = 20;
 const Double g_RCWeightHistoryLambda = 0.5;
@@ -74,11 +72,8 @@
 const Double g_RCBetaMinValue  = -3.0;
 const Double g_RCBetaMaxValue  = -0.1;
-#endif
-
-#if RATE_CONTROL_INTRA
+
 #define ALPHA     6.7542;
 #define BETA1     1.2517
 #define BETA2     1.7860
-#endif
 
 struct TRCLCU
@@ -88,14 +83,8 @@
   Int m_targetBits;
   Double m_lambda;
-#if M0036_RC_IMPROVEMENT
   Double m_bitWeight;
-#else
-  Double m_MAD;
-#endif
   Int m_numberOfPixel;
-#if RATE_CONTROL_INTRA
   Double m_costIntra;
   Int m_targetBitsLeft;
-#endif
 };
 
@@ -113,9 +102,5 @@
 
 public:
-#if M0036_RC_IMPROVEMENT
   Void create( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Int numberOfLevel, Bool useLCUSeparateModel, Int adaptiveBit );
-#else
-  Void create( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Int numberOfLevel, Bool useLCUSeparateModel );
-#endif
   Void destroy();
   Void initBitsRatio( Int bitsRatio[] );
@@ -124,10 +109,5 @@
   Void initLCUPara( TRCParameter** LCUPara = NULL );    // NULL to initial with default value
   Void updateAfterPic ( Int bits );
-#if !RATE_CONTROL_INTRA
-  Int  getRefineBitsForIntra( Int orgBits );
-#endif
-#if M0036_RC_IMPROVEMENT
   Void setAllBitRatio( Double basicLambda, Double* equaCoeffA, Double* equaCoeffB );
-#endif
 
 public:
@@ -167,9 +147,7 @@
   Double getBetaUpdate()                { return m_betaUpdate; }
 
-#if M0036_RC_IMPROVEMENT
   Int    getAdaptiveBits()              { return m_adaptiveBit;  }
   Double getLastLambda()                { return m_lastLambda;   }
   Void   setLastLambda( Double lamdba ) { m_lastLambda = lamdba; }
-#endif
 
 private:
@@ -200,8 +178,6 @@
   Bool m_useLCUSeparateModel;
 
-#if M0036_RC_IMPROVEMENT
   Int m_adaptiveBit;
   Double m_lastLambda;
-#endif
 };
 
@@ -219,8 +195,6 @@
 private:
   Int  xEstGOPTargetBits( TEncRCSeq* encRCSeq, Int GOPSize );
-#if M0036_RC_IMPROVEMENT
   Void   xCalEquaCoeff( TEncRCSeq* encRCSeq, Double* lambdaRatio, Double* equaCoeffA, Double* equaCoeffB, Int GOPSize );
   Double xSolveEqua( Double targetBpp, Double* equaCoeffA, Double* equaCoeffB, Int GOPSize );
-#endif
 
 public:
@@ -251,9 +225,5 @@
   Void destroy();
 
-#if !RATE_CONTROL_INTRA
-  Double estimatePicLambda( list<TEncRCPic*>& listPreviousPictures );
-#endif
   Int    estimatePicQP    ( Double lambda, list<TEncRCPic*>& listPreviousPictures );
-#if RATE_CONTROL_INTRA
   Int    getRefineBitsForIntra(Int orgBits);
   Double calculateLambdaIntra(double alpha, double beta, double MADPerPixel, double bitsPerPixel);
@@ -264,25 +234,11 @@
   Double getLCUTargetBpp(SliceType eSliceType);
   Double getLCUEstLambdaAndQP(Double bpp, Int clipPicQP, Int *estQP);
-#else
-  Double getLCUTargetBpp();
-#endif
   Double getLCUEstLambda( Double bpp );
   Int    getLCUEstQP( Double lambda, Int clipPicQP );
 
   Void updateAfterLCU( Int LCUIdx, Int bits, Int QP, Double lambda, Bool updateLCUParameter = true );
-#if M0036_RC_IMPROVEMENT
-#if RATE_CONTROL_INTRA
   Void updateAfterPicture( Int actualHeaderBits, Int actualTotalBits, Double averageQP, Double averageLambda, SliceType eSliceType);
-#else
-  Void updateAfterPicture( Int actualHeaderBits, Int actualTotalBits, Double averageQP, Double averageLambda );
-#endif
-#else
-  Void updateAfterPicture( Int actualHeaderBits, Int actualTotalBits, Double averageQP, Double averageLambda, Double effectivePercentage );
-#endif
 
   Void addToPictureLsit( list<TEncRCPic*>& listPreviousPictures );
-#if !M0036_RC_IMPROVEMENT
-  Double getEffectivePercentage();
-#endif
   Double calAverageQP();
   Double calAverageLambda();
@@ -300,7 +256,4 @@
   Int  getNumberOfLCU()                                   { return m_numberOfLCU; }
   Int  getTargetBits()                                    { return m_targetBits; }
-#if !RATE_CONTROL_INTRA 
-  Void setTargetBits( Int bits )                          { m_targetBits = bits; }
-#endif
   Int  getEstHeaderBits()                                 { return m_estHeaderBits; }
   Int  getLCULeft()                                       { return m_LCULeft; }
@@ -312,13 +265,7 @@
   TRCLCU& getLCU( Int LCUIdx )                            { return m_LCUs[LCUIdx]; }
   Int  getPicActualHeaderBits()                           { return m_picActualHeaderBits; }
-#if !M0036_RC_IMPROVEMENT
-  Double getTotalMAD()                                    { return m_totalMAD; }
-  Void   setTotalMAD( Double MAD )                        { m_totalMAD = MAD; }
-#endif
-#if RATE_CONTROL_INTRA
   Void setTargetBits( Int bits )                          { m_targetBits = bits; m_bitsLeft = bits;}
   Void setTotalIntraCost(Double cost)                     { m_totalCostIntra = cost; }
   Void getLCUInitTargetBits();
-#endif
 
   Int  getPicActualBits()                                 { return m_picActualBits; }
@@ -348,17 +295,9 @@
   TRCLCU* m_LCUs;
   Int m_picActualHeaderBits;    // only SH and potential APS
-#if !M0036_RC_IMPROVEMENT
-  Double m_totalMAD;
-#endif
-#if RATE_CONTROL_INTRA
   Double m_totalCostIntra; 
   Double m_remainingCostIntra;
-#endif
   Int m_picActualBits;          // the whole picture, including header
   Int m_picQP;                  // in integer form
   Double m_picLambda;
-#if !M0036_RC_IMPROVEMENT
-  TEncRCPic* m_lastPicture;
-#endif
 };
 
@@ -370,9 +309,5 @@
 
 public:
-#if M0036_RC_IMPROVEMENT
   Void init( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Int keepHierBits, Bool useLCUSeparateModel, GOPEntry GOPList[MAX_GOP] );
-#else
-  Void init( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Bool keepHierBits, Bool useLCUSeparateModel, GOPEntry GOPList[MAX_GOP] );
-#endif
   Void destroy();
   Void initRCPic( Int frameLevel );
@@ -396,133 +331,5 @@
 };
 
-#else
-
-// ====================================================================================================================
-// Class definition
-// ====================================================================================================================
-#define MAX_DELTA_QP    2
-#define MAX_CUDQP_DEPTH 0 
-
-typedef struct FrameData
-{
-  Bool       m_isReferenced;
-  Int        m_qp;
-  Int        m_bits;
-  Double     m_costMAD;
-}FrameData;
-
-typedef struct LCUData
-{
-  Int     m_qp;                ///<  coded QP
-  Int     m_bits;              ///<  actually generated bits
-  Int     m_pixels;            ///<  number of pixels for a unit
-  Int     m_widthInPixel;      ///<  number of pixels for width
-  Int     m_heightInPixel;     ///<  number of pixels for height
-  Double  m_costMAD;           ///<  texture complexity for a unit
-}LCUData;
-
-class MADLinearModel
-{
-private:
-  Bool   m_activeOn;
-  Double m_paramY1;
-  Double m_paramY2;
-  Double m_costMADs[3];
-
-public:
-  MADLinearModel ()   {};
-  ~MADLinearModel()   {};
-  
-  Void    initMADLinearModel      ();
-  Double  getMAD                  ();
-  Void    updateMADLiearModel     ();
-  Void    updateMADHistory        (Double costMAD);
-  Bool    IsUpdateAvailable       ()              { return m_activeOn; }
-};
-
-class PixelBaseURQQuadraticModel
-{
-private:
-  Double m_paramHighX1;
-  Double m_paramHighX2;
-  Double m_paramLowX1;
-  Double m_paramLowX2;
-public:
-  PixelBaseURQQuadraticModel () {};
-  ~PixelBaseURQQuadraticModel() {};
-
-  Void    initPixelBaseQuadraticModel       ();
-  Int     getQP                             (Int qp, Int targetBits, Int numberOfPixels, Double costPredMAD);
-  Void    updatePixelBasedURQQuadraticModel (Int qp, Int bits, Int numberOfPixels, Double costMAD);
-  Bool    checkUpdateAvailable              (Int qpReference );
-  Double  xConvertQP2QStep                  (Int qp );
-  Int     xConvertQStep2QP                  (Double qStep );
-};
-
-class TEncRateCtrl
-{
-private:
-  Bool            m_isLowdelay;
-  Int             m_prevBitrate;
-  Int             m_currBitrate;
-  Int             m_frameRate;
-  Int             m_refFrameNum;
-  Int             m_nonRefFrameNum;
-  Int             m_numOfPixels;
-  Int             m_sourceWidthInLCU;
-  Int             m_sourceHeightInLCU;      
-  Int             m_sizeGOP;
-  Int             m_indexGOP;
-  Int             m_indexFrame;
-  Int             m_indexLCU;
-  Int             m_indexUnit;
-  Int             m_indexRefFrame;
-  Int             m_indexNonRefFrame;
-  Int             m_indexPOCInGOP;
-  Int             m_indexPrevPOCInGOP;
-  Int             m_occupancyVB;
-  Int             m_initialOVB;
-  Int             m_targetBufLevel;
-  Int             m_initialTBL;
-  Int             m_remainingBitsInGOP;
-  Int             m_remainingBitsInFrame;
-  Int             m_occupancyVBInFrame;
-  Int             m_targetBits;
-  Int             m_numUnitInFrame;
-  Int             m_codedPixels;
-  Bool            m_activeUnitLevelOn;
-  Double          m_costNonRefAvgWeighting;
-  Double          m_costRefAvgWeighting;
-  Double          m_costAvgbpp;         
-  
-  FrameData*      m_pcFrameData;
-  LCUData*        m_pcLCUData;
-
-  MADLinearModel              m_cMADLinearModel;
-  PixelBaseURQQuadraticModel  m_cPixelURQQuadraticModel;
-  
-public:
-  TEncRateCtrl         () {};
-  virtual ~TEncRateCtrl() {};
-
-  Void          create                (Int sizeIntraPeriod, Int sizeGOP, Int frameRate, Int targetKbps, Int qp, Int numLCUInBasicUnit, Int sourceWidth, Int sourceHeight, Int maxCUWidth, Int maxCUHeight);
-  Void          destroy               ();
-
-  Void          initFrameData         (Int qp = 0);
-  Void          initUnitData          (Int qp = 0);
-  Int           getFrameQP            (Bool isReferenced, Int POC);
-  Bool          calculateUnitQP       ();
-  Int           getUnitQP             ()                                          { return m_pcLCUData[m_indexLCU].m_qp;  }
-  Void          updateRCGOPStatus     ();
-  Void          updataRCFrameStatus   (Int frameBits, SliceType eSliceType);
-  Void          updataRCUnitStatus    ();
-  Void          updateLCUData         (TComDataCU* pcCU, UInt64 actualLCUBits, Int qp);
-  Void          updateFrameData       (UInt64 actualFrameBits);
-  Double        xAdjustmentBits       (Int& reductionBits, Int& compensationBits);
-  Int           getGOPId              ()                                          { return m_indexFrame; }
-};
 #endif
 
-#endif
-
-
+
Index: trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp	(revision 494)
+++ trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp	(revision 540)
@@ -45,4 +45,1267 @@
 //! \{
 
+
+#if HM_CLEANUP_SAO
+
+/** rounding with IBDI
+ * \param  x
+ */
+inline Double xRoundIbdi2(Int bitDepth, Double x)
+{
+  return ((x)>0) ? (Int)(((Int)(x)+(1<<(bitDepth-8-1)))/(1<<(bitDepth-8))) : ((Int)(((Int)(x)-(1<<(bitDepth-8-1)))/(1<<(bitDepth-8))));
+}
+
+inline Double xRoundIbdi(Int bitDepth, Double x)
+{
+  return (bitDepth > 8 ? xRoundIbdi2(bitDepth, (x)) : ((x)>=0 ? ((Int)((x)+0.5)) : ((Int)((x)-0.5)))) ;
+}
+
+
+TEncSampleAdaptiveOffset::TEncSampleAdaptiveOffset()
+{
+  m_pppcRDSbacCoder = NULL;           
+  m_pcRDGoOnSbacCoder = NULL;
+  m_pppcBinCoderCABAC = NULL;    
+  m_statData = NULL;
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  m_preDBFstatData = NULL;
+#endif
+}
+
+TEncSampleAdaptiveOffset::~TEncSampleAdaptiveOffset()
+{
+  destroyEncData();
+}
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+Void TEncSampleAdaptiveOffset::createEncData(Bool isPreDBFSamplesUsed)
+#else
+Void TEncSampleAdaptiveOffset::createEncData()
+#endif
+{
+
+  //cabac coder for RDO
+  m_pppcRDSbacCoder = new TEncSbac* [NUM_SAO_CABACSTATE_LABELS];
+  m_pppcBinCoderCABAC = new TEncBinCABACCounter* [NUM_SAO_CABACSTATE_LABELS];
+
+  for(Int cs=0; cs < NUM_SAO_CABACSTATE_LABELS; cs++)
+  {
+    m_pppcRDSbacCoder[cs] = new TEncSbac;
+    m_pppcBinCoderCABAC[cs] = new TEncBinCABACCounter;
+    m_pppcRDSbacCoder   [cs]->init( m_pppcBinCoderCABAC [cs] );
+  }
+
+
+  //statistics
+  m_statData = new SAOStatData**[m_numCTUsPic];
+  for(Int i=0; i< m_numCTUsPic; i++)
+  {
+    m_statData[i] = new SAOStatData*[NUM_SAO_COMPONENTS];
+    for(Int compIdx=0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
+    {
+      m_statData[i][compIdx] = new SAOStatData[NUM_SAO_NEW_TYPES];
+    }
+  }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  if(isPreDBFSamplesUsed)
+  {
+    m_preDBFstatData = new SAOStatData**[m_numCTUsPic];
+    for(Int i=0; i< m_numCTUsPic; i++)
+    {
+      m_preDBFstatData[i] = new SAOStatData*[NUM_SAO_COMPONENTS];
+      for(Int compIdx=0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
+      {
+        m_preDBFstatData[i][compIdx] = new SAOStatData[NUM_SAO_NEW_TYPES];
+      }
+    }
+
+  }
+#endif
+
+#if SAO_ENCODING_CHOICE
+  ::memset(m_saoDisabledRate, 0, sizeof(m_saoDisabledRate));
+#endif
+
+  for(Int typeIdc=0; typeIdc < NUM_SAO_NEW_TYPES; typeIdc++)
+  {
+    m_skipLinesR[SAO_Y ][typeIdc]= 5;
+    m_skipLinesR[SAO_Cb][typeIdc]= m_skipLinesR[SAO_Cr][typeIdc]= 3;
+
+    m_skipLinesB[SAO_Y ][typeIdc]= 4;
+    m_skipLinesB[SAO_Cb][typeIdc]= m_skipLinesB[SAO_Cr][typeIdc]= 2;
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+    if(isPreDBFSamplesUsed)
+    {
+      switch(typeIdc)
+      {
+      case SAO_TYPE_EO_0:
+        {
+          m_skipLinesR[SAO_Y ][typeIdc]= 5;
+          m_skipLinesR[SAO_Cb][typeIdc]= m_skipLinesR[SAO_Cr][typeIdc]= 3;
+
+          m_skipLinesB[SAO_Y ][typeIdc]= 3;
+          m_skipLinesB[SAO_Cb][typeIdc]= m_skipLinesB[SAO_Cr][typeIdc]= 1;
+        }
+        break;
+      case SAO_TYPE_EO_90:
+        {
+          m_skipLinesR[SAO_Y ][typeIdc]= 4;
+          m_skipLinesR[SAO_Cb][typeIdc]= m_skipLinesR[SAO_Cr][typeIdc]= 2;
+
+          m_skipLinesB[SAO_Y ][typeIdc]= 4;
+          m_skipLinesB[SAO_Cb][typeIdc]= m_skipLinesB[SAO_Cr][typeIdc]= 2;
+        }
+        break;
+      case SAO_TYPE_EO_135:
+      case SAO_TYPE_EO_45:
+        {
+          m_skipLinesR[SAO_Y ][typeIdc]= 5;
+          m_skipLinesR[SAO_Cb][typeIdc]= m_skipLinesR[SAO_Cr][typeIdc]= 3;
+
+          m_skipLinesB[SAO_Y ][typeIdc]= 4;
+          m_skipLinesB[SAO_Cb][typeIdc]= m_skipLinesB[SAO_Cr][typeIdc]= 2;
+        }
+        break;
+      case SAO_TYPE_BO:
+        {
+          m_skipLinesR[SAO_Y ][typeIdc]= 4;
+          m_skipLinesR[SAO_Cb][typeIdc]= m_skipLinesR[SAO_Cr][typeIdc]= 2;
+
+          m_skipLinesB[SAO_Y ][typeIdc]= 3;
+          m_skipLinesB[SAO_Cb][typeIdc]= m_skipLinesB[SAO_Cr][typeIdc]= 1;
+        }
+        break;
+      default:
+        {
+          printf("Not a supported type");
+          assert(0);
+          exit(-1);
+        }
+      }
+    }
+#endif    
+  }
+
+}
+
+Void TEncSampleAdaptiveOffset::destroyEncData()
+{
+  if(m_pppcRDSbacCoder != NULL)
+  {
+    for (Int cs = 0; cs < NUM_SAO_CABACSTATE_LABELS; cs ++ )
+    {
+      delete m_pppcRDSbacCoder[cs];
+    }
+    delete[] m_pppcRDSbacCoder; m_pppcRDSbacCoder = NULL;
+  }
+
+  if(m_pppcBinCoderCABAC != NULL)
+  {
+    for (Int cs = 0; cs < NUM_SAO_CABACSTATE_LABELS; cs ++ )
+    {
+      delete m_pppcBinCoderCABAC[cs];
+    }
+    delete[] m_pppcBinCoderCABAC; m_pppcBinCoderCABAC = NULL;
+  }
+
+  if(m_statData != NULL)
+  {
+    for(Int i=0; i< m_numCTUsPic; i++)
+    {
+      for(Int compIdx=0; compIdx< NUM_SAO_COMPONENTS; compIdx++)
+      {
+        delete[] m_statData[i][compIdx];
+      }
+      delete[] m_statData[i];
+    }
+    delete[] m_statData; m_statData = NULL;
+  }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  if(m_preDBFstatData != NULL)
+  {
+    for(Int i=0; i< m_numCTUsPic; i++)
+    {
+      for(Int compIdx=0; compIdx< NUM_SAO_COMPONENTS; compIdx++)
+      {
+        delete[] m_preDBFstatData[i][compIdx];
+      }
+      delete[] m_preDBFstatData[i];
+    }
+    delete[] m_preDBFstatData; m_preDBFstatData = NULL;
+  }
+
+#endif
+}
+
+Void TEncSampleAdaptiveOffset::initRDOCabacCoder(TEncSbac* pcRDGoOnSbacCoder, TComSlice* pcSlice) 
+{
+  m_pcRDGoOnSbacCoder = pcRDGoOnSbacCoder;
+  m_pcRDGoOnSbacCoder->setSlice(pcSlice);
+  m_pcRDGoOnSbacCoder->resetEntropy();
+  m_pcRDGoOnSbacCoder->resetBits();
+
+  m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[SAO_CABACSTATE_PIC_INIT]);
+}
+
+
+
+Void TEncSampleAdaptiveOffset::SAOProcess(TComPic* pPic, Bool* sliceEnabled, const Double *lambdas
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                                         , Bool isPreDBFSamplesUsed
+#endif
+                                          )
+{
+  TComPicYuv* orgYuv= pPic->getPicYuvOrg();
+  TComPicYuv* resYuv= pPic->getPicYuvRec();
+  m_labmda[SAO_Y]= lambdas[0]; m_labmda[SAO_Cb]= lambdas[1]; m_labmda[SAO_Cr]= lambdas[2];
+  TComPicYuv* srcYuv = m_tempPicYuv;
+  resYuv->copyToPic(srcYuv);
+  srcYuv->setBorderExtension(false);
+  srcYuv->extendPicBorder();
+
+  //collect statistics
+  getStatistics(m_statData, orgYuv, srcYuv, pPic);
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  if(isPreDBFSamplesUsed)
+  {
+    addPreDBFStatistics(m_statData);
+  }
+#endif
+  //slice on/off 
+  decidePicParams(sliceEnabled, pPic->getSlice(0)->getDepth()); 
+
+  //block on/off 
+  SAOBlkParam* reconParams = new SAOBlkParam[m_numCTUsPic]; //temporary parameter buffer for storing reconstructed SAO parameters
+  decideBlkParams(pPic, sliceEnabled, m_statData, srcYuv, resYuv, reconParams, pPic->getPicSym()->getSAOBlkParam());
+  delete[] reconParams;
+
+}
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+Void TEncSampleAdaptiveOffset::getPreDBFStatistics(TComPic* pPic)
+{
+  getStatistics(m_preDBFstatData, pPic->getPicYuvOrg(), pPic->getPicYuvRec(), pPic, true);
+}
+
+Void TEncSampleAdaptiveOffset::addPreDBFStatistics(SAOStatData*** blkStats)
+{
+  for(Int n=0; n< m_numCTUsPic; n++)
+  {
+    for(Int compIdx=0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
+    {
+      for(Int typeIdc=0; typeIdc < NUM_SAO_NEW_TYPES; typeIdc++)
+      {
+        blkStats[n][compIdx][typeIdc] += m_preDBFstatData[n][compIdx][typeIdc];
+      }
+    }
+  }
+}
+
+#endif
+
+Void TEncSampleAdaptiveOffset::getStatistics(SAOStatData*** blkStats, TComPicYuv* orgYuv, TComPicYuv* srcYuv, TComPic* pPic
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                          , Bool isCalculatePreDeblockSamples
+#endif
+                          )
+{
+  Bool isLeftAvail,isRightAvail,isAboveAvail,isBelowAvail,isAboveLeftAvail,isAboveRightAvail,isBelowLeftAvail,isBelowRightAvail;
+
+  for(Int ctu= 0; ctu < m_numCTUsPic; ctu++)
+  {
+    Int yPos   = (ctu / m_numCTUInWidth)*m_maxCUHeight;
+    Int xPos   = (ctu % m_numCTUInWidth)*m_maxCUWidth;
+    Int height = (yPos + m_maxCUHeight > m_picHeight)?(m_picHeight- yPos):m_maxCUHeight;
+    Int width  = (xPos + m_maxCUWidth  > m_picWidth )?(m_picWidth - xPos):m_maxCUWidth;
+
+    pPic->getPicSym()->deriveLoopFilterBoundaryAvailibility(ctu, isLeftAvail,isRightAvail,isAboveAvail,isBelowAvail,isAboveLeftAvail,isAboveRightAvail,isBelowLeftAvail,isBelowRightAvail);
+
+    //NOTE: The number of skipped lines during gathering CTU statistics depends on the slice boundary availabilities.
+    //For simplicity, here only picture boundaries are considered.
+
+    isRightAvail      = (xPos + m_maxCUWidth  < m_picWidth );
+    isBelowAvail      = (yPos + m_maxCUHeight < m_picHeight);
+    isBelowRightAvail = (isRightAvail && isBelowAvail);
+    isBelowLeftAvail  = ((xPos > 0) && (isBelowAvail));
+    isAboveRightAvail = ((yPos > 0) && (isRightAvail));
+
+    for(Int compIdx=0; compIdx< NUM_SAO_COMPONENTS; compIdx++)
+    {
+      Bool isLuma     = (compIdx == SAO_Y);
+      Int  formatShift= isLuma?0:1;
+
+      Int  srcStride = isLuma?srcYuv->getStride():srcYuv->getCStride();
+      Pel* srcBlk    = getPicBuf(srcYuv, compIdx)+ (yPos >> formatShift)*srcStride+ (xPos >> formatShift);
+
+      Int  orgStride  = isLuma?orgYuv->getStride():orgYuv->getCStride();
+      Pel* orgBlk     = getPicBuf(orgYuv, compIdx)+ (yPos >> formatShift)*orgStride+ (xPos >> formatShift);
+
+      getBlkStats(compIdx, blkStats[ctu][compIdx]  
+                , srcBlk, orgBlk, srcStride, orgStride, (width  >> formatShift), (height >> formatShift)
+                , isLeftAvail,  isRightAvail, isAboveAvail, isBelowAvail, isAboveLeftAvail, isAboveRightAvail, isBelowLeftAvail, isBelowRightAvail
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                , isCalculatePreDeblockSamples
+#endif
+                );
+
+    }
+  }
+}
+
+Void TEncSampleAdaptiveOffset::decidePicParams(Bool* sliceEnabled, Int picTempLayer)
+{
+  //decide sliceEnabled[compIdx]
+  for (Int compIdx=0; compIdx<NUM_SAO_COMPONENTS; compIdx++)
+  {
+    // reset flags & counters
+    sliceEnabled[compIdx] = true;
+
+#if SAO_ENCODING_CHOICE
+#if SAO_ENCODING_CHOICE_CHROMA
+    // decide slice-level on/off based on previous results
+    if( (picTempLayer > 0) 
+      && (m_saoDisabledRate[compIdx][picTempLayer-1] > ((compIdx==SAO_Y) ? SAO_ENCODING_RATE : SAO_ENCODING_RATE_CHROMA)) )
+    {
+      sliceEnabled[compIdx] = false;
+    }
+#else
+    // decide slice-level on/off based on previous results
+    if( (picTempLayer > 0) 
+      && (m_saoDisabledRate[SAO_Y][0] > SAO_ENCODING_RATE) )
+    {
+      sliceEnabled[compIdx] = false;
+    }
+#endif
+#endif
+  }
+}
+
+Int64 TEncSampleAdaptiveOffset::getDistortion(Int ctu, Int compIdx, Int typeIdc, Int typeAuxInfo, Int* invQuantOffset, SAOStatData& statData)
+{
+  Int64 dist=0;
+  Int inputBitDepth    = (compIdx == SAO_Y) ? g_bitDepthY : g_bitDepthC ;
+  Int shift = 2 * DISTORTION_PRECISION_ADJUSTMENT(inputBitDepth-8);
+
+  switch(typeIdc)
+  {
+    case SAO_TYPE_EO_0:
+    case SAO_TYPE_EO_90:
+    case SAO_TYPE_EO_135:
+    case SAO_TYPE_EO_45:
+      {
+        for (Int offsetIdx=0; offsetIdx<NUM_SAO_EO_CLASSES; offsetIdx++)
+        {
+          dist += estSaoDist( statData.count[offsetIdx], invQuantOffset[offsetIdx], statData.diff[offsetIdx], shift);
+        }        
+      }
+      break;
+    case SAO_TYPE_BO:
+      {
+        for (Int offsetIdx=typeAuxInfo; offsetIdx<typeAuxInfo+4; offsetIdx++)
+        {
+          Int bandIdx = offsetIdx % NUM_SAO_BO_CLASSES ; 
+          dist += estSaoDist( statData.count[bandIdx], invQuantOffset[bandIdx], statData.diff[bandIdx], shift);
+        }
+      }
+      break;
+    default:
+      {
+        printf("Not a supported type");
+        assert(0);
+        exit(-1);
+      }
+  }
+
+  return dist;
+}
+
+inline Int64 TEncSampleAdaptiveOffset::estSaoDist(Int64 count, Int64 offset, Int64 diffSum, Int shift)
+{
+  return (( count*offset*offset-diffSum*offset*2 ) >> shift);
+}
+
+
+inline Int TEncSampleAdaptiveOffset::estIterOffset(Int typeIdx, Int classIdx, Double lambda, Int offsetInput, Int64 count, Int64 diffSum, Int shift, Int bitIncrease, Int64& bestDist, Double& bestCost, Int offsetTh )
+{
+  Int iterOffset, tempOffset;
+  Int64 tempDist, tempRate;
+  Double tempCost, tempMinCost;
+  Int offsetOutput = 0;
+  iterOffset = offsetInput;
+  // Assuming sending quantized value 0 results in zero offset and sending the value zero needs 1 bit. entropy coder can be used to measure the exact rate here. 
+  tempMinCost = lambda; 
+  while (iterOffset != 0)
+  {
+    // Calculate the bits required for signaling the offset
+    tempRate = (typeIdx == SAO_TYPE_BO) ? (abs((Int)iterOffset)+2) : (abs((Int)iterOffset)+1); 
+    if (abs((Int)iterOffset)==offsetTh) //inclusive 
+    {  
+      tempRate --;
+    }
+    // Do the dequantization before distortion calculation
+    tempOffset  = iterOffset << bitIncrease;
+    tempDist    = estSaoDist( count, tempOffset, diffSum, shift);
+    tempCost    = ((Double)tempDist + lambda * (Double) tempRate);
+    if(tempCost < tempMinCost)
+    {
+      tempMinCost = tempCost;
+      offsetOutput = iterOffset;
+      bestDist = tempDist;
+      bestCost = tempCost;
+    }
+    iterOffset = (iterOffset > 0) ? (iterOffset-1):(iterOffset+1);
+  }
+  return offsetOutput;
+}
+
+
+Void TEncSampleAdaptiveOffset::deriveOffsets(Int ctu, Int compIdx, Int typeIdc, SAOStatData& statData, Int* quantOffsets, Int& typeAuxInfo)
+{
+  Int bitDepth = (compIdx== SAO_Y) ? g_bitDepthY : g_bitDepthC;
+  Int shift = 2 * DISTORTION_PRECISION_ADJUSTMENT(bitDepth-8);
+  Int offsetTh = g_saoMaxOffsetQVal[compIdx];  //inclusive
+
+  ::memset(quantOffsets, 0, sizeof(Int)*MAX_NUM_SAO_CLASSES);
+
+  //derive initial offsets 
+  Int numClasses = (typeIdc == SAO_TYPE_BO)?((Int)NUM_SAO_BO_CLASSES):((Int)NUM_SAO_EO_CLASSES);
+  for(Int classIdx=0; classIdx< numClasses; classIdx++)
+  {
+    if( (typeIdc != SAO_TYPE_BO) && (classIdx==SAO_CLASS_EO_PLAIN)  ) 
+    {
+      continue; //offset will be zero
+    }
+
+    if(statData.count[classIdx] == 0)
+    {
+      continue; //offset will be zero
+    }
+
+    quantOffsets[classIdx] = (Int) xRoundIbdi(bitDepth, (Double)( statData.diff[classIdx]<<(bitDepth-8)) 
+                                                                  / 
+                                                          (Double)( statData.count[classIdx]<< m_offsetStepLog2[compIdx])
+                                               );
+    quantOffsets[classIdx] = Clip3(-offsetTh, offsetTh, quantOffsets[classIdx]);
+  }
+
+  // adjust offsets
+  switch(typeIdc)
+  {
+    case SAO_TYPE_EO_0:
+    case SAO_TYPE_EO_90:
+    case SAO_TYPE_EO_135:
+    case SAO_TYPE_EO_45:
+      {
+        Int64 classDist;
+        Double classCost;
+        for(Int classIdx=0; classIdx<NUM_SAO_EO_CLASSES; classIdx++)  
+        {         
+          if(classIdx==SAO_CLASS_EO_FULL_VALLEY && quantOffsets[classIdx] < 0) quantOffsets[classIdx] =0;
+          if(classIdx==SAO_CLASS_EO_HALF_VALLEY && quantOffsets[classIdx] < 0) quantOffsets[classIdx] =0;
+          if(classIdx==SAO_CLASS_EO_HALF_PEAK   && quantOffsets[classIdx] > 0) quantOffsets[classIdx] =0;
+          if(classIdx==SAO_CLASS_EO_FULL_PEAK   && quantOffsets[classIdx] > 0) quantOffsets[classIdx] =0;
+
+          if( quantOffsets[classIdx] != 0 ) //iterative adjustment only when derived offset is not zero
+          {
+            quantOffsets[classIdx] = estIterOffset( typeIdc, classIdx, m_labmda[compIdx], quantOffsets[classIdx], statData.count[classIdx], statData.diff[classIdx], shift, m_offsetStepLog2[compIdx], classDist , classCost , offsetTh );
+          }
+        }
+      
+        typeAuxInfo =0;
+      }
+      break;
+    case SAO_TYPE_BO:
+      {
+        Int64  distBOClasses[NUM_SAO_BO_CLASSES];
+        Double costBOClasses[NUM_SAO_BO_CLASSES];
+        ::memset(distBOClasses, 0, sizeof(Int64)*NUM_SAO_BO_CLASSES);
+        for(Int classIdx=0; classIdx< NUM_SAO_BO_CLASSES; classIdx++)
+        {         
+          costBOClasses[classIdx]= m_labmda[compIdx];
+          if( quantOffsets[classIdx] != 0 ) //iterative adjustment only when derived offset is not zero
+          {
+            quantOffsets[classIdx] = estIterOffset( typeIdc, classIdx, m_labmda[compIdx], quantOffsets[classIdx], statData.count[classIdx], statData.diff[classIdx], shift, m_offsetStepLog2[compIdx], distBOClasses[classIdx], costBOClasses[classIdx], offsetTh );
+          }
+        }
+
+        //decide the starting band index
+        Double minCost = MAX_DOUBLE, cost;
+        for(Int band=0; band< NUM_SAO_BO_CLASSES- 4+ 1; band++) 
+        {
+          cost  = costBOClasses[band  ];
+          cost += costBOClasses[band+1];
+          cost += costBOClasses[band+2];
+          cost += costBOClasses[band+3];
+
+          if(cost < minCost)
+          {
+            minCost = cost;
+            typeAuxInfo = band;
+          }
+        }
+        //clear those unused classes
+        Int clearQuantOffset[NUM_SAO_BO_CLASSES];
+        ::memset(clearQuantOffset, 0, sizeof(Int)*NUM_SAO_BO_CLASSES);
+        for(Int i=0; i< 4; i++) 
+        {
+          Int band = (typeAuxInfo+i)%NUM_SAO_BO_CLASSES;
+          clearQuantOffset[band] = quantOffsets[band];
+        }
+        ::memcpy(quantOffsets, clearQuantOffset, sizeof(Int)*NUM_SAO_BO_CLASSES);        
+      }
+      break;
+    default:
+      {
+        printf("Not a supported type");
+        assert(0);
+        exit(-1);
+      }
+
+  }
+
+
+}
+
+
+Void TEncSampleAdaptiveOffset::deriveModeNewRDO(Int ctu, std::vector<SAOBlkParam*>& mergeList, Bool* sliceEnabled, SAOStatData*** blkStats, SAOBlkParam& modeParam, Double& modeNormCost, TEncSbac** cabacCoderRDO, Int inCabacLabel)
+{
+  Double minCost, cost;
+  Int rate, minRate;
+  Int64 dist[NUM_SAO_COMPONENTS], modeDist[NUM_SAO_COMPONENTS];
+  SAOOffset testOffset[NUM_SAO_COMPONENTS];
+  Int compIdx;
+  Int invQuantOffset[MAX_NUM_SAO_CLASSES];
+
+  modeDist[SAO_Y]= modeDist[SAO_Cb] = modeDist[SAO_Cr] = 0;
+
+  //pre-encode merge flags
+  modeParam[SAO_Y ].modeIdc = SAO_MODE_OFF;
+  m_pcRDGoOnSbacCoder->load(cabacCoderRDO[inCabacLabel]);
+  m_pcRDGoOnSbacCoder->codeSAOBlkParam(modeParam, sliceEnabled, (mergeList[SAO_MERGE_LEFT]!= NULL), (mergeList[SAO_MERGE_ABOVE]!= NULL), true);
+  m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
+
+  //------ luma --------//
+  compIdx = SAO_Y;
+  //"off" case as initial cost
+  modeParam[compIdx].modeIdc = SAO_MODE_OFF;
+  m_pcRDGoOnSbacCoder->resetBits();
+  m_pcRDGoOnSbacCoder->codeSAOOffsetParam(compIdx, modeParam[compIdx], sliceEnabled[compIdx]);
+  minRate= m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
+  modeDist[compIdx] = 0;
+  minCost= m_labmda[compIdx]*((Double)minRate);
+  m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
+  if(sliceEnabled[compIdx])
+  {
+    for(Int typeIdc=0; typeIdc< NUM_SAO_NEW_TYPES; typeIdc++)
+    {
+      testOffset[compIdx].modeIdc = SAO_MODE_NEW;
+      testOffset[compIdx].typeIdc = typeIdc;
+
+      //derive coded offset
+      deriveOffsets(ctu, compIdx, typeIdc, blkStats[ctu][compIdx][typeIdc], testOffset[compIdx].offset, testOffset[compIdx].typeAuxInfo);
+
+      //inversed quantized offsets
+      invertQuantOffsets(compIdx, typeIdc, testOffset[compIdx].typeAuxInfo, invQuantOffset, testOffset[compIdx].offset);
+
+      //get distortion
+      dist[compIdx] = getDistortion(ctu, compIdx, testOffset[compIdx].typeIdc, testOffset[compIdx].typeAuxInfo, invQuantOffset, blkStats[ctu][compIdx][typeIdc]);
+
+      //get rate
+      m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
+      m_pcRDGoOnSbacCoder->resetBits();
+      m_pcRDGoOnSbacCoder->codeSAOOffsetParam(compIdx, testOffset[compIdx], sliceEnabled[compIdx]);
+      rate = m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
+      cost = (Double)dist[compIdx] + m_labmda[compIdx]*((Double)rate);
+      if(cost < minCost)
+      {
+        minCost = cost;
+        minRate = rate;
+        modeDist[compIdx] = dist[compIdx];
+        modeParam[compIdx]= testOffset[compIdx];
+        m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
+      }
+    }
+  }
+  m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
+  m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
+
+  //------ chroma --------//
+  assert(m_labmda[SAO_Cb] == m_labmda[SAO_Cr]);
+  Double chromaLambda = m_labmda[SAO_Cb];
+  //"off" case as initial cost
+  m_pcRDGoOnSbacCoder->resetBits();
+  modeParam[SAO_Cb].modeIdc = SAO_MODE_OFF; 
+  m_pcRDGoOnSbacCoder->codeSAOOffsetParam(SAO_Cb, modeParam[SAO_Cb], sliceEnabled[SAO_Cb]);
+  modeParam[SAO_Cr].modeIdc = SAO_MODE_OFF; 
+  m_pcRDGoOnSbacCoder->codeSAOOffsetParam(SAO_Cr, modeParam[SAO_Cr], sliceEnabled[SAO_Cr]);
+  minRate= m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
+  modeDist[SAO_Cb] = modeDist[SAO_Cr]= 0;
+  minCost= chromaLambda*((Double)minRate); 
+
+  //doesn't need to store cabac status here since the whole CTU parameters will be re-encoded at the end of this function
+
+  for(Int typeIdc=0; typeIdc< NUM_SAO_NEW_TYPES; typeIdc++)
+  {
+    for(compIdx= SAO_Cb; compIdx< NUM_SAO_COMPONENTS; compIdx++)
+    {
+      if(!sliceEnabled[compIdx])
+      {
+        testOffset[compIdx].modeIdc = SAO_MODE_OFF;
+        dist[compIdx]= 0;
+        continue;
+      }
+      testOffset[compIdx].modeIdc = SAO_MODE_NEW;
+      testOffset[compIdx].typeIdc = typeIdc;
+
+      //derive offset & get distortion
+      deriveOffsets(ctu, compIdx, typeIdc, blkStats[ctu][compIdx][typeIdc], testOffset[compIdx].offset, testOffset[compIdx].typeAuxInfo);
+      invertQuantOffsets(compIdx, typeIdc, testOffset[compIdx].typeAuxInfo, invQuantOffset, testOffset[compIdx].offset);
+      dist[compIdx]= getDistortion(ctu, compIdx, typeIdc, testOffset[compIdx].typeAuxInfo, invQuantOffset, blkStats[ctu][compIdx][typeIdc]);
+    }
+
+    //get rate
+    m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
+    m_pcRDGoOnSbacCoder->resetBits();
+    m_pcRDGoOnSbacCoder->codeSAOOffsetParam(SAO_Cb, testOffset[SAO_Cb], sliceEnabled[SAO_Cb]);
+    m_pcRDGoOnSbacCoder->codeSAOOffsetParam(SAO_Cr, testOffset[SAO_Cr], sliceEnabled[SAO_Cr]);
+    rate = m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
+
+    cost = (Double)(dist[SAO_Cb]+ dist[SAO_Cr]) + chromaLambda*((Double)rate);
+    if(cost < minCost)
+    {
+      minCost = cost;
+      minRate = rate;
+      modeDist[SAO_Cb] = dist[SAO_Cb];
+      modeDist[SAO_Cr] = dist[SAO_Cr];
+      modeParam[SAO_Cb]= testOffset[SAO_Cb];
+      modeParam[SAO_Cr]= testOffset[SAO_Cr];
+    }
+  }
+
+
+  //----- re-gen rate & normalized cost----//
+  modeNormCost  = (Double)modeDist[SAO_Y]/m_labmda[SAO_Y];
+  modeNormCost += (Double)(modeDist[SAO_Cb]+ modeDist[SAO_Cr])/chromaLambda; 
+  m_pcRDGoOnSbacCoder->load(cabacCoderRDO[inCabacLabel]);
+  m_pcRDGoOnSbacCoder->resetBits();
+  m_pcRDGoOnSbacCoder->codeSAOBlkParam(modeParam, sliceEnabled, (mergeList[SAO_MERGE_LEFT]!= NULL), (mergeList[SAO_MERGE_ABOVE]!= NULL), false);
+  modeNormCost += (Double)m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
+
+}
+
+Void TEncSampleAdaptiveOffset::deriveModeMergeRDO(Int ctu, std::vector<SAOBlkParam*>& mergeList, Bool* sliceEnabled, SAOStatData*** blkStats, SAOBlkParam& modeParam, Double& modeNormCost, TEncSbac** cabacCoderRDO, Int inCabacLabel)
+{
+  Int mergeListSize = (Int)mergeList.size();
+  modeNormCost = MAX_DOUBLE;
+
+  Double cost;
+  SAOBlkParam testBlkParam;
+
+  for(Int mergeType=0; mergeType< mergeListSize; mergeType++)
+  {
+    if(mergeList[mergeType] == NULL)
+    {
+      continue;
+    }
+
+    testBlkParam = *(mergeList[mergeType]);
+    //normalized distortion
+    Double normDist=0;
+    for(Int compIdx=0; compIdx< NUM_SAO_COMPONENTS; compIdx++)
+    {
+      testBlkParam[compIdx].modeIdc = SAO_MODE_MERGE;
+      testBlkParam[compIdx].typeIdc = mergeType;
+
+      SAOOffset& mergedOffsetParam = (*(mergeList[mergeType]))[compIdx];
+
+      if( mergedOffsetParam.modeIdc != SAO_MODE_OFF)
+      {
+        //offsets have been reconstructed. Don't call inversed quantization function.
+        normDist += (((Double)getDistortion(ctu, compIdx, mergedOffsetParam.typeIdc, mergedOffsetParam.typeAuxInfo, mergedOffsetParam.offset, blkStats[ctu][compIdx][mergedOffsetParam.typeIdc]))
+                       /m_labmda[compIdx]
+                    );
+      }
+
+    }
+
+    //rate
+    m_pcRDGoOnSbacCoder->load(cabacCoderRDO[inCabacLabel]);
+    m_pcRDGoOnSbacCoder->resetBits();
+    m_pcRDGoOnSbacCoder->codeSAOBlkParam(testBlkParam, sliceEnabled, (mergeList[SAO_MERGE_LEFT]!= NULL), (mergeList[SAO_MERGE_ABOVE]!= NULL), false);
+    Int rate = m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
+
+    cost = normDist+(Double)rate;
+
+    if(cost < modeNormCost)
+    {
+      modeNormCost = cost;
+      modeParam    = testBlkParam;
+      m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
+    }
+  }
+
+  m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
+
+
+}
+
+Void TEncSampleAdaptiveOffset::decideBlkParams(TComPic* pic, Bool* sliceEnabled, SAOStatData*** blkStats, TComPicYuv* srcYuv, TComPicYuv* resYuv, SAOBlkParam* reconParams, SAOBlkParam* codedParams)
+{
+  Bool isAllBlksDisabled = false;
+  if(!sliceEnabled[SAO_Y] && !sliceEnabled[SAO_Cb] && !sliceEnabled[SAO_Cr])
+  {
+    isAllBlksDisabled = true;
+  }
+
+  m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[ SAO_CABACSTATE_PIC_INIT ]);
+
+  SAOBlkParam modeParam;
+  Double minCost, modeCost;
+
+  for(Int ctu=0; ctu< m_numCTUsPic; ctu++)
+  {
+    if(isAllBlksDisabled)
+    {
+      codedParams[ctu].reset();
+      continue;
+    }
+
+    m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[ SAO_CABACSTATE_BLK_CUR ]);
+
+    //get merge list
+    std::vector<SAOBlkParam*> mergeList;
+    getMergeList(pic, ctu, reconParams, mergeList);
+
+    minCost = MAX_DOUBLE;
+    for(Int mode=0; mode < NUM_SAO_MODES; mode++)
+    {
+      switch(mode)
+      {
+      case SAO_MODE_OFF:
+        {
+          continue; //not necessary, since all-off case will be tested in SAO_MODE_NEW case.
+        }
+        break;
+      case SAO_MODE_NEW:
+        {
+          deriveModeNewRDO(ctu, mergeList, sliceEnabled, blkStats, modeParam, modeCost, m_pppcRDSbacCoder, SAO_CABACSTATE_BLK_CUR);
+
+        }
+        break;
+      case SAO_MODE_MERGE:
+        {
+          deriveModeMergeRDO(ctu, mergeList, sliceEnabled, blkStats , modeParam, modeCost, m_pppcRDSbacCoder, SAO_CABACSTATE_BLK_CUR);
+        }
+        break;
+      default:
+        {
+          printf("Not a supported SAO mode\n");
+          assert(0);
+          exit(-1);
+        }
+      }
+
+      if(modeCost < minCost)
+      {
+        minCost = modeCost;
+        codedParams[ctu] = modeParam;
+        m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[ SAO_CABACSTATE_BLK_NEXT ]);
+
+      }
+    } //mode
+    m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[ SAO_CABACSTATE_BLK_NEXT ]);
+
+    //apply reconstructed offsets
+    reconParams[ctu] = codedParams[ctu];
+    reconstructBlkSAOParam(reconParams[ctu], mergeList);
+    offsetCTU(ctu, srcYuv, resYuv, reconParams[ctu], pic);
+  } //ctu
+
+#if SAO_ENCODING_CHOICE 
+  Int picTempLayer = pic->getSlice(0)->getDepth();
+  Int numLcusForSAOOff[NUM_SAO_COMPONENTS];
+  numLcusForSAOOff[SAO_Y ] = numLcusForSAOOff[SAO_Cb]= numLcusForSAOOff[SAO_Cr]= 0;
+
+  for (Int compIdx=0; compIdx<NUM_SAO_COMPONENTS; compIdx++)
+  {
+    for(Int ctu=0; ctu< m_numCTUsPic; ctu++)
+    {
+      if( reconParams[ctu][compIdx].modeIdc == SAO_MODE_OFF)
+      {
+        numLcusForSAOOff[compIdx]++;
+      }
+    }
+  }
+#if SAO_ENCODING_CHOICE_CHROMA
+  for (Int compIdx=0; compIdx<NUM_SAO_COMPONENTS; compIdx++)
+  {
+    m_saoDisabledRate[compIdx][picTempLayer] = (Double)numLcusForSAOOff[compIdx]/(Double)m_numCTUsPic;
+  }
+#else
+  if (picTempLayer == 0)
+  {
+    m_saoDisabledRate[SAO_Y][0] = (Double)(numLcusForSAOOff[SAO_Y]+numLcusForSAOOff[SAO_Cb]+numLcusForSAOOff[SAO_Cr])/(Double)(m_numCTUsPic*3);
+  }
+#endif                                              
+#endif
+}
+
+
+Void TEncSampleAdaptiveOffset::getBlkStats(Int compIdx, SAOStatData* statsDataTypes  
+                        , Pel* srcBlk, Pel* orgBlk, Int srcStride, Int orgStride, Int width, Int height
+                        , Bool isLeftAvail,  Bool isRightAvail, Bool isAboveAvail, Bool isBelowAvail, Bool isAboveLeftAvail, Bool isAboveRightAvail, Bool isBelowLeftAvail, Bool isBelowRightAvail
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                        , Bool isCalculatePreDeblockSamples
+#endif
+                        )
+{
+  if(m_lineBufWidth != m_maxCUWidth)
+  {
+    m_lineBufWidth = m_maxCUWidth;
+
+    if (m_signLineBuf1) delete[] m_signLineBuf1; m_signLineBuf1 = NULL;
+    m_signLineBuf1 = new Char[m_lineBufWidth+1]; 
+
+    if (m_signLineBuf2) delete[] m_signLineBuf2; m_signLineBuf2 = NULL;
+    m_signLineBuf2 = new Char[m_lineBufWidth+1];
+  }
+
+  Int x,y, startX, startY, endX, endY, edgeType, firstLineStartX, firstLineEndX;
+  Char signLeft, signRight, signDown;
+  Int64 *diff, *count;
+  Pel *srcLine, *orgLine;
+  Int* skipLinesR = m_skipLinesR[compIdx];
+  Int* skipLinesB = m_skipLinesB[compIdx];
+
+  for(Int typeIdx=0; typeIdx< NUM_SAO_NEW_TYPES; typeIdx++)
+  {
+    SAOStatData& statsData= statsDataTypes[typeIdx];
+    statsData.reset();
+
+    srcLine = srcBlk;
+    orgLine = orgBlk;
+    diff    = statsData.diff;
+    count   = statsData.count;
+    switch(typeIdx)
+    {
+    case SAO_TYPE_EO_0:
+      {
+        diff +=2;
+        count+=2;
+        endY   = (isBelowAvail) ? (height - skipLinesB[typeIdx]) : height;
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        startX = (!isCalculatePreDeblockSamples) ? (isLeftAvail  ? 0 : 1)
+                                                 : (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
+                                                 ;
+#else
+        startX = isLeftAvail ? 0 : 1;
+#endif
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        endX   = (!isCalculatePreDeblockSamples) ? (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
+                                                 : (isRightAvail ? width : (width - 1))
+                                                 ;
+#else
+        endX   = isRightAvail ? (width - skipLinesR[typeIdx]): (width - 1);
+#endif
+        for (y=0; y<endY; y++)
+        {
+          signLeft = (Char)m_sign[srcLine[startX] - srcLine[startX-1]];
+          for (x=startX; x<endX; x++)
+          {
+            signRight =  (Char)m_sign[srcLine[x] - srcLine[x+1]]; 
+            edgeType  =  signRight + signLeft;
+            signLeft  = -signRight;
+
+            diff [edgeType] += (orgLine[x] - srcLine[x]);
+            count[edgeType] ++;
+          }
+          srcLine  += srcStride;
+          orgLine  += orgStride;
+        }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        if(isCalculatePreDeblockSamples)
+        {
+          if(isBelowAvail)
+          {
+            startX = isLeftAvail  ? 0 : 1;
+            endX   = isRightAvail ? width : (width -1);
+
+            for(y=0; y<skipLinesB[typeIdx]; y++)
+            {
+              signLeft = (Char)m_sign[srcLine[startX] - srcLine[startX-1]];
+              for (x=startX; x<endX; x++)
+              {
+                signRight =  (Char)m_sign[srcLine[x] - srcLine[x+1]]; 
+                edgeType  =  signRight + signLeft;
+                signLeft  = -signRight;
+
+                diff [edgeType] += (orgLine[x] - srcLine[x]);
+                count[edgeType] ++;
+              }
+              srcLine  += srcStride;
+              orgLine  += orgStride;
+            }
+          }
+        }
+#endif
+      }
+      break;
+    case SAO_TYPE_EO_90:
+      {
+        diff +=2;
+        count+=2;
+        Char *signUpLine = m_signLineBuf1;
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        startX = (!isCalculatePreDeblockSamples) ? 0
+                                                 : (isRightAvail ? (width - skipLinesR[typeIdx]) : width)
+                                                 ;
+#endif
+        startY = isAboveAvail ? 0 : 1;
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        endX   = (!isCalculatePreDeblockSamples) ? (isRightAvail ? (width - skipLinesR[typeIdx]) : width) 
+                                                 : width
+                                                 ;
+#else
+        endX   = isRightAvail ? (width - skipLinesR[typeIdx]) : width ;
+#endif
+        endY   = isBelowAvail ? (height - skipLinesB[typeIdx]) : (height - 1);
+        if (!isAboveAvail)
+        {
+          srcLine += srcStride;
+          orgLine += orgStride;
+        }
+
+        Pel* srcLineAbove = srcLine - srcStride;
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        for (x=startX; x<endX; x++) 
+#else
+        for (x=0; x< endX; x++) 
+#endif
+        {
+          signUpLine[x] = (Char)m_sign[srcLine[x] - srcLineAbove[x]];
+        }
+
+        Pel* srcLineBelow;
+        for (y=startY; y<endY; y++)
+        {
+          srcLineBelow = srcLine + srcStride;
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+          for (x=startX; x<endX; x++)
+#else
+          for (x=0; x<endX; x++)
+#endif
+          {
+            signDown  = (Char)m_sign[srcLine[x] - srcLineBelow[x]]; 
+            edgeType  = signDown + signUpLine[x];
+            signUpLine[x]= -signDown;
+
+            diff [edgeType] += (orgLine[x] - srcLine[x]);
+            count[edgeType] ++;
+          }
+          srcLine += srcStride;
+          orgLine += orgStride;
+        }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        if(isCalculatePreDeblockSamples)
+        {
+          if(isBelowAvail)
+          {
+            startX = 0;
+            endX   = width;
+
+            for(y=0; y<skipLinesB[typeIdx]; y++)
+            {
+              srcLineBelow = srcLine + srcStride;
+              srcLineAbove = srcLine - srcStride;
+
+              for (x=startX; x<endX; x++)
+              {
+                edgeType = m_sign[srcLine[x] - srcLineBelow[x]] + m_sign[srcLine[x] - srcLineAbove[x]];
+                diff [edgeType] += (orgLine[x] - srcLine[x]);
+                count[edgeType] ++;
+              }
+              srcLine  += srcStride;
+              orgLine  += orgStride;
+            }
+          }
+        }
+#endif
+
+      }
+      break;
+    case SAO_TYPE_EO_135:
+      {
+        diff +=2;
+        count+=2;
+        Char *signUpLine, *signDownLine, *signTmpLine;
+
+        signUpLine  = m_signLineBuf1;
+        signDownLine= m_signLineBuf2;
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        startX = (!isCalculatePreDeblockSamples) ? (isLeftAvail  ? 0 : 1)
+                                                 : (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
+                                                 ;
+#else
+        startX = isLeftAvail ? 0 : 1 ;
+#endif
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        endX   = (!isCalculatePreDeblockSamples) ? (isRightAvail ? (width - skipLinesR[typeIdx]): (width - 1))
+                                                 : (isRightAvail ? width : (width - 1))
+                                                 ;
+#else
+        endX   = isRightAvail ? (width - skipLinesR[typeIdx]): (width - 1);
+#endif
+        endY   = isBelowAvail ? (height - skipLinesB[typeIdx]) : (height - 1);
+
+        //prepare 2nd line's upper sign
+        Pel* srcLineBelow = srcLine + srcStride;
+        for (x=startX; x<endX+1; x++)
+        {
+          signUpLine[x] = (Char)m_sign[srcLineBelow[x] - srcLine[x-1]];
+        }
+
+        //1st line
+        Pel* srcLineAbove = srcLine - srcStride;
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        firstLineStartX = (!isCalculatePreDeblockSamples) ? (isAboveLeftAvail ? 0    : 1) : startX;
+        firstLineEndX   = (!isCalculatePreDeblockSamples) ? (isAboveAvail     ? endX : 1) : endX;
+#else
+        firstLineStartX = isAboveLeftAvail ? 0    : 1;
+        firstLineEndX   = isAboveAvail     ? endX : 1;
+#endif
+        for(x=firstLineStartX; x<firstLineEndX; x++)
+        {
+          edgeType = m_sign[srcLine[x] - srcLineAbove[x-1]] - signUpLine[x+1];
+          diff [edgeType] += (orgLine[x] - srcLine[x]);
+          count[edgeType] ++;
+        }
+        srcLine  += srcStride;
+        orgLine  += orgStride;
+
+
+        //middle lines
+        for (y=1; y<endY; y++)
+        {
+          srcLineBelow = srcLine + srcStride;
+
+          for (x=startX; x<endX; x++)
+          {
+            signDown = (Char)m_sign[srcLine[x] - srcLineBelow[x+1]] ;
+            edgeType = signDown + signUpLine[x];
+            diff [edgeType] += (orgLine[x] - srcLine[x]);
+            count[edgeType] ++;
+
+            signDownLine[x+1] = -signDown; 
+          }
+          signDownLine[startX] = (Char)m_sign[srcLineBelow[startX] - srcLine[startX-1]];
+
+          signTmpLine  = signUpLine;
+          signUpLine   = signDownLine;
+          signDownLine = signTmpLine;
+
+          srcLine += srcStride;
+          orgLine += orgStride;
+        }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        if(isCalculatePreDeblockSamples)
+        {
+          if(isBelowAvail)
+          {
+            startX = isLeftAvail  ? 0     : 1 ;
+            endX   = isRightAvail ? width : (width -1);
+
+            for(y=0; y<skipLinesB[typeIdx]; y++)
+            {
+              srcLineBelow = srcLine + srcStride;
+              srcLineAbove = srcLine - srcStride;
+
+              for (x=startX; x< endX; x++)
+              {
+                edgeType = m_sign[srcLine[x] - srcLineBelow[x+1]] + m_sign[srcLine[x] - srcLineAbove[x-1]];
+                diff [edgeType] += (orgLine[x] - srcLine[x]);
+                count[edgeType] ++;
+              }
+              srcLine  += srcStride;
+              orgLine  += orgStride;
+            }
+          }
+        }
+#endif
+      }
+      break;
+    case SAO_TYPE_EO_45:
+      {
+        diff +=2;
+        count+=2;
+        Char *signUpLine = m_signLineBuf1+1;
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        startX = (!isCalculatePreDeblockSamples) ? (isLeftAvail  ? 0 : 1)
+                                                 : (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
+                                                 ;
+#else
+        startX = isLeftAvail ? 0 : 1;
+#endif
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        endX   = (!isCalculatePreDeblockSamples) ? (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
+                                                 : (isRightAvail ? width : (width - 1))
+                                                 ;
+#else
+        endX   = isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1);
+#endif
+        endY   = isBelowAvail ? (height - skipLinesB[typeIdx]) : (height - 1);
+
+        //prepare 2nd line upper sign
+        Pel* srcLineBelow = srcLine + srcStride;
+        for (x=startX-1; x<endX; x++)
+        {
+          signUpLine[x] = (Char)m_sign[srcLineBelow[x] - srcLine[x+1]];
+        }
+
+
+        //first line
+        Pel* srcLineAbove = srcLine - srcStride;
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        firstLineStartX = (!isCalculatePreDeblockSamples) ? (isAboveAvail ? startX : endX)
+                                                          : startX
+                                                          ;
+        firstLineEndX   = (!isCalculatePreDeblockSamples) ? ((!isRightAvail && isAboveRightAvail) ? width : endX)
+                                                          : endX
+                                                          ;
+#else
+        firstLineStartX = isAboveAvail ? startX : endX;
+        firstLineEndX   = (!isRightAvail && isAboveRightAvail) ? width : endX;
+#endif
+        for(x=firstLineStartX; x<firstLineEndX; x++)
+        {
+          edgeType = m_sign[srcLine[x] - srcLineAbove[x+1]] - signUpLine[x-1];
+          diff [edgeType] += (orgLine[x] - srcLine[x]);
+          count[edgeType] ++;
+        }
+
+        srcLine += srcStride;
+        orgLine += orgStride;
+
+        //middle lines
+        for (y=1; y<endY; y++)
+        {
+          srcLineBelow = srcLine + srcStride;
+
+          for(x=startX; x<endX; x++)
+          {
+            signDown = (Char)m_sign[srcLine[x] - srcLineBelow[x-1]] ;
+            edgeType = signDown + signUpLine[x];
+
+            diff [edgeType] += (orgLine[x] - srcLine[x]);
+            count[edgeType] ++;
+
+            signUpLine[x-1] = -signDown; 
+          }
+          signUpLine[endX-1] = (Char)m_sign[srcLineBelow[endX-1] - srcLine[endX]];
+          srcLine  += srcStride;
+          orgLine  += orgStride;
+        }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        if(isCalculatePreDeblockSamples)
+        {
+          if(isBelowAvail)
+          {
+            startX = isLeftAvail  ? 0     : 1 ;
+            endX   = isRightAvail ? width : (width -1);
+
+            for(y=0; y<skipLinesB[typeIdx]; y++)
+            {
+              srcLineBelow = srcLine + srcStride;
+              srcLineAbove = srcLine - srcStride;
+
+              for (x=startX; x<endX; x++)
+              {
+                edgeType = m_sign[srcLine[x] - srcLineBelow[x-1]] + m_sign[srcLine[x] - srcLineAbove[x+1]];
+                diff [edgeType] += (orgLine[x] - srcLine[x]);
+                count[edgeType] ++;
+              }
+              srcLine  += srcStride;
+              orgLine  += orgStride;
+            }
+          }
+        }
+#endif
+      }
+      break;
+    case SAO_TYPE_BO:
+      {
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        startX = (!isCalculatePreDeblockSamples)?0
+                                                :( isRightAvail?(width- skipLinesR[typeIdx]):width)
+                                                ;
+        endX   = (!isCalculatePreDeblockSamples)?(isRightAvail ? (width - skipLinesR[typeIdx]) : width )
+                                                :width
+                                                ;
+#else
+        endX = isRightAvail ? (width- skipLinesR[typeIdx]) : width;
+#endif
+        endY = isBelowAvail ? (height- skipLinesB[typeIdx]) : height;
+        Int shiftBits = ((compIdx == SAO_Y)?g_bitDepthY:g_bitDepthC)- NUM_SAO_BO_CLASSES_LOG2;
+        for (y=0; y< endY; y++)
+        {
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+          for (x=startX; x< endX; x++)
+#else
+          for (x=0; x< endX; x++)
+#endif
+          {
+
+            Int bandIdx= srcLine[x] >> shiftBits; 
+            diff [bandIdx] += (orgLine[x] - srcLine[x]);
+            count[bandIdx] ++;
+          }
+          srcLine += srcStride;
+          orgLine += orgStride;
+        }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        if(isCalculatePreDeblockSamples)
+        {
+          if(isBelowAvail)
+          {
+            startX = 0;
+            endX   = width;
+
+            for(y= 0; y< skipLinesB[typeIdx]; y++)
+            {
+              for (x=startX; x< endX; x++)
+              {
+                Int bandIdx= srcLine[x] >> shiftBits; 
+                diff [bandIdx] += (orgLine[x] - srcLine[x]);
+                count[bandIdx] ++;
+              }
+              srcLine  += srcStride;
+              orgLine  += orgStride;
+
+            }
+
+          }
+        }
+#endif
+      }
+      break;
+    default:
+      {
+        printf("Not a supported SAO types\n");
+        assert(0);
+        exit(-1);
+      }
+    }
+  }
+}
+
+#else
+
+
+
 TEncSampleAdaptiveOffset::TEncSampleAdaptiveOffset()
 {
@@ -1661,5 +2924,4 @@
 }
 
-#if SAO_CHROMA_LAMBDA 
 /** Sample adaptive offset process
  * \param pcSaoParam
@@ -1671,10 +2933,4 @@
 #else
 Void TEncSampleAdaptiveOffset::SAOProcess(SAOParam *pcSaoParam, Double dLambdaLuma, Double dLambdaChroma)
-#endif
-#else
-/** Sample adaptive offset process
- * \param dLambda
- */
-Void TEncSampleAdaptiveOffset::SAOProcess(SAOParam *pcSaoParam, Double dLambda)
 #endif
 {
@@ -2501,3 +3757,5 @@
 }
 
+#endif
+
 //! \}
Index: trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h	(revision 494)
+++ trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h	(revision 540)
@@ -53,4 +53,112 @@
 // Class definition
 // ====================================================================================================================
+
+#if HM_CLEANUP_SAO
+enum SAOCabacStateLablesRDO //CABAC state labels
+{
+  SAO_CABACSTATE_PIC_INIT =0,
+  SAO_CABACSTATE_BLK_CUR,
+  SAO_CABACSTATE_BLK_NEXT,
+  SAO_CABACSTATE_BLK_MID,
+  SAO_CABACSTATE_BLK_TEMP,
+  NUM_SAO_CABACSTATE_LABELS
+};
+
+struct SAOStatData //data structure for SAO statistics
+{
+  Int64 diff[MAX_NUM_SAO_CLASSES];
+  Int64 count[MAX_NUM_SAO_CLASSES];
+
+  SAOStatData(){}
+  ~SAOStatData(){}
+  Void reset()
+  {
+    ::memset(diff, 0, sizeof(Int64)*MAX_NUM_SAO_CLASSES);
+    ::memset(count, 0, sizeof(Int64)*MAX_NUM_SAO_CLASSES);
+  }
+  const SAOStatData& operator=(const SAOStatData& src)
+  {
+    ::memcpy(diff, src.diff, sizeof(Int64)*MAX_NUM_SAO_CLASSES);
+    ::memcpy(count, src.count, sizeof(Int64)*MAX_NUM_SAO_CLASSES);
+    return *this;
+  }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  const SAOStatData& operator+= (const SAOStatData& src)
+  {
+    for(Int i=0; i< MAX_NUM_SAO_CLASSES; i++)
+    {
+      diff[i] += src.diff[i];
+      count[i] += src.count[i];
+    }
+    return *this;
+  }
+#endif
+};
+
+class TEncSampleAdaptiveOffset : public TComSampleAdaptiveOffset
+{
+public:
+  TEncSampleAdaptiveOffset();
+  virtual ~TEncSampleAdaptiveOffset();
+
+  //interface
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  Void createEncData(Bool isPreDBFSamplesUsed);
+#else
+  Void createEncData();
+#endif
+  Void destroyEncData();
+  Void initRDOCabacCoder(TEncSbac* pcRDGoOnSbacCoder, TComSlice* pcSlice) ;
+  Void SAOProcess(TComPic* pPic, Bool* sliceEnabled, const Double *lambdas
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                , Bool isPreDBFSamplesUsed
+#endif
+                ); 
+public: //methods
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  Void getPreDBFStatistics(TComPic* pPic); 
+#endif
+private: //methods
+  Void getStatistics(SAOStatData*** blkStats, TComPicYuv* orgYuv, TComPicYuv* srcYuv,TComPic* pPic
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                   , Bool isCalculatePreDeblockSamples = false
+#endif
+                   );
+  Void decidePicParams(Bool* sliceEnabled, Int picTempLayer);
+  Void decideBlkParams(TComPic* pic, Bool* sliceEnabled, SAOStatData*** blkStats, TComPicYuv* srcYuv, TComPicYuv* resYuv, SAOBlkParam* reconParams, SAOBlkParam* codedParams);
+  Void getBlkStats(Int compIdx, SAOStatData* statsDataTypes, Pel* srcBlk, Pel* orgBlk, Int srcStride, Int orgStride, Int width, Int height, Bool isLeftAvail,  Bool isRightAvail, Bool isAboveAvail, Bool isBelowAvail, Bool isAboveLeftAvail, Bool isAboveRightAvail, Bool isBelowLeftAvail, Bool isBelowRightAvail
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                  , Bool isCalculatePreDeblockSamples
+#endif
+                  );
+  Void deriveModeNewRDO(Int ctu, std::vector<SAOBlkParam*>& mergeList, Bool* sliceEnabled, SAOStatData*** blkStats, SAOBlkParam& modeParam, Double& modeNormCost, TEncSbac** cabacCoderRDO, Int inCabacLabel);
+  Void deriveModeMergeRDO(Int ctu, std::vector<SAOBlkParam*>& mergeList, Bool* sliceEnabled, SAOStatData*** blkStats, SAOBlkParam& modeParam, Double& modeNormCost, TEncSbac** cabacCoderRDO, Int inCabacLabel);
+  Int64 getDistortion(Int ctu, Int compIdx, Int typeIdc, Int typeAuxInfo, Int* offsetVal, SAOStatData& statData);
+  Void deriveOffsets(Int ctu, Int compIdx, Int typeIdc, SAOStatData& statData, Int* quantOffsets, Int& typeAuxInfo);
+  inline Int64 estSaoDist(Int64 count, Int64 offset, Int64 diffSum, Int shift);
+  inline Int estIterOffset(Int typeIdx, Int classIdx, Double lambda, Int offsetInput, Int64 count, Int64 diffSum, Int shift, Int bitIncrease, Int64& bestDist, Double& bestCost, Int offsetTh );
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  Void addPreDBFStatistics(SAOStatData*** blkStats);
+#endif
+private: //members
+  //for RDO
+  TEncSbac**             m_pppcRDSbacCoder;           
+  TEncSbac*              m_pcRDGoOnSbacCoder;
+  TEncBinCABACCounter**  m_pppcBinCoderCABAC;    
+  Double                 m_labmda[NUM_SAO_COMPONENTS];
+
+  //statistics
+  SAOStatData***         m_statData; //[ctu][comp][classes]
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  SAOStatData***         m_preDBFstatData;
+#endif
+#if SAO_ENCODING_CHOICE
+  Double                 m_saoDisabledRate[NUM_SAO_COMPONENTS][MAX_TLAYER];
+#endif
+  Int                    m_skipLinesR[NUM_SAO_COMPONENTS][NUM_SAO_NEW_TYPES];
+  Int                    m_skipLinesB[NUM_SAO_COMPONENTS][NUM_SAO_NEW_TYPES];
+};
+#else
+
 
 class TEncSampleAdaptiveOffset : public TComSampleAdaptiveOffset
@@ -95,12 +203,8 @@
   Void endSaoEnc();
   Void resetStats();
-#if SAO_CHROMA_LAMBDA
 #if SAO_ENCODING_CHOICE
   Void SAOProcess(SAOParam *pcSaoParam, Double dLambda, Double dLambdaChroma, Int depth);
 #else
   Void SAOProcess(SAOParam *pcSaoParam, Double dLambda, Double dLambdaChroma);
-#endif
-#else
-  Void SAOProcess(SAOParam *pcSaoParam, Double dLambda);
 #endif
 
@@ -131,5 +235,5 @@
   Int  getMaxNumOffsetsPerPic() {return m_maxNumOffsetsPerPic; }
 };
-
+#endif
 //! \}
 
Index: trunk/source/Lib/TLibEncoder/TEncSbac.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSbac.cpp	(revision 494)
+++ trunk/source/Lib/TLibEncoder/TEncSbac.cpp	(revision 540)
@@ -416,5 +416,4 @@
 {
   PartSize eSize         = pcCU->getPartitionSize( uiAbsPartIdx );
-
   if ( pcCU->isIntra( uiAbsPartIdx ) )
   {
@@ -1394,5 +1393,9 @@
   {
     m_pcBinIf->encodeBin( 1, m_cSaoTypeIdxSCModel.get( 0, 0, 0 ) );
+#if HM_CLEANUP_SAO
+    m_pcBinIf->encodeBinEP( uiCode == 1 ? 0 : 1 );
+#else
     m_pcBinIf->encodeBinEP( uiCode <= 4 ? 1 : 0 );
+#endif
   }
 }
@@ -1597,3 +1600,118 @@
 }
 
+#if HM_CLEANUP_SAO
+Void TEncSbac::codeSAOOffsetParam(Int compIdx, SAOOffset& ctbParam, Bool sliceEnabled)
+{
+  UInt uiSymbol;
+  if(!sliceEnabled)
+  {
+    assert(ctbParam.modeIdc == SAO_MODE_OFF);
+    return;
+  }
+
+  //type
+  if(compIdx == SAO_Y || compIdx == SAO_Cb)
+  {
+    //sao_type_idx_luma or sao_type_idx_chroma
+    if(ctbParam.modeIdc == SAO_MODE_OFF)
+    {
+      uiSymbol =0;
+    }
+    else if(ctbParam.typeIdc == SAO_TYPE_BO) //BO
+    {
+      uiSymbol = 1;
+    }
+    else
+    {
+      assert(ctbParam.typeIdc < SAO_TYPE_START_BO); //EO
+      uiSymbol = 2;
+    }
+    codeSaoTypeIdx(uiSymbol); 
+  }
+
+  if(ctbParam.modeIdc == SAO_MODE_NEW)
+  {
+    Int numClasses = (ctbParam.typeIdc == SAO_TYPE_BO)?4:NUM_SAO_EO_CLASSES; 
+    Int offset[4];
+    Int k=0;
+    for(Int i=0; i< numClasses; i++)
+    {
+      if(ctbParam.typeIdc != SAO_TYPE_BO && i == SAO_CLASS_EO_PLAIN)
+      {
+        continue;
+      }
+      Int classIdx = (ctbParam.typeIdc == SAO_TYPE_BO)?(  (ctbParam.typeAuxInfo+i)% NUM_SAO_BO_CLASSES   ):i;
+      offset[k] = ctbParam.offset[classIdx];
+      k++;
+    }
+
+    for(Int i=0; i< 4; i++)
+    {
+      codeSaoMaxUvlc((offset[i]<0)?(-offset[i]):(offset[i]),  g_saoMaxOffsetQVal[compIdx] ); //sao_offset_abs
+    }
+
+
+    if(ctbParam.typeIdc == SAO_TYPE_BO)
+    {
+      for(Int i=0; i< 4; i++)
+      {
+        if(offset[i] != 0)
+        {
+          codeSAOSign((offset[i]< 0)?1:0);
+        }
+      }
+
+      codeSaoUflc(NUM_SAO_BO_CLASSES_LOG2, ctbParam.typeAuxInfo ); //sao_band_position
+    }
+    else //EO
+    {
+      if(compIdx == SAO_Y || compIdx == SAO_Cb)
+      {
+        assert(ctbParam.typeIdc - SAO_TYPE_START_EO >=0);
+        codeSaoUflc(NUM_SAO_EO_TYPES_LOG2, ctbParam.typeIdc - SAO_TYPE_START_EO ); //sao_eo_class_luma or sao_eo_class_chroma
+      }
+    }
+
+  }
+}
+
+
+Void TEncSbac::codeSAOBlkParam(SAOBlkParam& saoBlkParam
+                              , Bool* sliceEnabled
+                              , Bool leftMergeAvail
+                              , Bool aboveMergeAvail
+                              , Bool onlyEstMergeInfo // = false
+                              )
+{
+
+  Bool isLeftMerge = false;
+  Bool isAboveMerge= false;
+
+  if(leftMergeAvail)
+  {
+    isLeftMerge = ((saoBlkParam[SAO_Y].modeIdc == SAO_MODE_MERGE) && (saoBlkParam[SAO_Y].typeIdc == SAO_MERGE_LEFT));
+    codeSaoMerge( isLeftMerge?1:0  ); //sao_merge_left_flag
+  }
+
+  if( aboveMergeAvail && !isLeftMerge)
+  {
+    isAboveMerge = ((saoBlkParam[SAO_Y].modeIdc == SAO_MODE_MERGE) && (saoBlkParam[SAO_Y].typeIdc == SAO_MERGE_ABOVE)); 
+    codeSaoMerge( isAboveMerge?1:0  ); //sao_merge_left_flag
+  }
+
+  if(onlyEstMergeInfo)
+  {
+    return; //only for RDO
+  }
+
+  if(!isLeftMerge && !isAboveMerge) //not merge mode
+  {
+    for(Int compIdx=0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
+    {
+      codeSAOOffsetParam(compIdx, saoBlkParam[compIdx], sliceEnabled[compIdx]);
+    }
+  }
+}
+#endif
+
 //! \}
Index: trunk/source/Lib/TLibEncoder/TEncSbac.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSbac.h	(revision 494)
+++ trunk/source/Lib/TLibEncoder/TEncSbac.h	(revision 540)
@@ -103,4 +103,14 @@
   Void  codeSAOSign       ( UInt  uiCode);  //<! code SAO offset sign
   Void  codeScalingList      ( TComScalingList* /*scalingList*/     ){ assert (0);  return;};
+
+#if HM_CLEANUP_SAO
+  Void codeSAOOffsetParam(Int compIdx, SAOOffset& ctbParam, Bool sliceEnabled);
+  Void codeSAOBlkParam(SAOBlkParam& saoBlkParam
+                    , Bool* sliceEnabled
+                    , Bool leftMergeAvail
+                    , Bool aboveMergeAvail
+                    , Bool onlyEstMergeInfo = false
+                    );
+#endif
 
 private:
Index: trunk/source/Lib/TLibEncoder/TEncSearch.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSearch.cpp	(revision 494)
+++ trunk/source/Lib/TLibEncoder/TEncSearch.cpp	(revision 540)
@@ -720,9 +720,5 @@
   Pel*  piRefPos;
   Int iRefStride = m_filteredBlock[0][0].getStride();
-#if NS_HAD
-  m_pcRdCost->setDistParam( pcPatternKey, m_filteredBlock[0][0].getLumaAddr(), iRefStride, 1, m_cDistParam, m_pcEncCfg->getUseHADME(), m_pcEncCfg->getUseNSQT() );
-#else
   m_pcRdCost->setDistParam( pcPatternKey, m_filteredBlock[0][0].getLumaAddr(), iRefStride, 1, m_cDistParam, m_pcEncCfg->getUseHADME() );
-#endif
   
   const TComMv* pcMvRefine = (iFrac == 2 ? s_acMvRefineH : s_acMvRefineQ);
@@ -737,7 +733,11 @@
     piRefPos = m_filteredBlock[ verVal & 3 ][ horVal & 3 ].getLumaAddr();
     if ( horVal == 2 && ( verVal & 1 ) == 0 )
+    {
       piRefPos += 1;
+    }
     if ( ( horVal & 1 ) == 0 && verVal == 2 )
+    {
       piRefPos += iRefStride;
+    }
     cMvTest = pcMvRefine[i];
     cMvTest += rcMvFrac;
@@ -774,28 +774,26 @@
   UInt  uiLog2TrafoSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth()] + 2 - uiFullDepth;
 
-  {
-    if( pcCU->getPredictionMode(0) == MODE_INTRA && pcCU->getPartitionSize(0) == SIZE_NxN && uiTrDepth == 0 )
-    {
-      assert( uiSubdiv );
-    }
-    else if( uiLog2TrafoSize > pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() )
-    {
-      assert( uiSubdiv );
-    }
-    else if( uiLog2TrafoSize == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
-    {
-      assert( !uiSubdiv );
-    }
-    else if( uiLog2TrafoSize == pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
-    {
-      assert( !uiSubdiv );
-    }
-    else
-    {
-      assert( uiLog2TrafoSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) );
-      if( bLuma )
-      {
-        m_pcEntropyCoder->encodeTransformSubdivFlag( uiSubdiv, 5 - uiLog2TrafoSize );
-      }
+  if( pcCU->getPredictionMode(0) == MODE_INTRA && pcCU->getPartitionSize(0) == SIZE_NxN && uiTrDepth == 0 )
+  {
+    assert( uiSubdiv );
+  }
+  else if( uiLog2TrafoSize > pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() )
+  {
+    assert( uiSubdiv );
+  }
+  else if( uiLog2TrafoSize == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+  {
+    assert( !uiSubdiv );
+  }
+  else if( uiLog2TrafoSize == pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
+  {
+    assert( !uiSubdiv );
+  }
+  else
+  {
+    assert( uiLog2TrafoSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) );
+    if( bLuma )
+    {
+      m_pcEntropyCoder->encodeTransformSubdivFlag( uiSubdiv, 5 - uiLog2TrafoSize );
     }
   }
@@ -806,7 +804,11 @@
     {
       if( uiTrDepth==0 || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth-1 ) )
+      {
         m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth );
+      }
       if( uiTrDepth==0 || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth-1 ) )
+      {
         m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth );
+      }
     }
   }
@@ -822,10 +824,8 @@
   }
   
-  {
-    //===== Cbfs =====
-    if( bLuma )
-    {
-      m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
-    }
+  //===== Cbfs =====
+  if( bLuma )
+  {
+    m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
   }
 }
@@ -944,5 +944,4 @@
     }
   }
-
   if( bChroma )
   {
@@ -1306,5 +1305,5 @@
 
 #if RDOQ_CHROMA_LAMBDA 
-    m_pcTrQuant->selectLambda      (TEXT_CHROMA);  
+    m_pcTrQuant->selectLambda(eText);
 #endif
     m_pcTrQuant->transformNxN      ( pcCU, piResi, uiStride, pcCoeff, 
@@ -1358,9 +1357,5 @@
   
   //===== update distortion =====
-#if WEIGHTED_CHROMA_DISTORTION
   ruiDist += m_pcRdCost->getDistPart(g_bitDepthC, piReco, uiStride, piOrg, uiStride, uiWidth, uiHeight, eText );
-#else
-  ruiDist += m_pcRdCost->getDistPart(g_bitDepthC, piReco, uiStride, piOrg, uiStride, uiWidth, uiHeight );
-#endif
 }
 
@@ -2539,5 +2534,4 @@
       
       for( Int j=0; j < numCand; j++)
-
       {
         Bool mostProbableModeIncluded = false;
@@ -3039,9 +3033,5 @@
                             pcYuvOrg->getLumaAddr( uiAbsPartIdx ), pcYuvOrg->getStride(), 
                             m_tmpYuvPred .getLumaAddr( uiAbsPartIdx ), m_tmpYuvPred .getStride(), 
-#if NS_HAD
-                            iWidth, iHeight, m_pcEncCfg->getUseHADME(), m_pcEncCfg->getUseNSQT() );
-#else
                             iWidth, iHeight, m_pcEncCfg->getUseHADME() );
-#endif
   ruiErr = cDistParam.DistFunc( &cDistParam );
 }
@@ -3246,5 +3236,8 @@
 
     UInt          uiCostTempL0[MAX_NUM_REF];
-    for (Int iNumRef=0; iNumRef < MAX_NUM_REF; iNumRef++) uiCostTempL0[iNumRef] = MAX_UINT;
+    for (Int iNumRef=0; iNumRef < MAX_NUM_REF; iNumRef++)
+    {
+      uiCostTempL0[iNumRef] = MAX_UINT;
+    }
     UInt          uiBitsTempL0[MAX_NUM_REF];
 
@@ -3716,18 +3709,14 @@
     {
       uiLastMode = 2;
-      {
-            pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMv( cMvBi[0], ePartSize, uiPartAddr, 0, iPartIdx );
-            pcCU->getCUMvField(REF_PIC_LIST_0)->setAllRefIdx( iRefIdxBi[0], ePartSize, uiPartAddr, 0, iPartIdx );
-            pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMv( cMvBi[1], ePartSize, uiPartAddr, 0, iPartIdx );
-            pcCU->getCUMvField(REF_PIC_LIST_1)->setAllRefIdx( iRefIdxBi[1], ePartSize, uiPartAddr, 0, iPartIdx );
-      }
-      {
-        TempMv = cMvBi[0] - cMvPredBi[0][iRefIdxBi[0]];
-            pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
-      }
-      {
-        TempMv = cMvBi[1] - cMvPredBi[1][iRefIdxBi[1]];
-            pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
-      }
+      pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMv( cMvBi[0], ePartSize, uiPartAddr, 0, iPartIdx );
+      pcCU->getCUMvField(REF_PIC_LIST_0)->setAllRefIdx( iRefIdxBi[0], ePartSize, uiPartAddr, 0, iPartIdx );
+      pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMv( cMvBi[1], ePartSize, uiPartAddr, 0, iPartIdx );
+      pcCU->getCUMvField(REF_PIC_LIST_1)->setAllRefIdx( iRefIdxBi[1], ePartSize, uiPartAddr, 0, iPartIdx );
+      
+      TempMv = cMvBi[0] - cMvPredBi[0][iRefIdxBi[0]];
+      pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
+      
+      TempMv = cMvBi[1] - cMvPredBi[1][iRefIdxBi[1]];
+      pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
       
       pcCU->setInterDirSubParts( 3, uiPartAddr, iPartIdx, pcCU->getDepth(0) );
@@ -3743,10 +3732,8 @@
     {
       uiLastMode = 0;
-          pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMv( cMv[0], ePartSize, uiPartAddr, 0, iPartIdx );
-          pcCU->getCUMvField(REF_PIC_LIST_0)->setAllRefIdx( iRefIdx[0], ePartSize, uiPartAddr, 0, iPartIdx );
-      {
-        TempMv = cMv[0] - cMvPred[0][iRefIdx[0]];
-            pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
-      }
+      pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMv( cMv[0], ePartSize, uiPartAddr, 0, iPartIdx );
+      pcCU->getCUMvField(REF_PIC_LIST_0)->setAllRefIdx( iRefIdx[0], ePartSize, uiPartAddr, 0, iPartIdx );
+      TempMv = cMv[0] - cMvPred[0][iRefIdx[0]];
+      pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
       pcCU->setInterDirSubParts( 1, uiPartAddr, iPartIdx, pcCU->getDepth(0) );
       
@@ -3759,10 +3746,8 @@
     {
       uiLastMode = 1;
-          pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMv( cMv[1], ePartSize, uiPartAddr, 0, iPartIdx );
-          pcCU->getCUMvField(REF_PIC_LIST_1)->setAllRefIdx( iRefIdx[1], ePartSize, uiPartAddr, 0, iPartIdx );
-      {
-        TempMv = cMv[1] - cMvPred[1][iRefIdx[1]];
-            pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
-      }
+      pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMv( cMv[1], ePartSize, uiPartAddr, 0, iPartIdx );
+      pcCU->getCUMvField(REF_PIC_LIST_1)->setAllRefIdx( iRefIdx[1], ePartSize, uiPartAddr, 0, iPartIdx );
+      TempMv = cMv[1] - cMvPred[1][iRefIdx[1]];
+      pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
       pcCU->setInterDirSubParts( 2, uiPartAddr, iPartIdx, pcCU->getDepth(0) );
       
@@ -3816,8 +3801,6 @@
         pcCU->setMergeIndexSubParts( uiMRGIndex,    uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
         pcCU->setInterDirSubParts  ( uiMRGInterDir, uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
-        {
-          pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( cMRGMvField[0], ePartSize, uiPartAddr, 0, iPartIdx );
-          pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMRGMvField[1], ePartSize, uiPartAddr, 0, iPartIdx );
-        }
+        pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( cMRGMvField[0], ePartSize, uiPartAddr, 0, iPartIdx );
+        pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMRGMvField[1], ePartSize, uiPartAddr, 0, iPartIdx );
 
         pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvd    ( cMvZero,            ePartSize, uiPartAddr, 0, iPartIdx );
@@ -3834,8 +3817,6 @@
         pcCU->setMergeFlagSubParts( false,        uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
         pcCU->setInterDirSubParts ( uiMEInterDir, uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
-        {
-          pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( cMEMvField[0], ePartSize, uiPartAddr, 0, iPartIdx );
-          pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMEMvField[1], ePartSize, uiPartAddr, 0, iPartIdx );
-        }
+        pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( cMEMvField[0], ePartSize, uiPartAddr, 0, iPartIdx );
+        pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMEMvField[1], ePartSize, uiPartAddr, 0, iPartIdx );
       }
     }
@@ -3944,5 +3925,7 @@
   
   if (iNum == 1)
+  {
     return 0;
+  }
   
   UInt uiLength = 1;
@@ -4123,17 +4106,9 @@
                             pcOrgYuv->getLumaAddr(uiPartAddr), pcOrgYuv->getStride(), 
                             pcTemplateCand->getLumaAddr(uiPartAddr), pcTemplateCand->getStride(), 
-#if NS_HAD
-                            iSizeX, iSizeY, m_pcEncCfg->getUseHADME(), m_pcEncCfg->getUseNSQT() );
-#else
                             iSizeX, iSizeY, m_pcEncCfg->getUseHADME() );
-#endif
   ruiDist = cDistParam.DistFunc( &cDistParam );
   uiCost = ruiDist + m_pcRdCost->getCost( m_auiMVPIdxCost[iMVPIdx][iMVPNum] );
 #else
-#if WEIGHTED_CHROMA_DISTORTION
   uiCost = m_pcRdCost->getDistPart(g_bitDepthY, pcTemplateCand->getLumaAddr(uiPartAddr), pcTemplateCand->getStride(), pcOrgYuv->getLumaAddr(uiPartAddr), pcOrgYuv->getStride(), iSizeX, iSizeY, TEXT_LUMA, DF_SAD );
-#else
-  uiCost = m_pcRdCost->getDistPart(g_bitDepthY, pcTemplateCand->getLumaAddr(uiPartAddr), pcTemplateCand->getStride(), pcOrgYuv->getLumaAddr(uiPartAddr), pcOrgYuv->getStride(), iSizeX, iSizeY, DF_SAD );
-#endif
   uiCost = (UInt) m_pcRdCost->calcRdCost( m_auiMVPIdxCost[iMVPIdx][iMVPNum], uiCost, false, DF_SAD );
 #endif
@@ -4228,24 +4203,18 @@
   m_pcRdCost->getMotionCost( 1, 0 );
   m_pcRdCost->setCostScale ( 1 );
-  
-  {
+
 #if REF_IDX_ME_ZEROMV
-    if( pcCU->getSlice()->getRefPic( eRefPicList, iRefIdxPred )->isILR(pcCU->getLayerId()))  //ILR reference pic
-    {
-      xPatternSearchFracDIFMv0( pcCU, pcPatternKey, piRefY, iRefStride, &rcMv, cMvHalf, cMvQter, ruiCost, bBi );
-    }
-    else    //non ILR reference pic
-    {
-      xPatternSearchFracDIF( pcCU, pcPatternKey, piRefY, iRefStride, &rcMv, cMvHalf, cMvQter, ruiCost, bBi );
-    }
+  if( pcCU->getSlice()->getRefPic( eRefPicList, iRefIdxPred )->isILR(pcCU->getLayerId()))  //ILR reference pic
+  {
+    xPatternSearchFracDIFMv0( pcCU, pcPatternKey, piRefY, iRefStride, &rcMv, cMvHalf, cMvQter, ruiCost, bBi );
+  }
+  else    //non ILR reference pic
+  {
+    xPatternSearchFracDIF( pcCU, pcPatternKey, piRefY, iRefStride, &rcMv, cMvHalf, cMvQter, ruiCost, bBi );
+  }
 #else
-    xPatternSearchFracDIF( pcCU, pcPatternKey, piRefY, iRefStride, &rcMv, cMvHalf, cMvQter, ruiCost
-                          ,bBi
-                          );
-#endif
-  }
-  
-  
-  
+  xPatternSearchFracDIF( pcCU, pcPatternKey, piRefY, iRefStride, &rcMv, cMvHalf, cMvQter, ruiCost,bBi );
+#endif
+
   m_pcRdCost->setCostScale( 0 );
   rcMv <<= 2;
@@ -4601,16 +4570,12 @@
     pcYuvPred->copyToPartYuv( rpcYuvRec, 0 );
     
-#if WEIGHTED_CHROMA_DISTORTION
     uiDistortion = m_pcRdCost->getDistPart(g_bitDepthY, rpcYuvRec->getLumaAddr(), rpcYuvRec->getStride(),  pcYuvOrg->getLumaAddr(), pcYuvOrg->getStride(),  uiWidth,      uiHeight      )
     + m_pcRdCost->getDistPart(g_bitDepthC, rpcYuvRec->getCbAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCbAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1, TEXT_CHROMA_U )
     + m_pcRdCost->getDistPart(g_bitDepthC, rpcYuvRec->getCrAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCrAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1, TEXT_CHROMA_V );
-#else
-    uiDistortion = m_pcRdCost->getDistPart(g_bitDepthY, rpcYuvRec->getLumaAddr(), rpcYuvRec->getStride(),  pcYuvOrg->getLumaAddr(), pcYuvOrg->getStride(),  uiWidth,      uiHeight      )
-    + m_pcRdCost->getDistPart(g_bitDepthC, rpcYuvRec->getCbAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCbAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1 )
-    + m_pcRdCost->getDistPart(g_bitDepthC, rpcYuvRec->getCrAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCrAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1 );
-#endif
 
     if( m_bUseSBACRD )
+    {
       m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_CURR_BEST]);
+    }
     
     m_pcEntropyCoder->resetBits();
@@ -4628,5 +4593,7 @@
     
     if( m_bUseSBACRD )
+    {
       m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_TEMP_BEST]);
+    }
     
     pcCU->setCbfSubParts( 0, 0, 0, 0, pcCU->getDepth( 0 ) );
@@ -4799,13 +4766,7 @@
   
   // update with clipped distortion and cost (qp estimation loop uses unclipped values)
-#if WEIGHTED_CHROMA_DISTORTION
     uiDistortionBest = m_pcRdCost->getDistPart(g_bitDepthY, rpcYuvRec->getLumaAddr(), rpcYuvRec->getStride(),  pcYuvOrg->getLumaAddr(), pcYuvOrg->getStride(),  uiWidth,      uiHeight      )
     + m_pcRdCost->getDistPart(g_bitDepthC, rpcYuvRec->getCbAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCbAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1, TEXT_CHROMA_U )
     + m_pcRdCost->getDistPart(g_bitDepthC, rpcYuvRec->getCrAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCrAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1, TEXT_CHROMA_V );
-#else
-  uiDistortionBest = m_pcRdCost->getDistPart(g_bitDepthY, rpcYuvRec->getLumaAddr(), rpcYuvRec->getStride(),  pcYuvOrg->getLumaAddr(), pcYuvOrg->getStride(),  uiWidth,      uiHeight      )
-  + m_pcRdCost->getDistPart(g_bitDepthC, rpcYuvRec->getCbAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCbAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1 )
-  + m_pcRdCost->getDistPart(g_bitDepthC, rpcYuvRec->getCrAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCrAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1 );
-#endif
   dCostBest = m_pcRdCost->calcRdCost( uiBitsBest, uiDistortionBest );
   
@@ -4832,7 +4793,11 @@
   Bool bCheckFull;
   if ( SplitFlag && uiDepth == pcCU->getDepth(uiAbsPartIdx) && ( uiLog2TrSize >  pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) ) )
+  {
      bCheckFull = false;
+  }
   else
+  {
      bCheckFull =  ( uiLog2TrSize <= pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() );
+  }
 
   const Bool bCheckSplit  = ( uiLog2TrSize >  pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) );
@@ -4932,5 +4897,5 @@
 
 #if RDOQ_CHROMA_LAMBDA 
-      m_pcTrQuant->selectLambda(TEXT_CHROMA); 
+      m_pcTrQuant->selectLambda(TEXT_CHROMA_U);
 #endif
 
@@ -4943,4 +4908,9 @@
       curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCrQpOffset() + pcCU->getSlice()->getSliceQpDeltaCr();
       m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
+      
+#if RDOQ_CHROMA_LAMBDA
+      m_pcTrQuant->selectLambda(TEXT_CHROMA_V);
+#endif
+
       m_pcTrQuant->transformNxN( pcCU, pcResi->getCrAddr(absTUPartIdxC), pcResi->getCStride(), pcCoeffCurrV, 
 #if ADAPTIVE_QP_SELECTION
@@ -4955,8 +4925,6 @@
     m_pcEntropyCoder->resetBits();
     
-    {
-      m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
-    }
-    
+    m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
+
     m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrY, uiAbsPartIdx,  trWidth,  trHeight,    uiDepth, TEXT_LUMA );
     const UInt uiSingleBitsY = m_pcEntropyCoder->getNumberOfWrittenBits();
@@ -4966,13 +4934,9 @@
     if( bCodeChroma )
     {
-      {
-        m_pcEntropyCoder->encodeQtCbf   ( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrMode );
-      }
+      m_pcEntropyCoder->encodeQtCbf   ( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrMode );
       m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrU, uiAbsPartIdx, trWidthC, trHeightC, uiDepth, TEXT_CHROMA_U );
       uiSingleBitsU = m_pcEntropyCoder->getNumberOfWrittenBits() - uiSingleBitsY;
       
-      {
-        m_pcEntropyCoder->encodeQtCbf   ( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrMode );
-      }
+      m_pcEntropyCoder->encodeQtCbf   ( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrMode );
       m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrV, uiAbsPartIdx, trWidthC, trHeightC, uiDepth, TEXT_CHROMA_V );
       uiSingleBitsV = m_pcEntropyCoder->getNumberOfWrittenBits() - ( uiSingleBitsY + uiSingleBitsU );
@@ -5003,4 +4967,5 @@
       assert(scalingListType < 6);     
       m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_LUMA,REG_DCT, pcResiCurrY, m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(),  pcCoeffCurrY, trWidth, trHeight, scalingListType );//this is for inter mode only
+      
       const UInt uiNonzeroDistY = m_pcRdCost->getDistPart(g_bitDepthY, m_pcQTTempTComYuv[uiQTTempAccessLayer].getLumaAddr( absTUPartIdx ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(),
       pcResi->getLumaAddr( absTUPartIdx ), pcResi->getStride(), trWidth,trHeight );
@@ -5059,7 +5024,5 @@
     {
       uiDistU = m_pcRdCost->getDistPart(g_bitDepthC, m_pTempPel, trWidthC, pcResi->getCbAddr( absTUPartIdxC ), pcResi->getCStride(), trWidthC, trHeightC
-#if WEIGHTED_CHROMA_DISTORTION
                                         , TEXT_CHROMA_U
-#endif
                                         ); // initialized with zero residual destortion
       if ( puiZeroDist )
@@ -5080,7 +5043,5 @@
         const UInt uiNonzeroDistU = m_pcRdCost->getDistPart(g_bitDepthC, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCbAddr( absTUPartIdxC), m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(),
                                                             pcResi->getCbAddr( absTUPartIdxC), pcResi->getCStride(), trWidthC, trHeightC
-#if WEIGHTED_CHROMA_DISTORTION
                                                             , TEXT_CHROMA_U
-#endif
                                                             );
 
@@ -5118,5 +5079,5 @@
       {
         m_pcEntropyCoder->resetBits();
-        m_pcEntropyCoder->encodeQtCbfZero( pcCU, TEXT_CHROMA_U, uiTrModeC );
+        m_pcEntropyCoder->encodeQtCbfZero( pcCU, TEXT_CHROMA_U, uiTrMode );
         const UInt uiNullBitsU = m_pcEntropyCoder->getNumberOfWrittenBits();
         minCostU = m_pcRdCost->calcRdCost( uiNullBitsU, uiDistU );
@@ -5134,7 +5095,5 @@
       
       uiDistV = m_pcRdCost->getDistPart(g_bitDepthC, m_pTempPel, trWidthC, pcResi->getCrAddr( absTUPartIdxC), pcResi->getCStride(), trWidthC, trHeightC
-#if WEIGHTED_CHROMA_DISTORTION
                                         , TEXT_CHROMA_V
-#endif
                                         ); // initialized with zero residual destortion
       if ( puiZeroDist )
@@ -5154,7 +5113,5 @@
         const UInt uiNonzeroDistV = m_pcRdCost->getDistPart(g_bitDepthC, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCrAddr( absTUPartIdxC ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(),
                                                             pcResi->getCrAddr( absTUPartIdxC ), pcResi->getCStride(), trWidthC, trHeightC
-#if WEIGHTED_CHROMA_DISTORTION
                                                             , TEXT_CHROMA_V
-#endif
                                                             );
         if (pcCU->isLosslessCoded(0)) 
@@ -5191,5 +5148,5 @@
       {
         m_pcEntropyCoder->resetBits();
-        m_pcEntropyCoder->encodeQtCbfZero( pcCU, TEXT_CHROMA_V, uiTrModeC );
+        m_pcEntropyCoder->encodeQtCbfZero( pcCU, TEXT_CHROMA_V, uiTrMode );
         const UInt uiNullBitsV = m_pcEntropyCoder->getNumberOfWrittenBits();
         minCostV = m_pcRdCost->calcRdCost( uiNullBitsV, uiDistV );
@@ -5352,5 +5309,5 @@
 
 #if RDOQ_CHROMA_LAMBDA 
-      m_pcTrQuant->selectLambda(TEXT_CHROMA); 
+      m_pcTrQuant->selectLambda(TEXT_CHROMA_U);
 #endif
 
@@ -5362,4 +5319,7 @@
       curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCrQpOffset() + pcCU->getSlice()->getSliceQpDeltaCr();
       m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
+#if RDOQ_CHROMA_LAMBDA
+      m_pcTrQuant->selectLambda(TEXT_CHROMA_V);
+#endif
       m_pcTrQuant->transformNxN( pcCU, pcResi->getCrAddr(absTUPartIdxC), pcResi->getCStride(), pcCoeffCurrV, 
 #if ADAPTIVE_QP_SELECTION
@@ -5391,7 +5351,5 @@
         uiNonzeroDistU = m_pcRdCost->getDistPart(g_bitDepthC, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCbAddr( absTUPartIdxC), m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(),
                                                  pcResi->getCbAddr( absTUPartIdxC), pcResi->getCStride(), trWidthC, trHeightC
-#if WEIGHTED_CHROMA_DISTORTION
                                                  , TEXT_CHROMA_U
-#endif
                                                  );
 
@@ -5435,7 +5393,5 @@
         uiNonzeroDistV = m_pcRdCost->getDistPart(g_bitDepthC, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCrAddr( absTUPartIdxC ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(),
                                                  pcResi->getCrAddr( absTUPartIdxC ), pcResi->getCStride(), trWidthC, trHeightC
-#if WEIGHTED_CHROMA_DISTORTION
                                                  , TEXT_CHROMA_V
-#endif
                                                  );
 
@@ -5474,20 +5430,16 @@
     m_pcEntropyCoder->resetBits();
 
-    {
-      if( uiLog2TrSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
-      {
-        m_pcEntropyCoder->encodeTransformSubdivFlag( 0, 5 - uiLog2TrSize );
-      }
-    }
-
-    {
-      if( bCodeChroma )
-      {
-        m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrMode );
-        m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrMode );
-      }
-
-      m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
-    }
+    if( uiLog2TrSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
+    {
+      m_pcEntropyCoder->encodeTransformSubdivFlag( 0, 5 - uiLog2TrSize );
+    }
+
+    if( bCodeChroma )
+    {
+      m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrMode );
+      m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrMode );
+    }
+
+    m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
 
     m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrY, uiAbsPartIdx, trWidth, trHeight,    uiDepth, TEXT_LUMA );
@@ -5546,11 +5498,9 @@
     m_pcEntropyCoder->resetBits();
     
-    {
-      xEncodeResidualQT( pcCU, uiAbsPartIdx, uiDepth, true,  TEXT_LUMA );
-      xEncodeResidualQT( pcCU, uiAbsPartIdx, uiDepth, false, TEXT_LUMA );
-      xEncodeResidualQT( pcCU, uiAbsPartIdx, uiDepth, false, TEXT_CHROMA_U );
-      xEncodeResidualQT( pcCU, uiAbsPartIdx, uiDepth, false, TEXT_CHROMA_V );
-    }
-    
+    xEncodeResidualQT( pcCU, uiAbsPartIdx, uiDepth, true,  TEXT_LUMA );
+    xEncodeResidualQT( pcCU, uiAbsPartIdx, uiDepth, false, TEXT_LUMA );
+    xEncodeResidualQT( pcCU, uiAbsPartIdx, uiDepth, false, TEXT_CHROMA_U );
+    xEncodeResidualQT( pcCU, uiAbsPartIdx, uiDepth, false, TEXT_CHROMA_V );
+
     uiSubdivBits = m_pcEntropyCoder->getNumberOfWrittenBits();
     dSubdivCost  = m_pcRdCost->calcRdCost( uiSubdivBits, uiSubdivDist );
@@ -5602,13 +5552,10 @@
   const UInt uiLog2TrSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiDepth]+2;
 
-  {
-    if( bSubdivAndCbf && uiLog2TrSize <= pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() && uiLog2TrSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
-    {
-      m_pcEntropyCoder->encodeTransformSubdivFlag( bSubdiv, 5 - uiLog2TrSize );
-    }
-  }
-
-  {
-    assert( pcCU->getPredictionMode(uiAbsPartIdx) != MODE_INTRA );
+  if( bSubdivAndCbf && uiLog2TrSize <= pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() && uiLog2TrSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
+  {
+    m_pcEntropyCoder->encodeTransformSubdivFlag( bSubdiv, 5 - uiLog2TrSize );
+  }
+
+  assert( pcCU->getPredictionMode(uiAbsPartIdx) != MODE_INTRA );
     if( bSubdivAndCbf )
     {
@@ -5631,5 +5578,4 @@
       }
     }
-  }
   
   if( !bSubdiv )
@@ -5655,7 +5601,5 @@
     if( bSubdivAndCbf )
     {
-      {
-        m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
-      }
+      m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
     }
     else
@@ -5725,7 +5669,5 @@
       if( bCodeChroma )
       {
-        {
-          m_pcQTTempTComYuv[uiQTTempAccessLayer].copyPartToPartChroma( pcResi, uiAbsPartIdx, 1 << uiLog2TrSizeC, 1 << uiLog2TrSizeC );
-        }
+        m_pcQTTempTComYuv[uiQTTempAccessLayer].copyPartToPartChroma( pcResi, uiAbsPartIdx, 1 << uiLog2TrSizeC, 1 << uiLog2TrSizeC );
       }
     }
@@ -5847,5 +5789,4 @@
     m_pcEntropyCoder->encodePartSize( pcCU, 0, pcCU->getDepth(0), true );
     m_pcEntropyCoder->encodePredInfo( pcCU, 0, true );
-
     Bool bDummy = false;
     m_pcEntropyCoder->encodeCoeff   ( pcCU, 0, pcCU->getDepth(0), pcCU->getWidth(0), pcCU->getHeight(0), bDummy );
Index: trunk/source/Lib/TLibEncoder/TEncSearch.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSearch.h	(revision 494)
+++ trunk/source/Lib/TLibEncoder/TEncSearch.h	(revision 540)
@@ -194,4 +194,5 @@
                                   UInt        uiPreCalcDistC );
   
+  
   /// encoder estimation - inter prediction (non-skip)
   Void predInterSearch          ( TComDataCU* pcCU,
Index: trunk/source/Lib/TLibEncoder/TEncSlice.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 494)
+++ trunk/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 540)
@@ -295,10 +295,4 @@
     dQP += pdQPs[ rpcSlice->getPOC() ];
   }
-#if !RATE_CONTROL_LAMBDA_DOMAIN
-  if ( m_pcCfg->getUseRateCtrl())
-  {
-    dQP = m_pcRateCtrl->getFrameQP(rpcSlice->isReferenced(), rpcSlice->getPOC());
-  }
-#endif
   // ------------------------------------------------------------------------------------------------------------------
   // Lambda computation
@@ -386,8 +380,7 @@
   // store lambda
   m_pcRdCost ->setLambda( dLambda );
-#if WEIGHTED_CHROMA_DISTORTION
 // for RDO
   // in RdCost there is only one lambda because the luma and chroma bits are not separated, instead we weight the distortion of chroma.
-  Double weight = 1.0;
+  Double weight[2] = { 1.0, 1.0 };
   Int qpc;
   Int chromaQPOffset;
@@ -395,33 +388,36 @@
   chromaQPOffset = rpcSlice->getPPS()->getChromaCbQpOffset() + rpcSlice->getSliceQpDeltaCb();
   qpc = Clip3( 0, 57, iQP + chromaQPOffset);
-  weight = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
-  m_pcRdCost->setCbDistortionWeight(weight);
+  weight[0] = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+  m_pcRdCost->setCbDistortionWeight(weight[0]);
 
   chromaQPOffset = rpcSlice->getPPS()->getChromaCrQpOffset() + rpcSlice->getSliceQpDeltaCr();
   qpc = Clip3( 0, 57, iQP + chromaQPOffset);
-  weight = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+  weight[1] = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+  m_pcRdCost->setCrDistortionWeight(weight[1]);
+
 #if JCTVC_M0259_LAMBDAREFINEMENT
   if( rpcSlice->getLayerId() > 0 && m_ppcTEncTop[layerId]->getNumActiveRefLayers() && m_pcCfg->getGOPSize() >= 8 && rpcSlice->isIntra() == false && depth == 0 )
   {
     dLambda *= 1.1;
-    weight *= 1.15;
-  }
-#endif
-  m_pcRdCost->setCrDistortionWeight(weight);
-#endif
-
+    weight[1] *= 1.15;
+    weight[0] *= 1.15;
+
+    m_pcRdCost ->setLambda( dLambda );
+    m_pcRdCost->setCbDistortionWeight(weight[0]);
+    m_pcRdCost->setCrDistortionWeight(weight[1]);
+  }
+#endif
+
+  const Double lambdaArray[3] = {dLambda, (dLambda / weight[0]), (dLambda / weight[1])};
+ 
 #if RDOQ_CHROMA_LAMBDA
 // for RDOQ
-  m_pcTrQuant->setLambda( dLambda, dLambda / weight );
+  m_pcTrQuant->setLambdas( lambdaArray );
 #else
   m_pcTrQuant->setLambda( dLambda );
 #endif
 
-#if SAO_CHROMA_LAMBDA
 // For SAO
-  rpcSlice   ->setLambda( dLambda, dLambda / weight );
-#else
-  rpcSlice   ->setLambda( dLambda );
-#endif
+  rpcSlice->setLambdas( lambdaArray );
 
 #if HB_LAMBDA_FOR_LDC
@@ -430,5 +426,5 @@
 
 #if SVC_EXTENSION
-  if(m_pcCfg->getLayerId() > 0)
+  if( m_pcCfg->getLayerId() > 0 && m_pcCfg->getNumActiveRefLayers() > 0 )
   {
     eSliceType=B_SLICE;
@@ -500,5 +496,4 @@
 
   pcPic->setTLayer( m_pcCfg->getGOPEntry(iGOPid).m_temporalId );
-
   if(eSliceType==I_SLICE)
   {
@@ -517,4 +512,10 @@
   rpcSlice->setSliceSegmentArgument ( m_pcCfg->getSliceSegmentArgument() );
   rpcSlice->setMaxNumMergeCand        ( m_pcCfg->getMaxNumMergeCand()        );
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+  if (m_pcCfg->getSkipPictureAtArcSwitch() && m_pcCfg->getAdaptiveResolutionChange() > 0 && rpcSlice->getLayerId() == 1 && rpcSlice->getPOC() == m_pcCfg->getAdaptiveResolutionChange())
+  {
+    rpcSlice->setMaxNumMergeCand        ( 1 );
+  }
+#endif
   xStoreWPparam( pPPS->getUseWP(), pPPS->getWPBiPred() );
 
@@ -546,5 +547,4 @@
 }
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
 Void TEncSlice::resetQP( TComPic* pic, Int sliceQP, Double lambda )
 {
@@ -555,8 +555,7 @@
   slice->setSliceQpBase ( sliceQP );
   m_pcRdCost ->setLambda( lambda );
-#if WEIGHTED_CHROMA_DISTORTION
   // for RDO
   // in RdCost there is only one lambda because the luma and chroma bits are not separated, instead we weight the distortion of chroma.
-  Double weight;
+  Double weight[2] = { 1.0, 1.0 };
   Int qpc;
   Int chromaQPOffset;
@@ -564,136 +563,24 @@
   chromaQPOffset = slice->getPPS()->getChromaCbQpOffset() + slice->getSliceQpDeltaCb();
   qpc = Clip3( 0, 57, sliceQP + chromaQPOffset);
-  weight = pow( 2.0, (sliceQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
-  m_pcRdCost->setCbDistortionWeight(weight);
+  weight[0] = pow( 2.0, (sliceQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+  m_pcRdCost->setCbDistortionWeight(weight[0]);
 
   chromaQPOffset = slice->getPPS()->getChromaCrQpOffset() + slice->getSliceQpDeltaCr();
   qpc = Clip3( 0, 57, sliceQP + chromaQPOffset);
-  weight = pow( 2.0, (sliceQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
-  m_pcRdCost->setCrDistortionWeight(weight);
-#endif
+  weight[1] = pow( 2.0, (sliceQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+  m_pcRdCost->setCrDistortionWeight(weight[1]);
+
+  const Double lambdaArray[3] = {lambda, (lambda / weight[0]), (lambda / weight[1])};
 
 #if RDOQ_CHROMA_LAMBDA
   // for RDOQ
-  m_pcTrQuant->setLambda( lambda, lambda / weight );
+  m_pcTrQuant->setLambdas( lambdaArray );
 #else
   m_pcTrQuant->setLambda( lambda );
 #endif
 
-#if SAO_CHROMA_LAMBDA
   // For SAO
-  slice   ->setLambda( lambda, lambda / weight );
-#else
-  slice   ->setLambda( lambda );
-#endif
+  slice->setLambdas( lambdaArray );
 }
-#else
-/**
- - lambda re-computation based on rate control QP
- */
-Void TEncSlice::xLamdaRecalculation(Int changeQP, Int idGOP, Int depth, SliceType eSliceType, TComSPS* pcSPS, TComSlice* pcSlice)
-{
-  Int qp;
-  Double recalQP= (Double)changeQP;
-  Double origQP = (Double)recalQP;
-  Double lambda;
-
-  // pre-compute lambda and QP values for all possible QP candidates
-  for ( Int deltqQpIdx = 0; deltqQpIdx < 2 * m_pcCfg->getDeltaQpRD() + 1; deltqQpIdx++ )
-  {
-    // compute QP value
-    recalQP = origQP + ((deltqQpIdx+1)>>1)*(deltqQpIdx%2 ? -1 : 1);
-
-    // compute lambda value
-    Int    NumberBFrames = ( m_pcCfg->getGOPSize() - 1 );
-    Int    SHIFT_QP = 12;
-    Double dLambda_scale = 1.0 - Clip3( 0.0, 0.5, 0.05*(Double)NumberBFrames );
-#if FULL_NBIT
-    Int    bitdepth_luma_qp_scale = 6 * (g_bitDepth - 8);
-#else
-    Int    bitdepth_luma_qp_scale = 0;
-#endif
-    Double qp_temp = (Double) recalQP + bitdepth_luma_qp_scale - SHIFT_QP;
-#if FULL_NBIT
-    Double qp_temp_orig = (Double) recalQP - SHIFT_QP;
-#endif
-    // Case #1: I or P-slices (key-frame)
-    Double dQPFactor = m_pcCfg->getGOPEntry(idGOP).m_QPFactor;
-    if ( eSliceType==I_SLICE )
-    {
-      dQPFactor=0.57*dLambda_scale;
-    }
-    lambda = dQPFactor*pow( 2.0, qp_temp/3.0 );
-
-    if ( depth>0 )
-    {
-#if FULL_NBIT
-      lambda *= Clip3( 2.00, 4.00, (qp_temp_orig / 6.0) ); // (j == B_SLICE && p_cur_frm->layer != 0 )
-#else
-      lambda *= Clip3( 2.00, 4.00, (qp_temp / 6.0) ); // (j == B_SLICE && p_cur_frm->layer != 0 )
-#endif
-    }
-
-    // if hadamard is used in ME process
-    if ( !m_pcCfg->getUseHADME() )
-    {
-      lambda *= 0.95;
-    }
-
-#if REPN_FORMAT_IN_VPS
-    qp = max( -pcSlice->getQpBDOffsetY(), min( MAX_QP, (Int) floor( recalQP + 0.5 ) ) );
-#else
-    qp = max( -pcSPS->getQpBDOffsetY(), min( MAX_QP, (Int) floor( recalQP + 0.5 ) ) );
-#endif
-
-    m_pdRdPicLambda[deltqQpIdx] = lambda;
-    m_pdRdPicQp    [deltqQpIdx] = recalQP;
-    m_piRdPicQp    [deltqQpIdx] = qp;
-  }
-
-  // obtain dQP = 0 case
-  lambda  = m_pdRdPicLambda[0];
-  recalQP = m_pdRdPicQp    [0];
-  qp      = m_piRdPicQp    [0];
-
-  if( pcSlice->getSliceType( ) != I_SLICE )
-  {
-    lambda *= m_pcCfg->getLambdaModifier( depth );
-  }
-
-  // store lambda
-  m_pcRdCost ->setLambda( lambda );
-#if WEIGHTED_CHROMA_DISTORTION
-  // for RDO
-  // in RdCost there is only one lambda because the luma and chroma bits are not separated, instead we weight the distortion of chroma.
-  Double weight = 1.0;
-  Int qpc;
-  Int chromaQPOffset;
-
-  chromaQPOffset = pcSlice->getPPS()->getChromaCbQpOffset() + pcSlice->getSliceQpDeltaCb();
-  qpc = Clip3( 0, 57, qp + chromaQPOffset);
-  weight = pow( 2.0, (qp-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
-  m_pcRdCost->setCbDistortionWeight(weight);
-
-  chromaQPOffset = pcSlice->getPPS()->getChromaCrQpOffset() + pcSlice->getSliceQpDeltaCr();
-  qpc = Clip3( 0, 57, qp + chromaQPOffset);
-  weight = pow( 2.0, (qp-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
-  m_pcRdCost->setCrDistortionWeight(weight);
-#endif
-
-#if RDOQ_CHROMA_LAMBDA
-  // for RDOQ
-  m_pcTrQuant->setLambda( lambda, lambda / weight );
-#else
-  m_pcTrQuant->setLambda( lambda );
-#endif
-
-#if SAO_CHROMA_LAMBDA
-  // For SAO
-  pcSlice   ->setLambda( lambda, lambda / weight );
-#else
-  pcSlice   ->setLambda( lambda );
-#endif
-}
-#endif
 // ====================================================================================================================
 // Public member functions
@@ -735,5 +622,4 @@
   }
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
   if ( m_pcCfg->getUseRateCtrl() )
   {
@@ -741,5 +627,4 @@
     assert(0);
   }
-#endif
 
   TComSlice* pcSlice        = rpcPic->getSlice(getSliceIdx());
@@ -773,9 +658,8 @@
 #endif
     m_pcRdCost    ->setLambda              ( m_pdRdPicLambda[uiQpIdx] );
-#if WEIGHTED_CHROMA_DISTORTION
     // for RDO
     // in RdCost there is only one lambda because the luma and chroma bits are not separated, instead we weight the distortion of chroma.
     Int iQP = m_piRdPicQp    [uiQpIdx];
-    Double weight = 1.0;
+    Double weight[2] = { 1.0, 1.0 };
     Int qpc;
     Int chromaQPOffset;
@@ -783,25 +667,21 @@
     chromaQPOffset = pcSlice->getPPS()->getChromaCbQpOffset() + pcSlice->getSliceQpDeltaCb();
     qpc = Clip3( 0, 57, iQP + chromaQPOffset);
-    weight = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
-    m_pcRdCost->setCbDistortionWeight(weight);
+    weight[0] = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+    m_pcRdCost->setCbDistortionWeight(weight[0]);
 
     chromaQPOffset = pcSlice->getPPS()->getChromaCrQpOffset() + pcSlice->getSliceQpDeltaCr();
     qpc = Clip3( 0, 57, iQP + chromaQPOffset);
-    weight = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
-    m_pcRdCost->setCrDistortionWeight(weight);
-#endif
-
+    weight[1] = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+    m_pcRdCost->setCrDistortionWeight(weight[1]);
+
+    const Double lambdaArray[3] = {m_pdRdPicLambda[uiQpIdx], (m_pdRdPicLambda[uiQpIdx] / weight[0]), (m_pdRdPicLambda[uiQpIdx] / weight[1])};
 #if RDOQ_CHROMA_LAMBDA
     // for RDOQ
-    m_pcTrQuant   ->setLambda( m_pdRdPicLambda[uiQpIdx], m_pdRdPicLambda[uiQpIdx] / weight );
+    m_pcTrQuant->setLambdas( lambdaArray );
 #else
     m_pcTrQuant   ->setLambda              ( m_pdRdPicLambda[uiQpIdx] );
 #endif
-#if SAO_CHROMA_LAMBDA
     // For SAO
-    pcSlice       ->setLambda              ( m_pdRdPicLambda[uiQpIdx], m_pdRdPicLambda[uiQpIdx] / weight );
-#else
-    pcSlice       ->setLambda              ( m_pdRdPicLambda[uiQpIdx] );
-#endif
+    pcSlice->setLambdas( lambdaArray );
 
     // try compress
@@ -830,8 +710,7 @@
 #endif
   m_pcRdCost    ->setLambda              ( m_pdRdPicLambda[uiQpIdxBest] );
-#if WEIGHTED_CHROMA_DISTORTION
   // in RdCost there is only one lambda because the luma and chroma bits are not separated, instead we weight the distortion of chroma.
   Int iQP = m_piRdPicQp    [uiQpIdxBest];
-  Double weight = 1.0;
+  Double weight[2] = { 1.0, 1.0 };
   Int qpc;
   Int chromaQPOffset;
@@ -839,30 +718,25 @@
   chromaQPOffset = pcSlice->getPPS()->getChromaCbQpOffset() + pcSlice->getSliceQpDeltaCb();
   qpc = Clip3( 0, 57, iQP + chromaQPOffset);
-  weight = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
-  m_pcRdCost->setCbDistortionWeight(weight);
+  weight[0] = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+  m_pcRdCost->setCbDistortionWeight(weight[0]);
 
   chromaQPOffset = pcSlice->getPPS()->getChromaCrQpOffset() + pcSlice->getSliceQpDeltaCr();
   qpc = Clip3( 0, 57, iQP + chromaQPOffset);
-  weight = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
-  m_pcRdCost->setCrDistortionWeight(weight);
-#endif
-
+  weight[1] = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+  m_pcRdCost->setCrDistortionWeight(weight[1]);
+
+  const Double lambdaArray[3] = {m_pdRdPicLambda[uiQpIdxBest], (m_pdRdPicLambda[uiQpIdxBest] / weight[0]), (m_pdRdPicLambda[uiQpIdxBest] / weight[1])};
 #if RDOQ_CHROMA_LAMBDA
   // for RDOQ
-  m_pcTrQuant   ->setLambda( m_pdRdPicLambda[uiQpIdxBest], m_pdRdPicLambda[uiQpIdxBest] / weight );
+  m_pcTrQuant->setLambdas( lambdaArray );
 #else
   m_pcTrQuant   ->setLambda              ( m_pdRdPicLambda[uiQpIdxBest] );
 #endif
-#if SAO_CHROMA_LAMBDA
   // For SAO
-  pcSlice       ->setLambda              ( m_pdRdPicLambda[uiQpIdxBest], m_pdRdPicLambda[uiQpIdxBest] / weight );
-#else
-  pcSlice       ->setLambda              ( m_pdRdPicLambda[uiQpIdxBest] );
-#endif
+  pcSlice->setLambdas( lambdaArray );
 }
 
 /** \param rpcPic   picture class
  */
-#if RATE_CONTROL_INTRA
 Void TEncSlice::calCostSliceI(TComPic*& rpcPic)
 {
@@ -903,5 +777,4 @@
   m_pcRateCtrl->getRCPic()->setTotalIntraCost(iSumHadSlice);
 }
-#endif
 
 Void TEncSlice::compressSlice( TComPic*& rpcPic )
@@ -1031,5 +904,4 @@
   UInt uiTileStartLCU = 0;
   UInt uiTileLCUX     = 0;
-
   Bool depSliceSegmentsEnabled = pcSlice->getPPS()->getDependentSliceSegmentsEnabledFlag();
   uiCUAddr = rpcPic->getPicSym()->getCUOrderMap( uiStartCUAddr /rpcPic->getNumPartInCU());
@@ -1080,13 +952,4 @@
     pcCU->initCU( rpcPic, uiCUAddr );
 
-#if !RATE_CONTROL_LAMBDA_DOMAIN
-    if(m_pcCfg->getUseRateCtrl())
-    {
-      if(m_pcRateCtrl->calculateUnitQP())
-      {
-        xLamdaRecalculation(m_pcRateCtrl->getUnitQP(), m_pcRateCtrl->getGOPId(), pcSlice->getDepth(), pcSlice->getSliceType(), pcSlice->getSPS(), pcSlice );
-      }
-    }
-#endif
     // inherit from TR if necessary, select substream to use.
     if( m_pcCfg->getUseSBACRD() )
@@ -1163,5 +1026,4 @@
       ((TEncBinCABAC*)m_pcRDGoOnSbacCoder->getEncBinIf())->setBinCountingEnableFlag(true);
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
       Double oldLambda = m_pcRdCost->getLambda();
       if ( m_pcCfg->getUseRateCtrl() )
@@ -1171,9 +1033,5 @@
         Double bpp       = -1.0;
 
-#if M0036_RC_IMPROVEMENT
         if ( ( rpcPic->getSlice( 0 )->getSliceType() == I_SLICE && m_pcCfg->getForceIntraQP() ) || !m_pcCfg->getLCULevelRC() )
-#else
-        if ( rpcPic->getSlice( 0 )->getSliceType() == I_SLICE || !m_pcCfg->getLCULevelRC() )
-#endif
         {
           estQP = pcSlice->getSliceQp();
@@ -1181,5 +1039,4 @@
         else
         {
-#if RATE_CONTROL_INTRA
           bpp = m_pcRateCtrl->getRCPic()->getLCUTargetBpp(pcSlice->getSliceType());
           if ( rpcPic->getSlice( 0 )->getSliceType() == I_SLICE)
@@ -1192,9 +1049,4 @@
             estQP     = m_pcRateCtrl->getRCPic()->getLCUEstQP    ( estLambda, pcSlice->getSliceQp() );
           }
-#else
-          bpp       = m_pcRateCtrl->getRCPic()->getLCUTargetBpp();
-          estLambda = m_pcRateCtrl->getRCPic()->getLCUEstLambda( bpp );
-          estQP     = m_pcRateCtrl->getRCPic()->getLCUEstQP    ( estLambda, pcSlice->getSliceQp() );
-#endif
 
 #if REPN_FORMAT_IN_VPS
@@ -1205,12 +1057,11 @@
 
           m_pcRdCost->setLambda(estLambda);
-#if M0036_RC_IMPROVEMENT
 #if RDOQ_CHROMA_LAMBDA
           // set lambda for RDOQ
           Double weight=m_pcRdCost->getChromaWeight();
-          m_pcTrQuant->setLambda( estLambda, estLambda / weight );
+          const Double lambdaArray[3] = { estLambda, (estLambda / weight), (estLambda / weight) };
+          m_pcTrQuant->setLambdas( lambdaArray );
 #else
           m_pcTrQuant->setLambda( estLambda );
-#endif
 #endif
         }
@@ -1219,58 +1070,7 @@
         pcCU->getSlice()->setSliceQpBase( estQP );
       }
-#endif
 
       // run CU encoder
       m_pcCuEncoder->compressCU( pcCU );
-
-#if !TICKET_1090_FIX
-#if RATE_CONTROL_LAMBDA_DOMAIN
-      if ( m_pcCfg->getUseRateCtrl() )
-      {
-#if !M0036_RC_IMPROVEMENT
-        UInt SAD    = m_pcCuEncoder->getLCUPredictionSAD();
-#if REPN_FORMAT_IN_VPS
-        Int height  = min( pcSlice->getSPS()->getMaxCUHeight(),pcSlice->getPicHeightInLumaSamples() - uiCUAddr / rpcPic->getFrameWidthInCU() * pcSlice->getSPS()->getMaxCUHeight() );
-        Int width   = min( pcSlice->getSPS()->getMaxCUWidth(),pcSlice->>getPicWidthInLumaSamples() - uiCUAddr % rpcPic->getFrameWidthInCU() * pcSlice->getSPS()->getMaxCUWidth() );
-#else
-        Int height  = min( pcSlice->getSPS()->getMaxCUHeight(),pcSlice->getSPS()->getPicHeightInLumaSamples() - uiCUAddr / rpcPic->getFrameWidthInCU() * pcSlice->getSPS()->getMaxCUHeight() );
-        Int width   = min( pcSlice->getSPS()->getMaxCUWidth(),pcSlice->getSPS()->getPicWidthInLumaSamples() - uiCUAddr % rpcPic->getFrameWidthInCU() * pcSlice->getSPS()->getMaxCUWidth() );
-#endif
-        Double MAD = (Double)SAD / (Double)(height * width);
-        MAD = MAD * MAD;
-        ( m_pcRateCtrl->getRCPic()->getLCU(uiCUAddr) ).m_MAD = MAD;
-#endif
-
-        Int actualQP        = g_RCInvalidQPValue;
-        Double actualLambda = m_pcRdCost->getLambda();
-        Int actualBits      = pcCU->getTotalBits();
-        Int numberOfEffectivePixels    = 0;
-        for ( Int idx = 0; idx < rpcPic->getNumPartInCU(); idx++ )
-        {
-          if ( pcCU->getPredictionMode( idx ) != MODE_NONE && ( !pcCU->isSkipped( idx ) ) )
-          {
-            numberOfEffectivePixels = numberOfEffectivePixels + 16;
-            break;
-          }
-        }
-
-        if ( numberOfEffectivePixels == 0 )
-        {
-          actualQP = g_RCInvalidQPValue;
-        }
-        else
-        {
-          actualQP = pcCU->getQP( 0 );
-        }
-        m_pcRdCost->setLambda(oldLambda);
-#if RATE_CONTROL_INTRA
-        m_pcRateCtrl->getRCPic()->updateAfterLCU( m_pcRateCtrl->getRCPic()->getLCUCoded(), actualBits, actualQP, actualLambda,
-          pcCU->getSlice()->getSliceType() == I_SLICE ? 0 : m_pcCfg->getLCULevelRC() );
-#else
-        m_pcRateCtrl->getRCPic()->updateAfterLCU( m_pcRateCtrl->getRCPic()->getLCUCoded(), actualBits, actualQP, actualLambda, m_pcCfg->getLCULevelRC() );
-#endif
-      }
-#endif
-#endif
 
       // restore entropy coder to an initial stage
@@ -1306,21 +1106,6 @@
       }
 
-#if TICKET_1090_FIX
-#if RATE_CONTROL_LAMBDA_DOMAIN
       if ( m_pcCfg->getUseRateCtrl() )
       {
-#if !M0036_RC_IMPROVEMENT
-        UInt SAD    = m_pcCuEncoder->getLCUPredictionSAD();
-#if REPN_FORMAT_IN_VPS
-        Int height  = min( pcSlice->getSPS()->getMaxCUHeight(),pcSlice->getPicHeightInLumaSamples() - uiCUAddr / rpcPic->getFrameWidthInCU() * pcSlice->getSPS()->getMaxCUHeight() );
-        Int width   = min( pcSlice->getSPS()->getMaxCUWidth(),pcSlice->getPicWidthInLumaSamples() - uiCUAddr % rpcPic->getFrameWidthInCU() * pcSlice->getSPS()->getMaxCUWidth() );
-#else
-        Int height  = min( pcSlice->getSPS()->getMaxCUHeight(),pcSlice->getSPS()->getPicHeightInLumaSamples() - uiCUAddr / rpcPic->getFrameWidthInCU() * pcSlice->getSPS()->getMaxCUHeight() );
-        Int width   = min( pcSlice->getSPS()->getMaxCUWidth(),pcSlice->getSPS()->getPicWidthInLumaSamples() - uiCUAddr % rpcPic->getFrameWidthInCU() * pcSlice->getSPS()->getMaxCUWidth() );
-#endif
-        Double MAD = (Double)SAD / (Double)(height * width);
-        MAD = MAD * MAD;
-        ( m_pcRateCtrl->getRCPic()->getLCU(uiCUAddr) ).m_MAD = MAD;
-#endif
 
         Int actualQP        = g_RCInvalidQPValue;
@@ -1347,13 +1132,7 @@
         m_pcRdCost->setLambda(oldLambda);
 
-#if RATE_CONTROL_INTRA
         m_pcRateCtrl->getRCPic()->updateAfterLCU( m_pcRateCtrl->getRCPic()->getLCUCoded(), actualBits, actualQP, actualLambda,
           pcCU->getSlice()->getSliceType() == I_SLICE ? 0 : m_pcCfg->getLCULevelRC() );
-#else
-        m_pcRateCtrl->getRCPic()->updateAfterLCU( m_pcRateCtrl->getRCPic()->getLCUCoded(), actualBits, actualQP, actualLambda, m_pcCfg->getLCULevelRC() );
-#endif
-      }
-#endif
-#endif
+      }
     }
     // other case: encodeCU is not called
@@ -1377,11 +1156,4 @@
     m_dPicRdCost     += pcCU->getTotalCost();
     m_uiPicDist      += pcCU->getTotalDistortion();
-#if !RATE_CONTROL_LAMBDA_DOMAIN
-    if(m_pcCfg->getUseRateCtrl())
-    {
-      m_pcRateCtrl->updateLCUData(pcCU, pcCU->getTotalBits(), pcCU->getQP(0));
-      m_pcRateCtrl->updataRCUnitStatus();
-    }
-#endif
   }
   if ((pcSlice->getPPS()->getNumSubstreams() > 1) && !depSliceSegmentsEnabled)
@@ -1398,10 +1170,4 @@
   }
   xRestoreWPparam( pcSlice );
-#if !RATE_CONTROL_LAMBDA_DOMAIN
-  if(m_pcCfg->getUseRateCtrl())
-  {
-    m_pcRateCtrl->updateFrameData(m_uiPicTotalBits);
-  }
-#endif
 }
 
@@ -1603,4 +1369,34 @@
 
     TComDataCU*& pcCU = rpcPic->getCU( uiCUAddr );
+#if HM_CLEANUP_SAO
+    if ( pcSlice->getSPS()->getUseSAO() )
+    {
+      if (pcSlice->getSaoEnabledFlag()||pcSlice->getSaoEnabledFlagChroma())
+      {
+        SAOBlkParam& saoblkParam = (rpcPic->getPicSym()->getSAOBlkParam())[uiCUAddr];
+        Bool sliceEnabled[NUM_SAO_COMPONENTS];
+        sliceEnabled[SAO_Y] = pcSlice->getSaoEnabledFlag();
+        sliceEnabled[SAO_Cb]= sliceEnabled[SAO_Cr]= pcSlice->getSaoEnabledFlagChroma();
+
+        Bool leftMergeAvail = false;
+        Bool aboveMergeAvail= false;
+        //merge left condition
+        Int rx = (uiCUAddr % uiWidthInLCUs);
+        if(rx > 0)
+        {
+          leftMergeAvail = rpcPic->getSAOMergeAvailability(uiCUAddr, uiCUAddr-1);
+        }
+
+        //merge up condition
+        Int ry = (uiCUAddr / uiWidthInLCUs);
+        if(ry > 0)
+        {
+          aboveMergeAvail = rpcPic->getSAOMergeAvailability(uiCUAddr, uiCUAddr-uiWidthInLCUs);
+        }
+
+        m_pcEntropyCoder->encodeSAOBlkParam(saoblkParam,sliceEnabled, leftMergeAvail, aboveMergeAvail);
+      }
+    }
+#else
     if ( pcSlice->getSPS()->getUseSAO() && (pcSlice->getSaoEnabledFlag()||pcSlice->getSaoEnabledFlagChroma()) )
     {
@@ -1685,4 +1481,6 @@
       }
     }
+#endif
+
 #if ENC_DEC_TRACE
     g_bJustDoIt = g_bEncDecTraceEnable;
Index: trunk/source/Lib/TLibEncoder/TEncSlice.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSlice.h	(revision 494)
+++ trunk/source/Lib/TLibEncoder/TEncSlice.h	(revision 540)
@@ -131,15 +131,9 @@
 #endif
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
   Void    resetQP             ( TComPic* pic, Int sliceQP, Double lambda );
-#else
-  Void    xLamdaRecalculation ( Int changeQP, Int idGOP, Int depth, SliceType eSliceType, TComSPS* pcSPS, TComSlice* pcSlice);
-#endif
   // compress and encode slice
   Void    precompressSlice    ( TComPic*& rpcPic                                );      ///< precompress slice for multi-loop opt.
   Void    compressSlice       ( TComPic*& rpcPic                                );      ///< analysis stage of slice
-#if RATE_CONTROL_INTRA
   Void    calCostSliceI       ( TComPic*& rpcPic );
-#endif
   Void    encodeSlice         ( TComPic*& rpcPic, TComOutputBitstream* pcSubstreams  );
   
Index: trunk/source/Lib/TLibEncoder/TEncTop.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncTop.cpp	(revision 494)
+++ trunk/source/Lib/TLibEncoder/TEncTop.cpp	(revision 540)
@@ -92,4 +92,10 @@
   m_pocAdjustmentValue     = 0;
 #endif
+#if NO_CLRAS_OUTPUT_FLAG
+  m_noClrasOutputFlag          = false;
+  m_layerInitializedFlag       = false;
+  m_firstPicInLayerDecodedFlag = false;
+  m_noOutputOfPriorPicsFlags   = false;
+#endif
 #endif //SVC_EXTENSION
 }
@@ -123,4 +129,16 @@
   if (m_bUseSAO)
   {
+#if HM_CLEANUP_SAO
+#if AUXILIARY_PICTURES
+    m_cEncSAO.create( getSourceWidth(), getSourceHeight(), m_chromaFormatIDC, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+#else
+    m_cEncSAO.create( getSourceWidth(), getSourceHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+#endif
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+    m_cEncSAO.createEncData(getSaoLcuBoundary());
+#else
+    m_cEncSAO.createEncData();
+#endif
+#else
     m_cEncSAO.setSaoLcuBoundary(getSaoLcuBoundary());
     m_cEncSAO.setSaoLcuBasedOptimization(getSaoLcuBasedOptimization());
@@ -128,4 +146,5 @@
     m_cEncSAO.create( getSourceWidth(), getSourceHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight );
     m_cEncSAO.createEncBuffer();
+#endif
   }
 #if ADAPTIVE_QP_SELECTION
@@ -137,5 +156,4 @@
   m_cLoopFilter.        create( g_uiMaxCUDepth );
   
-#if RATE_CONTROL_LAMBDA_DOMAIN
   if ( m_RCEnableRateControl )
   {
@@ -143,7 +161,4 @@
                       g_uiMaxCUWidth, g_uiMaxCUHeight, m_RCKeepHierarchicalBit, m_RCUseLCUSeparateModel, m_GOPList );
   }
-#else
-  m_cRateCtrl.create(getIntraPeriod(), getGOPSize(), getFrameRate(), getTargetBitrate(), getQP(), getNumLCUInUnit(), getSourceWidth(), getSourceHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight);
-#endif
   // if SBAC-based RD optimization is used
   if( m_bUseSBACRD )
@@ -244,6 +259,11 @@
   if (m_cSPS.getUseSAO())
   {
+#if HM_CLEANUP_SAO
+    m_cEncSAO.destroyEncData();
+    m_cEncSAO.destroy();
+#else
     m_cEncSAO.destroy();
     m_cEncSAO.destroyEncBuffer();
+#endif
   }
   m_cLoopFilter.        destroy();
@@ -395,5 +415,4 @@
 {
   // compress GOP
-#if RATE_CONTROL_LAMBDA_DOMAIN
 #if !RC_SHVC_HARMONIZATION
   if ( m_RCEnableRateControl )
@@ -402,10 +421,8 @@
   }
 #endif
-#endif
 
   // compress GOP
   m_cGOPEncoder.compressGOP(iPicIdInGOP, m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, false, false);
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
 #if !RC_SHVC_HARMONIZATION
   if ( m_RCEnableRateControl )
@@ -413,5 +430,4 @@
     m_cRateCtrl.destroyRCGOP();
   }
-#endif
 #endif
   
@@ -457,10 +473,8 @@
   }
   
-#if RATE_CONTROL_LAMBDA_DOMAIN
   if ( m_RCEnableRateControl )
   {
     m_cRateCtrl.initRCGOP( m_iNumPicRcvd );
   }
-#endif
 
   // compress GOP
@@ -468,10 +482,8 @@
   m_cGOPEncoder.compressGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, false, false);
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
   if ( m_RCEnableRateControl )
   {
     m_cRateCtrl.destroyRCGOP();
   }
-#endif
   
   iNumEncoded         = m_iNumPicRcvd;
@@ -513,5 +525,7 @@
     TComPic *pcTopField;
     xGetNewPicBuffer( pcTopField );
+#if !HM_CLEANUP_SAO
     pcTopField->getPicSym()->allocSaoParam(&m_cEncSAO);
+#endif
     pcTopField->setReconMark (false);
     
@@ -534,11 +548,11 @@
     Pel * pcTopFieldU =  pcTopField->getPicYuvOrg()->getCbAddr();
     Pel * pcTopFieldV =  pcTopField->getPicYuvOrg()->getCrAddr();
-    
+
     // compute image characteristics
     if ( getUseAdaptiveQP() )
     {
       m_cPreanalyzer.xPreanalyze( dynamic_cast<TEncPic*>( pcTopField ) );
-    }
-    
+    }    
+
     /* -- Defield -- */
     
@@ -554,5 +568,7 @@
     TComPic* pcBottomField;
     xGetNewPicBuffer( pcBottomField );
+#if !HM_CLEANUP_SAO
     pcBottomField->getPicSym()->allocSaoParam(&m_cEncSAO);
+#endif
     pcBottomField->setReconMark (false);
    
@@ -575,11 +591,11 @@
     Pel * pcBottomFieldU =  pcBottomField->getPicYuvOrg()->getCbAddr();
     Pel * pcBottomFieldV =  pcBottomField->getPicYuvOrg()->getCrAddr();
-    
-    // Compute image characteristics
+
+    // compute image characteristics
     if ( getUseAdaptiveQP() )
     {
       m_cPreanalyzer.xPreanalyze( dynamic_cast<TEncPic*>( pcBottomField ) );
-    }
-    
+    }       
+
     /* -- Defield -- */
     
@@ -636,5 +652,7 @@
     TComPic *pcTopField;
     xGetNewPicBuffer( pcTopField );
+#if !HM_CLEANUP_SAO
     pcTopField->getPicSym()->allocSaoParam(&m_cEncSAO);
+#endif
     pcTopField->setReconMark (false);
     
@@ -688,8 +706,10 @@
     TComPic* pcBottomField;
     xGetNewPicBuffer( pcBottomField );
+#if !HM_CLEANUP_SAO
     pcBottomField->getPicSym()->allocSaoParam(&m_cEncSAO);
+#endif
     pcBottomField->setReconMark (false);
     
-    TComPicYuv* rpcPicYuvRec = new TComPicYuv;
+    TComPicYuv* rpcPicYuvRec;
     if ( rcListPicYuvRecOut.size() == (UInt)m_iGOPSize )
     {
@@ -698,4 +718,5 @@
     else
     {
+      rpcPicYuvRec = new TComPicYuv;
       rpcPicYuvRec->create( m_iSourceWidth, m_iSourceHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
     }
@@ -791,5 +812,9 @@
         for(UInt i = 0; i < m_cVPS.getNumDirectRefLayers( m_layerId ); i++ )
         {
+#if O0098_SCALED_REF_LAYER_ID
+          const Window scalEL = getSPS()->getScaledRefLayerWindowForLayer(m_cVPS.getRefLayerId(m_layerId, i));
+#else
           const Window scalEL = getSPS()->getScaledRefLayerWindow(i);
+#endif
           Bool zeroOffsets = ( scalEL.getWindowLeftOffset() == 0 && scalEL.getWindowRightOffset() == 0 && scalEL.getWindowTopOffset() == 0 && scalEL.getWindowBottomOffset() == 0 );
 
@@ -842,5 +867,9 @@
         for(UInt i = 0; i < m_cVPS.getNumDirectRefLayers( m_layerId ); i++ )
         {
+#if O0098_SCALED_REF_LAYER_ID
+          const Window scalEL = getSPS()->getScaledRefLayerWindowForLayer(m_cVPS.getRefLayerId(m_layerId, i));
+#else
           const Window scalEL = getSPS()->getScaledRefLayerWindow(i);
+#endif
           Bool zeroOffsets = ( scalEL.getWindowLeftOffset() == 0 && scalEL.getWindowRightOffset() == 0 && scalEL.getWindowTopOffset() == 0 && scalEL.getWindowBottomOffset() == 0 );
 
@@ -883,9 +912,10 @@
 #endif
     }
-
+#if !HM_CLEANUP_SAO
     if (getUseSAO())
     {
       rpcPic->getPicSym()->allocSaoParam(&m_cEncSAO);
     }
+#endif
     m_cListPic.pushBack( rpcPic );
   }
@@ -912,4 +942,7 @@
   for(Int i = 0; i < m_cSPS.getNumScaledRefLayerOffsets(); i++)
   {
+#if O0098_SCALED_REF_LAYER_ID
+    m_cSPS.setScaledRefLayerId(i, m_scaledRefLayerId[i]);
+#endif
     m_cSPS.getScaledRefLayerWindow(i) = m_scaledRefLayerWindow[i];
   }
@@ -1063,6 +1096,6 @@
 Void TEncTop::xInitPPS()
 {
-#if IL_SL_SIGNALLING_N0371
-  m_cPPS.setLayerId(m_layerId);
+#if SCALINGLIST_INFERRING
+  m_cPPS.setLayerId( m_layerId );
 #endif
 
@@ -1072,4 +1105,14 @@
 #if REPN_FORMAT_IN_VPS
   Int lowestQP;
+#if O0096_REP_FORMAT_INDEX
+  if( m_layerId == 0 )
+  {
+    lowestQP = - m_cSPS.getQpBDOffsetY();
+  }
+  else
+  {
+    lowestQP = - (m_cVPS.getVpsRepFormat( m_cVPS.getVpsRepFormatIdx( m_cSPS.getUpdateRepFormatFlag() ? m_cSPS.getUpdateRepFormatIndex() : m_layerId ) )->getBitDepthVpsLuma() - 8) * 6;
+  }
+#else
   if( m_layerId == 0 || m_cSPS.getUpdateRepFormatFlag() )
   {
@@ -1080,4 +1123,5 @@
     lowestQP = - (m_cVPS.getVpsRepFormat( m_cVPS.getVpsRepFormatIdx( m_layerId ) )->getBitDepthVpsLuma() - 8) * 6;
   }
+#endif
 #else
   Int lowestQP = - m_cSPS.getQpBDOffsetY();
@@ -1119,5 +1163,4 @@
   }
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
   if ( m_RCEnableRateControl )
   {
@@ -1126,5 +1169,4 @@
     m_cPPS.setMinCuDQPSize( m_cPPS.getSPS()->getMaxCUWidth() >> ( m_cPPS.getMaxCuDQPDepth()) );
   } 
-#endif
 
   m_cPPS.setChromaCbQpOffset( m_chromaCbQpOffset );
@@ -1209,4 +1251,10 @@
 #if POC_RESET_FLAG
   m_cPPS.setNumExtraSliceHeaderBits( 2 );
+#endif
+#if O0149_CROSS_LAYER_BLA_FLAG
+  if (m_crossLayerBLAFlag)
+  {
+    m_cPPS.setNumExtraSliceHeaderBits( 3 );
+  }
 #endif
 }
@@ -1607,7 +1655,17 @@
 Void TEncTop::xInitILRP()
 {
+#if O0096_REP_FORMAT_INDEX
+  RepFormat *repFormat = m_cVPS.getVpsRepFormat( m_cVPS.getVpsRepFormatIdx( m_cSPS.getUpdateRepFormatFlag() ? m_cSPS.getUpdateRepFormatIndex() : m_layerId ) );
+#else
   RepFormat *repFormat = m_cVPS.getVpsRepFormat( m_cVPS.getVpsRepFormatIdx( m_layerId ) );
+#endif
   Int bitDepthY,bitDepthC,picWidth,picHeight;
 
+#if O0096_REP_FORMAT_INDEX
+  bitDepthY   = repFormat->getBitDepthVpsLuma();
+  bitDepthC   = repFormat->getBitDepthVpsChroma();
+  picWidth    = repFormat->getPicWidthVpsInLumaSamples();
+  picHeight   = repFormat->getPicHeightVpsInLumaSamples();
+#else
   if( m_cSPS.getUpdateRepFormatFlag() )
   {
@@ -1624,4 +1682,5 @@
     picHeight   = repFormat->getPicHeightVpsInLumaSamples();
   }
+#endif
   
   if(m_layerId > 0)
@@ -1661,4 +1720,23 @@
 }
 #endif
+
+#if O0098_SCALED_REF_LAYER_ID
+Window& TEncTop::getScaledRefLayerWindowForLayer(Int layerId)
+{
+  static Window win;
+
+  for (Int i = 0; i < m_numScaledRefLayerOffsets; i++)
+  {
+    if (layerId == m_scaledRefLayerId[i])
+    {
+      return m_scaledRefLayerWindow[i];
+    }
+  }
+
+  win.resetWindow();  // scaled reference layer offsets are inferred to be zero when not present
+  return win;
+}
+#endif
+
 #endif //SVC_EXTENSION
 //! \}
Index: trunk/source/Lib/TLibEncoder/TEncTop.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncTop.h	(revision 494)
+++ trunk/source/Lib/TLibEncoder/TEncTop.h	(revision 540)
@@ -83,5 +83,5 @@
   // encoder search
   TEncSearch              m_cSearch;                      ///< encoder search class
-  TEncEntropy*            m_pcEntropyCoder;                     ///< entropy encoder 
+  //TEncEntropy*            m_pcEntropyCoder;                     ///< entropy encoder
   TEncCavlc*              m_pcCavlcCoder;                       ///< CAVLC encoder  
   // coding tool
@@ -141,7 +141,16 @@
 #endif
   UInt                    m_numScaledRefLayerOffsets;
+#if O0098_SCALED_REF_LAYER_ID
+  UInt                    m_scaledRefLayerId[MAX_LAYERS];
+#endif
   Window                  m_scaledRefLayerWindow[MAX_LAYERS];
 #if POC_RESET_FLAG
   Int                     m_pocAdjustmentValue;
+#endif
+#if NO_CLRAS_OUTPUT_FLAG
+  Bool                    m_noClrasOutputFlag;
+  Bool                    m_layerInitializedFlag;
+  Bool                    m_firstPicInLayerDecodedFlag;
+  Bool                    m_noOutputOfPriorPicsFlags;
 #endif
 #endif //SVC_EXTENSION
@@ -209,4 +218,9 @@
   Void                    setNumScaledRefLayerOffsets(Int x) { m_numScaledRefLayerOffsets = x; }
   UInt                    getNumScaledRefLayerOffsets() { return m_numScaledRefLayerOffsets; }
+#if O0098_SCALED_REF_LAYER_ID
+  Void                    setScaledRefLayerId(Int x, UInt id) { m_scaledRefLayerId[x] = id;   }
+  UInt                    getScaledRefLayerId(Int x)          { return m_scaledRefLayerId[x]; }
+  Window&  getScaledRefLayerWindowForLayer(Int layerId);
+#endif
   Window&  getScaledRefLayerWindow(Int x)            { return m_scaledRefLayerWindow[x]; }
 #endif //SVC_EXTENSION
@@ -242,4 +256,14 @@
   Void setPocAdjustmentValue(Int x) { m_pocAdjustmentValue = x;   }
 #endif
+#if NO_CLRAS_OUTPUT_FLAG
+  Int  getNoClrasOutputFlag()                { return m_noClrasOutputFlag;}
+  Void setNoClrasOutputFlag(Bool x)          { m_noClrasOutputFlag = x;   }
+  Int  getLayerInitializedFlag()             { return m_layerInitializedFlag;}
+  Void setLayerInitializedFlag(Bool x)       { m_layerInitializedFlag = x;   }
+  Int  getFirstPicInLayerDecodedFlag()       { return m_firstPicInLayerDecodedFlag;}
+  Void setFirstPicInLayerDecodedFlag(Bool x) { m_firstPicInLayerDecodedFlag = x;   }
+  Int  getNoOutputOfPriorPicsFlags()         { return m_noOutputOfPriorPicsFlags;}
+  Void setNoOutputOfPriorPicsFlags(Bool x)   { m_noOutputOfPriorPicsFlags = x;   }
+#endif
 #else //SVC_EXTENSION
   Void encode( Bool bEos, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut,
