Index: trunk/source/Lib/TLibEncoder/TEncAnalyze.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncAnalyze.cpp	(revision 622)
+++ trunk/source/Lib/TLibEncoder/TEncAnalyze.cpp	(revision 655)
@@ -52,4 +52,6 @@
 TEncAnalyze             m_gcAnalyzeP;
 TEncAnalyze             m_gcAnalyzeB;
+
+TEncAnalyze             m_gcAnalyzeAll_in;
 #endif
 
Index: trunk/source/Lib/TLibEncoder/TEncAnalyze.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncAnalyze.h	(revision 622)
+++ trunk/source/Lib/TLibEncoder/TEncAnalyze.h	(revision 655)
@@ -116,4 +116,33 @@
   }
   
+  Void    printOutInterlaced ( Char cDelim, Double bits )
+  {
+    Double dFps     =   m_dFrmRate; //--CFG_KDY
+    Double dScale   = dFps / 1000 / (Double)m_uiNumPic;
+    
+    printf( "\tTotal Frames |  "   "Bitrate    "  "Y-PSNR    "  "U-PSNR    "  "V-PSNR \n" );
+    //printf( "\t------------ "  " ----------"   " -------- "  " -------- "  " --------\n" );
+    printf( "\t %8d    %c"          "%12.4lf  "    "%8.4lf  "   "%8.4lf  "    "%8.4lf\n",
+           getNumPic(), cDelim,
+           bits * dScale,
+           getPsnrY() / (Double)getNumPic(),
+           getPsnrU() / (Double)getNumPic(),
+           getPsnrV() / (Double)getNumPic() );
+  }
+  
+  Void    printSummaryOutInterlaced (Int bits)
+  {
+    FILE* pFile = fopen ("summaryTotal.txt", "at");
+    Double dFps     =   m_dFrmRate; //--CFG_KDY
+    Double dScale   = dFps / 1000 / (Double)m_uiNumPic;
+    
+    fprintf(pFile, "%f\t %f\t %f\t %f\n", bits * dScale,
+            getPsnrY() / (Double)getNumPic(),
+            getPsnrU() / (Double)getNumPic(),
+            getPsnrV() / (Double)getNumPic() );
+    fclose(pFile);
+  }
+  
+  
   Void    printSummary(Char ch)
   {
@@ -155,4 +184,6 @@
 extern TEncAnalyze             m_gcAnalyzeP;
 extern TEncAnalyze             m_gcAnalyzeB;
+
+extern TEncAnalyze             m_gcAnalyzeAll_in;
 #endif
 
Index: trunk/source/Lib/TLibEncoder/TEncCavlc.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 622)
+++ trunk/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 655)
@@ -229,5 +229,4 @@
     }
   }
-#if H_MV5
 #if H_MV
   if ( pcPPS->getLayerId() > 0 )
@@ -243,5 +242,4 @@
   {  
 #endif  
-#endif
   WRITE_FLAG( pcPPS->getScalingListPresentFlag() ? 1 : 0,                          "pps_scaling_list_data_present_flag" ); 
   if( pcPPS->getScalingListPresentFlag() )
@@ -252,8 +250,6 @@
     codeScalingList( m_pcSlice->getScalingList() );
   }
-#if H_MV5
 #if H_MV
   }
-#endif
 #endif
   WRITE_FLAG( pcPPS->getListsModificationPresentFlag(), "lists_modification_present_flag");
@@ -339,12 +335,4 @@
   {
     WRITE_FLAG(pcVUI->getTilesFixedStructureFlag(),             "tiles_fixed_structure_flag");
-#if !H_MV5
-#if H_MV
-    if ( pcSPS->getLayerId() > 0 )
-    {
-      WRITE_FLAG( pcVUI->getTileBoundariesAlignedFlag( ) ? 1 : 0 , "tile_boundaries_aligned_flag" );
-    }
-#endif
-#endif
     WRITE_FLAG(pcVUI->getMotionVectorsOverPicBoundariesFlag(),  "motion_vectors_over_pic_boundaries_flag");
     WRITE_FLAG(pcVUI->getRestrictedRefPicListsFlag(),           "restricted_ref_pic_lists_flag");
@@ -451,5 +439,4 @@
 #endif
   WRITE_UVLC( pcSPS->getSPSId (),                   "sps_seq_parameter_set_id" );
-#if H_MV5
 #if H_MV
   if ( pcSPS->getLayerId() > 0 )
@@ -460,5 +447,4 @@
   if ( pcSPS->getUpdateRepFormatFlag() )
   { 
-#endif
 #endif
   WRITE_UVLC( pcSPS->getChromaFormatIdc (),         "chroma_format_idc" );
@@ -472,8 +458,6 @@
   WRITE_UVLC( pcSPS->getPicWidthInLumaSamples (),   "pic_width_in_luma_samples" );
   WRITE_UVLC( pcSPS->getPicHeightInLumaSamples(),   "pic_height_in_luma_samples" );
-#if H_MV5
 #if H_MV
   }
-#endif
 #endif
   Window conf = pcSPS->getConformanceWindow();
@@ -487,16 +471,12 @@
     WRITE_UVLC( conf.getWindowBottomOffset() / TComSPS::getWinUnitY(pcSPS->getChromaFormatIdc() ), "conf_win_bottom_offset" );
   }
-#if H_MV5
 #if H_MV
   if ( pcSPS->getUpdateRepFormatFlag() )
   { 
 #endif
-#endif
   WRITE_UVLC( pcSPS->getBitDepthY() - 8,             "bit_depth_luma_minus8" );
   WRITE_UVLC( pcSPS->getBitDepthC() - 8,             "bit_depth_chroma_minus8" );
-#if H_MV5
 #if H_MV
   }
-#endif
 #endif
   WRITE_UVLC( pcSPS->getBitsForPOC()-4,                 "log2_max_pic_order_cnt_lsb_minus4" );
@@ -525,5 +505,4 @@
   if(pcSPS->getScalingListFlag())
   {
-#if H_MV5
 #if H_MV
     if ( pcSPS->getLayerId() > 0 )
@@ -539,5 +518,4 @@
     {    
 #endif
-#endif
     WRITE_FLAG( pcSPS->getScalingListPresentFlag() ? 1 : 0,                          "sps_scaling_list_data_present_flag" ); 
     if(pcSPS->getScalingListPresentFlag())
@@ -548,8 +526,6 @@
       codeScalingList( m_pcSlice->getScalingList() );
     }
-#if H_MV5
 #if H_MV
     }
-#endif
 #endif
   }
@@ -598,61 +574,4 @@
   }
 
-#if !H_MV5
-#if H_MV
-  WRITE_FLAG( 1, "sps_extension_flag" );
-  WRITE_FLAG( pcSPS->getInterViewMvVertConstraintFlag() ? 1 : 0, "inter_view_mv_vert_constraint_flag" );
-  ////   sps_extension_vui_parameters( )
-  if( pcSPS->getVuiParameters()->getBitstreamRestrictionFlag() )
-  {  
-    WRITE_UVLC( pcSPS->getNumIlpRestrictedRefLayers( ),           "num_ilp_restricted_ref_layers" ); 
-    for( Int i = 0; i < pcSPS->getNumIlpRestrictedRefLayers( ); i++ ) 
-    {  
-      WRITE_UVLC( pcSPS->getMinSpatialSegmentOffsetPlus1( i ),    "min_spatial_segment_offset_plus1" ); 
-      if( pcSPS->getMinSpatialSegmentOffsetPlus1( i ) > 0 ) 
-      {  
-        WRITE_FLAG( pcSPS->getCtuBasedOffsetEnabledFlag( i ),      "ctu_based_offset_enabled_flag[ i ]"); 
-        if( pcSPS->getCtuBasedOffsetEnabledFlag( i ) )  
-        {
-          WRITE_UVLC( pcSPS->getMinHorizontalCtuOffsetPlus1( i ), "min_horizontal_ctu_offset_plus1[ i ]"); 
-        }
-      }  
-    }  
-  } 
-#if H_3D_QTLPC
-  if( depthFlag )
-  {
-    WRITE_FLAG( pcSPS->getUseQTL() ? 1 : 0, "use_qtl_flag");
-    WRITE_FLAG( pcSPS->getUsePC()  ? 1 : 0, "use_pc_flag");
-  }
-#endif
-  ////   sps_extension_vui_parameters( ) END
-  WRITE_UVLC( 0, "sps_shvc_reserved_zero_idc" ); 
-#if !H_3D
-  WRITE_FLAG( 0, "sps_extension2_flag" );
-#else
-  WRITE_FLAG( 1, "sps_extension2_flag"  );
-  if (!depthFlag )
-  {
-    WRITE_UVLC( pcSPS->getCamParPrecision(), "cp_precision" );
-    WRITE_FLAG( pcSPS->hasCamParInSliceHeader() ? 1 : 0, "cp_in_slice_header_flag" );
-    if( !pcSPS->hasCamParInSliceHeader() )
-    {
-      for( UInt uiIndex = 0; uiIndex < viewIndex; uiIndex++ )
-      {
-        WRITE_SVLC( pcSPS->getCodedScale    ()[ uiIndex ],                                      "cp_scale" );
-        WRITE_SVLC( pcSPS->getCodedOffset   ()[ uiIndex ],                                      "cp_off" );
-        WRITE_SVLC( pcSPS->getInvCodedScale ()[ uiIndex ] + pcSPS->getCodedScale ()[ uiIndex ], "cp_inv_scale_plus_scale" );
-        WRITE_SVLC( pcSPS->getInvCodedOffset()[ uiIndex ] + pcSPS->getCodedOffset()[ uiIndex ], "cp_inv_off_plus_off" );
-      }
-    }
-  }
-
-  WRITE_FLAG( 0, "sps_extension3_flag" );
-#endif
-#else
-  WRITE_FLAG( 0, "sps_extension_flag" );
-#endif
-}
-#else
 #if !H_MV
   WRITE_FLAG( 0, "sps_extension_flag" );
@@ -706,5 +625,4 @@
 }
 #endif
-#endif
 
 Void TEncCavlc::codeVPS( TComVPS* pcVPS )
@@ -713,9 +631,5 @@
   WRITE_CODE( 3,                                    2,        "vps_reserved_three_2bits" );
 #if H_MV
-#if H_MV5
   WRITE_CODE( pcVPS->getMaxLayersMinus1(),       6,        "vps_max_layers_minus1" );
-#else
-  WRITE_CODE( pcVPS->getMaxLayers() - 1,            6,        "vps_max_layers_minus1" );
-#endif
 #else
   WRITE_CODE( 0,                                    6,        "vps_reserved_zero_6bits" );
@@ -800,191 +714,4 @@
     }
   }
-#if !H_MV5
-#if H_MV
-  WRITE_FLAG( 1,                                             "vps_extension_flag" );
-
-  m_pcBitIf->writeAlignOne();                        
-
-  WRITE_FLAG( pcVPS->getAvcBaseLayerFlag() ? 1 : 0,          "avc_base_layer_flag" );
-  WRITE_FLAG( pcVPS->getSplittingFlag() ? 1 : 0,             "splitting_flag" );
-  
-  for( Int type = 0; type < MAX_NUM_SCALABILITY_TYPES; type++ )
-  {
-    WRITE_FLAG( pcVPS->getScalabilityMask( type ) ? 1 : 0,   "scalability_mask[i]" );
-  }
-
-  for( Int sIdx = 0; sIdx < pcVPS->getNumScalabilityTypes( ) - ( pcVPS->getSplittingFlag() ? 1 : 0 ); sIdx++ )
-  {
-    WRITE_CODE( pcVPS->getDimensionIdLen( sIdx ) - 1 , 3,    "dimension_id_len_minus1[j]");    
-  }
-
-  if ( pcVPS->getSplittingFlag() )
-  { // Ignore old dimension id length
-    pcVPS->setDimensionIdLen( pcVPS->getNumScalabilityTypes( ) - 1 ,pcVPS->inferLastDimsionIdLenMinus1() + 1 );       
-  }    
-
-
-  WRITE_FLAG( pcVPS->getVpsNuhLayerIdPresentFlag() ? 1 : 0,  "vps_nuh_layer_id_present_flag");
-
-  for( Int i = 0; i <= pcVPS->getMaxLayers() - 1; i++ )
-  {
-    if ( pcVPS->getVpsNuhLayerIdPresentFlag() && ( i > 0 ) )
-    {      
-      WRITE_CODE( pcVPS->getLayerIdInNuh( i ), 6,          "layer_id_in_nuh[i]");
-  }
-    else
-    {
-      assert( pcVPS->getLayerIdInNuh( i ) == i ); 
-  }
-
-    assert(  pcVPS->getLayerIdInVps( pcVPS->getLayerIdInNuh( i ) ) == i ); 
-
-    for( Int j = 0; j < pcVPS->getNumScalabilityTypes() ; j++ )
-  {
-      if ( !pcVPS->getSplittingFlag() )
-    {
-        WRITE_CODE( pcVPS->getDimensionId( i, j ), pcVPS->getDimensionIdLen( j ), "dimension_id[i][j]");      
-      }
-      else
-      {
-        assert( pcVPS->getDimensionId( i, j ) ==  pcVPS->inferDimensionId( i, j )  );
-      }
-    }
-  }
-
-  for( Int i = 1; i <= pcVPS->getMaxLayers() - 1; i++ )
-  {
-    for( Int j = 0; j < i; j++ )
-    {
-      WRITE_FLAG( pcVPS->getDirectDependencyFlag( i, j ),    "direct_dependency_flag[i][j]" );
-    }
-  }
-
-  for( Int i = 0; i < pcVPS->getMaxLayers() - 1; i++ )
-  {
-    WRITE_CODE( pcVPS->getMaxTidIlRefPicPlus1( i ), 3,       "max_tid_il_ref_pics_plus1[i]" );
-  }
-
-  WRITE_CODE( pcVPS->getVpsNumberLayerSetsMinus1( )    , 10,    "vps_number_layer_sets_minus1"      );
-  WRITE_CODE( pcVPS->getVpsNumProfileTierLevelMinus1( ), 6,     "vps_num_profile_tier_level_minus1" );
-
-  for( Int i = 1; i <= pcVPS->getVpsNumProfileTierLevelMinus1(); i++ )
-  {
-    WRITE_FLAG( pcVPS->getVpsProfilePresentFlag( i ) ? 1 : 0, "vps_profile_present_flag[i]" );
-    if( !pcVPS->getVpsProfilePresentFlag( i ) )
-    {    
-      WRITE_CODE( pcVPS->getProfileRefMinus1( i ), 6, "profile_ref_minus1[i]" );
-    }
-    codePTL( pcVPS->getPTL( i ), pcVPS->getVpsProfilePresentFlag( i ), pcVPS->getMaxTLayers() - 1 );
-  }
-
-  Int numOutputLayerSets = pcVPS->getVpsNumberLayerSetsMinus1( ) + 1; 
-
-  WRITE_FLAG( pcVPS->getMoreOutputLayerSetsThanDefaultFlag( ) ? 1 : 0, "more_output_layer_sets_than_default_flag" );
-
-  if ( pcVPS->getMoreOutputLayerSetsThanDefaultFlag( ) )
-  {
-    WRITE_CODE( pcVPS->getNumAddOutputLayerSetsMinus1( )    , 10,    "num_add_output_layer_sets_minus1"      );
-    numOutputLayerSets += ( pcVPS->getNumAddOutputLayerSetsMinus1( ) + 1 ); 
-  }
-
-  if( numOutputLayerSets > 1)
-  {
-    WRITE_FLAG( pcVPS->getDefaultOneTargetOutputLayerFlag( ) ? 1 : 0, "default_one_target_output_layer_flag" );
-  }  
-
-  for( Int i = 1; i < numOutputLayerSets; i++ )
-  {
-    if( i > pcVPS->getVpsNumberLayerSetsMinus1( ) )
-    {      
-      WRITE_UVLC( pcVPS->getOutputLayerSetIdxMinus1( i ),      "output_layer_set_idx_minus1[i]" );
-      for( Int j = 0; j < pcVPS->getNumLayersInIdList( j ) - 1 ; j++ )
-      {
-        WRITE_FLAG( pcVPS->getOutputLayerFlag( i, j) ? 1 : 0, "output_layer_flag" );
-      }      
-    }
-    if ( pcVPS->getProfileLevelTierIdxLen()  > 0 )
-    {      
-      WRITE_CODE( pcVPS->getProfileLevelTierIdx( i ), pcVPS->getProfileLevelTierIdxLen() ,"profile_level_tier_idx[ i ]" );   
-    }
-  }
-
-  WRITE_FLAG( pcVPS->getMaxOneActiveRefLayerFlag( ) ? 1 : 0, "max_one_active_ref_layer_flag" );
-  WRITE_UVLC( pcVPS->getDirectDepTypeLenMinus2 ( ),         "direct_dep_type_len_minus2"); 
-
-    for( Int i = 1; i <= pcVPS->getMaxLayers() - 1; i++ )
-    {
-      for( Int j = 0; j < i; j++ )
-      {
-        if (pcVPS->getDirectDependencyFlag( i, j) )
-        {        
-          assert ( pcVPS->getDirectDependencyType( i, j ) != -1 ); 
-          WRITE_CODE( pcVPS->getDirectDependencyType( i, j ),pcVPS->getDirectDepTypeLenMinus2( ) + 2,  "direct_dependency_type[i][j]" );
-        }
-      }
-    }
-
-    WRITE_FLAG ( 0,                    "vps_shvc_reserved_zero_flag" ); 
-
-#if H_3D
-  WRITE_FLAG( 1,                                             "vps_extension2_flag" );
-  m_pcBitIf->writeAlignOne();      
-  for( Int i = 0; i <= pcVPS->getMaxLayers() - 1; i++ )
-  {
-    if (i!= 0)
-    {
-      if ( !( pcVPS->getDepthId( i ) == 1 ) )
-      {
-#if H_3D_IV_MERGE
-        WRITE_FLAG( pcVPS->getIvMvPredFlag         ( i ) ? 1 : 0 , "iv_mv_pred_flag[i]");
-#endif
-#if H_3D_ARP
-        WRITE_FLAG( pcVPS->getUseAdvRP             ( i ) ? 1 : 0,  "iv_res_pred_flag[i]"  );
-#endif
-#if H_3D_NBDV_REF
-        WRITE_FLAG( pcVPS->getDepthRefinementFlag  ( i ) ? 1 : 0 , "depth_refinement_flag[i]");
-#endif
-#if H_3D_VSP
-        WRITE_FLAG( pcVPS->getViewSynthesisPredFlag( i ) ? 1 : 0 , "view_synthesis_pred_flag[i]");
-#endif
-      }          
-      else
-      {
-        WRITE_FLAG( pcVPS->getVpsDepthModesFlag( i ) ? 1 : 0 ,          "vps_depth_modes_flag[i]" );
-        //WRITE_FLAG( pcVPS->getLimQtPredFlag    ( i ) ? 1 : 0 ,          "lim_qt_pred_flag[i]"     ); 
-#if H_3D_DIM_DLT
-        if( pcVPS->getVpsDepthModesFlag( i ) )
-        {
-          WRITE_FLAG( pcVPS->getUseDLTFlag( i ) ? 1 : 0, "dlt_flag[i]" );
-        }
-        if( pcVPS->getUseDLTFlag( i ) )
-        {
-          // code mapping
-          WRITE_UVLC(pcVPS->getNumDepthValues(i), "num_depth_values_in_dlt[i]");
-          for(Int d=0; d<pcVPS->getNumDepthValues(i); d++)
-          {
-            WRITE_UVLC( pcVPS->idx2DepthValue(i, d), "dlt_depth_value[i][d]" );
-          }
-        }        
-#endif
-#if LGE_INTER_SDC_E0156
-        WRITE_FLAG( pcVPS->getInterSDCFlag( i ) ? 1 : 0, "depth_inter_SDC_flag" );
-#endif
-      }
-    }  
-  }
-  WRITE_FLAG( pcVPS->getIvMvScalingFlag( ) ? 1 : 0 ,          "iv_mv_scaling_flag" );
-#else
-  WRITE_FLAG( 0,                                             "vps_extension2_flag" );
-#endif
-#else
-  WRITE_FLAG( 0,                     "vps_extension_flag" );
-#endif
-  
-  //future extensions here..
-  
-  return;
-}
-#else
 #if H_MV
   WRITE_FLAG( 1,                     "vps_extension_flag" );
@@ -1003,10 +730,10 @@
 #endif
   //future extensions here..
-}
-
-#endif
-
-
-#if H_MV5
+
+  return;
+}
+
+
+
 #if H_MV
 Void TEncCavlc::codeVPSExtension( TComVPS *pcVPS ) 
@@ -1309,5 +1036,5 @@
         }        
 #endif
-#if LGE_INTER_SDC_E0156
+#if H_3D_INTER_SDC
         WRITE_FLAG( pcVPS->getInterSDCFlag( i ) ? 1 : 0, "depth_inter_SDC_flag" );
 #endif
@@ -1319,5 +1046,4 @@
 #endif
 }
-#endif
 #endif
 
@@ -1370,5 +1096,4 @@
   {
 #if H_MV    
-#if H_MV5
     Int esb = 0;  //Don't use i, otherwise will shadow something below
     if ( pcSlice->getPPS()->getNumExtraSliceHeaderBits() > esb )
@@ -1385,12 +1110,4 @@
 
     for (; esb < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); esb++)    
-#else
-    if ( pcSlice->getPPS()->getNumExtraSliceHeaderBits() > 0 )
-    {
-      WRITE_FLAG( pcSlice->getDiscardableFlag( ) ? 1 : 0 , "discardable_flag" );
-    }
-
-    for (Int i = 1; i < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); i++)    
-#endif
 #else
     for (Int i = 0; i < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); i++)
@@ -1415,5 +1132,5 @@
     if( !pcSlice->getIdrPicFlag() )
     {
-      Int picOrderCntLSB = (pcSlice->getPOC()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC()))%(1<<pcSlice->getSPS()->getBitsForPOC());
+      Int picOrderCntLSB = (pcSlice->getPOC()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC())) & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
       WRITE_CODE( picOrderCntLSB, pcSlice->getSPS()->getBitsForPOC(), "pic_order_cnt_lsb");
       TComReferencePictureSet* rps = pcSlice->getRPS();
@@ -1530,5 +1247,4 @@
     }
 #if H_MV
-#if H_MV5
     Int layerId = pcSlice->getLayerId(); 
     if( pcSlice->getLayerId() > 0 && !vps->getAllRefLayersActiveFlag() && vps->getNumDirectRefLayers( layerId ) > 0 )
@@ -1550,28 +1266,4 @@
       }  
     }
-#else
-    Int layerIdInVps       = pcSlice->getLayerIdInVps(); 
-    if( pcSlice->getLayerId() > 0 && vps->getNumDirectRefLayers( layerIdInVps ) > 0 )
-    {   
-      WRITE_FLAG( pcSlice->getInterLayerPredEnabledFlag( ) ? 1 : 0 , "inter_layer_pred_enabled_flag" );
-      if( pcSlice->getInterLayerPredEnabledFlag() && vps->getNumDirectRefLayers( layerIdInVps ) > 1 )
-      {            
-        if( !vps->getMaxOneActiveRefLayerFlag())  
-        {
-          WRITE_CODE( pcSlice->getNumInterLayerRefPicsMinus1( ), pcSlice->getNumInterLayerRefPicsMinus1Len( ), "num_inter_layer_ref_pics_minus1" );
-        }
-        for( Int i = 0; i < pcSlice->getNumActiveRefLayerPics(); i++ )   
-        {
-          WRITE_CODE( pcSlice->getInterLayerPredLayerIdc( i ), pcSlice->getInterLayerPredLayerIdcLen( ), "inter_layer_pred_layer_idc" );
-        }
-      }  
-    }
-
-    if( vps->getNumSamplePredRefLayers( layerIdInVps ) > 0  &&  pcSlice->getNumActiveRefLayerPics() > 0 )
-    {
-      WRITE_FLAG( pcSlice->getInterLayerSamplePredOnlyFlag( ) ? 1 : 0 , "inter_layer_sample_pred_only_flag" );
-    }
-
-#endif
 #endif
     if(pcSlice->getSPS()->getUseSAO())
@@ -1678,18 +1370,4 @@
     if ( pcSlice->getEnableTMVPFlag() )
     {
-#if !H_MV5
-#if H_MV
-      if( pcSlice->getLayerId() > 0 && pcSlice->getNumActiveMotionPredRefLayers() > 0 )
-      {
-        WRITE_FLAG( pcSlice->getAltCollocatedIndicationFlag( ) ? 1 : 0 , "alt_collocated_indication_flag" );
-      }
-      if( pcSlice->getAltCollocatedIndicationFlag() && pcSlice->getNumActiveMotionPredRefLayers() > 1 ) 
-      {          
-        WRITE_UVLC( pcSlice->getCollocatedRefLayerIdx( ), "collocated_ref_layer_idx" );
-      }      
-      else 
-      {
-#endif
-#endif
       if ( pcSlice->getSliceType() == B_SLICE )
       {
@@ -1704,9 +1382,4 @@
       }
     }
-#if !H_MV5
-#if H_MV
-    }
-#endif
-#endif
     if ( (pcSlice->getPPS()->getUseWP() && pcSlice->getSliceType()==P_SLICE) || (pcSlice->getPPS()->getWPBiPred() && pcSlice->getSliceType()==B_SLICE) )
     {
@@ -2256,5 +1929,5 @@
 {
   // Bool state = true, state2 = false;
-  Int lsb = ltrpPOC % (1<<pcSlice->getSPS()->getBitsForPOC());
+  Int lsb = ltrpPOC & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
   for (Int k = 0; k < pcSlice->getSPS()->getNumLongTermRefPicSPS(); k++)
   {
@@ -2282,5 +1955,5 @@
 }
 
-#if LGE_INTER_SDC_E0156
+#if H_3D_INTER_SDC
 Void TEncCavlc::codeInterSDCFlag ( TComDataCU* pcCU, UInt uiAbsPartIdx )
 {
Index: trunk/source/Lib/TLibEncoder/TEncCavlc.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncCavlc.h	(revision 622)
+++ trunk/source/Lib/TLibEncoder/TEncCavlc.h	(revision 655)
@@ -84,5 +84,4 @@
   UInt  getCoeffCost          ()                { return  m_uiCoeffCost;  }
   Void  codeVPS                 ( TComVPS* pcVPS );
-#if H_MV5
 #if H_MV
   Void  codeVPSExtension       ( TComVPS *pcVPS );
@@ -90,16 +89,11 @@
   Void  codeVPSVUI             ( TComVPS* pcVPS );
 #endif 
-#endif
   Void  codeVUI                 ( TComVUI *pcVUI, TComSPS* pcSPS );
-#if H_MV5
 #if H_MV
   Void  codeSPSExtension        ( TComSPS* pcSPS ); 
 #endif
-#endif
 #if H_3D
-#if H_MV5
   Void  codeVPSExtension2       ( TComVPS* pcVPS ); 
   Void  codeSPSExtension2       ( TComSPS* pcSPS, Int viewIndex, Bool depthFlag  ); 
-#endif
   Void  codeSPS                 ( TComSPS* pcSPS, Int viewIndex, Bool depthFlag );
 #else
@@ -133,5 +127,5 @@
   Void codeICFlag        ( TComDataCU* pcCU, UInt uiAbsPartIdx );
 #endif
-#if LGE_INTER_SDC_E0156
+#if H_3D_INTER_SDC
   Void codeInterSDCFlag          ( TComDataCU* pcCU, UInt uiAbsPartIdx );
   Void codeInterSDCResidualData  ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiSegment );
Index: trunk/source/Lib/TLibEncoder/TEncCfg.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncCfg.h	(revision 622)
+++ trunk/source/Lib/TLibEncoder/TEncCfg.h	(revision 655)
@@ -77,7 +77,4 @@
   Int m_interLayerPredLayerIdc [MAX_NUM_REF_PICS];
   Int m_interViewRefPosL[2][MAX_NUM_REF_PICS];  
-#if !H_MV5
-  Int m_collocatedRefLayerIdx; 
-#endif
 #endif
   GOPEntry()
@@ -97,7 +94,4 @@
 #if H_MV
   , m_numActiveRefLayerPics(0)
-#if !H_MV5
-  , m_collocatedRefLayerIdx(-1)
-#endif
 #endif
   {
@@ -310,8 +304,22 @@
   Int       m_RCInitialQP;
   Bool      m_RCForceIntraQP;
+
+#if KWU_RC_MADPRED_E0227
+  UInt       m_depthMADPred;
+#endif
+#if KWU_RC_VIEWRC_E0227
+  Bool      m_bViewWiseRateCtrl;
+#endif
 #else
   Bool      m_enableRateCtrl;                                ///< Flag for using rate control algorithm
   Int       m_targetBitrate;                                 ///< target bitrate
   Int       m_numLCUInUnit;                                  ///< Total number of LCUs in a frame should be divided by the NumLCUInUnit
+
+#if KWU_RC_MADPRED_E0227
+  UInt       m_depthMADPred;
+#endif
+#if KWU_RC_VIEWRC_E0227
+  Bool      m_bViewWiseRateCtrl;
+#endif
 #endif
   Bool      m_TransquantBypassEnableFlag;                     ///< transquant_bypass_enable_flag setting in PPS.
@@ -361,13 +369,8 @@
   Int       m_layerIdInVps;
   Int       m_viewId;
-#if H_MV5
   Int       m_viewIndex; 
-#endif
 #endif 
 
 #if H_3D
-#if !H_MV5
-  Int       m_viewIndex; 
-#endif
   Bool      m_isDepth;
 
@@ -403,5 +406,5 @@
   Bool      m_bUseIC;
 #endif
-#if LGE_INTER_SDC_E0156
+#if H_3D_INTER_SDC
   bool      m_bInterSDC;
 #endif
@@ -426,11 +429,6 @@
   , m_layerIdInVps(-1)
   , m_viewId(-1)
-#if H_MV5
   , m_viewIndex(-1)
-#endif
 #if H_3D
-#if !H_MV5
-  , m_viewIndex(-1)
-#endif
   , m_isDepth(false)
   , m_bUseVSO(false)
@@ -465,13 +463,7 @@
   Void      setViewId                        ( Int viewId  )      { m_viewId  = viewId;  }
   Int       getViewId                        ()                   { return m_viewId;    }
-#if H_MV5
   Void      setViewIndex                     ( Int viewIndex  )   { m_viewIndex  = viewIndex;  }
   Int       getViewIndex                     ()                   { return m_viewIndex;    }
-#endif
 #if H_3D
-#if !H_MV5
-  Void      setViewIndex                     ( Int viewIndex  )   { m_viewIndex  = viewIndex;  }
-  Int       getViewIndex                     ()                   { return m_viewIndex;    }
-#endif
   Void      setIsDepth                       ( Bool isDepth )   { m_isDepth = isDepth; }
   Bool      getIsDepth                       ()                 { return m_isDepth; }
@@ -514,5 +506,5 @@
   Bool       getUseIC                       ()               { return m_bUseIC; }
 #endif
-#if LGE_INTER_SDC_E0156
+#if H_3D_INTER_SDC
   Void       setInterSDCEnable              ( Bool bVal )    { m_bInterSDC = bVal; }
   Bool       getInterSDCEnable              ()               { return m_bInterSDC; }
@@ -826,4 +818,13 @@
   Bool      getForceIntraQP        ()              { return m_RCForceIntraQP;        }
   Void      setForceIntraQP        ( Bool b )      { m_RCForceIntraQP = b;           }
+
+#if KWU_RC_MADPRED_E0227
+  UInt      getUseDepthMADPred    ()                { return m_depthMADPred;        }
+  Void      setUseDepthMADPred    (UInt b)          { m_depthMADPred    = b;        }
+#endif
+#if KWU_RC_VIEWRC_E0227
+  Bool      getUseViewWiseRateCtrl    ()                { return m_bViewWiseRateCtrl;        }
+  Void      setUseViewWiseRateCtrl    (Bool b)          { m_bViewWiseRateCtrl    = b;        }
+#endif
 #else
   Bool      getUseRateCtrl    ()                { return m_enableRateCtrl;    }
@@ -833,4 +834,13 @@
   Int       getNumLCUInUnit   ()                { return m_numLCUInUnit;      }
   Void      setNumLCUInUnit   (Int numLCUs)     { m_numLCUInUnit   = numLCUs; }
+
+#if KWU_RC_MADPRED_E0227
+  UInt      getUseDepthMADPred    ()                { return m_depthMADPred;        }
+  Void      setUseDepthMADPred    (UInt b)          { m_depthMADPred    = b;        }
+#endif
+#if KWU_RC_VIEWRC_E0227
+  Bool      getUseViewWiseRateCtrl    ()                { return m_bViewWiseRateCtrl;        }
+  Void      setUseViewWiseRateCtrl    (Bool b)          { m_bViewWiseRateCtrl    = b;        }
+#endif
 #endif
   Bool      getTransquantBypassEnableFlag()           { return m_TransquantBypassEnableFlag; }
Index: trunk/source/Lib/TLibEncoder/TEncCu.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncCu.cpp	(revision 622)
+++ trunk/source/Lib/TLibEncoder/TEncCu.cpp	(revision 655)
@@ -103,8 +103,22 @@
   
   m_bEncodeDQP = false;
-#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
+#if RATE_CONTROL_LAMBDA_DOMAIN
+#if !M0036_RC_IMPROVEMENT
   m_LCUPredictionSAD = 0;
   m_addSADDepth      = 0;
   m_temporalSAD      = 0;
+#endif
+#if M0036_RC_IMPROVEMENT && KWU_RC_MADPRED_E0227
+  m_LCUPredictionSAD = 0;
+  m_addSADDepth      = 0;
+  m_temporalSAD      = 0;
+  m_spatialSAD       = 0;
+#endif
+#endif
+#if !RATE_CONTROL_LAMBDA_DOMAIN && KWU_RC_MADPRED_E0227
+  m_LCUPredictionSAD = 0;
+  m_addSADDepth      = 0;
+  m_temporalSAD      = 0;
+  m_spatialSAD       = 0;
 #endif
 
@@ -256,8 +270,22 @@
   m_ppcTempCU[0]->initCU( rpcCU->getPic(), rpcCU->getAddr() );
 
-#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
+#if RATE_CONTROL_LAMBDA_DOMAIN
+#if !M0036_RC_IMPROVEMENT
   m_addSADDepth      = 0;
   m_LCUPredictionSAD = 0;
   m_temporalSAD      = 0;
+#endif
+#if M0036_RC_IMPROVEMENT && KWU_RC_MADPRED_E0227
+  m_LCUPredictionSAD = 0;
+  m_addSADDepth      = 0;
+  m_temporalSAD      = 0;
+  m_spatialSAD       = 0;
+#endif
+#endif
+#if KWU_RC_MADPRED_E0227
+  m_LCUPredictionSAD = 0;
+  m_addSADDepth      = 0;
+  m_temporalSAD      = 0;
+  m_spatialSAD       = 0;
 #endif
 
@@ -404,7 +432,8 @@
 
   // variables for fast encoder decision
-  Bool    bEarlySkip  = false;
-  Bool    bTrySplit    = true;
-  Double  fRD_Skip    = MAX_DOUBLE;
+#if H_3D_QTLPC  
+  Bool    bTrySplit     = true;
+  Bool    bTrySplitDQP  = true;
+#endif
 
   // variable for Early CU determination
@@ -415,5 +444,4 @@
   Bool earlyDetectionSkipMode = false;
 
-  Bool    bTrySplitDQP  = true;
 #if H_3D_VSP
   DisInfo DvInfo; 
@@ -425,13 +453,4 @@
 #endif
 #endif
-  static  Double  afCost[ MAX_CU_DEPTH ];
-  static  Int      aiNum [ MAX_CU_DEPTH ];
-
-  if ( rpcBestCU->getAddr() == 0 )
-  {
-    ::memset( afCost, 0, sizeof( afCost ) );
-    ::memset( aiNum,  0, sizeof( aiNum  ) );
-  }
-
   Bool bBoundary = false;
   UInt uiLPelX   = rpcBestCU->getCUPelX();
@@ -489,5 +508,5 @@
   if(!bSliceEnd && !bSliceStart && bInsidePicture )
   {
-#if  MTK_FAST_TEXTURE_ENCODING_E0173
+#if  H_3D_FAST_TEXTURE_ENCODING
     Bool bIVFMerge = false;
     Int  iIVFMaxD = 0;
@@ -501,7 +520,7 @@
       }
       // variables for fast encoder decision
-      bEarlySkip  = false;
+#if H_3D_QTLPC
       bTrySplit    = true;
-      fRD_Skip    = MAX_DOUBLE;
+#endif
 
       rpcTempCU->initEstData( uiDepth, iQP );
@@ -560,5 +579,5 @@
         }
       }
-#if  MTK_FAST_TEXTURE_ENCODING_E0173
+#if  H_3D_FAST_TEXTURE_ENCODING
       if(rpcTempCU->getSlice()->getViewIndex() && !rpcTempCU->getSlice()->getIsDepth())
       {
@@ -584,5 +603,5 @@
           rpcTempCU->setICFlagSubParts(bICFlag, 0, 0, uiDepth);
 #endif
-#if  MTK_FAST_TEXTURE_ENCODING_E0173
+#if  H_3D_FAST_TEXTURE_ENCODING
           xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N, bFMD );  rpcTempCU->initEstData( uiDepth, iQP );//by Competition for inter_2Nx2N
 #else
@@ -598,5 +617,5 @@
 #endif
         xCheckRDCostMerge2Nx2N( rpcBestCU, rpcTempCU, &earlyDetectionSkipMode );//by Merge for inter_2Nx2N
-#if  MTK_FAST_TEXTURE_ENCODING_E0173
+#if  H_3D_FAST_TEXTURE_ENCODING
         bFMD = bIVFMerge && rpcBestCU->isSkipped(0);
 #endif
@@ -605,24 +624,12 @@
         rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
 #endif
-        // fast encoder decision for early skip
-        if ( m_pcEncCfg->getUseFastEnc() )
-        {
-          Int iIdx = g_aucConvertToBit[ rpcBestCU->getWidth(0) ];
-          if ( aiNum [ iIdx ] > 5 && fRD_Skip < EARLY_SKIP_THRES*afCost[ iIdx ]/aiNum[ iIdx ] )
-          {
-            bEarlySkip = true;
-            bTrySplit  = false;
-          }
-        }
 
         if(!m_pcEncCfg->getUseEarlySkipDetection())
         {
           // 2Nx2N, NxN
-          if ( !bEarlySkip )
-          {
 #if H_3D_IC
             rpcTempCU->setICFlagSubParts(bICFlag, 0, 0, uiDepth);
 #endif
-#if  MTK_FAST_TEXTURE_ENCODING_E0173
+#if  H_3D_FAST_TEXTURE_ENCODING
             xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N, bFMD );  rpcTempCU->initEstData( uiDepth, iQP );
 #else
@@ -636,5 +643,4 @@
               doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
             }
-          }
         }
 #if H_3D_IC
@@ -643,25 +649,9 @@
       }
 
-#if H_3D_QTLPC
+#if H_3D_QTLPC      
       if(depthMapDetect && !bIntraSliceDetect && !rapPic && sps->getUseQTL())
       {
         bTrySplitDQP = bTrySplit;
       }
-      else
-      {
-#endif
-        if( (g_uiMaxCUWidth>>uiDepth) >= rpcTempCU->getSlice()->getPPS()->getMinCuDQPSize() )
-        {
-          if(iQP == iBaseQP)
-          {
-            bTrySplitDQP = bTrySplit;
-          }
-        }
-        else
-        {
-          bTrySplitDQP = bTrySplit;
-        }
-#if H_3D_QTLPC
-      }
 #endif
       if (isAddLowestQP && (iQP == lowestQP))
@@ -678,4 +668,26 @@
     }
 #endif
+#if RATE_CONTROL_LAMBDA_DOMAIN && M0036_RC_IMPROVEMENT && KWU_RC_MADPRED_E0227
+    if ( uiDepth <= m_addSADDepth )
+    {
+      m_LCUPredictionSAD += m_temporalSAD;
+      m_addSADDepth = uiDepth;
+    }
+#endif
+#if !RATE_CONTROL_LAMBDA_DOMAIN && KWU_RC_MADPRED_E0227
+if ( uiDepth <= m_addSADDepth )
+{
+  m_LCUPredictionSAD += m_temporalSAD;
+  m_addSADDepth = uiDepth;
+}
+#endif
+#if !RATE_CONTROL_LAMBDA_DOMAIN && KWU_FIX_URQ
+    if(m_pcEncCfg->getUseRateCtrl())
+    {
+      Int qp = m_pcRateCtrl->getUnitQP();
+      iMinQP  = Clip3( MIN_QP, MAX_QP, qp);
+      iMaxQP  = Clip3( MIN_QP, MAX_QP, qp);
+    }
+#endif
 
 #if H_3D_DIM_ENC
@@ -700,6 +712,4 @@
         {
           // 2Nx2N, NxN
-          if ( !bEarlySkip )
-          {
             if(!( (rpcBestCU->getWidth(0)==8) && (rpcBestCU->getHeight(0)==8) ))
             {
@@ -710,5 +720,5 @@
                 )
               {
-#if  MTK_FAST_TEXTURE_ENCODING_E0173
+#if  H_3D_FAST_TEXTURE_ENCODING
                 xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_NxN, bFMD  );
 #else
@@ -721,5 +731,4 @@
               }
             }
-          }
 
           // 2NxN, Nx2N
@@ -730,5 +739,5 @@
             )
           {
-#if  MTK_FAST_TEXTURE_ENCODING_E0173
+#if  H_3D_FAST_TEXTURE_ENCODING
             xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_Nx2N, bFMD  );
 #else
@@ -750,5 +759,5 @@
             )
           {
-#if  MTK_FAST_TEXTURE_ENCODING_E0173
+#if  H_3D_FAST_TEXTURE_ENCODING
             xCheckRDCostInter      ( rpcBestCU, rpcTempCU, SIZE_2NxN, bFMD  );
 #else
@@ -789,5 +798,5 @@
                 )
               {
-#if  MTK_FAST_TEXTURE_ENCODING_E0173
+#if  H_3D_FAST_TEXTURE_ENCODING
                 xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU, bFMD );
 #else
@@ -809,5 +818,5 @@
                 )
               {
-#if  MTK_FAST_TEXTURE_ENCODING_E0173
+#if  H_3D_FAST_TEXTURE_ENCODING
                 xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD, bFMD );
 #else
@@ -833,5 +842,5 @@
                 )
               {
-#if  MTK_FAST_TEXTURE_ENCODING_E0173
+#if  H_3D_FAST_TEXTURE_ENCODING
                 xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU, bFMD, true );
 #else
@@ -853,5 +862,5 @@
                 )
               {
-#if  MTK_FAST_TEXTURE_ENCODING_E0173
+#if  H_3D_FAST_TEXTURE_ENCODING
                 xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD, bFMD, true );
 #else
@@ -879,5 +888,5 @@
                 )
               {
-#if  MTK_FAST_TEXTURE_ENCODING_E0173
+#if  H_3D_FAST_TEXTURE_ENCODING
                 xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N, bFMD );
 #else
@@ -899,5 +908,5 @@
                 )
               {
-#if  MTK_FAST_TEXTURE_ENCODING_E0173
+#if  H_3D_FAST_TEXTURE_ENCODING
                 xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N, bFMD );
 #else
@@ -919,5 +928,5 @@
                 )
               {
-#if  MTK_FAST_TEXTURE_ENCODING_E0173
+#if  H_3D_FAST_TEXTURE_ENCODING
                 xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N, bFMD, true );
 #else
@@ -939,5 +948,5 @@
                 )
               {
-#if  MTK_FAST_TEXTURE_ENCODING_E0173
+#if  H_3D_FAST_TEXTURE_ENCODING
                 xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N, bFMD, true );
 #else
@@ -990,15 +999,10 @@
 #endif
         }
-#if  MTK_FAST_TEXTURE_ENCODING_E0173
+#if  H_3D_FAST_TEXTURE_ENCODING
         if(!bFMD)
         {
 #endif
         // do normal intra modes
-#if H_3D_DIM_ENC
-        if ( !bEarlySkip || ( rpcBestCU->getSlice()->getIsDepth() && rpcBestCU->getSlice()->isIRAP() ) )
-#else
-        if ( !bEarlySkip )
-#endif
-        {
+       
           // speedup for inter frames
           if( rpcBestCU->getSlice()->getSliceType() == I_SLICE || 
@@ -1012,4 +1016,27 @@
           {
             xCheckRDCostIntra( rpcBestCU, rpcTempCU, SIZE_2Nx2N );
+
+#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT && KWU_RC_MADPRED_E0227
+            if ( uiDepth <= m_addSADDepth )
+            {
+              m_LCUPredictionSAD += m_spatialSAD;
+              m_addSADDepth = uiDepth;
+            }
+#endif
+#if RATE_CONTROL_LAMBDA_DOMAIN && M0036_RC_IMPROVEMENT && KWU_RC_MADPRED_E0227
+            if ( uiDepth <= m_addSADDepth )
+            {
+              m_LCUPredictionSAD += m_spatialSAD;
+              m_addSADDepth = uiDepth;
+            }
+#endif
+
+#if !RATE_CONTROL_LAMBDA_DOMAIN && KWU_RC_MADPRED_E0227
+            if ( uiDepth <= m_addSADDepth )
+            {
+              m_LCUPredictionSAD += m_spatialSAD;
+              m_addSADDepth = uiDepth;
+            }
+#endif
             rpcTempCU->initEstData( uiDepth, iQP );
             if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
@@ -1029,6 +1056,4 @@
             }
           }
-        }
-
         // test PCM
         if(pcPic->getSlice(0)->getSPS()->getUsePCM()
@@ -1049,5 +1074,5 @@
           }
         }
-#if  MTK_FAST_TEXTURE_ENCODING_E0173
+#if  H_3D_FAST_TEXTURE_ENCODING
         }
 #endif
@@ -1074,15 +1099,4 @@
     rpcBestCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcBestCU->getTotalBits(), rpcBestCU->getTotalDistortion() );
 
-    // accumulate statistics for early skip
-    if ( m_pcEncCfg->getUseFastEnc() )
-    {
-      if ( rpcBestCU->isSkipped(0) )
-      {
-        Int iIdx = g_aucConvertToBit[ rpcBestCU->getWidth(0) ];
-        afCost[ iIdx ] += rpcBestCU->getTotalCost();
-        aiNum [ iIdx ] ++;
-      }
-    }
-
     // Early CU determination
     if( m_pcEncCfg->getUseEarlyCU() && rpcBestCU->isSkipped(0) )
@@ -1094,5 +1108,5 @@
       bSubBranch = true;
     }
-#if  MTK_FAST_TEXTURE_ENCODING_E0173
+#if  H_3D_FAST_TEXTURE_ENCODING
     if(rpcBestCU->getSlice()->getViewIndex() && !rpcBestCU->getSlice()->getIsDepth() && (uiDepth >=iIVFMaxD) && rpcBestCU->isSkipped(0))
     {
@@ -1168,5 +1182,9 @@
 
     // further split
+#if H_3D_QTLPC
     if( bSubBranch && bTrySplitDQP && uiDepth < g_uiMaxCUDepth - g_uiAddCUDepth )
+#else
+    if( bSubBranch && uiDepth < g_uiMaxCUDepth - g_uiAddCUDepth )
+#endif
     {
 #if H_3D_VSO // M9
@@ -1580,5 +1598,5 @@
   m_pcEntropyCoder->encodeARPW( pcCU , uiAbsPartIdx );
 #endif
-#if LGE_INTER_SDC_E0156
+#if H_3D_INTER_SDC
   m_pcEntropyCoder->encodeInterSDCFlag( pcCU, uiAbsPartIdx, false );
 #endif
@@ -1875,5 +1893,5 @@
 
           rpcTempCU->setSkipFlagSubParts( rpcTempCU->getQtRootCbf(0) == 0, 0, uhDepth );
-#if LGE_INTER_SDC_E0156
+#if H_3D_INTER_SDC
           TComDataCU *rpcTempCUPre = rpcTempCU;
 #endif
@@ -1881,5 +1899,5 @@
           xCheckDQP( rpcTempCU );
           xCheckBestMode(rpcBestCU, rpcTempCU, uhDepth);
-#if LGE_INTER_SDC_E0156
+#if H_3D_INTER_SDC
           if( rpcTempCU->getSlice()->getVPS()->getInterSDCFlag( rpcTempCU->getSlice()->getLayerIdInVps() ) && rpcTempCU->getSlice()->getIsDepth() && !uiNoResidual )
           {
@@ -1917,5 +1935,5 @@
       if( m_pcEncCfg->getUseFastDecisionForMerge() && !bestIsSkip )
       {
-#if LGE_INTER_SDC_E0156
+#if H_3D_INTER_SDC
         if( rpcTempCU->getSlice()->getVPS()->getInterSDCFlag( rpcTempCU->getSlice()->getLayerIdInVps() ) )
         {
@@ -1926,5 +1944,5 @@
 #endif
         bestIsSkip = rpcBestCU->getQtRootCbf(0) == 0;
-#if LGE_INTER_SDC_E0156
+#if H_3D_INTER_SDC
         }
 #endif
@@ -1971,5 +1989,5 @@
 
 #if AMP_MRG
-#if  MTK_FAST_TEXTURE_ENCODING_E0173
+#if  H_3D_FAST_TEXTURE_ENCODING
 Void TEncCu::xCheckRDCostInter( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize, Bool bFMD, Bool bUseMRG)
 #else
@@ -1980,5 +1998,5 @@
 #endif
 {
-#if  MTK_FAST_TEXTURE_ENCODING_E0173
+#if  H_3D_FAST_TEXTURE_ENCODING
   if(!(bFMD && (ePartSize == SIZE_2Nx2N)))  //have  motion estimation or merge check
   {
@@ -2057,5 +2075,5 @@
 #if AMP_MRG
   rpcTempCU->setMergeAMP (true);
-#if  MTK_FAST_TEXTURE_ENCODING_E0173
+#if  H_3D_FAST_TEXTURE_ENCODING
   m_pcPredSearch->predInterSearch ( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcRecoYuvTemp[uhDepth], bFMD, false, bUseMRG );
 #else
@@ -2102,5 +2120,5 @@
 #endif
 
-#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
+#if RATE_CONTROL_LAMBDA_DOMAIN  && (!M0036_RC_IMPROVEMENT || KWU_RC_MADPRED_E0227)
   if ( m_pcEncCfg->getUseRateCtrl() && m_pcEncCfg->getLCULevelRC() && ePartSize == SIZE_2Nx2N && uhDepth <= m_addSADDepth )
   {
@@ -2111,4 +2129,13 @@
   }
 #endif
+#if !RATE_CONTROL_LAMBDA_DOMAIN  && KWU_RC_MADPRED_E0227
+  if ( m_pcEncCfg->getUseRateCtrl() && ePartSize == SIZE_2Nx2N && uhDepth <= m_addSADDepth )
+  {
+    UInt SAD = m_pcRdCost->getSADPart( g_bitDepthY, m_ppcPredYuvTemp[uhDepth]->getLumaAddr(), m_ppcPredYuvTemp[uhDepth]->getStride(),
+      m_ppcOrigYuv[uhDepth]->getLumaAddr(), m_ppcOrigYuv[uhDepth]->getStride(),
+      rpcTempCU->getWidth(0), rpcTempCU->getHeight(0) );
+    m_temporalSAD = (Int)SAD;
+  }
+#endif
 
   m_pcPredSearch->encodeResAndCalcRdInterCU( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcResiYuvBest[uhDepth], m_ppcRecoYuvTemp[uhDepth], false );
@@ -2121,10 +2148,10 @@
 #endif
   rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
-#if LGE_INTER_SDC_E0156
+#if H_3D_INTER_SDC
   TComDataCU *rpcTempCUPre = rpcTempCU;
 #endif
   xCheckDQP( rpcTempCU );
   xCheckBestMode(rpcBestCU, rpcTempCU, uhDepth);
-#if LGE_INTER_SDC_E0156
+#if H_3D_INTER_SDC
   if( rpcTempCU->getSlice()->getVPS()->getInterSDCFlag( rpcTempCU->getSlice()->getLayerIdInVps() ) && rpcTempCU->getSlice()->getIsDepth() )
   {
@@ -2163,5 +2190,5 @@
   }
 #endif
-#if  MTK_FAST_TEXTURE_ENCODING_E0173
+#if  H_3D_FAST_TEXTURE_ENCODING
   }
 #endif
@@ -2235,4 +2262,34 @@
   rpcTempCU->getTotalCost() = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
   
+#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT && KWU_RC_MADPRED_E0227
+  UChar uhDepth = rpcTempCU->getDepth( 0 );
+  if ( m_pcEncCfg->getUseRateCtrl() && m_pcEncCfg->getLCULevelRC() && eSize == SIZE_2Nx2N && uhDepth <= m_addSADDepth )
+  {
+    UInt SAD = m_pcRdCost->getSADPart( g_bitDepthY, m_ppcPredYuvTemp[uhDepth]->getLumaAddr(), m_ppcPredYuvTemp[uhDepth]->getStride(),
+      m_ppcOrigYuv[uhDepth]->getLumaAddr(), m_ppcOrigYuv[uhDepth]->getStride(),
+      rpcTempCU->getWidth(0), rpcTempCU->getHeight(0) );
+    m_spatialSAD = (Int)SAD;
+  }
+#endif
+#if RATE_CONTROL_LAMBDA_DOMAIN && M0036_RC_IMPROVEMENT && KWU_RC_MADPRED_E0227
+  UChar uhDepth = rpcTempCU->getDepth( 0 );
+  if ( m_pcEncCfg->getUseRateCtrl() && m_pcEncCfg->getLCULevelRC() && eSize == SIZE_2Nx2N && uhDepth <= m_addSADDepth )
+  {
+    UInt SAD = m_pcRdCost->getSADPart( g_bitDepthY, m_ppcPredYuvTemp[uhDepth]->getLumaAddr(), m_ppcPredYuvTemp[uhDepth]->getStride(),
+      m_ppcOrigYuv[uhDepth]->getLumaAddr(), m_ppcOrigYuv[uhDepth]->getStride(),
+      rpcTempCU->getWidth(0), rpcTempCU->getHeight(0) );
+    m_spatialSAD = (Int)SAD;
+  }
+#endif
+#if !RATE_CONTROL_LAMBDA_DOMAIN && KWU_RC_MADPRED_E0227
+  UChar uhDepth = rpcTempCU->getDepth( 0 );
+  if ( m_pcEncCfg->getUseRateCtrl() && eSize == SIZE_2Nx2N && uhDepth <= m_addSADDepth )
+  {
+    UInt SAD = m_pcRdCost->getSADPart( g_bitDepthY, m_ppcPredYuvTemp[uhDepth]->getLumaAddr(), m_ppcPredYuvTemp[uhDepth]->getStride(),
+      m_ppcOrigYuv[uhDepth]->getLumaAddr(), m_ppcOrigYuv[uhDepth]->getStride(),
+      rpcTempCU->getWidth(0), rpcTempCU->getHeight(0) );
+    m_spatialSAD = (Int)SAD;
+  }
+#endif
   xCheckDQP( rpcTempCU );
   xCheckBestMode(rpcBestCU, rpcTempCU, uiDepth);
Index: trunk/source/Lib/TLibEncoder/TEncCu.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncCu.h	(revision 622)
+++ trunk/source/Lib/TLibEncoder/TEncCu.h	(revision 655)
@@ -102,9 +102,24 @@
   Bool                    m_bUseSBACRD;
   TEncRateCtrl*           m_pcRateCtrl;
-#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
+#if RATE_CONTROL_LAMBDA_DOMAIN
+#if !M0036_RC_IMPROVEMENT
   UInt                    m_LCUPredictionSAD;
   Int                     m_addSADDepth;
   Int                     m_temporalSAD;
 #endif
+#if M0036_RC_IMPROVEMENT && KWU_RC_MADPRED_E0227
+  UInt                    m_LCUPredictionSAD;
+  Int                     m_addSADDepth;
+  Int                     m_temporalSAD;
+  Int                     m_spatialSAD;
+#endif
+#endif
+#if !RATE_CONTROL_LAMBDA_DOMAIN && KWU_RC_MADPRED_E0227
+  UInt                    m_LCUPredictionSAD;
+  Int                     m_addSADDepth;
+  Int                     m_temporalSAD;
+  Int                     m_spatialSAD;
+#endif
+
 public:
   /// copy parameters from encoder class
@@ -124,5 +139,5 @@
   
   Void setBitCounter        ( TComBitCounter* pcBitCounter ) { m_pcBitCounter = pcBitCounter; }
-#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
+#if (RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT) || KWU_RC_MADPRED_E0227
   UInt getLCUPredictionSAD() { return m_LCUPredictionSAD; }
 #endif
@@ -145,5 +160,5 @@
 
 #if AMP_MRG
-#if  MTK_FAST_TEXTURE_ENCODING_E0173
+#if  H_3D_FAST_TEXTURE_ENCODING
   Void  xCheckRDCostInter   ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize,  Bool bFMD, Bool bUseMRG = false  ) ;
 #else
Index: trunk/source/Lib/TLibEncoder/TEncEntropy.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncEntropy.cpp	(revision 622)
+++ trunk/source/Lib/TLibEncoder/TEncEntropy.cpp	(revision 655)
@@ -662,5 +662,5 @@
 #endif
 
-#if LGE_INTER_SDC_E0156
+#if H_3D_INTER_SDC
   if( pcCU->getInterSDCFlag( uiAbsPartIdx ) )
   {
@@ -824,5 +824,5 @@
 }
 
-#if LGE_INTER_SDC_E0156
+#if H_3D_INTER_SDC
 Void TEncEntropy::encodeInterSDCFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
 {
Index: trunk/source/Lib/TLibEncoder/TEncEntropy.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncEntropy.h	(revision 622)
+++ trunk/source/Lib/TLibEncoder/TEncEntropy.h	(revision 655)
@@ -94,5 +94,5 @@
   virtual Void codeICFlag        ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
 #endif
-#if LGE_INTER_SDC_E0156
+#if H_3D_INTER_SDC
   virtual Void codeInterSDCFlag  ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
   virtual Void codeInterSDCResidualData ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiSegment ) = 0;
@@ -185,5 +185,5 @@
   Void encodeICFlag       ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
 #endif
-#if LGE_INTER_SDC_E0156
+#if H_3D_INTER_SDC
   Void encodeInterSDCFlag ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
   Void encodeInterSDCResidualData( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD );
Index: trunk/source/Lib/TLibEncoder/TEncGOP.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 622)
+++ trunk/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 655)
@@ -153,4 +153,8 @@
 #endif
 #endif
+
+#if KWU_FIX_URQ
+  m_pcRateCtrl           = pcTEncTop->getRateCtrl();
+#endif
 }
 
@@ -351,7 +355,7 @@
 #endif
 #if H_MV
-Void TEncGOP::compressPicInGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP, Int iGOPid)
-#else
-Void TEncGOP::compressGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP)
+Void TEncGOP::compressPicInGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP, Int iGOPid, bool isField, bool isTff)
+#else
+Void TEncGOP::compressGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP, bool isField, bool isTff)
 #endif
 {
@@ -367,5 +371,6 @@
 
 #if !H_MV
-  xInitGOP( iPOCLast, iNumPicRcvd, rcListPic, rcListPicYuvRecOut );
+  xInitGOP( iPOCLast, iNumPicRcvd, rcListPic, rcListPicYuvRecOut, isField );
+
   
   m_iNumPicCoded = 0;
@@ -439,10 +444,21 @@
 
     /////////////////////////////////////////////////////////////////////////////////////////////////// Initial to start encoding
-    Int pocCurr = iPOCLast -iNumPicRcvd+ m_pcCfg->getGOPEntry(iGOPid).m_POC;
-    Int iTimeOffset = m_pcCfg->getGOPEntry(iGOPid).m_POC;
-    if(iPOCLast == 0)
+    Int iTimeOffset;
+    Int pocCurr;
+    
+    if(iPOCLast == 0) //case first frame or first top field
     {
       pocCurr=0;
       iTimeOffset = 1;
+    }
+    else if(iPOCLast == 1 && isField) //case first bottom field, just like the first frame, the poc computation is not right anymore, we set the right value
+    {
+      pocCurr = 1;
+      iTimeOffset = 1;
+    }
+    else
+    {
+      pocCurr = iPOCLast - iNumPicRcvd + m_pcCfg->getGOPEntry(iGOPid).m_POC - isField;
+      iTimeOffset = m_pcCfg->getGOPEntry(iGOPid).m_POC;
     }
     if(pocCurr>=m_pcCfg->getFramesToBeEncoded())
@@ -463,5 +479,5 @@
     accessUnitsInGOP.push_back(AccessUnit());
     AccessUnit& accessUnit = accessUnitsInGOP.back();
-    xGetBuffer( rcListPic, rcListPicYuvRecOut, iNumPicRcvd, iTimeOffset, pcPic, pcPicYuvRecOut, pocCurr );
+    xGetBuffer( rcListPic, rcListPicYuvRecOut, iNumPicRcvd, iTimeOffset, pcPic, pcPicYuvRecOut, pocCurr, isField);
 
     //  Slice data initialization
@@ -472,25 +488,17 @@
 
 
-#if H_MV5
 #if H_MV
-    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, pocCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getVPS(), m_pcEncTop->getSPS(), m_pcEncTop->getPPS(), getLayerId() );     
-#else
-    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, pocCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getSPS(), m_pcEncTop->getPPS() );
-#endif
-#else
-#if H_3D
-    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, pocCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getVPS(), m_pcEncTop->getSPS(), m_pcEncTop->getPPS(), getLayerId() );     
-#else
-    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, pocCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getSPS(), m_pcEncTop->getPPS() );
-#endif
-#endif
+    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, pocCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getVPS(), m_pcEncTop->getSPS(), m_pcEncTop->getPPS(), getLayerId(), isField  );     
+#else
+    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, pocCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getSPS(), m_pcEncTop->getPPS(), isField  );
+#endif
+    
+    //Set Frame/Field coding
+    pcSlice->getPic()->setField(isField);
+
     pcSlice->setLastIDR(m_iLastIDR);
     pcSlice->setSliceIdx(0);
 #if H_MV
-#if H_MV5
     pcSlice->setRefPicSetInterLayer ( &m_refPicSetInterLayer0, &m_refPicSetInterLayer1 ); 
-#else
-    pcSlice->setRefPicSetInterLayer ( &m_refPicSetInterLayer ); 
-#endif
     pcPic  ->setLayerId     ( getLayerId()   );
     pcPic  ->setViewId      ( getViewId()    );    
@@ -508,5 +516,4 @@
     pcSlice->setLFCrossSliceBoundaryFlag(  pcSlice->getPPS()->getLoopFilterAcrossSlicesEnabledFlag()  );
     pcSlice->setScalingList ( m_pcEncTop->getScalingList()  );
-    pcSlice->getScalingList()->setUseTransformSkip(m_pcEncTop->getPPS()->getUseTransformSkip());
     if(m_pcEncTop->getUseScalingListId() == SCALING_LIST_OFF)
     {
@@ -562,5 +569,7 @@
     if(pcSlice->getTemporalLayerNonReferenceFlag())
     {
-      if(pcSlice->getNalUnitType()==NAL_UNIT_CODED_SLICE_TRAIL_R)
+      if (pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_TRAIL_R &&
+          !(m_iGopSize == 1 && pcSlice->getSliceType() == I_SLICE))
+        // Add this condition to avoid POC issues with encoder_intra_main.cfg configuration (see #1127 in bug tracker)
       {
         pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TRAIL_N);
@@ -655,5 +664,4 @@
     refPicListModification->setRefPicListModificationFlagL1(0);
 #if H_MV
-#if H_MV5
     if ( pcSlice->getPPS()->getNumExtraSliceHeaderBits() > 1 )
     {
@@ -699,56 +707,4 @@
     xSetRefPicListModificationsMv( tempRefPicLists, pcSlice, iGOPid );    
 #else
-    if ( pcSlice->getPPS()->getNumExtraSliceHeaderBits() > 0 )
-    {
-      pcSlice->setDiscardableFlag           ( false );     
-    }    
-
-    TComVPS*           vps = pcSlice->getVPS(); 
-    Int       layerIdInVps = vps    ->getLayerIdInVps( getLayerId()); 
-    Int numDirectRefLayers = vps    ->getNumDirectRefLayers( layerIdInVps ); 
-    GOPEntry gopEntry      = m_pcCfg->getGOPEntry( (pcSlice->getRapPicFlag() && getLayerId() > 0) ? MAX_GOP : iGOPid );     
-    
-    if ( getLayerId() > 0 && numDirectRefLayers > 0 )
-    {         
-      pcSlice->setInterLayerPredEnabledFlag ( gopEntry.m_numActiveRefLayerPics > 0 );     
-      if ( pcSlice->getInterLayerPredEnabledFlag() && numDirectRefLayers > 1 )
-      {
-        if ( !vps->getMaxOneActiveRefLayerFlag() )
-        {    
-          pcSlice->setNumInterLayerRefPicsMinus1( gopEntry.m_numActiveRefLayerPics - 1 ); 
-        }
-        for (Int i = 0; i < gopEntry.m_numActiveRefLayerPics; i++ )
-        {
-          pcSlice->setInterLayerPredLayerIdc( i, gopEntry.m_interLayerPredLayerIdc[ i ] ); 
-        }
-      }
-    }
-    assert( pcSlice->getNumActiveRefLayerPics() == gopEntry.m_numActiveRefLayerPics ); 
-    
-    if ( vps->getNumSamplePredRefLayers( layerIdInVps ) > 0 && pcSlice->getNumActiveRefLayerPics() > 0)
-    {
-      pcSlice->setInterLayerSamplePredOnlyFlag( gopEntry.m_numRefPics == 0 ); 
-    }    
-
-    pcSlice->createAndApplyIvReferencePictureSet( m_ivPicLists, m_refPicSetInterLayer ); 
-    pcSlice->setNumRefIdx(REF_PIC_LIST_0,min(gopEntry.m_numRefPicsActive,( pcSlice->getRPS()->getNumberOfPictures() + (Int) m_refPicSetInterLayer.size() ) ) );
-    pcSlice->setNumRefIdx(REF_PIC_LIST_1,min(gopEntry.m_numRefPicsActive,( pcSlice->getRPS()->getNumberOfPictures() + (Int) m_refPicSetInterLayer.size() ) ) );
-
-    xSetRefPicListModificationsMv( pcSlice, iGOPid );    
-
-    pcSlice->setActiveMotionPredRefLayers( );
-
-    if ( getLayerId() > 0 && pcSlice->getNumActiveMotionPredRefLayers() > 0 && pcSlice->getEnableTMVPFlag() && 
-        ( pcSlice->getSliceType() == B_SLICE || pcSlice->getSliceType() == P_SLICE ))
-    {
-      pcSlice->setAltCollocatedIndicationFlag( gopEntry.m_collocatedRefLayerIdx >= 0 );
-      if ( pcSlice->getNumActiveRefLayerPics() && pcSlice->getNumActiveMotionPredRefLayers() > 0 )
-      {
-        pcSlice->setCollocatedRefLayerIdx( gopEntry.m_collocatedRefLayerIdx );
-      }
-    }
-
-#endif
-#else
     pcSlice->setNumRefIdx(REF_PIC_LIST_0,min(m_pcCfg->getGOPEntry(iGOPid).m_numRefPicsActive,pcSlice->getRPS()->getNumberOfPictures()));
     pcSlice->setNumRefIdx(REF_PIC_LIST_1,min(m_pcCfg->getGOPEntry(iGOPid).m_numRefPicsActive,pcSlice->getRPS()->getNumberOfPictures()));
@@ -760,5 +716,4 @@
 
     //  Set reference list
-#if H_MV5
 #if H_MV    
     pcSlice->setRefPicList( tempRefPicLists, usedAsLongTerm, numPocTotalCurr ); 
@@ -782,26 +737,4 @@
       }
     }
-#endif
-#else
-#if H_MV    
-    pcSlice->setRefPicList( rcListPic, m_refPicSetInterLayer );
-#if H_3D_ARP
-    pcSlice->setARPStepNum();
-    if(pcSlice->getARPStepNum() > 1)
-    {
-      for(Int iLayerId = 0; iLayerId < getLayerId(); iLayerId ++ )
-      {
-        Int  iViewIdx =   pcSlice->getVPS()->getViewIndex(iLayerId);
-        Bool bIsDepth = ( pcSlice->getVPS()->getDepthId  ( iLayerId ) == 1 );
-        if( iViewIdx<getViewIndex() && !bIsDepth )
-        {
-          pcSlice->setBaseViewRefPicList( m_ivPicLists->getPicList( iLayerId ), iViewIdx );
-        }
-      }
-    }
-#endif
-#else
-    pcSlice->setRefPicList ( rcListPic );
-#endif
 #endif
 #if H_3D
@@ -913,6 +846,13 @@
 
     // SAIT_VSO_EST_A0033
+#if H_3D_FCO
+    Bool flagRec;
+    flagRec =  ((m_pcEncTop->getIvPicLists()->getPicYuv( pcSlice->getViewIndex(), false, pcSlice->getPOC(), true) == NULL) ? false: true);
+    pcRdCost->setVideoRecPicYuv( m_pcEncTop->getIvPicLists()->getPicYuv( pcSlice->getViewIndex(), false, pcSlice->getPOC(), flagRec ) );
+    pcRdCost->setDepthPicYuv   ( m_pcEncTop->getIvPicLists()->getPicYuv( pcSlice->getViewIndex(), true, pcSlice->getPOC(), false ) );
+#else
     pcRdCost->setVideoRecPicYuv( m_pcEncTop->getIvPicLists()->getPicYuv( pcSlice->getViewIndex(), false , pcSlice->getPOC(), true ) );
     pcRdCost->setDepthPicYuv   ( m_pcEncTop->getIvPicLists()->getPicYuv( pcSlice->getViewIndex(), true  , pcSlice->getPOC(), false ) );
+#endif
 
     // LGE_WVSO_A0119
@@ -970,4 +910,12 @@
       }
       m_pcRateCtrl->initRCPic( frameLevel );
+
+#if KWU_RC_MADPRED_E0227
+      if(m_pcCfg->getLayerId() != 0)
+      {
+        m_pcRateCtrl->getRCPic()->setIVPic( m_pcEncTop->getEncTop()->getTEncTop(0)->getRateCtrl()->getRCPic() );
+      }
+#endif
+
       estimatedBits = m_pcRateCtrl->getRCPic()->getTargetBits();
 
@@ -1014,4 +962,14 @@
       else    // normal case
       {
+#if KWU_RC_MADPRED_E0227
+        if(m_pcRateCtrl->getLayerID() != 0)
+        {
+          list<TEncRCPic*> listPreviousPicture = m_pcRateCtrl->getPicList();
+          lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambdaIV( listPreviousPicture, pcSlice->getPOC() );
+          sliceQP = m_pcRateCtrl->getRCPic()->estimatePicQP( lambda, listPreviousPicture );
+        }
+        else
+        {
+#endif
         list<TEncRCPic*> listPreviousPicture = m_pcRateCtrl->getPicList();
 #if RATE_CONTROL_INTRA
@@ -1021,4 +979,7 @@
 #endif
         sliceQP = m_pcRateCtrl->getRCPic()->estimatePicQP( lambda, listPreviousPicture );
+#if KWU_RC_MADPRED_E0227
+        }
+#endif
       }
 
@@ -1155,16 +1116,16 @@
         pcPic->setNumDdvCandPics(pcPic->getDisCandRefPictures(iColPoc));
       }
+#endif
 #if H_3D
       pcSlice->setDepthToDisparityLUTs(); 
 
 #endif
-#endif
-#if MTK_NBDV_TN_FIX_E0172 
+
+#if H_3D_NBDV
       if(pcSlice->getViewIndex() && !pcSlice->getIsDepth() && !pcSlice->isIntra()) //Notes from QC: this condition shall be changed once the configuration is completed, e.g. in pcSlice->getSPS()->getMultiviewMvPredMode() || ARP in prev. HTM. Remove this comment once it is done.
       {
         pcPic->checkTemporalIVRef();
       }
-#endif
-#if MTK_TEXTURE_MRGCAND_BUGFIX_E0182
+
       if(pcSlice->getIsDepth())
       {
@@ -1412,5 +1373,5 @@
         }
       }
-      pictureTimingSEI.m_auCpbRemovalDelay = std::max<Int>(1, m_totalCoded - m_lastBPSEI); // Syntax element signalled as minus, hence the .
+      pictureTimingSEI.m_auCpbRemovalDelay = std::min<Int>(std::max<Int>(1, m_totalCoded - m_lastBPSEI), static_cast<Int>(pow(2, static_cast<double>(pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getCpbRemovalDelayLengthMinus1()+1)))); // Syntax element signalled as minus, hence the .
       pictureTimingSEI.m_picDpbOutputDelay = pcSlice->getSPS()->getNumReorderPics(0) + pcSlice->getPOC() - m_totalCoded;
       Int factor = pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getTickDivisorMinus2() + 2;
@@ -1862,5 +1823,5 @@
         pcPic->destroyNonDBFilterInfo();
       }
-#if MTK_SONY_PROGRESSIVE_MV_COMPRESSION_E0170
+#if H_3D
       pcPic->compressMotion(2); 
 #endif
@@ -1898,5 +1859,5 @@
           digestStr = digestToString(sei_recon_picture_digest.digest, 4);
         }
-#if H_MV_FIX_LID_PIC_HASH_SEI_T40
+#if H_MV
         OutputNALUnit nalu(NAL_UNIT_SUFFIX_SEI, pcSlice->getTLayer(), getLayerId() );
 #else
@@ -1940,4 +1901,18 @@
       xCalculateAddPSNR( pcPic, pcPic->getPicYuvRec(), accessUnit, dEncTime );
 
+    //In case of field coding, compute the interlaced PSNR for both fields
+    if (isField && ((!pcPic->isTopField() && isTff) || (pcPic->isTopField() && !isTff)))
+    {
+      //get complementary top field
+      TComPic* pcPicTop;
+      TComList<TComPic*>::iterator   iterPic = rcListPic.begin();
+      while ((*iterPic)->getPOC() != pcPic->getPOC()-1)
+      {
+        iterPic ++;
+      }
+      pcPicTop = *(iterPic);
+      xCalculateInterlacedAddPSNR(pcPicTop, pcPic, pcPicTop->getPicYuvRec(), pcPic->getPicYuvRec(), accessUnit, dEncTime );
+    }
+    
       if (digestStr)
       {
@@ -2072,4 +2047,5 @@
             OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI, pcSlice->getTLayer());
           m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
+          pictureTimingSEI.m_picStruct = (isField && pcSlice->getPic()->isTopField())? 1 : isField? 2 : 0;
           m_seiWriter.writeSEImessage(nalu.m_Bitstream, pictureTimingSEI, pcSlice->getSPS());
           writeRBSPTrailingBits(nalu.m_Bitstream);
@@ -2166,9 +2142,5 @@
       pcPic->setReconMark   ( true );
 #if H_MV
-#if H_MV5
       TComSlice::markIvRefPicsAsShortTerm( m_refPicSetInterLayer0, m_refPicSetInterLayer1 );  
-#else
-      TComSlice::markIvRefPicsAsShortTerm( m_refPicSetInterLayer );  
-#endif
       std::vector<Int> temp; 
       TComSlice::markCurrPic( pcPic ); 
@@ -2184,5 +2156,5 @@
       delete[] pcSubstreamsOut;
   }
-#if !RATE_CONTROL_LAMBDA_DOMAIN
+#if !KWU_FIX_URQ && !RATE_CONTROL_LAMBDA_DOMAIN
   if(m_pcCfg->getUseRateCtrl())
   {
@@ -2196,10 +2168,10 @@
 
 #if !H_MV
-  assert ( m_iNumPicCoded == iNumPicRcvd );
+  assert ( (m_iNumPicCoded == iNumPicRcvd) || (isField && iPOCLast == 1) );
 #endif
 }
 
 #if !H_MV
-Void TEncGOP::printOutSummary(UInt uiNumAllPicCoded)
+Void TEncGOP::printOutSummary(UInt uiNumAllPicCoded, bool isField)
 {
   assert (uiNumAllPicCoded == m_gcAnalyzeAll.getNumPic());
@@ -2207,8 +2179,18 @@
     
   //--CFG_KDY
+  if(isField)
+  {
+    m_gcAnalyzeAll.setFrmRate( m_pcCfg->getFrameRate() * 2);
+    m_gcAnalyzeI.setFrmRate( m_pcCfg->getFrameRate() * 2);
+    m_gcAnalyzeP.setFrmRate( m_pcCfg->getFrameRate() * 2);
+    m_gcAnalyzeB.setFrmRate( m_pcCfg->getFrameRate() * 2);
+  }
+  else
+  {
   m_gcAnalyzeAll.setFrmRate( m_pcCfg->getFrameRate() );
   m_gcAnalyzeI.setFrmRate( m_pcCfg->getFrameRate() );
   m_gcAnalyzeP.setFrmRate( m_pcCfg->getFrameRate() );
   m_gcAnalyzeB.setFrmRate( m_pcCfg->getFrameRate() );
+  }
   
   //-- all
@@ -2233,4 +2215,16 @@
   m_gcAnalyzeB.printSummary('B');
 #endif
+
+  if(isField)
+  {
+    //-- interlaced summary
+    m_gcAnalyzeAll_in.setFrmRate( m_pcCfg->getFrameRate());
+    printf( "\n\nSUMMARY INTERLACED ---------------------------------------------\n" );
+    m_gcAnalyzeAll_in.printOutInterlaced('a',  m_gcAnalyzeAll.getBits());
+    
+#if _SUMMARY_OUT_
+    m_gcAnalyzeAll_in.printSummaryOutInterlaced();
+#endif
+  }
 
   printf("\nRVM: %.3lf\n" , xCalculateRVM());
@@ -2276,4 +2270,22 @@
 // Protected member functions
 // ====================================================================================================================
+
+
+Void TEncGOP::xInitGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, bool isField )
+{
+  assert( iNumPicRcvd > 0 );
+  //  Exception for the first frames
+  if ( ( isField && (iPOCLast == 0 || iPOCLast == 1) ) || (!isField  && (iPOCLast == 0))  )
+  {
+    m_iGopSize    = 1;
+  }
+  else
+  {
+    m_iGopSize    = m_pcCfg->getGOPSize();
+  }
+  assert (m_iGopSize > 0);
+  
+  return;
+}
 
 Void TEncGOP::xInitGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut )
@@ -2299,14 +2311,34 @@
                          TComPic*&                 rpcPic,
                          TComPicYuv*&              rpcPicYuvRecOut,
-                         Int                       pocCurr )
+                         Int                       pocCurr,
+                         bool                      isField)
 {
   Int i;
   //  Rec. output
   TComList<TComPicYuv*>::iterator     iterPicYuvRec = rcListPicYuvRecOut.end();
-  for ( i = 0; i < iNumPicRcvd - iTimeOffset + 1; i++ )
+  
+  if (isField)
+  {
+    for ( i = 0; i < ( (pocCurr == 0 ) || (pocCurr == 1 ) ? (iNumPicRcvd - iTimeOffset + 1) : (iNumPicRcvd - iTimeOffset + 2) ); i++ )
+    {
+      iterPicYuvRec--;
+    }
+  }
+  else
+  {
+    for ( i = 0; i < (iNumPicRcvd - iTimeOffset + 1); i++ )
   {
     iterPicYuvRec--;
   }
   
+  }
+  
+  if (isField)
+  {
+    if(pocCurr == 1)
+    {
+      iterPicYuvRec++;
+    }
+  }
   rpcPicYuvRecOut = *(iterPicYuvRec);
   
@@ -2323,5 +2355,8 @@
     iterPic++;
   }
-  
+
+#if !H_MV
+  assert( rpcPic != NULL );
+#endif
   assert (rpcPic->getPOC() == pocCurr);
   
@@ -2642,4 +2677,167 @@
 }
 
+
+Void reinterlace(Pel* top, Pel* bottom, Pel* dst, UInt stride, UInt width, UInt height, bool isTff)
+{
+  
+  for (Int y = 0; y < height; y++)
+  {
+    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];
+    }
+    top += stride;
+    bottom += stride;
+    dst += stride*2;
+  }
+}
+
+
+Void TEncGOP::xCalculateInterlacedAddPSNR( TComPic* pcPicOrgTop, TComPic* pcPicOrgBottom, TComPicYuv* pcPicRecTop, TComPicYuv* pcPicRecBottom, const AccessUnit& accessUnit, Double dEncTime )
+{
+#if  H_MV
+  assert( 0 ); // Field coding and MV need to be aligned. 
+#else
+  Int     x, y;
+  
+  UInt64 uiSSDY_in  = 0;
+  UInt64 uiSSDU_in  = 0;
+  UInt64 uiSSDV_in  = 0;
+  
+  Double  dYPSNR_in  = 0.0;
+  Double  dUPSNR_in  = 0.0;
+  Double  dVPSNR_in  = 0.0;
+  
+  /*------ INTERLACED PSNR -----------*/
+  
+  /* Luma */
+  
+  Pel*  pOrgTop = pcPicOrgTop->getPicYuvOrg()->getLumaAddr();
+  Pel*  pOrgBottom = pcPicOrgBottom->getPicYuvOrg()->getLumaAddr();
+  Pel*  pRecTop = pcPicRecTop->getLumaAddr();
+  Pel*  pRecBottom = pcPicRecBottom->getLumaAddr();
+  
+  Int   iWidth;
+  Int   iHeight;
+  Int iStride;
+  
+  iWidth  = pcPicOrgTop->getPicYuvOrg()->getWidth () - m_pcEncTop->getPad(0);
+  iHeight = pcPicOrgTop->getPicYuvOrg()->getHeight() - m_pcEncTop->getPad(1);
+  iStride = pcPicOrgTop->getPicYuvOrg()->getStride();
+  Int   iSize   = iWidth*iHeight;
+  bool isTff = pcPicOrgTop->isTopField();
+  
+  TComPicYuv* pcOrgInterlaced = new TComPicYuv;
+  pcOrgInterlaced->create( iWidth, iHeight << 1, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+  
+  TComPicYuv* pcRecInterlaced = new TComPicYuv;
+  pcRecInterlaced->create( iWidth, iHeight << 1, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+  
+  Pel* pOrgInterlaced = pcOrgInterlaced->getLumaAddr();
+  Pel* pRecInterlaced = pcRecInterlaced->getLumaAddr();
+  
+  //=== Interlace fields ====
+  reinterlace(pOrgTop, pOrgBottom, pOrgInterlaced, iStride, iWidth, iHeight, isTff);
+  reinterlace(pRecTop, pRecBottom, pRecInterlaced, iStride, iWidth, iHeight, isTff);
+  
+  //===== calculate PSNR =====
+  for( y = 0; y < iHeight << 1; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+      Int iDiff = (Int)( pOrgInterlaced[x] - pRecInterlaced[x] );
+      uiSSDY_in   += iDiff * iDiff;
+    }
+    pOrgInterlaced += iStride;
+    pRecInterlaced += iStride;
+  }
+  
+  /*Chroma*/
+  
+  iHeight >>= 1;
+  iWidth  >>= 1;
+  iStride >>= 1;
+  
+  pOrgTop = pcPicOrgTop->getPicYuvOrg()->getCbAddr();
+  pOrgBottom = pcPicOrgBottom->getPicYuvOrg()->getCbAddr();
+  pRecTop = pcPicRecTop->getCbAddr();
+  pRecBottom = pcPicRecBottom->getCbAddr();
+  pOrgInterlaced = pcOrgInterlaced->getCbAddr();
+  pRecInterlaced = pcRecInterlaced->getCbAddr();
+  
+  //=== Interlace fields ====
+  reinterlace(pOrgTop, pOrgBottom, pOrgInterlaced, iStride, iWidth, iHeight, isTff);
+  reinterlace(pRecTop, pRecBottom, pRecInterlaced, iStride, iWidth, iHeight, isTff);
+  
+  //===== calculate PSNR =====
+  for( y = 0; y < iHeight << 1; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+      Int iDiff = (Int)( pOrgInterlaced[x] - pRecInterlaced[x] );
+      uiSSDU_in   += iDiff * iDiff;
+    }
+    pOrgInterlaced += iStride;
+    pRecInterlaced += iStride;
+  }
+  
+  pOrgTop = pcPicOrgTop->getPicYuvOrg()->getCrAddr();
+  pOrgBottom = pcPicOrgBottom->getPicYuvOrg()->getCrAddr();
+  pRecTop = pcPicRecTop->getCrAddr();
+  pRecBottom = pcPicRecBottom->getCrAddr();
+  pOrgInterlaced = pcOrgInterlaced->getCrAddr();
+  pRecInterlaced = pcRecInterlaced->getCrAddr();
+  
+  //=== Interlace fields ====
+  reinterlace(pOrgTop, pOrgBottom, pOrgInterlaced, iStride, iWidth, iHeight, isTff);
+  reinterlace(pRecTop, pRecBottom, pRecInterlaced, iStride, iWidth, iHeight, isTff);
+  
+  //===== calculate PSNR =====
+  for( y = 0; y < iHeight << 1; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+      Int iDiff = (Int)( pOrgInterlaced[x] - pRecInterlaced[x] );
+      uiSSDV_in   += iDiff * iDiff;
+    }
+    pOrgInterlaced += iStride;
+    pRecInterlaced += iStride;
+  }
+  
+  Int maxvalY = 255 << (g_bitDepthY-8);
+  Int maxvalC = 255 << (g_bitDepthC-8);
+  Double fRefValueY = (Double) maxvalY * maxvalY * iSize*2;
+  Double fRefValueC = (Double) maxvalC * maxvalC * iSize*2 / 4.0;
+  dYPSNR_in            = ( uiSSDY_in ? 10.0 * log10( fRefValueY / (Double)uiSSDY_in ) : 99.99 );
+  dUPSNR_in            = ( uiSSDU_in ? 10.0 * log10( fRefValueC / (Double)uiSSDU_in ) : 99.99 );
+  dVPSNR_in            = ( uiSSDV_in ? 10.0 * log10( fRefValueC / (Double)uiSSDV_in ) : 99.99 );
+  
+  /* calculate the size of the access unit, excluding:
+   *  - any AnnexB contributions (start_code_prefix, zero_byte, etc.,)
+   *  - SEI NAL units
+   */
+  UInt numRBSPBytes = 0;
+  for (AccessUnit::const_iterator it = accessUnit.begin(); it != accessUnit.end(); it++)
+  {
+    UInt numRBSPBytes_nal = UInt((*it)->m_nalUnitData.str().size());
+    
+    if ((*it)->m_nalUnitType != NAL_UNIT_PREFIX_SEI && (*it)->m_nalUnitType != NAL_UNIT_SUFFIX_SEI)
+      numRBSPBytes += numRBSPBytes_nal;
+  }
+  
+  UInt uibits = numRBSPBytes * 8 ;
+  
+  //===== add PSNR =====
+  m_gcAnalyzeAll_in.addResult (dYPSNR_in, dUPSNR_in, dVPSNR_in, (Double)uibits);
+  
+  printf("\n                                      Interlaced frame %d: [Y %6.4lf dB    U %6.4lf dB    V %6.4lf dB]", pcPicOrgBottom->getPOC()/2 , dYPSNR_in, dUPSNR_in, dVPSNR_in );
+  
+  pcOrgInterlaced->destroy();
+  delete pcOrgInterlaced;
+  pcRecInterlaced->destroy();
+  delete pcRecInterlaced;
+#endif
+}
 /** Function for deciding the nal_unit_type.
  * \param pocCurr POC of the current picture
@@ -3002,5 +3200,4 @@
 
 #if H_MV
-#if H_MV5
 Void TEncGOP::xSetRefPicListModificationsMv( std::vector<TComPic*> tempPicLists[2], TComSlice* pcSlice, UInt iGOPid )
 { 
@@ -3086,68 +3283,4 @@
   }
 }
-#else
-Void TEncGOP::xSetRefPicListModificationsMv( TComSlice* pcSlice, UInt iGOPid )
-{ 
-  Int layer    = pcSlice->getLayerIdInVps( ); 
-  
-  if( pcSlice->getSliceType() == I_SLICE || !(pcSlice->getPPS()->getListsModificationPresentFlag()) || pcSlice->getNumActiveRefLayerPics() == 0 )
-  {
-    return;
-  }
-
-  // analyze inter-view modifications
-  GOPEntry ge = m_pcCfg->getGOPEntry( (pcSlice->getRapPicFlag() && ( layer > 0) ) ? MAX_GOP : iGOPid );
-  assert( ge.m_numActiveRefLayerPics == pcSlice->getNumActiveRefLayerPics() ); 
-  
-  Int maxRefListSize  = pcSlice->getNumRpsCurrTempList();
-  Int numTemporalRefs = maxRefListSize - pcSlice->getNumActiveRefLayerPics();
-
-  for (Int li = 0; li < 2; li ++) // Loop over lists L0 and L1
-  {
-    // set inter-view modifications    
-    Int tempList[16];
-    for( Int k = 0; k < 16; k++ )
-    {
-      tempList[ k ] = -1;
-    }
-
-    Bool isModified = false;
-    if ( maxRefListSize > 1 )
-    {
-      for( Int k = 0, orgIdx = numTemporalRefs; k < ge.m_numActiveRefLayerPics; k++, orgIdx++ )
-      {
-          Int targetIdx = ge.m_interViewRefPosL[ li ][ k ];
-
-        isModified = ( targetIdx != orgIdx ) && ( targetIdx >= 0  );
-        if ( isModified )
-            {
-          assert( tempList[ targetIdx ] == -1 ); // Assert when two inter layer reference pictures are sorted to the same position
-              tempList[ targetIdx ] = orgIdx;              
-        }
-      }
-    }
-
-    TComRefPicListModification* refPicListModification = pcSlice->getRefPicListModification();
-    refPicListModification->setRefPicListModificationFlagL( li, isModified );  
-
-      if( isModified )
-      {
-        Int temporalRefIdx = 0;
-        for( Int i = 0; i < pcSlice->getNumRefIdx( ( li == 0 ) ? REF_PIC_LIST_0 : REF_PIC_LIST_1 ); i++ )
-        {
-          if( tempList[i] >= 0 ) 
-          {
-            refPicListModification->setRefPicSetIdxL( li, i, tempList[i] );
-          }
-          else
-          {
-            refPicListModification->setRefPicSetIdxL( li, i, temporalRefIdx );
-            temporalRefIdx++;
-          }
-        }
-      }
-  }
-}
-#endif
 #endif
 //! \}
Index: trunk/source/Lib/TLibEncoder/TEncGOP.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncGOP.h	(revision 622)
+++ trunk/source/Lib/TLibEncoder/TEncGOP.h	(revision 655)
@@ -57,4 +57,7 @@
 #include "TEncAnalyze.h"
 #include "TEncRateCtrl.h"
+#if KWU_RC_MADPRED_E0227
+#include "../App/TAppEncoder/TAppEncTop.h"
+#endif
 #include <vector>
 
@@ -99,10 +102,6 @@
 #if H_MV
   TComPicLists*           m_ivPicLists;
-#if H_MV5
   std::vector<TComPic*>   m_refPicSetInterLayer0; 
   std::vector<TComPic*>   m_refPicSetInterLayer1; 
-#else
-  std::vector<TComPic*>   m_refPicSetInterLayer; 
-#endif
 
   Int                     m_pocLastCoded;
@@ -148,7 +147,7 @@
 #if H_MV
   Void  initGOP     ( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP);
-  Void  compressPicInGOP ( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP, Int iGOPid );
+  Void  compressPicInGOP ( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP, Int iGOPid, Bool isField, Bool isTff  );
 #else
-  Void  compressGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRec, std::list<AccessUnit>& accessUnitsInGOP );
+  Void  compressGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRec, std::list<AccessUnit>& accessUnitsInGOP, Bool isField, Bool isTff  );
 #endif
   Void  xAttachSliceDataToNalUnit (OutputNALUnit& rNalu, TComOutputBitstream*& rpcBitstreamRedirect);
@@ -169,5 +168,5 @@
 
 #if !H_MV
-  Void  printOutSummary      ( UInt uiNumAllPicCoded );
+  Void  printOutSummary      ( UInt uiNumAllPicCoded , bool isField);
 #endif
 #if H_3D_VSO
@@ -176,5 +175,9 @@
   Void  preLoopFilterPicAll  ( TComPic* pcPic, UInt64& ruiDist, UInt64& ruiBits );
 #endif
-  
+
+#if KWU_RC_MADPRED_E0227
+  TEncTop* getEncTop() { return m_pcEncTop; }
+#endif
+
   TEncSlice*  getSliceEncoder()   { return m_pcSliceEncoder; }
   NalUnitType getNalUnitType( Int pocCurr, Int lastIdr );
@@ -184,8 +187,12 @@
 
 protected:
+  Void xInitGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, bool isField );
+
   Void  xInitGOP          ( Int iPOC, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut );
-  Void  xGetBuffer        ( TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, Int iNumPicRcvd, Int iTimeOffset, TComPic*& rpcPic, TComPicYuv*& rpcPicYuvRecOut, Int pocCurr );
+  Void  xGetBuffer        ( TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, Int iNumPicRcvd, Int iTimeOffset, TComPic*& rpcPic, TComPicYuv*& rpcPicYuvRecOut, Int pocCurr, bool isField );
   
   Void  xCalculateAddPSNR ( TComPic* pcPic, TComPicYuv* pcPicD, const AccessUnit&, Double dEncTime );
+  Void  xCalculateInterlacedAddPSNR( TComPic* pcPicOrgTop, TComPic* pcPicOrgBottom, TComPicYuv* pcPicRecTop, TComPicYuv* pcPicRecBottom, const AccessUnit& accessUnit, Double dEncTime );
+
 #if H_3D_VSO
   Dist64 xFindDistortionFrame (TComPicYuv* pcPic0, TComPicYuv* pcPic1);
@@ -216,9 +223,5 @@
   }
 #if H_MV
-#if H_MV5
    Void  xSetRefPicListModificationsMv( std::vector<TComPic*> tempPicLists[2], TComSlice* pcSlice, UInt iGOPid );
-#else
-   Void  xSetRefPicListModificationsMv( TComSlice* pcSlice, UInt iGOPid );
-#endif
 #endif
   Void dblMetric( TComPic* pcPic, UInt uiNumSlices );
Index: trunk/source/Lib/TLibEncoder/TEncRateCtrl.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncRateCtrl.cpp	(revision 622)
+++ trunk/source/Lib/TLibEncoder/TEncRateCtrl.cpp	(revision 655)
@@ -537,4 +537,9 @@
   m_lastPicture  = NULL;
 #endif
+
+#if KWU_RC_MADPRED_E0227
+  m_lastIVPicture = NULL;
+#endif
+
   m_picActualHeaderBits = 0;
 #if !M0036_RC_IMPROVEMENT
@@ -544,4 +549,8 @@
   m_picQP               = 0;
   m_picLambda           = 0.0;
+
+#if KWU_RC_MADPRED_E0227
+  m_IVtotalMAD            = 0.0;
+#endif
 }
 
@@ -621,5 +630,22 @@
 }
 
+#if KWU_RC_MADPRED_E0227
+Void TEncRCPic::addToPictureLsitIV( list<TEncRCPic*>& listPreviousPictures )
+{
+  m_lastIVPicture = NULL;
+  m_lastIVPicture = this;
+}
+
+Void TEncRCPic::setIVPic( TEncRCPic* BaseRCPic )
+{
+  m_lastIVPicture = BaseRCPic;
+}
+#endif
+
+#if KWU_RC_MADPRED_E0227
+Void TEncRCPic::create( TEncRCSeq* encRCSeq, TEncRCGOP* encRCGOP, Int frameLevel, list<TEncRCPic*>& listPreviousPictures, Int layerID )
+#else
 Void TEncRCPic::create( TEncRCSeq* encRCSeq, TEncRCGOP* encRCGOP, Int frameLevel, list<TEncRCPic*>& listPreviousPictures )
+#endif
 {
   destroy();
@@ -673,4 +699,10 @@
       Int currHeight = ( (j == picHeightInLCU-1) ? picHeight - LCUHeight*(picHeightInLCU-1) : LCUHeight );
       m_LCUs[LCUIdx].m_numberOfPixel = currWidth * currHeight;
+
+#if KWU_RC_MADPRED_E0227
+      m_LCUs[LCUIdx].m_CUWidth = currWidth;
+      m_LCUs[LCUIdx].m_CUHeight = currHeight;
+      m_LCUs[LCUIdx].m_IVMAD = -1.0;
+#endif
     }
   }
@@ -683,7 +715,41 @@
   m_picLambda           = 0.0;
 
+
+#if KWU_RC_MADPRED_E0227
+  m_LayerID = layerID;
+  m_lastIVPicture = NULL;
+  m_IVtotalMAD            = 0.0;
+#endif
+
+
 #if !M0036_RC_IMPROVEMENT
   m_lastPicture = NULL;
   list<TEncRCPic*>::reverse_iterator it;
+  for ( it = listPreviousPictures.rbegin(); it != listPreviousPictures.rend(); it++ )
+  {
+    if ( (*it)->getFrameLevel() == m_frameLevel )
+    {
+      m_lastPicture = (*it);
+      break;
+    }
+  }
+#endif
+
+#if KWU_RC_MADPRED_E0227
+  list<TEncRCPic*>::reverse_iterator it;
+  if( m_LayerID != 0)
+  {
+    m_lastIVPicture = NULL;
+    for ( it = listPreviousPictures.rbegin(); it != listPreviousPictures.rend(); it++ )
+    {
+      if ( (*it)->getLayerID() == 0 )
+      {
+        m_lastIVPicture = (*it);
+        break;
+      }
+    }
+  }
+
+  m_lastPicture = NULL;
   for ( it = listPreviousPictures.rbegin(); it != listPreviousPictures.rend(); it++ )
   {
@@ -856,4 +922,71 @@
 }
 
+
+#if KWU_RC_MADPRED_E0227
+Double TEncRCPic::estimatePicLambdaIV( list<TEncRCPic*>& listPreviousPictures, Int CurPOC )
+{
+  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;
+  Double estLambda = alpha * pow( bpp, beta );
+  Double lastLevelLambda = -1.0;
+  Double lastPicLambda   = -1.0;
+  Double lastValidLambda = -1.0;
+  list<TEncRCPic*>::iterator it;
+
+  if(listPreviousPictures.size() == 0 || CurPOC%8 == 0)
+  {
+    lastLevelLambda = m_lastIVPicture->getPicActualLambda();
+    lastPicLambda     = m_lastIVPicture->getPicActualLambda();
+  }
+  else
+  {
+    for ( it = listPreviousPictures.begin(); it != listPreviousPictures.end(); it++ )
+    {
+      if ( (*it)->getFrameLevel() == m_frameLevel )
+      {
+        lastLevelLambda = (*it)->getPicActualLambda();
+      }
+      lastPicLambda     = (*it)->getPicActualLambda();
+
+      if ( lastPicLambda > 0.0 )
+      {
+        lastValidLambda = lastPicLambda;
+      }
+    }
+  }
+
+  if ( lastLevelLambda > 0.0 )
+  {
+    lastLevelLambda = Clip3( 0.1, 10000.0, lastLevelLambda );
+    estLambda = Clip3( lastLevelLambda * pow( 2.0, -3.0/3.0 ), lastLevelLambda * pow( 2.0, 3.0/3.0 ), estLambda );
+  }
+
+  if ( lastPicLambda > 0.0 )
+  {
+    lastPicLambda = Clip3( 0.1, 2000.0, lastPicLambda );
+    estLambda = Clip3( lastPicLambda * pow( 2.0, -10.0/3.0 ), lastPicLambda * pow( 2.0, 10.0/3.0 ), estLambda );
+  }
+  else if ( lastValidLambda > 0.0 )
+  {
+    lastValidLambda = Clip3( 0.1, 2000.0, lastValidLambda );
+    estLambda = Clip3( lastValidLambda * pow(2.0, -10.0/3.0), lastValidLambda * pow(2.0, 10.0/3.0), estLambda );
+  }
+  else
+  {
+    estLambda = Clip3( 0.1, 10000.0, estLambda );
+  }
+
+  if ( estLambda < 0.1 )
+  {
+    estLambda = 0.1;
+  }
+
+  m_estPicLambda = estLambda;
+  return estLambda;
+}
+#endif
+
+
 #if RATE_CONTROL_INTRA
 Double TEncRCPic::getLCUTargetBpp(SliceType eSliceType)  
@@ -937,4 +1070,121 @@
 }
 
+
+#if KWU_RC_MADPRED_E0227
+Double TEncRCPic::getLCUTargetBppforInterView( list<TEncRCPic*>& listPreviousPictures, TComDataCU* pcCU, Double basePos, Double curPos, Double focalLen, Double znear, Double zfar, Int direction, Int* disparity )
+{
+  Int   LCUIdx    = getLCUCoded();
+  Double bpp      = -1.0;
+  Int avgBits     = 0;
+#if !M0036_RC_IMPROVEMENT
+  Double totalMAD = -1.0;
+  Double MAD      = -1.0;
+#endif
+
+  Double totalMAD = -1.0;
+  Double MAD      = -1.0;
+
+  Double IVMAD      = -1.0;
+  Double SAD = 0.0;
+  Int     x, y;
+  Int Sum = 0;
+
+  {
+    Pel*  pOrg    = pcCU->getSlice()->getIvPic(false, 0)->getPicYuvOrg()->getLumaAddr(pcCU->getAddr(), 0);
+    Pel*  pRec    = pcCU->getSlice()->getIvPic(false, 0)->getPicYuvRec()->getLumaAddr(pcCU->getAddr(), 0);
+    Pel*  pDep    = pcCU->getSlice()->getIvPic(true, pcCU->getSlice()->getViewIndex())->getPicYuvOrg()->getLumaAddr(pcCU->getAddr(), 0);
+    Int   iStride = pcCU->getSlice()->getIvPic(true, pcCU->getSlice()->getViewIndex())->getPicYuvOrg()->getStride();
+
+    Int   width  = m_LCUs[ LCUIdx ].m_CUWidth;
+    Int   height = m_LCUs[ LCUIdx ].m_CUHeight;
+
+    for( y = 0 ; y < pcCU->getSlice()->getSPS()->getMaxCUHeight() ; y+=8)
+    {
+      for( x = 0 ; x < pcCU->getSlice()->getSPS()->getMaxCUWidth() ; x+=8)
+      {
+        Sum += pDep[x];
+      }
+      pDep += iStride;
+    }
+
+    Double AvgDepth = (Double)Sum/((pcCU->getSlice()->getSPS()->getMaxCUHeight()/8)*(pcCU->getSlice()->getSPS()->getMaxCUWidth()/8));
+
+    Double fL = focalLen * abs( basePos - curPos );
+    Double z  = abs( 1.0 / znear - 1.0 / zfar ) * ((Double)(AvgDepth) / (( 1 << g_bitDepthY ) - 1) ) + abs(1.0 / zfar);
+    *disparity = (Int)(direction*fL * z);
+    Int shift = DISTORTION_PRECISION_ADJUSTMENT(g_bitDepthY-8);
+
+    Int disp = *disparity;
+    Int posX, posY;
+    pcCU->getPosInPic(0, posX, posY);
+    if((posX + *disparity) < 0 || (posX + *disparity + width) >= pcCU->getSlice()->getSPS()->getMaxCUWidth())
+    {
+      disp = 0;
+    }
+
+    for( y = 0; y < height; y++ )
+    {
+      for( x = 0; x < width; x++ )
+      {
+        SAD += abs( pOrg[Clip3(0, (Int)(pcCU->getPic()->getPicYuvOrg()->getWidth() - pcCU->getSlice()->getSPS()->getMaxCUWidth()), x + disp)]
+                  - pRec[Clip3(0, (Int)(pcCU->getPic()->getPicYuvOrg()->getWidth() - pcCU->getSlice()->getSPS()->getMaxCUWidth()), x + disp)] )>>shift;
+      }
+      pOrg += iStride;
+      pRec += iStride;
+    }
+    IVMAD = SAD / (Double)(height * width);
+    IVMAD = IVMAD * IVMAD;
+
+    m_LCUs[ LCUIdx ].m_IVMAD = IVMAD;
+    if(m_lastPicture)
+    {
+      m_LCUs[ LCUIdx ].m_MAD = m_lastPicture->getLCU(LCUIdx).m_MAD;
+    }
+
+    MAD = m_LCUs[ LCUIdx ].m_IVMAD;
+
+    if(m_lastPicture)
+    {
+      totalMAD = m_lastPicture->getTotalMAD();      // get total MAD of temporal frame
+      for ( Int i=0; i<LCUIdx; i++ )
+      {
+        totalMAD -= m_lastPicture->getLCU(i).m_MAD;
+      }
+    }
+    else
+    {
+      totalMAD = m_lastIVPicture->getTotalMAD();      // get total MAD of inter-view frame
+      for ( Int i=0; i<LCUIdx; i++ )
+      {
+        totalMAD -= m_lastIVPicture->getLCU(i).m_MAD;
+      }
+    }
+
+
+    if ( totalMAD > 0.1 )
+    {
+      avgBits = Int( (m_bitsLeft * MAD) / totalMAD );
+    }
+    else
+    {
+      avgBits = Int( (m_bitsLeft) / m_LCULeft );
+    }
+  }
+
+  if ( avgBits < 5 )
+  {
+    avgBits = 5;
+  }
+
+  bpp = ( Double )avgBits/( Double )m_LCUs[ LCUIdx ].m_numberOfPixel;
+  m_LCUs[ LCUIdx ].m_targetBits = avgBits;
+
+  return bpp;
+}
+#endif
+
+
+
+
 Double TEncRCPic::getLCUEstLambda( Double bpp )
 {
@@ -1185,5 +1435,8 @@
   }
   m_picLambda           = averageLambda;
-#if !M0036_RC_IMPROVEMENT
+#if !M0036_RC_IMPROVEMENT || KWU_RC_MADPRED_E0227
+#if KWU_RC_MADPRED_E0227
+  m_totalMAD = 0;
+#endif
   for ( Int i=0; i<m_numberOfLCU; i++ )
   {
@@ -1393,5 +1646,9 @@
 
 #if M0036_RC_IMPROVEMENT
+#if KWU_RC_MADPRED_E0227
+Void TEncRateCtrl::init( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Bool keepHierBits, Bool useLCUSeparateModel, GOPEntry  GOPList[MAX_GOP], Int layerID )
+#else
 Void TEncRateCtrl::init( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Int keepHierBits, Bool useLCUSeparateModel, GOPEntry  GOPList[MAX_GOP] )
+#endif
 #else
 Void TEncRateCtrl::init( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Bool keepHierBits, Bool useLCUSeparateModel, GOPEntry  GOPList[MAX_GOP] )
@@ -1607,4 +1864,8 @@
   }
 
+#if KWU_RC_MADPRED_E0227
+  setLayerID(layerID);
+#endif
+
   delete[] bitsRatio;
   delete[] GOPID2Level;
@@ -1614,5 +1875,9 @@
 {
   m_encRCPic = new TEncRCPic;
+#if KWU_RC_MADPRED_E0227
+  m_encRCPic->create( m_encRCSeq, m_encRCGOP, frameLevel, m_listRCPictures, m_LayerID );
+#else
   m_encRCPic->create( m_encRCSeq, m_encRCGOP, frameLevel, m_listRCPictures );
+#endif
 }
 
@@ -1815,6 +2080,8 @@
   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);
@@ -2212,4 +2479,54 @@
 }
 
+
+#if KWU_RC_MADPRED_E0227
+Void  TEncRateCtrl::updateLCUDataEnhancedView(TComDataCU* pcCU, UInt64 uiBits, Int qp, Double basePos, Double curPos, Double focalLen, Double znear, Double zfar, Int direction)
+{
+  Int     x, y;
+  Double dMAD = 0.0;
+  Int Sum = 0;
+  Double SAD = 0.0;
+
+  Pel*  pOrg    = pcCU->getSlice()->getIvPic(false, 0)->getPicYuvOrg()->getLumaAddr(pcCU->getAddr(), 0);
+  Pel*  pRec    = pcCU->getSlice()->getIvPic(false, 0)->getPicYuvRec()->getLumaAddr(pcCU->getAddr(), 0);
+  Pel*  pDep    = pcCU->getSlice()->getIvPic(true, pcCU->getSlice()->getViewIndex())->getPicYuvOrg()->getLumaAddr(pcCU->getAddr(), 0);
+  Int   iStride = pcCU->getSlice()->getIvPic(true, pcCU->getSlice()->getViewIndex())->getPicYuvOrg()->getStride();
+
+  Int   width  = m_pcLCUData[m_indexLCU].m_widthInPixel;
+  Int   height = m_pcLCUData[m_indexLCU].m_heightInPixel;
+
+  for( y = 0 ; y < pcCU->getSlice()->getSPS()->getMaxCUHeight() ; y+=8)
+  {
+    for( x = 0 ; x < pcCU->getSlice()->getSPS()->getMaxCUWidth() ; x+=8)
+    {
+      Sum += pDep[x];
+    }
+    pDep += iStride;
+  }
+
+  Double AvgDepth = (Double)Sum/((pcCU->getSlice()->getSPS()->getMaxCUHeight()/8)*(pcCU->getSlice()->getSPS()->getMaxCUWidth()/8));
+  Double fL = focalLen * abs( basePos - curPos );
+  Double z  = abs( 1.0 / znear - 1.0 / zfar ) * ((Double)(AvgDepth) / (( 1 << g_bitDepthY ) - 1) ) + abs(1.0 / zfar);
+  Int   disparity = (Int)(direction*fL * z);
+  Int shift = DISTORTION_PRECISION_ADJUSTMENT(g_bitDepthY-8);
+  Int disp = disparity;
+
+  for( y = 0; y < height; y++ )
+  {
+    for( x = 0; x < width; x++ )
+    {
+      SAD += abs( pOrg[Clip3(0, (Int)(pcCU->getPic()->getPicYuvOrg()->getWidth() - pcCU->getSlice()->getSPS()->getMaxCUWidth()), x + disp)]
+      - pRec[Clip3(0, (Int)(pcCU->getPic()->getPicYuvOrg()->getWidth() - pcCU->getSlice()->getSPS()->getMaxCUWidth()), x + disp)] )>>shift;
+    }
+    pOrg += iStride;
+    pRec += iStride;
+  }
+  m_pcLCUData[m_indexLCU].m_qp   = qp;
+  m_pcLCUData[m_indexLCU].m_costMAD  = (SAD /(Double)(width*height));
+  m_pcLCUData[m_indexLCU].m_bits = (Int)uiBits;
+}
+#endif
+
+
 Double TEncRateCtrl::xAdjustmentBits(Int& reductionBits, Int& compensationBits)
 {
Index: trunk/source/Lib/TLibEncoder/TEncRateCtrl.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncRateCtrl.h	(revision 622)
+++ trunk/source/Lib/TLibEncoder/TEncRateCtrl.h	(revision 655)
@@ -98,4 +98,12 @@
   Int m_targetBitsLeft;
 #endif
+
+#if KWU_RC_MADPRED_E0227
+  Double m_MAD;
+
+  Int m_CUWidth;
+  Int m_CUHeight;
+  Double m_IVMAD;
+#endif
 };
 
@@ -248,7 +256,14 @@
 
 public:
+#if KWU_RC_MADPRED_E0227
+  Void create( TEncRCSeq* encRCSeq, TEncRCGOP* encRCGOP, Int frameLevel, list<TEncRCPic*>& listPreviousPictures, Int layerID );
+#else
   Void create( TEncRCSeq* encRCSeq, TEncRCGOP* encRCGOP, Int frameLevel, list<TEncRCPic*>& listPreviousPictures );
+#endif
   Void destroy();
 
+#if KWU_RC_MADPRED_E0227
+  Double estimatePicLambdaIV( list<TEncRCPic*>& listPreviousPictures, Int curPOC );
+#endif
 #if !RATE_CONTROL_INTRA
   Double estimatePicLambda( list<TEncRCPic*>& listPreviousPictures );
@@ -267,4 +282,9 @@
   Double getLCUTargetBpp();
 #endif
+
+#if KWU_RC_MADPRED_E0227
+  Double getLCUTargetBppforInterView( list<TEncRCPic*>& listPreviousPictures, TComDataCU* pcCU, Double basePos, Double curPos, Double focalLen, Double znear, Double zfar, Int direction, Int* disparity );
+#endif
+
   Double getLCUEstLambda( Double bpp );
   Int    getLCUEstQP( Double lambda, Int clipPicQP );
@@ -282,4 +302,10 @@
 
   Void addToPictureLsit( list<TEncRCPic*>& listPreviousPictures );
+
+#if KWU_RC_MADPRED_E0227
+  Void addToPictureLsitIV( list<TEncRCPic*>& listPreviousPictures );
+  Void setIVPic( TEncRCPic* baseRCPic );
+#endif
+
 #if !M0036_RC_IMPROVEMENT
   Double getEffectivePercentage();
@@ -322,4 +348,12 @@
 #endif
 
+#if KWU_RC_MADPRED_E0227
+  Double getTotalMAD()                                    { return m_totalMAD; }
+  Void   setTotalMAD( Double MAD )                        { m_totalMAD = MAD; }
+
+  Double getIVTotalMAD()                                    { return m_IVtotalMAD; }
+  Void   setIVTotalMAD( Double MAD )                        { m_IVtotalMAD = MAD; }
+#endif
+
   Int  getPicActualBits()                                 { return m_picActualBits; }
   Int  getPicActualQP()                                   { return m_picQP; }
@@ -330,4 +364,9 @@
   Void setPicEstLambda( Double lambda )                   { m_picLambda = lambda; }
 
+#if KWU_RC_MADPRED_E0227
+  Int getLayerID()                                         { return m_LayerID; }
+  Void setLayerID(Int layerid)                              { m_LayerID = layerid; }
+#endif
+
 private:
   TEncRCSeq* m_encRCSeq;
@@ -361,4 +400,12 @@
   TEncRCPic* m_lastPicture;
 #endif
+
+#if KWU_RC_MADPRED_E0227
+  Double m_totalMAD;
+  TEncRCPic* m_lastPicture;
+  Int m_LayerID;
+  TEncRCPic* m_lastIVPicture;
+  Double m_IVtotalMAD;
+#endif
 };
 
@@ -371,5 +418,9 @@
 public:
 #if M0036_RC_IMPROVEMENT
+#if KWU_RC_MADPRED_E0227
+  Void init( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Bool keepHierBits, Bool useLCUSeparateModel, GOPEntry GOPList[MAX_GOP], Int layerID );
+#else
   Void init( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Int keepHierBits, Bool useLCUSeparateModel, GOPEntry GOPList[MAX_GOP] );
+#endif
 #else
   Void init( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Bool keepHierBits, Bool useLCUSeparateModel, GOPEntry GOPList[MAX_GOP] );
@@ -388,4 +439,9 @@
   list<TEncRCPic*>& getPicList() { return m_listRCPictures; }
 
+#if KWU_RC_MADPRED_E0227
+  Int getLayerID()                { return m_LayerID; }
+  Void setLayerID(Int layerid)     { m_LayerID = layerid; }
+#endif
+
 private:
   TEncRCSeq* m_encRCSeq;
@@ -394,4 +450,8 @@
   list<TEncRCPic*> m_listRCPictures;
   Int        m_RCQP;
+
+#if KWU_RC_MADPRED_E0227
+  Int m_LayerID;
+#endif
 };
 
@@ -518,4 +578,7 @@
   Void          updataRCUnitStatus    ();
   Void          updateLCUData         (TComDataCU* pcCU, UInt64 actualLCUBits, Int qp);
+#if KWU_RC_MADPRED_E0227
+  Void          updateLCUDataEnhancedView(TComDataCU* pcCU, UInt64 uiBits, Int qp, Double basePos, Double curPos, Double focalLen, Double znear, Double zfar, Int direction);
+#endif
   Void          updateFrameData       (UInt64 actualFrameBits);
   Double        xAdjustmentBits       (Int& reductionBits, Int& compensationBits);
Index: trunk/source/Lib/TLibEncoder/TEncSbac.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSbac.cpp	(revision 622)
+++ trunk/source/Lib/TLibEncoder/TEncSbac.cpp	(revision 655)
@@ -95,7 +95,4 @@
 #if H_3D_DIM_DMM
 , m_cDmm1DataSCModel          ( 1,             1,               NUM_DMM1_DATA_CTX             , m_contextModels + m_numContextModels, m_numContextModels)
-#if !SEC_DMM2_E0146_HHIFIX
-, m_cDmm2DataSCModel          ( 1,             1,               NUM_DMM2_DATA_CTX             , m_contextModels + m_numContextModels, m_numContextModels)
-#endif
 , m_cDmm3DataSCModel          ( 1,             1,               NUM_DMM3_DATA_CTX             , m_contextModels + m_numContextModels, m_numContextModels)
 #endif
@@ -108,5 +105,5 @@
 #endif
 #endif
-#if LGE_INTER_SDC_E0156
+#if H_3D_INTER_SDC
 , m_cInterSDCFlagSCModel             ( 1,             1,  NUM_INTER_SDC_FLAG_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
 , m_cInterSDCResidualSCModel         ( 1,             1,  NUM_INTER_SDC_RESIDUAL_CTX       , m_contextModels + m_numContextModels, m_numContextModels)
@@ -177,7 +174,4 @@
 #if H_3D_DIM_DMM
   m_cDmm1DataSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_DMM1_DATA );
-#if !SEC_DMM2_E0146_HHIFIX
-  m_cDmm2DataSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_DMM2_DATA );
-#endif
   m_cDmm3DataSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_DMM3_DATA );
 #endif
@@ -190,5 +184,5 @@
 #endif
 #endif
-#if LGE_INTER_SDC_E0156
+#if H_3D_INTER_SDC
   m_cInterSDCFlagSCModel.initBuffer         ( eSliceType, iQp, (UChar*)INIT_INTER_SDC_FLAG );
   m_cInterSDCResidualSCModel.initBuffer     ( eSliceType, iQp, (UChar*)INIT_INTER_SDC_RESIDUAL );
@@ -232,5 +226,5 @@
       curCost += m_cCUICFlagSCModel.calcCost          ( curSliceType, qp, (UChar*)INIT_IC_FLAG );
 #endif
-#if LGE_INTER_SDC_E0156
+#if H_3D_INTER_SDC
       curCost += m_cInterSDCFlagSCModel.calcCost      ( curSliceType, qp, (UChar*)INIT_INTER_SDC_FLAG );
       curCost += m_cInterSDCResidualSCModel.calcCost  ( curSliceType, qp, (UChar*)INIT_INTER_SDC_RESIDUAL );
@@ -268,7 +262,4 @@
 #if H_3D_DIM_DMM
       curCost += m_cDmm1DataSCModel.calcCost          ( curSliceType, qp, (UChar*)INIT_DMM1_DATA );
-#if !SEC_DMM2_E0146_HHIFIX
-      curCost += m_cDmm2DataSCModel.calcCost          ( curSliceType, qp, (UChar*)INIT_DMM2_DATA );
-#endif
       curCost += m_cDmm3DataSCModel.calcCost          ( curSliceType, qp, (UChar*)INIT_DMM3_DATA );
 #endif
@@ -340,7 +331,4 @@
 #if H_3D_DIM_DMM
   m_cDmm1DataSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_DMM1_DATA );
-#if !SEC_DMM2_E0146_HHIFIX
-  m_cDmm2DataSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_DMM2_DATA );
-#endif
   m_cDmm3DataSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_DMM3_DATA );
 #endif
@@ -353,5 +341,5 @@
 #endif
 #endif
-#if LGE_INTER_SDC_E0156
+#if H_3D_INTER_SDC
   m_cInterSDCFlagSCModel.initBuffer         ( eSliceType, iQp, (UChar*)INIT_INTER_SDC_FLAG );
   m_cInterSDCResidualSCModel.initBuffer     ( eSliceType, iQp, (UChar*)INIT_INTER_SDC_RESIDUAL );
@@ -548,23 +536,4 @@
   }
 }
-
-#if !SEC_DMM2_E0146_HHIFIX
-Void TEncSbac::xCodeDmm2Offset( Int iOffset )
-{
-  if( DMM2_DELTAEND_MAX > 0 )
-  {
-    m_pcBinIf->encodeBin( (iOffset != 0) , m_cDmm2DataSCModel.get(0, 0, 0) );
-    if( iOffset != 0 )
-    {
-      UInt uiAbsValMinus1 = abs(iOffset)-1;
-      m_pcBinIf->encodeBin( (uiAbsValMinus1 & 0x01),      m_cDmm2DataSCModel.get(0, 0, 0) );
-      m_pcBinIf->encodeBin( (uiAbsValMinus1 & 0x02) >> 1, m_cDmm2DataSCModel.get(0, 0, 0) );
-
-      UInt uiSign = (iOffset > 0) ? 0 : 1;
-      m_pcBinIf->encodeBinEP( uiSign );
-    }
-  }
-}
-#endif
 
 Void TEncSbac::xCodeDmm3WedgeIdx( UInt uiIntraIdx, Int iNumBit )
@@ -1240,10 +1209,4 @@
       xCodeDmm1WedgeIdx( pcCU->getDmmWedgeTabIdx( dimType, absPartIdx ), g_dmm1TabIdxBits[pcCU->getIntraSizeIdx(absPartIdx)] );
     } break;
-#if !SEC_DMM2_E0146_HHIFIX
-  case( DMM2_IDX ):
-    {
-      xCodeDmm2Offset( pcCU->getDmm2DeltaEnd( absPartIdx ) );
-    } break;
-#endif
   case( DMM3_IDX ):
     {
@@ -1294,26 +1257,6 @@
 Void TEncSbac::codeIntraDepthMode( TComDataCU* pcCU, UInt absPartIdx )
 {
-#if ZJU_DEPTH_INTRA_MODE_E0204
     UInt codeWordTable[3][7] =    {{0, 0, 0, 2, 0,6, 7},{0, 0, 2, 7, 3, 6, 2},{0, 1, 0, 0, 0, 0, 0}};
     UInt codeWordLenTable[3][7] = {{0, 1, 0, 2, 0,3, 3},{1, 1, 2, 3, 2, 3, 2},{1, 1, 0, 0, 0, 0, 0}};
-#else
-#if LGE_SDC_REMOVE_DC_E0158
-#if SEC_DMM2_E0146_HHIFIX
-  UInt codeWordTable[3][7] =    {{0, 0, 0, 2, 0,6, 7},{0, 2, 3, 4, 5, 6, 7},{0, 1, 0, 0, 0, 0, 0}};
-  UInt codeWordLenTable[3][7] = {{0, 1, 0, 2, 0,3, 3},{2, 3, 3, 3, 3, 3, 3},{1, 1, 0, 0, 0, 0, 0}};
-#else
-  UInt codeWordTable[3][8] =    { { 0, 0, 0, 2, 0, 6, 0, 7 }, { 0, 2, 3, 4, 5, 6, 15, 14 }, { 0, 1, 0, 0, 0, 0, 0, 0 } };
-  UInt codeWordLenTable[3][8] = { { 0, 1, 0, 2, 0, 3, 0, 3 }, { 2, 3, 3, 3, 3, 3,  4,  4 }, { 1, 1, 0, 0, 0, 0, 0, 0 } };
-#endif
-#else
-#if SEC_DMM2_E0146_HHIFIX
-  UInt codeWordTable[3][8] =    {{0, 0, 0, 2, 0,6, 0, 7},{0, 2, 3, 4, 5, 6, 14, 15},{0, 2, 0, 0, 0, 0, 3, 0}};
-  UInt codeWordLenTable[3][8] = {{0, 1, 0, 2, 0,3, 0, 3},{2, 3, 3, 3, 3, 3,  4,  4},{1, 2, 0, 0, 0, 0, 2, 0}};
-#else
-  UInt codeWordTable[3][9] =    {{0, 0, 0, 2, 0,6, 0, 0, 7},{0, 2, 3, 4, 5, 6, 14, 31, 30},{0, 2, 0, 0, 0, 0, 3, 0, 0}};
-  UInt codeWordLenTable[3][9] = {{0, 1, 0, 2, 0,3, 0, 0, 3},{2, 3, 3, 3, 3, 3,  4,  5,  5},{1, 2, 0, 0, 0, 0, 2, 0, 0}};
-#endif
-#endif
-#endif
   UInt dir = pcCU->getLumaIntraDir( absPartIdx );
   UInt puIdx = (pcCU->getWidth(absPartIdx) == 64) ? 2 : ( (pcCU->getPartitionSize(absPartIdx) == SIZE_NxN && pcCU->getWidth(absPartIdx) == 8) ? 0 : 1 );
@@ -1331,19 +1274,5 @@
     case DMM4_IDX: codeIdx = 4; break;
     case DMM3_IDX: codeIdx = 5; break;
-#if LGE_SDC_REMOVE_DC_E0158
-#if SEC_DMM2_E0146_HHIFIX
     case  RBC_IDX: codeIdx = 6; break;
-#else
-    case DMM2_IDX: codeIdx = 6; break;
-    case  RBC_IDX: codeIdx = 7; break;
-#endif
-#else
-#if SEC_DMM2_E0146_HHIFIX
-    case  RBC_IDX: codeIdx = 7; break;
-#else
-    case DMM2_IDX: codeIdx = 7; break;
-    case  RBC_IDX: codeIdx = 8; break;
-#endif
-#endif
     default:                    break;
     }
@@ -1356,12 +1285,8 @@
     {
       case PLANAR_IDX:  codeIdx = 0; break;
-#if !LGE_SDC_REMOVE_DC_E0158
-      case DC_IDX:      codeIdx = 6; break;
-#endif
       default:          codeIdx = 2; break;
     }
   }
 #endif
-#if ZJU_DEPTH_INTRA_MODE_E0204
   if( puIdx==1 )
   {
@@ -1375,5 +1300,4 @@
       }
   }
-#endif
   //mode coding
   for( UInt i = 0; i < codeWordLenTable[puIdx][codeIdx]; i++ )
@@ -2304,5 +2228,5 @@
 }
 
-#if LGE_INTER_SDC_E0156
+#if H_3D_INTER_SDC
 Void TEncSbac::codeInterSDCFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
 {
Index: trunk/source/Lib/TLibEncoder/TEncSbac.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSbac.h	(revision 622)
+++ trunk/source/Lib/TLibEncoder/TEncSbac.h	(revision 655)
@@ -121,7 +121,4 @@
 #if H_3D_DIM_DMM
   Void  xCodeDmm1WedgeIdx    ( UInt uiTabIdx, Int iNumBit );
-#if !SEC_DMM2_E0146_HHIFIX
-  Void  xCodeDmm2Offset      ( Int iOffset );
-#endif
   Void  xCodeDmm3WedgeIdx    ( UInt uiIntraIdx, Int iNumBit );
 #endif
@@ -160,5 +157,5 @@
   Void codeICFlag        ( TComDataCU* pcCU, UInt uiAbsPartIdx );
 #endif
-#if LGE_INTER_SDC_E0156
+#if H_3D_INTER_SDC
   Void codeInterSDCFlag  ( TComDataCU* pcCU, UInt uiAbsPartIdx );
   Void codeInterSDCResidualData  ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiSegment );
@@ -256,7 +253,4 @@
 #if H_3D_DIM_DMM
   ContextModel3DBuffer m_cDmm1DataSCModel;
-#if !SEC_DMM2_E0146_HHIFIX
-  ContextModel3DBuffer m_cDmm2DataSCModel;
-#endif
   ContextModel3DBuffer m_cDmm3DataSCModel;
 #endif
@@ -269,5 +263,5 @@
 #endif
 #endif
-#if LGE_INTER_SDC_E0156
+#if H_3D_INTER_SDC
   ContextModel3DBuffer m_cInterSDCFlagSCModel;
   ContextModel3DBuffer m_cInterSDCResidualSCModel;
Index: trunk/source/Lib/TLibEncoder/TEncSearch.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSearch.cpp	(revision 622)
+++ trunk/source/Lib/TLibEncoder/TEncSearch.cpp	(revision 655)
@@ -41,5 +41,5 @@
 #include "TEncSearch.h"
 #include <math.h>
-#if LGE_INTER_SDC_E0156
+#if H_3D_INTER_SDC
 #include <memory.h>
 #endif
@@ -323,5 +323,5 @@
   m_cDistParam.bUseIC = pcPatternKey->getICFlag();
 #endif
-#if LGE_INTER_SDC_E0156
+#if H_3D_INTER_SDC
   m_cDistParam.bUseSDCMRSAD = pcPatternKey->getSDCMRSADFlag();
 #endif
@@ -755,5 +755,5 @@
     m_cDistParam.bUseIC = pcPatternKey->getICFlag();
 #endif
-#if LGE_INTER_SDC_E0156
+#if H_3D_INTER_SDC
     m_cDistParam.bUseSDCMRSAD = pcPatternKey->getSDCMRSADFlag();
 #endif
@@ -1900,17 +1900,9 @@
   // get DC prediction for each segment
   Pel apDCPredValues[2];
-#if KWU_SDC_SIMPLE_DC_E0117
   analyzeSegmentsSDC(piPred, uiStride, uiWidth, apDCPredValues, uiNumSegments, pbMask, uiMaskStride, uiLumaPredMode );
-#else
-  analyzeSegmentsSDC(piPred, uiStride, uiWidth, apDCPredValues, uiNumSegments, pbMask, uiMaskStride );
-#endif
   
   // get original DC for each segment
   Pel apDCOrigValues[2];
-#if KWU_SDC_SIMPLE_DC_E0117
   analyzeSegmentsSDC(piOrg, uiStride, uiWidth, apDCOrigValues, uiNumSegments, pbMask, uiMaskStride, uiLumaPredMode, true );
-#else
-  analyzeSegmentsSDC(piOrg, uiStride, uiWidth, apDCOrigValues, uiNumSegments, pbMask, uiMaskStride );
-#endif
   
   for( UInt uiSegment = 0; uiSegment < uiNumSegments; uiSegment++ )
@@ -2851,5 +2843,5 @@
     {
 
-#if SCU_HS_FAST_DEPTH_INTRA_E0238_HHIFIX
+#if H_3D_FAST_DEPTH_INTRA
       Int  threshold    = max(((pcCU->getQP(0))>>3)-1,3);
       Int  varThreshold = (Int)( threshold * threshold - 8 );
@@ -2859,5 +2851,5 @@
 #if H_3D_DIM_DMM
       if( m_pcEncCfg->getUseDMM()
-#if SCU_HS_FAST_DEPTH_INTRA_E0238_HHIFIX
+#if H_3D_FAST_DEPTH_INTRA
          && (uiRdModeList[0] != PLANAR_IDX || varCU >= varThreshold)
 #endif
@@ -2866,4 +2858,11 @@
         for( UInt dmmType = 0; dmmType < DMM_NUM_TYPE; dmmType++ )
         {
+#if H_3D_FCO
+            TComPic* picTexture  = pcCU->getSlice()->getIvPic(false, pcCU->getSlice()->getViewIndex() );
+            if ( !picTexture->getReconMark() && (DMM3_IDX == dmmType || DMM4_IDX == dmmType ) )
+            {
+                continue;
+            }
+#endif
           UInt uiTabIdx = 0;
           TComWedgelet* biSegmentation = NULL;
@@ -2877,20 +2876,7 @@
               biSegmentation = &(g_dmmWedgeLists[(g_aucConvertToBit[uiWidth])][uiTabIdx]);
             } break;
-#if !SEC_DMM2_E0146_HHIFIX
-          case( DMM2_IDX ):
-            {
-              if( uiWidth > 4 )
-              {
-                Int dmm2DeltaEnd = 0;
-                xSearchDmm2Wedge( pcCU, uiPartOffset, piOrg, uiStride, uiWidth, uiHeight, uiTabIdx, dmm2DeltaEnd );
-                pcCU->setDmmWedgeTabIdxSubParts( uiTabIdx, dmmType, uiPartOffset, uiDepth + uiInitTrDepth );
-                pcCU->setDmm2DeltaEndSubParts( dmm2DeltaEnd, uiPartOffset, uiDepth + uiInitTrDepth );
-                biSegmentation = &(g_dmmWedgeLists[(g_aucConvertToBit[uiWidth])][uiTabIdx]);
-              }
-            } break;
-#endif
           case( DMM3_IDX ):
             {
-#if LGE_PKU_DMM3_OVERLAP_E0159_HHIFIX
+
               TComPic*      pcPicTex = pcCU->getSlice()->getTexturePic();
               TComDataCU* pcColTexCU = pcPicTex->getCU( pcCU->getAddr() );
@@ -2900,17 +2886,10 @@
               if( uiColTexIntraDir > DC_IDX && uiColTexIntraDir < 35 )
               {
-#endif
-              UInt uiIntraTabIdx = 0;
-#if LGE_PKU_DMM3_OVERLAP_E0159_HHIFIX
+             UInt uiIntraTabIdx = 0;
               xSearchDmm3Wedge( pcCU, uiPartOffset, piOrg, uiStride, uiWidth, uiHeight, uiTabIdx, uiIntraTabIdx, uiColTexIntraDir );
-#else
-              xSearchDmm3Wedge( pcCU, uiPartOffset, piOrg, uiStride, uiWidth, uiHeight, uiTabIdx, uiIntraTabIdx );
-#endif
               pcCU->setDmmWedgeTabIdxSubParts( uiTabIdx, dmmType, uiPartOffset, uiDepth + uiInitTrDepth );
               pcCU->setDmm3IntraTabIdxSubParts( uiIntraTabIdx, uiPartOffset, uiDepth + uiInitTrDepth );
               biSegmentation = &(g_dmmWedgeLists[(g_aucConvertToBit[uiWidth])][uiTabIdx]);
-#if LGE_PKU_DMM3_OVERLAP_E0159_HHIFIX
               }
-#endif
             } break;
           case( DMM4_IDX ):
@@ -2941,5 +2920,5 @@
 #if H_3D_DIM_RBC
       if( m_pcEncCfg->getUseRBC()
-#if SCU_HS_FAST_DEPTH_INTRA_E0238_HHIFIX
+#if H_3D_FAST_DEPTH_INTRA
           && (uiRdModeList[0] != PLANAR_IDX || varCU >= varThreshold)
 #endif
@@ -3581,5 +3560,5 @@
   cDistParam.bUseIC = false;
 #endif
-#if LGE_INTER_SDC_E0156
+#if H_3D_INTER_SDC
   cDistParam.bUseSDCMRSAD = false;
 #endif
@@ -3724,5 +3703,5 @@
  */
 #if AMP_MRG
-#if  MTK_FAST_TEXTURE_ENCODING_E0173
+#if  H_3D_FAST_TEXTURE_ENCODING
 Void TEncSearch::predInterSearch( TComDataCU* pcCU, TComYuv* pcOrgYuv, TComYuv*& rpcPredYuv, TComYuv*& rpcResiYuv, TComYuv*& rpcRecoYuv, Bool bFMD, Bool bUseRes, Bool bUseMRG )
 #else
@@ -3836,5 +3815,5 @@
 #if AMP_MRG
     Bool bTestNormalMC = true;
-#if  MTK_FAST_TEXTURE_ENCODING_E0173
+#if  H_3D_FAST_TEXTURE_ENCODING
     if (bFMD||( bUseMRG && pcCU->getWidth( 0 ) > 8 && iNumPart == 2 ))
 #else            
@@ -4706,5 +4685,5 @@
   pcPatternKey->setICFlag( bICFlag );
 #endif
-#if LGE_INTER_SDC_E0156
+#if H_3D_INTER_SDC
   if ( pcCU->getSlice()->getIsDepth() && pcCU->getSlice()->getVPS()->getInterSDCFlag( pcCU->getSlice()->getLayerIdInVps() ) )
   {
@@ -4862,5 +4841,5 @@
       m_cDistParam.bUseIC = pcPatternKey->getICFlag();
 #endif
-#if LGE_INTER_SDC_E0156
+#if H_3D_INTER_SDC
       m_cDistParam.bUseSDCMRSAD = pcPatternKey->getSDCMRSADFlag();
 #endif
@@ -5471,5 +5450,5 @@
 }
 
-#if LGE_INTER_SDC_E0156
+#if H_3D_INTER_SDC
 Void TEncSearch::encodeResAndCalcRdInterSDCCU( TComDataCU* pcCU, TComYuv* pcOrg, TComYuv* pcPred, TComYuv* pcResi, TComYuv* pcRec, const UInt uiDepth )
 {
@@ -6794,5 +6773,5 @@
     m_pcEntropyCoder->encodeARPW( pcCU , 0 );
 #endif
-#if LGE_INTER_SDC_E0156
+#if H_3D_INTER_SDC
     m_pcEntropyCoder->encodeInterSDCFlag( pcCU, 0, true );
 #endif
@@ -7045,8 +7024,8 @@
 }
 
+#if H_3D_DIM
   // -------------------------------------------------------------------------------------------------------------------
   // Depth intra search
   // -------------------------------------------------------------------------------------------------------------------
-#if H_3D_DIM
 Void TEncSearch::xCalcBiSegDCs( Pel* ptrSrc, UInt srcStride, Bool* biSegPattern, Int patternStride, Pel& valDC1, Pel& valDC2 )
 {
@@ -7321,73 +7300,4 @@
 }
 
-#if !SEC_DMM2_E0146_HHIFIX
-Void TEncSearch::xSearchDmm2Wedge( TComDataCU* pcCU, UInt uiAbsPtIdx, Pel* piRef, UInt uiRefStride, UInt uiWidth, UInt uiHeight, UInt& ruiTabIdx, Int& riWedgeDeltaEnd )
-{
-  ruiTabIdx       = 0;
-  riWedgeDeltaEnd = 0;
-
-  // local pred buffer
-  TComYuv cPredYuv;
-  cPredYuv.create( uiWidth, uiHeight );
-  cPredYuv.clear();
-
-  UInt uiPredStride = cPredYuv.getStride();
-  Pel* piPred       = cPredYuv.getLumaAddr();
-
-
-  // regular wedge search
-  Dist uiBestDist    = RDO_DIST_MAX;
-  UInt uiBestTabIdx  = 0;
-  Int  iBestDeltaEnd = 0;
-
-  UInt uiIdx = 0;
-  Pel refDC1 = 0; Pel refDC2 = 0;
-  for( Int iTestDeltaEnd = -DMM2_DELTAEND_MAX; iTestDeltaEnd <= DMM2_DELTAEND_MAX; iTestDeltaEnd++ )
-  {
-    uiIdx = xPredWedgeFromIntra( pcCU, uiAbsPtIdx, uiWidth, uiHeight, iTestDeltaEnd );
-    TComWedgelet* pcWedgelet = &(g_dmmWedgeLists[(g_aucConvertToBit[uiWidth])][uiIdx]);
-    xCalcBiSegDCs  ( piRef,  uiRefStride,  pcWedgelet->getPattern(), pcWedgelet->getStride(), refDC1, refDC2 );
-    xAssignBiSegDCs( piPred, uiPredStride, pcWedgelet->getPattern(), pcWedgelet->getStride(), refDC1, refDC2 );
-
-    Dist uiActDist = RDO_DIST_MAX;
-#if H_3D_VSO
-    if( m_pcRdCost->getUseVSO() )
-    {
-      if( m_pcRdCost->getUseEstimatedVSD() )
-      {
-        uiActDist = m_pcRdCost->getDistPartVSD( pcCU, uiAbsPtIdx, piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, false );
-      }
-      else
-      {
-        uiActDist = m_pcRdCost->getDistPartVSO( pcCU, uiAbsPtIdx, piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, false );
-      }
-    }
-    else
-#endif
-    {
-      uiActDist = m_pcRdCost->getDistPart( g_bitDepthY, piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, TEXT_LUMA, DF_SAD );
-    }
-
-    if( uiActDist < uiBestDist || uiBestDist == RDO_DIST_MAX )
-    {
-      uiBestDist    = uiActDist;
-      uiBestTabIdx  = uiIdx;
-      iBestDeltaEnd = iTestDeltaEnd;
-    }
-    else if( uiIdx == uiBestTabIdx && abs(iTestDeltaEnd) < abs(iBestDeltaEnd) )
-    {
-      iBestDeltaEnd = iTestDeltaEnd;
-    }
-  }
-
-  ruiTabIdx       = uiBestTabIdx;
-  riWedgeDeltaEnd = iBestDeltaEnd;
-
-  cPredYuv.destroy();
-  return;
-}
-#endif
-
-#if LGE_PKU_DMM3_OVERLAP_E0159_HHIFIX
 Void TEncSearch::xSearchDmm3Wedge( TComDataCU* pcCU, UInt uiAbsPtIdx, Pel* piRef, UInt uiRefStride, UInt uiWidth, UInt uiHeight, UInt& ruiTabIdx, UInt& ruiIntraTabIdx, UInt colTexIntraDir )
 {
@@ -7426,73 +7336,5 @@
   cPredYuv.destroy();
 }
-#else
-Void TEncSearch::xSearchDmm3Wedge( TComDataCU* pcCU, UInt uiAbsPtIdx, Pel* piRef, UInt uiRefStride, UInt uiWidth, UInt uiHeight, UInt& ruiTabIdx, UInt& ruiIntraTabIdx )
-{
-  ruiTabIdx       = 0;
-  ruiIntraTabIdx  = 0;
-
-  // local pred buffer
-  TComYuv cPredYuv; 
-  cPredYuv.create( uiWidth, uiHeight ); 
-  cPredYuv.clear();
-  Pel* piPred = cPredYuv.getLumaAddr();
-  UInt uiPredStride = cPredYuv.getStride();
-
-  // wedge search
-  UInt uiBestDist = MAX_UINT;
-  WedgeList* pacWedgeList = &g_dmmWedgeLists[(g_aucConvertToBit[uiWidth])];
-  Pel refDC1 = 0; Pel refDC2 = 0;
-
-  TComPic*      pcPicTex = pcCU->getSlice()->getTexturePic();
-  assert( pcPicTex != NULL );
-  TComDataCU* pcColTexCU = pcPicTex->getCU(pcCU->getAddr());
-  UInt      uiTexPartIdx = pcCU->getZorderIdxInCU() + uiAbsPtIdx;
-  Int   uiColTexIntraDir = pcColTexCU->isIntra( uiTexPartIdx ) ? pcColTexCU->getLumaIntraDir( uiTexPartIdx ) : 255;
-
-  std::vector< std::vector<UInt> > pauiWdgLstSz = g_aauiWdgLstM3[g_aucConvertToBit[uiWidth]];
-  if( uiColTexIntraDir > DC_IDX && uiColTexIntraDir < 35 )
-  {
-    std::vector<UInt>* pauiWdgLst = &pauiWdgLstSz[uiColTexIntraDir-2];
-    for( UInt uiIdxW = 0; uiIdxW < pauiWdgLst->size(); uiIdxW++ )
-    {
-      UInt uiIdx     =   pauiWdgLst->at(uiIdxW);
-      TComWedgelet* pcWedgelet = &(pacWedgeList->at(uiIdx));
-      xCalcBiSegDCs  ( piRef,  uiRefStride,  pcWedgelet->getPattern(), pcWedgelet->getStride(), refDC1, refDC2 );
-      xAssignBiSegDCs( piPred, uiPredStride, pcWedgelet->getPattern(), pcWedgelet->getStride(), refDC1, refDC2 );
-
-      UInt uiActDist = m_pcRdCost->getDistPart( g_bitDepthY, piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, TEXT_LUMA, DF_SAD );
-      if( uiActDist < uiBestDist || uiBestDist == MAX_UINT )
-      {
-        uiBestDist     = uiActDist;
-        ruiTabIdx      = uiIdx;
-        ruiIntraTabIdx = uiIdxW;
-      }
-    }
-  }
-  else
-  {
-    WedgeNodeList* pacWedgeNodeList = &g_dmmWedgeNodeLists[(g_aucConvertToBit[uiWidth])];
-    UInt uiBestNodeDist = MAX_UINT;
-    UInt uiBestNodeId   = 0;
-    for( UInt uiNodeId = 0; uiNodeId < pacWedgeNodeList->size(); uiNodeId++ )
-    {
-      TComWedgelet* pcWedgelet = &(pacWedgeList->at(pacWedgeNodeList->at(uiNodeId).getPatternIdx()));
-      xCalcBiSegDCs  ( piRef,  uiRefStride,  pcWedgelet->getPattern(), pcWedgelet->getStride(), refDC1, refDC2 );
-      xAssignBiSegDCs( piPred, uiPredStride, pcWedgelet->getPattern(), pcWedgelet->getStride(), refDC1, refDC2 );
-
-      UInt uiActDist = m_pcRdCost->getDistPart( g_bitDepthY, piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, TEXT_LUMA, DF_SAD );
-      if( uiActDist < uiBestNodeDist || uiBestNodeDist == MAX_UINT )
-      {
-        uiBestNodeDist = uiActDist;
-        uiBestNodeId   = uiNodeId;
-        ruiIntraTabIdx = uiNodeId;
-      }
-    }
-    ruiTabIdx = pacWedgeNodeList->at(uiBestNodeId).getPatternIdx();
-  }
-
-  cPredYuv.destroy();
-}
-#endif
+
 #endif
 #if H_3D_DIM_RBC
Index: trunk/source/Lib/TLibEncoder/TEncSearch.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSearch.h	(revision 622)
+++ trunk/source/Lib/TLibEncoder/TEncSearch.h	(revision 655)
@@ -196,5 +196,5 @@
                                   TComYuv*&   rpcResiYuv,
                                   TComYuv*&   rpcRecoYuv,
-#if MTK_FAST_TEXTURE_ENCODING_E0173
+#if H_3D_FAST_TEXTURE_ENCODING
                                   Bool        bFMD,
 #endif
@@ -213,5 +213,5 @@
                                   TComYuv*&   rpcYuvRec,
                                   Bool        bSkipRes );
-#if LGE_INTER_SDC_E0156
+#if H_3D_INTER_SDC
   Void encodeResAndCalcRdInterSDCCU( TComDataCU* pcCU,
     TComYuv* pcOrg, 
@@ -343,21 +343,13 @@
                                     UInt         stateU0V1Both2 );
 
-
+#if H_3D_DIM
   // -------------------------------------------------------------------------------------------------------------------
   // Depth intra search
   // -------------------------------------------------------------------------------------------------------------------
-#if H_3D_DIM
   Void xCalcBiSegDCs              ( Pel* ptrSrc, UInt srcStride, Bool* biSegPattern, Int patternStride, Pel& valDC1, Pel& valDC2 );
 #if H_3D_DIM_DMM
   Void xSearchDmmDeltaDCs         ( TComDataCU* pcCU, UInt uiAbsPtIdx, Pel* piOrig, Pel* piPredic, UInt uiStride, Bool* biSegPattern, Int patternStride, UInt uiWidth, UInt uiHeight, Pel& rDeltaDC1, Pel& rDeltaDC2 );
   Void xSearchDmm1Wedge           ( TComDataCU* pcCU, UInt uiAbsPtIdx, Pel* piRef, UInt uiRefStride, UInt uiWidth, UInt uiHeight, UInt& ruiTabIdx );
-#if !SEC_DMM2_E0146_HHIFIX
-  Void xSearchDmm2Wedge           ( TComDataCU* pcCU, UInt uiAbsPtIdx, Pel* piRef, UInt uiRefStride, UInt uiWidth, UInt uiHeight, UInt& ruiTabIdx, Int& riWedgeDeltaEnd );
-#endif
-#if LGE_PKU_DMM3_OVERLAP_E0159_HHIFIX
   Void xSearchDmm3Wedge           ( TComDataCU* pcCU, UInt uiAbsPtIdx, Pel* piRef, UInt uiRefStride, UInt uiWidth, UInt uiHeight, UInt& ruiTabIdx, UInt& ruiIntraTabIdx, UInt colTexIntraDir );
-#else
-  Void xSearchDmm3Wedge           ( TComDataCU* pcCU, UInt uiAbsPtIdx, Pel* piRef, UInt uiRefStride, UInt uiWidth, UInt uiHeight, UInt& ruiTabIdx, UInt& ruiIntraTabIdx );
-#endif
 #endif
 #if H_3D_DIM_RBC
Index: trunk/source/Lib/TLibEncoder/TEncSlice.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 622)
+++ trunk/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 655)
@@ -157,5 +157,16 @@
   m_pdRdPicQp         = (Double*)xMalloc( Double, m_pcCfg->getDeltaQpRD() * 2 + 1 );
   m_piRdPicQp         = (Int*   )xMalloc( Int,    m_pcCfg->getDeltaQpRD() * 2 + 1 );
+#if KWU_RC_MADPRED_E0227
+  if(m_pcCfg->getUseRateCtrl())
+  {
+    m_pcRateCtrl        = pcEncTop->getRateCtrl();
+  }
+  else
+  {
+    m_pcRateCtrl        = NULL;
+  }
+#else
   m_pcRateCtrl        = pcEncTop->getRateCtrl();
+#endif
 }
 
@@ -176,16 +187,8 @@
  \param pPPS          PPS associated with the slice
  */
-#if H_MV5
 #if H_MV
-Void TEncSlice::initEncSlice( TComPic* pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd, Int iGOPid, TComSlice*& rpcSlice, TComVPS* pVPS, TComSPS* pSPS, TComPPS *pPPS, Int layerId )
-#else
-Void TEncSlice::initEncSlice( TComPic* pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd, Int iGOPid, TComSlice*& rpcSlice, TComSPS* pSPS, TComPPS *pPPS )
-#endif
-#else
-#if H_3D
-Void TEncSlice::initEncSlice( TComPic* pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd, Int iGOPid, TComSlice*& rpcSlice, TComVPS* pVPS, TComSPS* pSPS, TComPPS *pPPS, Int layerId )
-#else
-Void TEncSlice::initEncSlice( TComPic* pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd, Int iGOPid, TComSlice*& rpcSlice, TComSPS* pSPS, TComPPS *pPPS )
-#endif
+Void TEncSlice::initEncSlice( TComPic* pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd, Int iGOPid, TComSlice*& rpcSlice, TComVPS* pVPS, TComSPS* pSPS, TComPPS *pPPS, Int layerId, bool isField )
+#else
+Void TEncSlice::initEncSlice( TComPic* pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd, Int iGOPid, TComSlice*& rpcSlice, TComSPS* pSPS, TComPPS *pPPS, bool isField )
 #endif
 {
@@ -195,5 +198,5 @@
   rpcSlice = pcPic->getSlice(0);
 
-#if H_MV5
+#if H_MV
   rpcSlice->setVPS( pVPS ); 
 
@@ -203,15 +206,4 @@
 #if H_3D
   rpcSlice->setIsDepth     ( pVPS->getDepthId     ( layerId ) != 0 );    
-#endif
-#else
-#if H_3D
-  // GT: Should also be activated for MV-HEVC at some stage
-  rpcSlice->setVPS( pVPS );
-  Int vpsLayerId = pVPS->getLayerIdInNuh( layerId ); 
-
-  rpcSlice->setLayerId     ( layerId );
-  rpcSlice->setViewId      ( pVPS->getViewId      ( vpsLayerId ) );    
-  rpcSlice->setViewIndex   ( pVPS->getViewIndex   ( vpsLayerId ) );
-  rpcSlice->setIsDepth     ( pVPS->getDepthId     ( vpsLayerId ) != 0 );    
 #endif
 #endif
@@ -342,5 +334,5 @@
     Int    NumberBFrames = ( m_pcCfg->getGOPSize() - 1 );
     Int    SHIFT_QP = 12;
-    Double dLambda_scale = 1.0 - Clip3( 0.0, 0.5, 0.05*(Double)NumberBFrames );
+    Double dLambda_scale = 1.0 - Clip3( 0.0, 0.5, 0.05*(Double)(isField ? NumberBFrames/2 : NumberBFrames) );
 #if FULL_NBIT
     Int    bitdepth_luma_qp_scale = 6 * (g_bitDepth - 8);
@@ -1125,4 +1117,19 @@
     if(m_pcCfg->getUseRateCtrl())
     {
+#if KWU_RC_MADPRED_E0227
+      if(pcSlice->getLayerId() != 0 && m_pcCfg->getUseDepthMADPred() && !pcSlice->getIsDepth())
+      {
+        Double zn, zf, focallength, position, camshift;
+        Double basepos;
+        Bool bInterpolated;
+        Int direction = pcSlice->getViewId() - pcCU->getSlice()->getIvPic(false, 0)->getViewId();
+
+        pcEncTop->getCamParam()->xGetZNearZFar(pcEncTop->getCamParam()->getBaseViewNumbers()[pcSlice->getViewIndex()], pcSlice->getPOC(), zn, zf);
+        pcEncTop->getCamParam()->xGetGeometryData(pcEncTop->getCamParam()->getBaseViewNumbers()[0], pcSlice->getPOC(), focallength, basepos, camshift, bInterpolated);
+        pcEncTop->getCamParam()->xGetGeometryData(pcEncTop->getCamParam()->getBaseViewNumbers()[pcSlice->getViewIndex()], pcSlice->getPOC(), focallength, position, camshift, bInterpolated);
+
+        m_pcRateCtrl->updateLCUDataEnhancedView(pcCU, pcCU->getTotalBits(), pcCU->getQP(0), basepos, position, focallength, zn, zf, (direction > 0 ? 1 : -1));
+      }
+#endif
       if(m_pcRateCtrl->calculateUnitQP())
       {
@@ -1223,4 +1230,22 @@
         else
         {
+#if KWU_RC_MADPRED_E0227
+          if(pcSlice->getLayerId() != 0 && m_pcCfg->getUseDepthMADPred() && !pcSlice->getIsDepth())
+          {
+            Double zn, zf, focallength, position, camShift;
+            Double basePos;
+            Bool bInterpolated;
+            Int direction = pcSlice->getViewId() - pcCU->getSlice()->getIvPic(false, 0)->getViewId();
+            Int disparity;
+
+            pcEncTop->getCamParam()->xGetZNearZFar(pcEncTop->getCamParam()->getBaseViewNumbers()[pcSlice->getViewIndex()], pcSlice->getPOC(), zn, zf);
+            pcEncTop->getCamParam()->xGetGeometryData(pcEncTop->getCamParam()->getBaseViewNumbers()[0], pcSlice->getPOC(), focallength, basePos, camShift, bInterpolated);
+            pcEncTop->getCamParam()->xGetGeometryData(pcEncTop->getCamParam()->getBaseViewNumbers()[pcSlice->getViewIndex()], pcSlice->getPOC(), focallength, position, camShift, bInterpolated);
+            bpp       = m_pcRateCtrl->getRCPic()->getLCUTargetBppforInterView( m_pcRateCtrl->getPicList(), pcCU,
+              basePos, position, focallength, zn, zf, (direction > 0 ? 1 : -1), &disparity );
+          }
+          else
+          {
+#endif
 #if RATE_CONTROL_INTRA
           bpp = m_pcRateCtrl->getRCPic()->getLCUTargetBpp(pcSlice->getSliceType());
@@ -1239,5 +1264,11 @@
           estQP     = m_pcRateCtrl->getRCPic()->getLCUEstQP    ( estLambda, pcSlice->getSliceQp() );
 #endif
-
+#if KWU_RC_MADPRED_E0227
+          }
+#endif
+#if KWU_RC_MADPRED_E0227
+          estLambda = m_pcRateCtrl->getRCPic()->getLCUEstLambda( bpp );
+          estQP     = m_pcRateCtrl->getRCPic()->getLCUEstQP    ( estLambda, pcSlice->getSliceQp() );
+#endif
           estQP     = Clip3( -pcSlice->getSPS()->getQpBDOffsetY(), MAX_QP, estQP );
 
@@ -1343,5 +1374,5 @@
       if ( m_pcCfg->getUseRateCtrl() )
       {
-#if !M0036_RC_IMPROVEMENT
+#if !M0036_RC_IMPROVEMENT || KWU_RC_MADPRED_E0227
         UInt SAD    = m_pcCuEncoder->getLCUPredictionSAD();
         Int height  = min( pcSlice->getSPS()->getMaxCUHeight(),pcSlice->getSPS()->getPicHeightInLumaSamples() - uiCUAddr / rpcPic->getFrameWidthInCU() * pcSlice->getSPS()->getMaxCUHeight() );
Index: trunk/source/Lib/TLibEncoder/TEncSlice.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSlice.h	(revision 622)
+++ trunk/source/Lib/TLibEncoder/TEncSlice.h	(revision 655)
@@ -116,20 +116,10 @@
   
   /// preparation of slice encoding (reference marking, QP and lambda)
-#if H_MV5
 #if H_MV
   Void    initEncSlice        ( TComPic* pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd, 
-                                Int iGOPid, TComSlice*& rpcSlice, TComVPS* pVPS, TComSPS* pSPS, TComPPS *pPPS, Int layerId ); 
+                                Int iGOPid, TComSlice*& rpcSlice, TComVPS* pVPS, TComSPS* pSPS, TComPPS *pPPS, Int layerId, bool isField  ); 
 #else
   Void    initEncSlice        ( TComPic*  pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd,
-                                Int iGOPid,   TComSlice*& rpcSlice, TComSPS* pSPS, TComPPS *pPPS );
-#endif
-#else
-#if H_3D
-  Void    initEncSlice        ( TComPic* pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd, 
-                                Int iGOPid, TComSlice*& rpcSlice, TComVPS* pVPS, TComSPS* pSPS, TComPPS *pPPS, Int layerId ); 
-#else
-  Void    initEncSlice        ( TComPic*  pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd,
-                                Int iGOPid,   TComSlice*& rpcSlice, TComSPS* pSPS, TComPPS *pPPS );
-#endif
+                                Int iGOPid,   TComSlice*& rpcSlice, TComSPS* pSPS, TComPPS *pPPS, bool isField  );
 #endif
 #if RATE_CONTROL_LAMBDA_DOMAIN
Index: trunk/source/Lib/TLibEncoder/TEncTop.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncTop.cpp	(revision 622)
+++ trunk/source/Lib/TLibEncoder/TEncTop.cpp	(revision 655)
@@ -123,9 +123,17 @@
   if ( m_RCEnableRateControl )
   {
+#if KWU_RC_MADPRED_E0227
+    m_cRateCtrl.init( m_framesToBeEncoded, m_RCTargetBitrate, m_iFrameRate, m_iGOPSize, m_iSourceWidth, m_iSourceHeight,
+      g_uiMaxCUWidth, g_uiMaxCUHeight, m_RCKeepHierarchicalBit, m_RCUseLCUSeparateModel, m_GOPList, getLayerId() );
+#else
     m_cRateCtrl.init( m_framesToBeEncoded, m_RCTargetBitrate, m_iFrameRate, m_iGOPSize, m_iSourceWidth, m_iSourceHeight,
                       g_uiMaxCUWidth, g_uiMaxCUHeight, m_RCKeepHierarchicalBit, m_RCUseLCUSeparateModel, m_GOPList );
+#endif
   }
 #else
-  m_cRateCtrl.create(getIntraPeriod(), getGOPSize(), getFrameRate(), getTargetBitrate(), getQP(), getNumLCUInUnit(), getSourceWidth(), getSourceHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight);
+#if KWU_FIX_URQ
+  if(m_enableRateCtrl)
+#endif
+    m_cRateCtrl.create(getIntraPeriod(), getGOPSize(), getFrameRate(), getTargetBitrate(), getQP(), getNumLCUInUnit(), getSourceWidth(), getSourceHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight);
 #endif
   // if SBAC-based RD optimization is used
@@ -284,5 +292,9 @@
 }
 
-Void TEncTop::init()
+#if KWU_RC_MADPRED_E0227
+Void TEncTop::init(TAppEncTop* pcTAppEncTop, Bool isFieldCoding)
+#else
+Void TEncTop::init(Bool isFieldCoding)
+#endif
 {
   // initialize SPS
@@ -301,5 +313,5 @@
   m_cPPS.setSPS(&m_cSPS);
   xInitPPS();
-  xInitRPS();
+  xInitRPS(isFieldCoding);
 
   xInitPPSforTiles();
@@ -310,4 +322,7 @@
   m_cCuEncoder.   init( this );
   
+#if KWU_RC_MADPRED_E0227
+  m_pcTAppEncTop = pcTAppEncTop;
+#endif
   // initialize transform & quantization class
   m_pcCavlcCoder = getCavlcCoder();
@@ -392,9 +407,5 @@
   if( picLastCoded )
   {
-#if MTK_SONY_PROGRESSIVE_MV_COMPRESSION_E0170
     picLastCoded->compressMotion(1); 
-#else
-    picLastCoded->compressMotion(); 
-#endif
   }
 #endif
@@ -433,5 +444,5 @@
 #if H_MV
   }
-  m_cGOPEncoder.compressPicInGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, gopId );
+  m_cGOPEncoder.compressPicInGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, gopId, false, false );
 
   if( gopId + 1 == m_cGOPEncoder.getGOPSize() )
@@ -439,5 +450,5 @@
 #else
   // compress GOP
-  m_cGOPEncoder.compressGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut);
+  m_cGOPEncoder.compressGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, false, false);
 #endif
 
@@ -456,4 +467,160 @@
 #endif
 }
+/**------------------------------------------------
+ Separate interlaced frame into two fields
+ -------------------------------------------------**/
+void separateFields(Pel* org, Pel* dstField, UInt stride, UInt width, UInt height, bool isTop)
+{
+  if (!isTop)
+  {
+    org += stride;
+  }
+  for (Int y = 0; y < height>>1; y++)
+  {
+    for (Int x = 0; x < width; x++)
+    {
+      dstField[x] = org[x];
+    }
+    
+    dstField += stride;
+    org += stride*2;
+  }
+  
+}
+
+#if H_MV
+Void TEncTop::encode(Bool flush, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded, bool isTff, Int gopId )
+{
+  assert( 0 ); // Field coding and multiview need to be furhter harmonized. 
+}
+#else
+Void TEncTop::encode(Bool flush, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded, bool isTff)
+{
+  /* -- TOP FIELD -- */
+  
+  if (pcPicYuvOrg)
+  {
+    
+    /* -- Top field initialization -- */
+    
+    TComPic *pcTopField;
+    xGetNewPicBuffer( pcTopField );
+    pcTopField->getPicSym()->allocSaoParam(&m_cEncSAO);
+    pcTopField->setReconMark (false);
+    
+    pcTopField->getSlice(0)->setPOC( m_iPOCLast );
+    pcTopField->getPicYuvRec()->setBorderExtension(false);
+    pcTopField->setTopField(isTff);
+    
+    int nHeight = pcPicYuvOrg->getHeight();
+    int nWidth = pcPicYuvOrg->getWidth();
+    int nStride = pcPicYuvOrg->getStride();
+    int nPadLuma = pcPicYuvOrg->getLumaMargin();
+    int nPadChroma = pcPicYuvOrg->getChromaMargin();
+    
+    // Get pointers
+    Pel * PicBufY = pcPicYuvOrg->getBufY();
+    Pel * PicBufU = pcPicYuvOrg->getBufU();
+    Pel * PicBufV = pcPicYuvOrg->getBufV();
+    
+    Pel * pcTopFieldY =  pcTopField->getPicYuvOrg()->getLumaAddr();
+    Pel * pcTopFieldU =  pcTopField->getPicYuvOrg()->getCbAddr();
+    Pel * pcTopFieldV =  pcTopField->getPicYuvOrg()->getCrAddr();
+    
+    // compute image characteristics
+    if ( getUseAdaptiveQP() )
+    {
+      m_cPreanalyzer.xPreanalyze( dynamic_cast<TEncPic*>( pcTopField ) );
+    }
+    
+    /* -- Defield -- */
+    
+    bool isTop = isTff;
+    
+    separateFields(PicBufY + nPadLuma + nStride*nPadLuma, pcTopFieldY, nStride, nWidth, nHeight, isTop);
+    separateFields(PicBufU + nPadChroma + (nStride >> 1)*nPadChroma, pcTopFieldU, nStride >> 1, nWidth >> 1, nHeight >> 1, isTop);
+    separateFields(PicBufV + nPadChroma + (nStride >> 1)*nPadChroma, pcTopFieldV, nStride >> 1, nWidth >> 1, nHeight >> 1, isTop);
+    
+  }
+  
+  if (m_iPOCLast == 0) // compress field 0
+  {
+    m_cGOPEncoder.compressGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, true, isTff);
+  }
+  
+  /* -- BOTTOM FIELD -- */
+  
+  if (pcPicYuvOrg)
+  {
+    
+    /* -- Bottom field initialization -- */
+    
+    TComPic* pcBottomField;
+    xGetNewPicBuffer( pcBottomField );
+    pcBottomField->getPicSym()->allocSaoParam(&m_cEncSAO);
+    pcBottomField->setReconMark (false);
+    
+    TComPicYuv* rpcPicYuvRec = new TComPicYuv;
+    if ( rcListPicYuvRecOut.size() == (UInt)m_iGOPSize )
+    {
+      rpcPicYuvRec = rcListPicYuvRecOut.popFront();
+    }
+    else
+    {
+      rpcPicYuvRec->create( m_iSourceWidth, m_iSourceHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+    }
+    rcListPicYuvRecOut.pushBack( rpcPicYuvRec );
+    
+    pcBottomField->getSlice(0)->setPOC( m_iPOCLast);
+    pcBottomField->getPicYuvRec()->setBorderExtension(false);
+    pcBottomField->setTopField(!isTff);
+    
+    int nHeight = pcPicYuvOrg->getHeight();
+    int nWidth = pcPicYuvOrg->getWidth();
+    int nStride = pcPicYuvOrg->getStride();
+    int nPadLuma = pcPicYuvOrg->getLumaMargin();
+    int nPadChroma = pcPicYuvOrg->getChromaMargin();
+    
+    // Get pointers
+    Pel * PicBufY = pcPicYuvOrg->getBufY();
+    Pel * PicBufU = pcPicYuvOrg->getBufU();
+    Pel * PicBufV = pcPicYuvOrg->getBufV();
+    
+    Pel * pcBottomFieldY =  pcBottomField->getPicYuvOrg()->getLumaAddr();
+    Pel * pcBottomFieldU =  pcBottomField->getPicYuvOrg()->getCbAddr();
+    Pel * pcBottomFieldV =  pcBottomField->getPicYuvOrg()->getCrAddr();
+    
+    // Compute image characteristics
+    if ( getUseAdaptiveQP() )
+    {
+      m_cPreanalyzer.xPreanalyze( dynamic_cast<TEncPic*>( pcBottomField ) );
+    }
+    
+    /* -- Defield -- */
+    
+    bool isTop = !isTff;
+    
+    separateFields(PicBufY + nPadLuma + nStride*nPadLuma, pcBottomFieldY, nStride, nWidth, nHeight, isTop);
+    separateFields(PicBufU + nPadChroma + (nStride >> 1)*nPadChroma, pcBottomFieldU, nStride >> 1, nWidth >> 1, nHeight >> 1, isTop);
+    separateFields(PicBufV + nPadChroma + (nStride >> 1)*nPadChroma, pcBottomFieldV, nStride >> 1, nWidth >> 1, nHeight >> 1, isTop);
+    
+  }
+  
+  if ( ( !(m_iNumPicRcvd) || (!flush && m_iPOCLast != 1 && m_iNumPicRcvd != m_iGOPSize && m_iGOPSize)) )
+  {
+    iNumEncoded = 0;
+    return;
+  }
+  
+  // compress GOP
+  m_cGOPEncoder.compressGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, true, isTff);
+  
+  iNumEncoded = m_iNumPicRcvd;
+  m_iNumPicRcvd = 0;
+  m_uiNumAllPicCoded += iNumEncoded;
+}
+#endif
+
+
 
 // ====================================================================================================================
@@ -551,10 +718,8 @@
    * that chooses the actual compatibility based upon options */
 
-#if H_MV5
 #if H_MV  
   m_cSPS.setUpdateRepFormatFlag           ( m_layerId == 0 );    
   m_cSPS.setSpsInferScalingListFlag       ( m_layerId > 0 && m_cVPS->getInDirectDependencyFlag( getLayerIdInVps(), 0 ) ); 
   m_cSPS.setSpsScalingListRefLayerId      ( 0              ); 
-#endif
 #endif
   m_cSPS.setPicWidthInLumaSamples         ( m_iSourceWidth      );
@@ -680,10 +845,6 @@
 {
 #if H_MV
-#if H_MV5
   m_cPPS.setLayerId( getLayerId() );
   if( getVPS()->getNumDirectRefLayers( getLayerId() ) > 0 )
-#else
-  if( getVPS()->getNumDirectRefLayers( getLayerIdInVps() ) > 0 )
-#endif
   {
     m_cPPS.setListsModificationPresentFlag( true );
@@ -734,4 +895,12 @@
 #if RATE_CONTROL_LAMBDA_DOMAIN
   if ( m_RCEnableRateControl )
+  {
+    m_cPPS.setUseDQP(true);
+    m_cPPS.setMaxCuDQPDepth( 0 );
+    m_cPPS.setMinCuDQPSize( m_cPPS.getSPS()->getMaxCUWidth() >> ( m_cPPS.getMaxCuDQPDepth()) );
+  }
+#endif 
+#if !RATE_CONTROL_LAMBDA_DOMAIN && KWU_FIX_URQ
+  if ( m_enableRateCtrl )
   {
     m_cPPS.setUseDQP(true);
@@ -751,12 +920,19 @@
   m_cPPS.setOutputFlagPresentFlag( false );
 #if H_MV
-#if H_MV5
   m_cPPS.setNumExtraSliceHeaderBits( 2 ); 
-#else
-  m_cPPS.setNumExtraSliceHeaderBits( 1 ); 
-#endif
 #endif
   m_cPPS.setSignHideFlag(getSignHideFlag());
-  m_cPPS.setDeblockingFilterControlPresentFlag (m_DeblockingFilterControlPresent );
+  if ( getDeblockingFilterMetric() )
+  {
+    m_cPPS.setDeblockingFilterControlPresentFlag (true);
+    m_cPPS.setDeblockingFilterOverrideEnabledFlag(true);
+    m_cPPS.setPicDisableDeblockingFilterFlag(false);
+    m_cPPS.setDeblockingFilterBetaOffsetDiv2(0);
+    m_cPPS.setDeblockingFilterTcOffsetDiv2(0);
+  } 
+  else
+  {
+    m_cPPS.setDeblockingFilterControlPresentFlag (m_DeblockingFilterControlPresent );
+  }
   m_cPPS.setLog2ParallelMergeLevelMinus2   (m_log2ParallelMergeLevelMinus2 );
   m_cPPS.setCabacInitPresentFlag(CABAC_INIT_PRESENT_FLAG);
@@ -812,9 +988,9 @@
 
 //Function for initializing m_RPSList, a list of TComReferencePictureSet, based on the GOPEntry objects read from the config file.
-Void TEncTop::xInitRPS()
+Void TEncTop::xInitRPS(Bool isFieldCoding)
 {
   TComReferencePictureSet*      rps;
   
-  m_cSPS.createRPSList(getGOPSize()+m_extraRPSs);
+  m_cSPS.createRPSList(getGOPSize()+m_extraRPSs+1);
   TComRPSList* rpsList = m_cSPS.getRPSList();
 
@@ -913,5 +1089,5 @@
         printf("Warning: number of negative pictures in RPS is different between intra and inter RPS specified in the config file.\n");
         rps->setNumberOfNegativePictures(numNeg);
-        rps->setNumberOfPositivePictures(numNeg+numPos);
+        rps->setNumberOfPictures(numNeg+numPos);
       }
       if (numPos != rps->getNumberOfPositivePictures())
@@ -919,5 +1095,5 @@
         printf("Warning: number of positive pictures in RPS is different between intra and inter RPS specified in the config file.\n");
         rps->setNumberOfPositivePictures(numPos);
-        rps->setNumberOfPositivePictures(numNeg+numPos);
+        rps->setNumberOfPictures(numNeg+numPos);
       }
       RPSTemp.setNumberOfPictures(numNeg+numPos);
@@ -983,5 +1159,21 @@
 #endif //INTER_RPS_AUTO
   }
-  
+  //In case of field coding, we need to set special parameters for the first bottom field of the sequence, since it is not specified in the cfg file. 
+  //The position = GOPSize + extraRPSs which is (a priori) unused is reserved for this field in the RPS. 
+  if (isFieldCoding) 
+  {
+    rps = rpsList->getReferencePictureSet(getGOPSize()+m_extraRPSs);
+    rps->setNumberOfPictures(1);
+    rps->setNumberOfNegativePictures(1);
+    rps->setNumberOfPositivePictures(0);
+    rps->setNumberOfLongtermPictures(0);
+    rps->setDeltaPOC(0,-1);
+    rps->setPOC(0,0);
+    rps->setUsed(0,true);
+    rps->setInterRPSPrediction(false);
+    rps->setDeltaRIdxMinus1(0);
+    rps->setDeltaRPS(0);
+    rps->setNumRefIdc(0);
+}
 }
 
@@ -1028,4 +1220,8 @@
     }
   }
+  if(POCCurr == 1 && slice->getPic()->isField())
+  {
+    slice->setRPSidx(m_iGOPSize+m_extraRPSs);
+  }
 
   slice->setRPS(getSPS()->getRPSList()->getReferencePictureSet(slice->getRPSidx()));
@@ -1147,6 +1343,7 @@
 }
 #if H_MV
-Void TEncTop::printSummary( Int numAllPicCoded )
-{
+Void TEncTop::printSummary( Int numAllPicCoded, Bool isField )
+{
+  assert ( !isField ); // Multiview and field coding need to be further unified
   assert (numAllPicCoded == m_cAnalyzeAll.getNumPic());
 
Index: trunk/source/Lib/TLibEncoder/TEncTop.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncTop.h	(revision 622)
+++ trunk/source/Lib/TLibEncoder/TEncTop.h	(revision 655)
@@ -64,4 +64,7 @@
 // ====================================================================================================================
 
+#if KWU_RC_MADPRED_E0227
+class TAppEncTop;
+#endif
 /// encoder class
 class TEncTop : public TEncCfg
@@ -124,4 +127,9 @@
   TComScalingList         m_scalingList;                 ///< quantization matrix information
   TEncRateCtrl            m_cRateCtrl;                    ///< Rate control class
+
+#if KWU_RC_MADPRED_E0227
+  TAppEncTop*             m_pcTAppEncTop;
+  TAppComCamPara*         m_cCamParam;
+#endif
   
 #if H_MV
@@ -137,5 +145,5 @@
   
   Void  xInitPPSforTiles  ();
-  Void  xInitRPS          ();                             ///< initialize PPS from encoder options
+  Void  xInitRPS          (Bool isFieldCoding);           ///< initialize PPS from encoder options
 
 public:
@@ -145,5 +153,10 @@
   Void      create          ();
   Void      destroy         ();
-  Void      init            ();
+#if KWU_RC_MADPRED_E0227
+  Void      init            ( TAppEncTop* pcTAppEncTop, Bool isFieldCoding );
+#else
+  Void      init            (Bool isFieldCoding);
+#endif
+
 #if H_MV  
   TComPicLists* getIvPicLists() { return m_ivPicLists; }
@@ -185,4 +198,9 @@
   TEncSbac*               getRDGoOnSbacCoders   () { return  m_pcRDGoOnSbacCoders;   }
   TEncRateCtrl*           getRateCtrl           () { return &m_cRateCtrl;             }
+#if KWU_RC_MADPRED_E0227
+  TAppEncTop*             getEncTop             () { return m_pcTAppEncTop; }
+  TAppComCamPara*         getCamParam()                 { return m_cCamParam;}
+  Void                    setCamParam(TAppComCamPara * pCamparam)                 { m_cCamParam = pCamparam;}
+#endif
   TComSPS*                getSPS                () { return  &m_cSPS;                 }
   TComPPS*                getPPS                () { return  &m_cPPS;                 }
@@ -210,13 +228,22 @@
 #if H_MV
   Void encode( Bool bEos, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded  , Int gopId  );  
+
+   /// encode several number of pictures until end-of-sequence
+  Void encode( bool bEos, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut,
+              std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded, bool isTff  , Int gopId );
+
 #else
   Void encode( Bool bEos, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut,
-              std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded );  
-#endif
-
-#if H_MV
-  Void printSummary      ( Int numAllPicCoded ); 
-#else
-  void printSummary() { m_cGOPEncoder.printOutSummary (m_uiNumAllPicCoded); } 
+              std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded ); 
+   /// encode several number of pictures until end-of-sequence
+  Void encode( bool bEos, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut,
+              std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded, bool isTff);
+
+#endif
+
+#if H_MV
+  Void printSummary      ( Int numAllPicCoded, bool isField ); 
+#else
+  Void printSummary(bool isField) { m_cGOPEncoder.printOutSummary (m_uiNumAllPicCoded, isField); }
 #endif
 
