Index: branches/SHM-2.1-dev/source/Lib/TLibCommon/CommonDef.h
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibCommon/CommonDef.h	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibCommon/CommonDef.h	(revision 302)
@@ -56,5 +56,9 @@
 // ====================================================================================================================
 
+#if SVC_EXTENSION
 #define NV_VERSION        "2.1"                 ///< Current software version
+#else
+#define NV_VERSION        "11.0"                ///< Current software version
+#endif
 
 // ====================================================================================================================
@@ -110,7 +114,4 @@
 #define MAX_NUM_REF_PICS            16          ///< max. number of pictures used for reference
 #define MAX_NUM_REF                 16          ///< max. number of entries in picture reference list
-#if !L0034_COMBINED_LIST_CLEANUP
-#define MAX_NUM_REF_LC              MAX_NUM_REF_PICS  // TODO: remove this macro definition (leftover from combined list concept)
-#endif
 
 #define MAX_UINT                    0xFFFFFFFFU ///< max. value of unsigned 32-bit integer
Index: branches/SHM-2.1-dev/source/Lib/TLibCommon/NAL.h
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibCommon/NAL.h	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibCommon/NAL.h	(revision 302)
@@ -91,5 +91,4 @@
         || m_nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R;
   }
-#if L0045_NON_NESTED_SEI_RESTRICTIONS
   Bool isSei()
   {
@@ -102,5 +101,4 @@
     return ( (UInt)m_nalUnitType < 32 );
   }
-#endif
 };
 
Index: branches/SHM-2.1-dev/source/Lib/TLibCommon/SEI.cpp
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibCommon/SEI.cpp	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibCommon/SEI.cpp	(revision 302)
@@ -39,8 +39,6 @@
 #include "SEI.h"
 
-#if J0149_TONE_MAPPING_SEI 
 //Table D-7 Meaning of camera iso sensitivity indicator and exposure index rating indicator
 Int  Table_exp_indicator[32] = {0, 10, 12, 16, 20, 25, 32, 40, 50, 64, 80, 100, 125, 160, 200, 250, 320, 400, 500, 640, 800, 1000, 1250, 1600, 2000, 2500, 3200, 4000, 5000, 6400, 8000, -1};
-#endif
 
 SEIMessages getSeisByType(SEIMessages &seiList, SEI::PayloadType seiType)
Index: branches/SHM-2.1-dev/source/Lib/TLibCommon/SEI.h
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibCommon/SEI.h	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibCommon/SEI.h	(revision 302)
@@ -127,20 +127,14 @@
 
   SEIActiveParameterSets() 
-#if !L0047_APS_FLAGS
-    :numSpsIdsMinus1(0)
-#else
     : activeVPSId            (0)
     , m_fullRandomAccessFlag (false)
     , m_noParamSetUpdateFlag (false)
     , numSpsIdsMinus1        (0)
-#endif
   {}
   virtual ~SEIActiveParameterSets() {}
 
   Int activeVPSId; 
-#if L0047_APS_FLAGS
   Bool m_fullRandomAccessFlag;
   Bool m_noParamSetUpdateFlag;
-#endif
   Int numSpsIdsMinus1;
   std::vector<Int> activeSeqParamSetId; 
@@ -153,5 +147,4 @@
 
   SEIBufferingPeriod()
-#if L0044_CPB_DPB_DELAY_OFFSET
   : m_bpSeqParameterSetId (0)
   , m_rapCpbParamsPresentFlag (false)
@@ -164,23 +157,16 @@
     ::memset(m_initialAltCpbRemovalDelayOffset, 0, sizeof(m_initialAltCpbRemovalDelayOffset));
   }
-#else
-  {}
-#endif
   virtual ~SEIBufferingPeriod() {}
 
   UInt m_bpSeqParameterSetId;
   Bool m_rapCpbParamsPresentFlag;
-#if L0044_CPB_DPB_DELAY_OFFSET
   Bool m_cpbDelayOffset;
   Bool m_dpbDelayOffset;
-#endif
   UInt m_initialCpbRemovalDelay         [MAX_CPB_CNT][2];
   UInt m_initialCpbRemovalDelayOffset   [MAX_CPB_CNT][2];
   UInt m_initialAltCpbRemovalDelay      [MAX_CPB_CNT][2];
   UInt m_initialAltCpbRemovalDelayOffset[MAX_CPB_CNT][2];
-#if L0328_SPLICING
   Bool m_concatenationFlag;
   UInt m_auCpbRemovalDelayDelta;
-#endif
 };
 class SEIPictureTiming : public SEI
@@ -191,13 +177,7 @@
   SEIPictureTiming()
   : m_picStruct               (0)
-#if L0046_RENAME_PROG_SRC_IDC
   , m_sourceScanType          (0)
-#else
-  , m_progressiveSourceIdc    (0)
-#endif
   , m_duplicateFlag           (false)
-#if L0044_DU_DPB_OUTPUT_DELAY_HRD
   , m_picDpbOutputDuDelay     (0)
-#endif
   , m_numNalusInDuMinus1      (NULL)
   , m_duCpbRemovalDelayMinus1 (NULL)
@@ -216,16 +196,10 @@
 
   UInt  m_picStruct;
-#if L0046_RENAME_PROG_SRC_IDC
   UInt  m_sourceScanType;
-#else
-  UInt  m_progressiveSourceIdc;
-#endif
   Bool  m_duplicateFlag;
 
   UInt  m_auCpbRemovalDelay;
   UInt  m_picDpbOutputDelay;
-#if L0044_DU_DPB_OUTPUT_DELAY_HRD
   UInt  m_picDpbOutputDuDelay;
-#endif
   UInt  m_numDecodingUnitsMinus1;
   Bool  m_duCommonCpbRemovalDelayFlag;
@@ -243,16 +217,12 @@
     : m_decodingUnitIdx(0)
     , m_duSptCpbRemovalDelay(0)
-#if L0044_DU_DPB_OUTPUT_DELAY_HRD
     , m_dpbOutputDuDelayPresentFlag(false)
     , m_picSptDpbOutputDuDelay(0)
-#endif
   {}
   virtual ~SEIDecodingUnitInfo() {}
   Int m_decodingUnitIdx;
   Int m_duSptCpbRemovalDelay;
-#if L0044_DU_DPB_OUTPUT_DELAY_HRD
   Bool m_dpbOutputDuDelayPresentFlag;
   Int m_picSptDpbOutputDuDelay;
-#endif
 };
 
@@ -293,9 +263,5 @@
   Int  m_frame1GridPositionY;
   Int  m_arrangementReservedByte;
-#if L0045_PERSISTENCE_FLAGS
   Bool m_arrangementPersistenceFlag;
-#else
-  Int  m_arrangementRepetetionPeriod;
-#endif
   Bool m_upsampledAspectRatio;
 };
@@ -308,9 +274,5 @@
   SEIDisplayOrientation()
     : cancelFlag(true)
-#if L0045_PERSISTENCE_FLAGS
     , persistenceFlag(0)
-#else
-    , repetitionPeriod(1)
-#endif
     , extensionFlag(false)
     {}
@@ -322,9 +284,5 @@
 
   UInt anticlockwiseRotation;
-#if L0045_PERSISTENCE_FLAGS
   Bool persistenceFlag;
-#else
-  UInt repetitionPeriod;
-#endif
   Bool extensionFlag;
 };
@@ -373,5 +331,4 @@
 #endif
 
-#if L0208_SOP_DESCRIPTION_SEI
 class SEISOPDescription : public SEI
 {
@@ -390,7 +347,5 @@
   Int m_sopDescPocDelta[MAX_NUM_PICS_IN_SOP];
 };
-#endif
-
-#if J0149_TONE_MAPPING_SEI 
+
 class SEIToneMappingInfo : public SEI
 {
@@ -425,5 +380,4 @@
   Int    m_extendedWhiteLevelLumaCodeValue;
 };
-#endif
 
 typedef std::list<SEI*> SEIMessages;
@@ -438,5 +392,4 @@
 Void deleteSEIs (SEIMessages &seiList);
 
-#if K0180_SCALABLE_NESTING_SEI
 class SEIScalableNesting : public SEI
 {
@@ -468,5 +421,4 @@
   SEIMessages m_nestedSEIs;
 };
-#endif
 
 //! \}
Index: branches/SHM-2.1-dev/source/Lib/TLibCommon/TComBitStream.h
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibCommon/TComBitStream.h	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibCommon/TComBitStream.h	(revision 302)
@@ -193,4 +193,10 @@
   }
 
+  Void        peekPreviousByte( UInt &byte )
+  {
+    assert(m_fifo_idx > 0);
+    byte = (*m_fifo)[m_fifo_idx - 1];
+  }
+  
   Void        readOutTrailingBits ();
   UChar getHeldBits  ()          { return m_held_bits;          }
Index: branches/SHM-2.1-dev/source/Lib/TLibCommon/TComDataCU.cpp
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibCommon/TComDataCU.cpp	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibCommon/TComDataCU.cpp	(revision 302)
@@ -589,11 +589,9 @@
   }
 
-  UInt uiTmp = uhWidth*uhHeight;
-
   if(getPic()->getPicSym()->getInverseCUOrderMap(getAddr())*m_pcPic->getNumPartInCU()+m_uiAbsIdxInLCU >= getSlice()->getSliceSegmentCurStartCUAddr())
   {
     m_acCUMvField[0].clearMvField();
     m_acCUMvField[1].clearMvField();
-    uiTmp = uhWidth*uhHeight;
+    UInt uiTmp = uhWidth*uhHeight;
     
     memset( m_pcTrCoeffY,    0, uiTmp * sizeof( *m_pcTrCoeffY    ) );
@@ -794,7 +792,4 @@
   m_uiCUPelY           = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
   
-  UInt uiWidth         = g_uiMaxCUWidth  >> uiDepth;
-  UInt uiHeight        = g_uiMaxCUHeight >> uiDepth;
-  
   m_skipFlag=pcCU->getSkipFlag()          + uiPart;
 
@@ -838,5 +833,4 @@
   m_apcCUColocated[1] = pcCU->getCUColocated(REF_PIC_LIST_1);
   
-  UInt uiTmp = uiWidth*uiHeight;
   UInt uiMaxCuWidth=pcCU->getSlice()->getSPS()->getMaxCUWidth();
   UInt uiMaxCuHeight=pcCU->getSlice()->getSPS()->getMaxCUHeight();
@@ -850,5 +844,4 @@
   m_pcIPCMSampleY = pcCU->getPCMSampleY() + uiCoffOffset;
 
-  uiTmp >>= 2;
   uiCoffOffset >>=2;
   m_pcTrCoeffCb=pcCU->getCoeffCb() + uiCoffOffset;
@@ -1577,6 +1570,5 @@
     return getSlice()->getSliceQp();
   }
-  else
-  if ( iLastValidPartIdx >= 0 )
+  else if ( iLastValidPartIdx >= 0 )
   {
     return getQP( iLastValidPartIdx );
@@ -2860,5 +2852,4 @@
     //>> MTK colocated-RightBottom
     UInt uiPartIdxRB;
-    Int uiLCUIdx = getAddr();
 
     deriveRightBottomIdx( uiPUIdx, uiPartIdxRB );  
@@ -2869,12 +2860,11 @@
     TComMv cColMv;
     Int iRefIdx;
+    Int uiLCUIdx = -1;
 
     if      ( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelX() + g_auiRasterToPelX[uiAbsPartIdxTmp] + m_pcPic->getMinCUWidth() ) >= m_pcSlice->getSPS()->getPicWidthInLumaSamples() )  // image boundary check
     {
-      uiLCUIdx = -1;
     }
     else if ( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelY() + g_auiRasterToPelY[uiAbsPartIdxTmp] + m_pcPic->getMinCUHeight() ) >= m_pcSlice->getSPS()->getPicHeightInLumaSamples() )
     {
-      uiLCUIdx = -1;
     }
     else
@@ -2889,5 +2879,4 @@
       {
         uiAbsPartAddr = g_auiRasterToZscan[ (uiAbsPartIdxTmp + uiNumPartInCUWidth + 1) % m_pcPic->getNumPartInCU() ];
-        uiLCUIdx = -1 ; 
       }
       else if ( uiAbsPartIdxTmp / uiNumPartInCUWidth < m_pcPic->getNumPartInHeight() - 1 ) // is not at the last row of LCU But is last column of LCU
@@ -2899,5 +2888,4 @@
       {
         uiAbsPartAddr = 0;
-        uiLCUIdx = -1 ; 
       }
     }
@@ -3163,5 +3151,5 @@
     if (!bAdded) 
     {
-      bAdded = xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxLB, MD_LEFT );
+      xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxLB, MD_LEFT );
     }
   }
@@ -3176,5 +3164,5 @@
   if(!bAdded)
   {
-    bAdded = xAddMVPCand( pInfo, eRefPicList, iRefIdx, uiPartIdxLT, MD_ABOVE_LEFT);
+    xAddMVPCand( pInfo, eRefPicList, iRefIdx, uiPartIdxLT, MD_ABOVE_LEFT);
   }
   bAdded = bAddedSmvp;
@@ -3191,5 +3179,5 @@
     if(!bAdded)
     {
-      bAdded = xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxLT, MD_ABOVE_LEFT);
+      xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxLT, MD_ABOVE_LEFT);
     }
   }
@@ -3211,5 +3199,4 @@
     UInt uiAbsPartIdx;  
     UInt uiAbsPartAddr;
-    Int uiLCUIdx = getAddr();
 
     deriveRightBottomIdx( uiPartIdx, uiPartIdxRB );
@@ -3218,11 +3205,10 @@
     //----  co-located RightBottom Temporal Predictor (H) ---//
     uiAbsPartIdx = g_auiZscanToRaster[uiPartIdxRB];
+    Int uiLCUIdx = -1;
     if ( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelX() + g_auiRasterToPelX[uiAbsPartIdx] + m_pcPic->getMinCUWidth() ) >= m_pcSlice->getSPS()->getPicWidthInLumaSamples() )  // image boundary check
     {
-      uiLCUIdx = -1;
     }
     else if ( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelY() + g_auiRasterToPelY[uiAbsPartIdx] + m_pcPic->getMinCUHeight() ) >= m_pcSlice->getSPS()->getPicHeightInLumaSamples() )
     {
-      uiLCUIdx = -1;
     }
     else
@@ -3237,5 +3223,4 @@
       {
         uiAbsPartAddr = g_auiRasterToZscan[ (uiAbsPartIdx + uiNumPartInCUWidth + 1) % m_pcPic->getNumPartInCU() ];
-        uiLCUIdx      = -1 ; 
       }
       else if ( uiAbsPartIdx / uiNumPartInCUWidth < m_pcPic->getNumPartInHeight() - 1 ) // is not at the last row of LCU But is last column of LCU
@@ -3247,5 +3232,4 @@
       {
         uiAbsPartAddr = 0;
-        uiLCUIdx      = -1 ; 
       }
     }
@@ -3309,6 +3293,5 @@
 UInt TComDataCU::getIntraSizeIdx(UInt uiAbsPartIdx)
 {
-  UInt uiShift = ( (m_puhTrIdx[uiAbsPartIdx]==0) && (m_pePartSize[uiAbsPartIdx]==SIZE_NxN) ) ? m_puhTrIdx[uiAbsPartIdx]+1 : m_puhTrIdx[uiAbsPartIdx];
-  uiShift = ( m_pePartSize[uiAbsPartIdx]==SIZE_NxN ? 1 : 0 );
+  UInt uiShift = ( m_pePartSize[uiAbsPartIdx]==SIZE_NxN ? 1 : 0 );
   
   UChar uiWidth = m_puhWidth[uiAbsPartIdx]>>uiShift;
@@ -3396,9 +3379,5 @@
   }
   
-#if L0363_MVP_POC
   if ( pcTmpCU->getCUMvField(eRefPicList)->getRefIdx(uiIdx) >= 0 && m_pcSlice->getRefPic( eRefPicList, iRefIdx)->getPOC() == pcTmpCU->getSlice()->getRefPOC( eRefPicList, pcTmpCU->getCUMvField(eRefPicList)->getRefIdx(uiIdx) ))
-#else
-  if ( m_pcSlice->isEqualRef(eRefPicList, pcTmpCU->getCUMvField(eRefPicList)->getRefIdx(uiIdx), iRefIdx) )
-#endif
   {
     TComMv cMvPred = pcTmpCU->getCUMvField(eRefPicList)->getMv(uiIdx);
@@ -3602,5 +3581,4 @@
   }
   iCurrPOC = m_pcSlice->getPOC();    
-  iCurrRefPOC = m_pcSlice->getRefPic(eRefPicList, riRefIdx)->getPOC();
   iColPOC = pColCU->getSlice()->getPOC();  
 
Index: branches/SHM-2.1-dev/source/Lib/TLibCommon/TComLoopFilter.cpp
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibCommon/TComLoopFilter.cpp	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibCommon/TComLoopFilter.cpp	(revision 302)
@@ -461,5 +461,4 @@
         if ( ((piRefP0==piRefQ0)&&(piRefP1==piRefQ1)) || ((piRefP0==piRefQ1)&&(piRefP1==piRefQ0)) )
         {
-          uiBs = 0;
           if ( piRefP0 != piRefP1 )   // Different L0 & L1
           {
@@ -694,6 +693,4 @@
   for ( UInt iIdx = 0; iIdx < uiNumParts; iIdx++ )
   {
-    ucBs = 0;
-    
     uiBsAbsIdx = xCalcBsIdx( pcCU, uiAbsZorderIdx, iDir, iEdge, iIdx);
     ucBs = m_aapucBS[iDir][uiBsAbsIdx];
Index: branches/SHM-2.1-dev/source/Lib/TLibCommon/TComPrediction.cpp
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibCommon/TComPrediction.cpp	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibCommon/TComPrediction.cpp	(revision 302)
@@ -122,4 +122,5 @@
 Pel TComPrediction::predIntraGetPredValDC( Int* pSrc, Int iSrcStride, UInt iWidth, UInt iHeight, Bool bAbove, Bool bLeft )
 {
+  assert(iWidth > 0 && iHeight > 0);
   Int iInd, iSum = 0;
   Pel pDcVal;
Index: branches/SHM-2.1-dev/source/Lib/TLibCommon/TComRdCost.cpp
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibCommon/TComRdCost.cpp	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibCommon/TComRdCost.cpp	(revision 302)
@@ -485,5 +485,5 @@
 }
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
+#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
 UInt TComRdCost::getSADPart ( Int bitDepth, Pel* pelCur, Int curStride,  Pel* pelOrg, Int orgStride, UInt width, UInt height )
 {
Index: branches/SHM-2.1-dev/source/Lib/TLibCommon/TComRdCost.h
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibCommon/TComRdCost.h	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibCommon/TComRdCost.h	(revision 302)
@@ -168,4 +168,7 @@
 #if RATE_CONTROL_LAMBDA_DOMAIN
   Double  getLambda() { return m_dLambda; }
+#if M0036_RC_IMPROVEMENT
+  Double  getChromaWeight () {return((m_cbDistortionWeight+m_crDistortionWeight)/2.0);}
+#endif
 #endif
   
@@ -264,5 +267,5 @@
 #endif
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
+#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
   UInt   getSADPart ( Int bitDepth, Pel* pelCur, Int curStride,  Pel* pelOrg, Int orgStride, UInt width, UInt height );
 #endif
Index: branches/SHM-2.1-dev/source/Lib/TLibCommon/TComSlice.cpp
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibCommon/TComSlice.cpp	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibCommon/TComSlice.cpp	(revision 302)
@@ -65,8 +65,4 @@
 , m_deblockingFilterBetaOffsetDiv2 ( 0 )
 , m_deblockingFilterTcOffsetDiv2   ( 0 )
-#if !L0034_COMBINED_LIST_CLEANUP
-, m_bRefPicListModificationFlagLC ( false )
-, m_bRefPicListCombinationFlag    ( false )
-#endif
 , m_bCheckLDC                     ( false )
 , m_iSliceQpDelta                 ( 0 )
@@ -88,7 +84,4 @@
 #else
 , m_dLambda                       ( 0.0 )
-#endif
-#if !L0034_COMBINED_LIST_CLEANUP
-, m_bNoBackPredFlag             ( false )
 #endif
 , m_uiTLayer                      ( 0 )
@@ -119,9 +112,5 @@
 , m_enableTMVPFlag                ( true )
 {
-#if L0034_COMBINED_LIST_CLEANUP
   m_aiNumRefIdx[0] = m_aiNumRefIdx[1] = 0;
-#else
-  m_aiNumRefIdx[0] = m_aiNumRefIdx[1] = m_aiNumRefIdx[2] = 0;
-#endif
 
 #if SVC_EXTENSION
@@ -148,20 +137,8 @@
   initEqualRef();
   
-#if L0034_COMBINED_LIST_CLEANUP
   for ( Int idx = 0; idx < MAX_NUM_REF; idx++ )
   {
     m_list1IdxToList0Idx[idx] = -1;
   }
-#else
-  for(Int iNumCount = 0; iNumCount < MAX_NUM_REF_LC; iNumCount++)
-  {
-    m_iRefIdxOfLC[REF_PIC_LIST_0][iNumCount]=-1;
-    m_iRefIdxOfLC[REF_PIC_LIST_1][iNumCount]=-1;
-    m_eListIdFromIdxOfLC[iNumCount]=0;
-    m_iRefIdxFromIdxOfLC[iNumCount]=0;
-    m_iRefIdxOfL0FromRefIdxOfL1[iNumCount] = -1;
-    m_iRefIdxOfL1FromRefIdxOfL0[iNumCount] = -1;
-  }    
-#endif
   for(Int iNumCount = 0; iNumCount < MAX_NUM_REF; iNumCount++)
   {
@@ -210,16 +187,7 @@
   m_colRefIdx = 0;
   initEqualRef();
-#if !L0034_COMBINED_LIST_CLEANUP
-  m_bNoBackPredFlag = false;
-  m_bRefPicListCombinationFlag = false;
-  m_bRefPicListModificationFlagLC = false;
-#endif
   m_bCheckLDC = false;
   m_iSliceQpDeltaCb = 0;
   m_iSliceQpDeltaCr = 0;
-
-#if !L0034_COMBINED_LIST_CLEANUP
-  m_aiNumRefIdx[REF_PIC_LIST_C]      = 0;
-#endif
 
   m_maxNumMergeCand = MRG_MAX_NUM_CANDS;
@@ -364,5 +332,4 @@
 }
 
-#if L0034_COMBINED_LIST_CLEANUP
 Void TComSlice::setList1IdxToList0Idx()
 {
@@ -381,71 +348,11 @@
   }
 }
-#else
-Void TComSlice::generateCombinedList()
-{
-  if(m_aiNumRefIdx[REF_PIC_LIST_C] > 0)
-  {
-    m_aiNumRefIdx[REF_PIC_LIST_C]=0;
-    for(Int iNumCount = 0; iNumCount < MAX_NUM_REF_LC; iNumCount++)
-    {
-      m_iRefIdxOfLC[REF_PIC_LIST_0][iNumCount]=-1;
-      m_iRefIdxOfLC[REF_PIC_LIST_1][iNumCount]=-1;
-      m_eListIdFromIdxOfLC[iNumCount]=0;
-      m_iRefIdxFromIdxOfLC[iNumCount]=0;
-      m_iRefIdxOfL0FromRefIdxOfL1[iNumCount] = -1;
-      m_iRefIdxOfL1FromRefIdxOfL0[iNumCount] = -1;
-    }
-
-    for (Int iNumRefIdx = 0; iNumRefIdx < MAX_NUM_REF; iNumRefIdx++)
-    {
-      if(iNumRefIdx < m_aiNumRefIdx[REF_PIC_LIST_0])
-      {
-        Bool bTempRefIdxInL2 = true;
-        for ( Int iRefIdxLC = 0; iRefIdxLC < m_aiNumRefIdx[REF_PIC_LIST_C]; iRefIdxLC++ )
-        {
-          if ( m_apcRefPicList[REF_PIC_LIST_0][iNumRefIdx]->getPOC() == m_apcRefPicList[m_eListIdFromIdxOfLC[iRefIdxLC]][m_iRefIdxFromIdxOfLC[iRefIdxLC]]->getPOC() )
-          {
-            m_iRefIdxOfL1FromRefIdxOfL0[iNumRefIdx] = m_iRefIdxFromIdxOfLC[iRefIdxLC];
-            m_iRefIdxOfL0FromRefIdxOfL1[m_iRefIdxFromIdxOfLC[iRefIdxLC]] = iNumRefIdx;
-            bTempRefIdxInL2 = false;
-            break;
-          }
-        }
-
-        if(bTempRefIdxInL2 == true)
-        { 
-          m_eListIdFromIdxOfLC[m_aiNumRefIdx[REF_PIC_LIST_C]] = REF_PIC_LIST_0;
-          m_iRefIdxFromIdxOfLC[m_aiNumRefIdx[REF_PIC_LIST_C]] = iNumRefIdx;
-          m_iRefIdxOfLC[REF_PIC_LIST_0][iNumRefIdx] = m_aiNumRefIdx[REF_PIC_LIST_C]++;
-        }
-      }
-
-      if(iNumRefIdx < m_aiNumRefIdx[REF_PIC_LIST_1])
-      {
-        Bool bTempRefIdxInL2 = true;
-        for ( Int iRefIdxLC = 0; iRefIdxLC < m_aiNumRefIdx[REF_PIC_LIST_C]; iRefIdxLC++ )
-        {
-          if ( m_apcRefPicList[REF_PIC_LIST_1][iNumRefIdx]->getPOC() == m_apcRefPicList[m_eListIdFromIdxOfLC[iRefIdxLC]][m_iRefIdxFromIdxOfLC[iRefIdxLC]]->getPOC() )
-          {
-            m_iRefIdxOfL0FromRefIdxOfL1[iNumRefIdx] = m_iRefIdxFromIdxOfLC[iRefIdxLC];
-            m_iRefIdxOfL1FromRefIdxOfL0[m_iRefIdxFromIdxOfLC[iRefIdxLC]] = iNumRefIdx;
-            bTempRefIdxInL2 = false;
-            break;
-          }
-        }
-        if(bTempRefIdxInL2 == true)
-        {
-          m_eListIdFromIdxOfLC[m_aiNumRefIdx[REF_PIC_LIST_C]] = REF_PIC_LIST_1;
-          m_iRefIdxFromIdxOfLC[m_aiNumRefIdx[REF_PIC_LIST_C]] = iNumRefIdx;
-          m_iRefIdxOfLC[REF_PIC_LIST_1][iNumRefIdx] = m_aiNumRefIdx[REF_PIC_LIST_C]++;
-        }
-      }
-    }
-  }
-}
-#endif
 
 #if FIX1071
+#if SVC_EXTENSION
 Void TComSlice::setRefPicList( TComList<TComPic*>& rcListPic, Bool checkNumPocTotalCurr, TComPic** ilpPic)
+#else
+Void TComSlice::setRefPicList( TComList<TComPic*>& rcListPic, Bool checkNumPocTotalCurr )
+#endif
 #else
 Void TComSlice::setRefPicList( TComList<TComPic*>& rcListPic )
@@ -456,8 +363,9 @@
 #endif
   {
-    if( m_eSliceType == I_SLICE )
+    if (m_eSliceType == I_SLICE)
     {
       ::memset( m_apcRefPicList, 0, sizeof (m_apcRefPicList));
       ::memset( m_aiNumRefIdx,   0, sizeof ( m_aiNumRefIdx ));
+      
       return;
     }
@@ -672,5 +580,5 @@
     }
     
-    assert(numPocTotalCurr != 0);
+    assert(numPocTotalCurr > 0);
     
     m_aiNumRefIdx[0] = getNumRefIdx(REF_PIC_LIST_0);
@@ -699,5 +607,6 @@
     {
       rpsCurrList0[cIdx] = RefPicSetLtCurr[i];
-    }
+    }    
+
 #if REF_IDX_FRAMEWORK
     if( m_layerId > 0 )
@@ -718,4 +627,6 @@
     }
 #endif
+  assert(cIdx == numPocTotalCurr);
+
   if (m_eSliceType==B_SLICE)
   {
@@ -732,5 +643,6 @@
     {
       rpsCurrList1[cIdx] = RefPicSetLtCurr[i];
-    }
+    }    
+
 #if REF_IDX_FRAMEWORK
     if( m_layerId > 0 )
@@ -751,15 +663,18 @@
     }
 #endif
+
+    assert(cIdx == numPocTotalCurr);
   }
 
   ::memset(m_bIsUsedAsLongTerm, 0, sizeof(m_bIsUsedAsLongTerm));
 
-  for (Int rIdx = 0; rIdx <= (m_aiNumRefIdx[0]-1); rIdx ++)
-  {
-    m_apcRefPicList[0][rIdx] = m_RefPicListModification.getRefPicListModificationFlagL0() ? rpsCurrList0[ m_RefPicListModification.getRefPicSetIdxL0(rIdx) ] : rpsCurrList0[rIdx % numPocTotalCurr];
-    m_bIsUsedAsLongTerm[0][rIdx] = m_RefPicListModification.getRefPicListModificationFlagL0() ? (m_RefPicListModification.getRefPicSetIdxL0(rIdx) >= (NumPocStCurr0 + NumPocStCurr1))
-                                  : ((rIdx % numPocTotalCurr) >= (NumPocStCurr0 + NumPocStCurr1));
-  }
-  if ( m_eSliceType == P_SLICE )
+  for (Int rIdx = 0; rIdx < m_aiNumRefIdx[0]; rIdx ++)
+  {
+    cIdx = m_RefPicListModification.getRefPicListModificationFlagL0() ? m_RefPicListModification.getRefPicSetIdxL0(rIdx) : rIdx % numPocTotalCurr;
+    assert(cIdx >= 0 && cIdx < numPocTotalCurr);
+    m_apcRefPicList[0][rIdx] = rpsCurrList0[ cIdx ];
+    m_bIsUsedAsLongTerm[0][rIdx] = ( cIdx >= NumPocStCurr0 + NumPocStCurr1 );
+  }
+  if ( m_eSliceType != B_SLICE )
   {
     m_aiNumRefIdx[1] = 0;
@@ -768,9 +683,10 @@
   else
   {
-    for (Int rIdx = 0; rIdx <= (m_aiNumRefIdx[1]-1); rIdx ++)
-    {
-      m_apcRefPicList[1][rIdx] = m_RefPicListModification.getRefPicListModificationFlagL1() ? rpsCurrList1[ m_RefPicListModification.getRefPicSetIdxL1(rIdx) ] : rpsCurrList1[rIdx % numPocTotalCurr];
-      m_bIsUsedAsLongTerm[1][rIdx] = m_RefPicListModification.getRefPicListModificationFlagL1() ?
-                                  (m_RefPicListModification.getRefPicSetIdxL1(rIdx) >= (NumPocStCurr0 + NumPocStCurr1)): ((rIdx % numPocTotalCurr) >= (NumPocStCurr0 + NumPocStCurr1));
+    for (Int rIdx = 0; rIdx < m_aiNumRefIdx[1]; rIdx ++)
+    {
+      cIdx = m_RefPicListModification.getRefPicListModificationFlagL1() ? m_RefPicListModification.getRefPicSetIdxL1(rIdx) : rIdx % numPocTotalCurr;
+      assert(cIdx >= 0 && cIdx < numPocTotalCurr);
+      m_apcRefPicList[1][rIdx] = rpsCurrList1[ cIdx ];
+      m_bIsUsedAsLongTerm[1][rIdx] = ( cIdx >= NumPocStCurr0 + NumPocStCurr1 );
     }
   }
@@ -1071,36 +987,13 @@
   m_deblockingFilterTcOffsetDiv2 = pSrc->m_deblockingFilterTcOffsetDiv2;
   
-#if L0034_COMBINED_LIST_CLEANUP
   for (i = 0; i < 2; i++)
-#else
-  for (i = 0; i < 3; i++)
-#endif
   {
     m_aiNumRefIdx[i]     = pSrc->m_aiNumRefIdx[i];
   }
 
-#if L0034_COMBINED_LIST_CLEANUP
   for (i = 0; i < MAX_NUM_REF; i++)
   {
     m_list1IdxToList0Idx[i] = pSrc->m_list1IdxToList0Idx[i];
   } 
-#else
-  for (i = 0; i < 2; i++)
-  {
-    for (j = 0; j < MAX_NUM_REF_LC; j++)
-    {
-       m_iRefIdxOfLC[i][j]  = pSrc->m_iRefIdxOfLC[i][j];
-    }
-  }
-  for (i = 0; i < MAX_NUM_REF_LC; i++)
-  {
-    m_eListIdFromIdxOfLC[i] = pSrc->m_eListIdFromIdxOfLC[i];
-    m_iRefIdxFromIdxOfLC[i] = pSrc->m_iRefIdxFromIdxOfLC[i];
-    m_iRefIdxOfL1FromRefIdxOfL0[i] = pSrc->m_iRefIdxOfL1FromRefIdxOfL0[i];
-    m_iRefIdxOfL0FromRefIdxOfL1[i] = pSrc->m_iRefIdxOfL0FromRefIdxOfL1[i];
-  }
-  m_bRefPicListModificationFlagLC = pSrc->m_bRefPicListModificationFlagLC;
-  m_bRefPicListCombinationFlag    = pSrc->m_bRefPicListCombinationFlag;
-#endif
   m_bCheckLDC             = pSrc->m_bCheckLDC;
   m_iSliceQpDelta        = pSrc->m_iSliceQpDelta;
@@ -1164,7 +1057,4 @@
   }
 
-#if !L0034_COMBINED_LIST_CLEANUP
-  m_bNoBackPredFlag      = pSrc->m_bNoBackPredFlag;
-#endif
   m_uiTLayer                      = pSrc->m_uiTLayer;
   m_bTLayerSwitchingFlag          = pSrc->m_bTLayerSwitchingFlag;
@@ -1471,5 +1361,9 @@
 /** Function for constructing an explicit Reference Picture Set out of the available pictures in a referenced Reference Picture Set
 */
+#if FIX1071
+Void TComSlice::createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool isRAP)
+#else
 Void TComSlice::createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet)
+#endif
 {
   TComPic* rpcPic;
@@ -1496,5 +1390,9 @@
         // and should be added to the explicit Reference Picture Set
         pcRPS->setDeltaPOC(k, pReferencePictureSet->getDeltaPOC(i));
+#if FIX1071
+        pcRPS->setUsed(k, pReferencePictureSet->getUsed(i) && (!isRAP));
+#else
         pcRPS->setUsed(k, pReferencePictureSet->getUsed(i));
+#endif
         if(pcRPS->getDeltaPOC(k) < 0)
         {
@@ -1674,9 +1572,5 @@
   {
     m_numReorderPics[i] = 0;
-#if L0323_DPB
     m_uiMaxDecPicBuffering[i] = 1; 
-#else
-    m_uiMaxDecPicBuffering[i] = 0; 
-#endif
     m_uiMaxLatencyIncrease[i] = 0;
   }
@@ -1786,7 +1680,4 @@
 , m_pcmLog2MaxSize            (  5)
 , m_uiPCMLog2MinSize          (  7)
-#if !L0034_COMBINED_LIST_CLEANUP
-, m_bUseLComb                 (false)
-#endif
 , m_bitDepthY                 (  8)
 , m_bitDepthC                 (  8)
@@ -1820,9 +1711,5 @@
   {
     m_uiMaxLatencyIncrease[i] = 0;
-#if L0323_DPB
     m_uiMaxDecPicBuffering[i] = 1;
-#else
-    m_uiMaxDecPicBuffering[i] = 0;
-#endif
     m_numReorderPics[i]       = 0;
   }
@@ -1862,5 +1749,4 @@
   TComHRD *hrd = vui->getHrdParameters();
 
-#if L0043_TIMING_INFO
   TimingInfo *timingInfo = vui->getTimingInfo();
   timingInfo->setTimingInfoPresentFlag( true );
@@ -1886,28 +1772,4 @@
     break;
   }
-#else
-  hrd->setTimingInfoPresentFlag( true );
-  switch( frameRate )
-  {
-  case 24:
-    hrd->setNumUnitsInTick( 1125000 );    hrd->setTimeScale    ( 27000000 );
-    break;
-  case 25:
-    hrd->setNumUnitsInTick( 1080000 );    hrd->setTimeScale    ( 27000000 );
-    break;
-  case 30:
-    hrd->setNumUnitsInTick( 900900 );     hrd->setTimeScale    ( 27000000 );
-    break;
-  case 50:
-    hrd->setNumUnitsInTick( 540000 );     hrd->setTimeScale    ( 27000000 );
-    break;
-  case 60:
-    hrd->setNumUnitsInTick( 450450 );     hrd->setTimeScale    ( 27000000 );
-    break;
-  default:
-    hrd->setNumUnitsInTick( 1001 );       hrd->setTimeScale    ( 60000 );
-    break;
-  }
-#endif
 
   Bool rateCnt = ( bitRate > 0 );
@@ -1922,7 +1784,5 @@
     hrd->setDuCpbRemovalDelayLengthMinus1( 7 );                    // 8-bit precision ( plus 1 for last DU in AU )
     hrd->setSubPicCpbParamsInPicTimingSEIFlag( true );
-#if L0044_DU_DPB_OUTPUT_DELAY_HRD
     hrd->setDpbOutputDelayDuLengthMinus1( 5 + 7 );                 // With sub-clock tick factor of 100, at least 7 bits to have the same value as AU dpb delay
-#endif
   }
   else
@@ -1953,7 +1813,5 @@
   UInt birateValue, cpbSizeValue;
   UInt ducpbSizeValue;
-#if L0363_DU_BIT_RATE
   UInt duBitRateValue = 0;
-#endif
 
   for( i = 0; i < MAX_TLAYER; i ++ )
@@ -1967,7 +1825,5 @@
     cpbSizeValue = bitRate;                                     // 1 second
     ducpbSizeValue = bitRate/numDU;
-#if L0363_DU_BIT_RATE
     duBitRateValue = bitRate;
-#endif
     for( j = 0; j < ( hrd->getCpbCntMinus1( i ) + 1 ); j ++ )
     {
@@ -1980,7 +1836,5 @@
       hrd->setCpbSizeValueMinus1( i, j, 1, ( cpbSizeValue - 1 ) );
       hrd->setDuCpbSizeValueMinus1( i, j, 1, ( ducpbSizeValue - 1 ) );
-#if L0363_DU_BIT_RATE
       hrd->setDuBitRateValueMinus1( i, j, 1, ( duBitRateValue - 1 ) );
-#endif
       hrd->setCbrFlag( i, j, 1, ( j == 0 ) );
     }
@@ -2559,10 +2413,8 @@
   , m_profileIdc      (0)
   , m_levelIdc        (0)
-#if L0046_CONSTRAINT_FLAGS
 , m_progressiveSourceFlag  (false)
 , m_interlacedSourceFlag   (false)
 , m_nonPackedConstraintFlag(false)
 , m_frameOnlyConstraintFlag(false)
-#endif
 {
   ::memset(m_profileCompatibilityFlag, 0, sizeof(m_profileCompatibilityFlag));
@@ -2595,15 +2447,4 @@
   // Copy all information related to general profile
   this->getGeneralPTL()->copyProfileInfo(ptl->getGeneralPTL());
-}
-#endif
-#if SIGNAL_BITRATE_PICRATE_IN_VPS
-TComBitRatePicRateInfo::TComBitRatePicRateInfo()
-{
-  ::memset(m_bitRateInfoPresentFlag, 0, sizeof(m_bitRateInfoPresentFlag));
-  ::memset(m_picRateInfoPresentFlag, 0, sizeof(m_picRateInfoPresentFlag));
-  ::memset(m_avgBitRate,             0, sizeof(m_avgBitRate));
-  ::memset(m_maxBitRate,             0, sizeof(m_maxBitRate));
-  ::memset(m_constantPicRateIdc,     0, sizeof(m_constantPicRateIdc));
-  ::memset(m_avgPicRate,             0, sizeof(m_avgPicRate));
 }
 #endif
Index: branches/SHM-2.1-dev/source/Lib/TLibCommon/TComSlice.h
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibCommon/TComSlice.h	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibCommon/TComSlice.h	(revision 302)
@@ -191,10 +191,8 @@
   Int     m_levelIdc;
 
-#if L0046_CONSTRAINT_FLAGS
   Bool m_progressiveSourceFlag;
   Bool m_interlacedSourceFlag;
   Bool m_nonPackedConstraintFlag;
   Bool m_frameOnlyConstraintFlag;
-#endif
   
 public:
@@ -216,5 +214,4 @@
   Void  setLevelIdc(Int x)      { m_levelIdc = x; }
   
-#if L0046_CONSTRAINT_FLAGS
   Bool getProgressiveSourceFlag() const { return m_progressiveSourceFlag; }
   Void setProgressiveSourceFlag(Bool b) { m_progressiveSourceFlag = b; }
@@ -228,5 +225,4 @@
   Bool getFrameOnlyConstraintFlag() const { return m_frameOnlyConstraintFlag; }
   Void setFrameOnlyConstraintFlag(Bool b) { m_frameOnlyConstraintFlag = b; }
-#endif
 #if VPS_EXTN_PROFILE_INFO
   Void copyProfileInfo(ProfileTierLevel *ptl);
@@ -257,35 +253,4 @@
 };
 /// VPS class
-
-#if SIGNAL_BITRATE_PICRATE_IN_VPS
-class TComBitRatePicRateInfo
-{
-  Bool        m_bitRateInfoPresentFlag[MAX_TLAYER];
-  Bool        m_picRateInfoPresentFlag[MAX_TLAYER];
-  Int         m_avgBitRate[MAX_TLAYER];
-  Int         m_maxBitRate[MAX_TLAYER];
-  Int         m_constantPicRateIdc[MAX_TLAYER];
-  Int         m_avgPicRate[MAX_TLAYER];
-public:
-  TComBitRatePicRateInfo();
-  Bool        getBitRateInfoPresentFlag(Int i) {return m_bitRateInfoPresentFlag[i];}
-  Void        setBitRateInfoPresentFlag(Int i, Bool x) {m_bitRateInfoPresentFlag[i] = x;}
-
-  Bool        getPicRateInfoPresentFlag(Int i) {return m_picRateInfoPresentFlag[i];}
-  Void        setPicRateInfoPresentFlag(Int i, Bool x) {m_picRateInfoPresentFlag[i] = x;}
-
-  Int         getAvgBitRate(Int i) {return m_avgBitRate[i];}
-  Void        setAvgBitRate(Int i, Int x) {m_avgBitRate[i] = x;}
-
-  Int         getMaxBitRate(Int i) {return m_maxBitRate[i];}
-  Void        setMaxBitRate(Int i, Int x) {m_maxBitRate[i] = x;}
-
-  Int         getConstantPicRateIdc(Int i) {return m_constantPicRateIdc[i];}
-  Void        setConstantPicRateIdc(Int i, Int x) {m_constantPicRateIdc[i] = x;}
-
-  Int         getAvgPicRate(Int i) {return m_avgPicRate[i];}
-  Void        setAvgPicRate(Int i, Int x) {m_avgPicRate[i] = x;}
-};
-#endif
 
 struct HrdSubLayerInfo
@@ -300,7 +265,5 @@
   UInt ducpbSizeValue    [MAX_CPB_CNT][2];
   UInt cbrFlag           [MAX_CPB_CNT][2];
-#if L0363_DU_BIT_RATE
   UInt duBitRateValue    [MAX_CPB_CNT][2];
-#endif
 };
 
@@ -308,9 +271,4 @@
 {
 private:
-#if !L0043_TIMING_INFO
-  Bool m_timingInfoPresentFlag;
-  UInt m_numUnitsInTick;
-  UInt m_timeScale;
-#endif
   Bool m_nalHrdParametersPresentFlag;
   Bool m_vclHrdParametersPresentFlag;
@@ -319,7 +277,5 @@
   UInt m_duCpbRemovalDelayLengthMinus1;
   Bool m_subPicCpbParamsInPicTimingSEIFlag;
-#if L0044_DU_DPB_OUTPUT_DELAY_HRD
   UInt m_dpbOutputDelayDuLengthMinus1;
-#endif
   UInt m_bitRateScale;
   UInt m_cpbSizeScale;
@@ -333,12 +289,5 @@
 public:
   TComHRD()
-#if !L0043_TIMING_INFO
-  :m_timingInfoPresentFlag(false)
-  ,m_numUnitsInTick(1001)
-  ,m_timeScale(60000)
-  ,m_nalHrdParametersPresentFlag(0)
-#else
   :m_nalHrdParametersPresentFlag(0)
-#endif
   ,m_vclHrdParametersPresentFlag(0)
   ,m_subPicCpbParamsPresentFlag(false)
@@ -346,7 +295,5 @@
   ,m_duCpbRemovalDelayLengthMinus1(0)
   ,m_subPicCpbParamsInPicTimingSEIFlag(false)
-#if L0044_DU_DPB_OUTPUT_DELAY_HRD
   ,m_dpbOutputDelayDuLengthMinus1(0)
-#endif
   ,m_bitRateScale(0)
   ,m_cpbSizeScale(0)
@@ -357,14 +304,4 @@
 
   virtual ~TComHRD() {}
-#if !L0043_TIMING_INFO
-  Void setTimingInfoPresentFlag             ( Bool flag )  { m_timingInfoPresentFlag = flag;               }
-  Bool getTimingInfoPresentFlag             ( )            { return m_timingInfoPresentFlag;               }
-
-  Void setNumUnitsInTick                    ( UInt value ) { m_numUnitsInTick = value;                     }
-  UInt getNumUnitsInTick                    ( )            { return m_numUnitsInTick;                      }
-
-  Void setTimeScale                         ( UInt value ) { m_timeScale = value;                          }
-  UInt getTimeScale                         ( )            { return m_timeScale;                           }
-#endif
 
   Void setNalHrdParametersPresentFlag       ( Bool flag )  { m_nalHrdParametersPresentFlag = flag;         }
@@ -386,8 +323,6 @@
   Bool getSubPicCpbParamsInPicTimingSEIFlag ()             { return m_subPicCpbParamsInPicTimingSEIFlag;   }
 
-#if L0044_DU_DPB_OUTPUT_DELAY_HRD
   Void setDpbOutputDelayDuLengthMinus1      (UInt value )  { m_dpbOutputDelayDuLengthMinus1 = value;       }
   UInt getDpbOutputDelayDuLengthMinus1      ()             { return m_dpbOutputDelayDuLengthMinus1;        }
-#endif
 
   Void setBitRateScale                      ( UInt value ) { m_bitRateScale = value;                       }
@@ -430,8 +365,6 @@
   Void setDuCpbSizeValueMinus1     ( Int layer, Int cpbcnt, Int nalOrVcl, UInt value ) { m_HRD[layer].ducpbSizeValue[cpbcnt][nalOrVcl] = value;       }
   UInt getDuCpbSizeValueMinus1     ( Int layer, Int cpbcnt, Int nalOrVcl            )  { return m_HRD[layer].ducpbSizeValue[cpbcnt][nalOrVcl];        }
-#if L0363_DU_BIT_RATE
   Void setDuBitRateValueMinus1     ( Int layer, Int cpbcnt, Int nalOrVcl, UInt value ) { m_HRD[layer].duBitRateValue[cpbcnt][nalOrVcl] = value;       }
   UInt getDuBitRateValueMinus1     (Int layer, Int cpbcnt, Int nalOrVcl )              { return m_HRD[layer].duBitRateValue[cpbcnt][nalOrVcl];        }
-#endif
   Void setCbrFlag                ( Int layer, Int cpbcnt, Int nalOrVcl, UInt value ) { m_HRD[layer].cbrFlag[cpbcnt][nalOrVcl] = value;            }
   Bool getCbrFlag                ( Int layer, Int cpbcnt, Int nalOrVcl             ) { return m_HRD[layer].cbrFlag[cpbcnt][nalOrVcl];             }
@@ -439,10 +372,7 @@
   Void setNumDU                              ( UInt value ) { m_numDU = value;                            }
   UInt getNumDU                              ( )            { return m_numDU;          }
-#if L0045_CONDITION_SIGNALLING
   Bool getCpbDpbDelaysPresentFlag() { return getNalHrdParametersPresentFlag() || getVclHrdParametersPresentFlag(); }
-#endif
 };
 
-#if L0043_TIMING_INFO
 class TimingInfo
 {
@@ -475,5 +405,4 @@
   Void setNumTicksPocDiffOneMinus1          (Int x       ) { m_numTicksPocDiffOneMinus1 = x;               }
 };
-#endif
 
 class TComVPS
@@ -487,5 +416,5 @@
   UInt        m_numReorderPics[MAX_TLAYER];
   UInt        m_uiMaxDecPicBuffering[MAX_TLAYER]; 
-  UInt        m_uiMaxLatencyIncrease[MAX_TLAYER];
+  UInt        m_uiMaxLatencyIncrease[MAX_TLAYER]; // Really max latency increase plus 1 (value 0 expresses no limit)
 
   UInt        m_numHrdParameters;
@@ -509,10 +438,5 @@
 #endif
   TComPTL     m_pcPTL;
-#if SIGNAL_BITRATE_PICRATE_IN_VPS
-  TComBitRatePicRateInfo    m_bitRatePicRateInfo;
-#endif
-#if L0043_TIMING_INFO
   TimingInfo  m_timingInfo;
-#endif
 
   // ------------------------------------------
@@ -636,10 +560,5 @@
 #endif
   TComPTL* getPTL() { return &m_pcPTL; }
-#if SIGNAL_BITRATE_PICRATE_IN_VPS
-  TComBitRatePicRateInfo *getBitratePicrateInfo() { return &m_bitRatePicRateInfo; }
-#endif
-#if L0043_TIMING_INFO
   TimingInfo* getTimingInfo() { return &m_timingInfo; }
-#endif
 #if VPS_EXTN_MASK_AND_DIM_INFO
   Bool   getAvcBaseLayerFlag()                                  { return m_avcBaseLayerFlag;       }
@@ -814,10 +733,5 @@
   Int  m_log2MaxMvLengthVertical;
   TComHRD m_hrdParameters;
-#if L0043_TIMING_INFO
   TimingInfo m_timingInfo;
-#else
-  Bool m_pocProportionalToTimingFlag;
-  Int  m_numTicksPocDiffOneMinus1;
-#endif
 #if M0464_TILE_BOUNDARY_ALIGNED_FLAG
   Bool m_tileBoundariesAlignedFlag;
@@ -856,8 +770,4 @@
     ,m_log2MaxMvLengthHorizontal(15)
     ,m_log2MaxMvLengthVertical(15)
-#if !L0043_TIMING_INFO  
-    ,m_pocProportionalToTimingFlag(false)
-    ,m_numTicksPocDiffOneMinus1(0)
-#endif
 #if M0464_TILE_BOUNDARY_ALIGNED_FLAG
     ,m_tileBoundariesAlignedFlag(true)
@@ -957,12 +867,5 @@
 
   TComHRD* getHrdParameters                 ()             { return &m_hrdParameters; }
-#if L0043_TIMING_INFO
   TimingInfo* getTimingInfo() { return &m_timingInfo; }
-#else
-  Bool getPocProportionalToTimingFlag() {return m_pocProportionalToTimingFlag; }
-  Void setPocProportionalToTimingFlag(Bool x) {m_pocProportionalToTimingFlag = x;}
-  Int  getNumTicksPocDiffOneMinus1() {return m_numTicksPocDiffOneMinus1;}
-  Void setNumTicksPocDiffOneMinus1(Int x) { m_numTicksPocDiffOneMinus1 = x;}
-#endif
 #if M0464_TILE_BOUNDARY_ALIGNED_FLAG
   Bool getTileBoundariesAlignedFlag(  ) { return m_tileBoundariesAlignedFlag; } 
@@ -1008,8 +911,4 @@
   Bool        m_useAMP;
 
-#if !L0034_COMBINED_LIST_CLEANUP
-  Bool        m_bUseLComb;
-#endif
-  
   // Parameter
   Int         m_bitDepthY;
@@ -1040,5 +939,5 @@
   TComScalingList*     m_scalingList;   //!< ScalingList class pointer
   UInt        m_uiMaxDecPicBuffering[MAX_TLAYER]; 
-  UInt        m_uiMaxLatencyIncrease[MAX_TLAYER];
+  UInt        m_uiMaxLatencyIncrease[MAX_TLAYER];  // Really max latency increase plus 1 (value 0 expresses no limit)
 
   Bool        m_useDF;
@@ -1146,9 +1045,4 @@
   
   // Tool list
-#if !L0034_COMBINED_LIST_CLEANUP
-  Void setUseLComb    (Bool b)   { m_bUseLComb = b;         }
-  Bool getUseLComb    ()         { return m_bUseLComb;      }
-#endif
-
   Bool getUseLossless ()         { return m_useLossless; }
   Void setUseLossless ( Bool b ) { m_useLossless  = b; }
@@ -1504,17 +1398,6 @@
   Bool        m_interLayerSamplePredOnlyFlag;
 #endif
-#if L0034_COMBINED_LIST_CLEANUP
   Int         m_list1IdxToList0Idx[MAX_NUM_REF];
   Int         m_aiNumRefIdx   [2];    //  for multiple reference of current slice
-#else
-  Int         m_aiNumRefIdx   [3];    //  for multiple reference of current slice
-  Int         m_iRefIdxOfLC[2][MAX_NUM_REF_LC];
-  Int         m_eListIdFromIdxOfLC[MAX_NUM_REF_LC];
-  Int         m_iRefIdxFromIdxOfLC[MAX_NUM_REF_LC];
-  Int         m_iRefIdxOfL1FromRefIdxOfL0[MAX_NUM_REF_LC];
-  Int         m_iRefIdxOfL0FromRefIdxOfL1[MAX_NUM_REF_LC];
-  Bool        m_bRefPicListModificationFlagLC;
-  Bool        m_bRefPicListCombinationFlag;
-#endif
 
   Bool        m_bCheckLDC;
@@ -1558,7 +1441,4 @@
 
   Bool        m_abEqualRef  [2][MAX_NUM_REF][MAX_NUM_REF];
-#if !L0034_COMBINED_LIST_CLEANUP
-  Bool        m_bNoBackPredFlag;
-#endif
   UInt        m_uiTLayer;
 #if SVC_EXTENSION
@@ -1680,17 +1560,5 @@
   Bool      getMvdL1ZeroFlag ()                                  { return m_bLMvdL1Zero;    }
   Int       getNumRpsCurrTempList();
-#if L0034_COMBINED_LIST_CLEANUP
   Int       getList1IdxToList0Idx ( Int list1Idx )               { return m_list1IdxToList0Idx[list1Idx]; }
-#else
-  Int       getRefIdxOfLC       (RefPicList e, Int iRefIdx)     { return m_iRefIdxOfLC[e][iRefIdx];           }
-  Int       getListIdFromIdxOfLC(Int iRefIdx)                   { return m_eListIdFromIdxOfLC[iRefIdx];       }
-  Int       getRefIdxFromIdxOfLC(Int iRefIdx)                   { return m_iRefIdxFromIdxOfLC[iRefIdx];       }
-  Int       getRefIdxOfL0FromRefIdxOfL1(Int iRefIdx)            { return m_iRefIdxOfL0FromRefIdxOfL1[iRefIdx];}
-  Int       getRefIdxOfL1FromRefIdxOfL0(Int iRefIdx)            { return m_iRefIdxOfL1FromRefIdxOfL0[iRefIdx];}
-  Bool      getRefPicListModificationFlagLC()                   {return m_bRefPicListModificationFlagLC;}
-  Void      setRefPicListModificationFlagLC(Bool bflag)         {m_bRefPicListModificationFlagLC=bflag;}     
-  Bool      getRefPicListCombinationFlag()                      {return m_bRefPicListCombinationFlag;}
-  Void      setRefPicListCombinationFlag(Bool bflag)            {m_bRefPicListCombinationFlag=bflag;}   
-#endif
   Void      setReferenced(Bool b)                               { m_bRefenced = b; }
   Bool      isReferenced()                                      { return m_bRefenced; }
@@ -1733,5 +1601,9 @@
 
 #if FIX1071
+#if SVC_EXTENSION
   Void      setRefPicList       ( TComList<TComPic*>& rcListPic, Bool checkNumPocTotalCurr = false, TComPic** ilpPic = NULL );
+#else
+  Void      setRefPicList       ( TComList<TComPic*>& rcListPic, Bool checkNumPocTotalCurr = false );
+#endif
 #else
   Void      setRefPicList       ( TComList<TComPic*>& rcListPic );
@@ -1769,11 +1641,5 @@
   
   static Void      sortPicList         ( TComList<TComPic*>& rcListPic );
-#if L0034_COMBINED_LIST_CLEANUP
   Void setList1IdxToList0Idx();
-#else
-  Bool getNoBackPredFlag() { return m_bNoBackPredFlag; }
-  Void setNoBackPredFlag( Bool b ) { m_bNoBackPredFlag = b; }
-  Void generateCombinedList       ();
-#endif
 
   UInt getTLayer             ()                            { return m_uiTLayer;                      }
@@ -1786,5 +1652,9 @@
   Bool isStepwiseTemporalLayerSwitchingPointCandidate( TComList<TComPic*>& rcListPic );
   Int       checkThatAllRefPicsAreAvailable( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool printErrors, Int pocRandomAccess = 0);
+#if FIX1071
+  Void      createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool isRAP);
+#else
   Void      createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet);
+#endif
 
   Void setMaxNumMergeCand               (UInt val )         { m_maxNumMergeCand = val;                    }
Index: branches/SHM-2.1-dev/source/Lib/TLibCommon/TComTrQuant.cpp
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibCommon/TComTrQuant.cpp	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibCommon/TComTrQuant.cpp	(revision 302)
@@ -1075,13 +1075,12 @@
     Int iTransformShift = MAX_TR_DYNAMIC_RANGE - uiBitDepth - uiLog2TrSize;  // Represents scaling through forward transform
 
-    Int iQBits = QUANT_SHIFT + m_cQP.m_iPer + iTransformShift;                // Right shift of non-RDOQ quantizer;  level = (coeff*uiQ + offset)>>q_bits
-
-    iAdd = (pcCU->getSlice()->getSliceType()==I_SLICE ? 171 : 85) << (iQBits-9);
-
 #if ADAPTIVE_QP_SELECTION
-    iQBits = QUANT_SHIFT + cQpBase.m_iPer + iTransformShift;
+    Int iQBits = QUANT_SHIFT + cQpBase.m_iPer + iTransformShift;
     iAdd = (pcCU->getSlice()->getSliceType()==I_SLICE ? 171 : 85) << (iQBits-9);
     Int iQBitsC = QUANT_SHIFT + cQpBase.m_iPer + iTransformShift - ARL_C_PRECISION;  
     Int iAddC   = 1 << (iQBitsC-1);
+#else
+    Int iQBits = QUANT_SHIFT + m_cQP.m_iPer + iTransformShift;                // Right shift of non-RDOQ quantizer;  level = (coeff*uiQ + offset)>>q_bits
+    iAdd = (pcCU->getSlice()->getSliceType()==I_SLICE ? 171 : 85) << (iQBits-9);
 #endif
 
@@ -1364,19 +1363,14 @@
 #else
   Int j;
-  {
-    Short block[ 64 * 64 ];
-    Short coeff[ 64 * 64 ];
-    {
-      for (j = 0; j < iHeight; j++)
-      {    
-        memcpy( block + j * iWidth, piBlkResi + j * uiStride, iWidth * sizeof( Short ) );
-      }
-    }
-    xTrMxN(bitDepth, block, coeff, iWidth, iHeight, uiMode );
-    for ( j = 0; j < iHeight * iWidth; j++ )
-    {    
-      psCoeff[ j ] = coeff[ j ];
-    }
-    return ;
+  Short block[ 32 * 32 ];
+  Short coeff[ 32 * 32 ];
+  for (j = 0; j < iHeight; j++)
+  {    
+    memcpy( block + j * iWidth, piBlkResi + j * uiStride, iWidth * sizeof( Short ) );
+  }
+  xTrMxN(bitDepth, block, coeff, iWidth, iHeight, uiMode );
+  for ( j = 0; j < iHeight * iWidth; j++ )
+  {    
+    psCoeff[ j ] = coeff[ j ];
   }
 #endif  
@@ -1399,6 +1393,6 @@
   Int j;
   {
-    Short block[ 64 * 64 ];
-    Short coeff[ 64 * 64 ];
+    Short block[ 32 * 32 ];
+    Short coeff[ 32 * 32 ];
     for ( j = 0; j < iHeight * iWidth; j++ )
     {    
@@ -1522,8 +1516,5 @@
                                                       UInt                            uiAbsPartIdx )
 {
-  Int    iQBits      = m_cQP.m_iBits;
-  Double dTemp       = 0;
   UInt uiLog2TrSize = g_aucConvertToBit[ uiWidth ] + 2;
-  Int uiQ = g_quantScales[m_cQP.rem()];
   
   UInt uiBitDepth = eTType == TEXT_LUMA ? g_bitDepthY : g_bitDepthC;
@@ -1536,6 +1527,5 @@
   assert(scalingListType < 6);
   
-  iQBits = QUANT_SHIFT + m_cQP.m_iPer + iTransformShift;                   // Right shift of non-RDOQ quantizer;  level = (coeff*uiQ + offset)>>q_bits
-  Double dErrScale   = 0;
+  Int iQBits = QUANT_SHIFT + m_cQP.m_iPer + iTransformShift;                   // Right shift of non-RDOQ quantizer;  level = (coeff*uiQ + offset)>>q_bits
   Double *pdErrScaleOrg = getErrScaleCoeff(scalingListType,uiLog2TrSize-2,m_cQP.m_iRem);
   Int *piQCoefOrg = getQuantCoeff(scalingListType,m_cQP.m_iRem,uiLog2TrSize-2);
@@ -1589,5 +1579,4 @@
   Double  d64BaseCost         = 0;
   Int     iLastScanPos        = -1;
-  dTemp                       = dErrScale;
   
   UInt    c1Idx     = 0;
@@ -1618,6 +1607,6 @@
       UInt    uiBlkPos          = scan[iScanPos];
       // set coeff
-      uiQ  = piQCoef[uiBlkPos];
-      dTemp = pdErrScale[uiBlkPos];
+      Int uiQ  = piQCoef[uiBlkPos];
+      Double dTemp = pdErrScale[uiBlkPos];
       Int lLevelDouble          = plSrcCoeff[ uiBlkPos ];
       lLevelDouble              = (Int)min<Int64>((Int64)abs((Int)lLevelDouble) * uiQ , MAX_INT - (1 << (iQBits - 1)));
Index: branches/SHM-2.1-dev/source/Lib/TLibCommon/TComWeightPrediction.cpp
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibCommon/TComWeightPrediction.cpp	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibCommon/TComWeightPrediction.cpp	(revision 302)
@@ -271,4 +271,6 @@
 Void TComWeightPrediction::getWpScaling( TComDataCU* pcCU, Int iRefIdx0, Int iRefIdx1, wpScalingParam *&wp0, wpScalingParam *&wp1)
 {
+  assert(iRefIdx0 >= 0 || iRefIdx1 >= 0);
+  
   TComSlice*      pcSlice       = pcCU->getSlice();
   TComPPS*        pps           = pcCU->getSlice()->getPPS();
Index: branches/SHM-2.1-dev/source/Lib/TLibCommon/TypeDef.h
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibCommon/TypeDef.h	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibCommon/TypeDef.h	(revision 302)
@@ -44,4 +44,6 @@
 
 #if SVC_EXTENSION
+#define MAX_LAYERS                       2      ///< max number of layers the codec is supposed to handle
+
 #define M0464_TILE_BOUNDARY_ALIGNED_FLAG 1      ///< VUI flag to indicate tile boundary alignment
 #define M0463_VUI_EXT_ILP_REF            1      ///< VUI extension inter-layer dependency offset signalling
@@ -49,5 +51,4 @@
 #define SCALED_REF_LAYER_OFFSET_FLAG     0      ///< M0309: Signal scaled reference layer offsets in SPS
 #define SCALED_REF_LAYER_OFFSETS         1      ///< M0309: Signal scaled reference layer offsets in SPS
-#define MAX_LAYERS                       2      ///< max number of layers the codec is supposed to handle
 
 #define VPS_RENAME                       1      ///< Rename variables max_layer_id and num_layer_sets_minus1 in VPS
@@ -73,5 +74,4 @@
 #define SVC_COL_BLK                      1      ///< get co-located block
 #define SVC_UPSAMPLING                   1      ///< upsampling filters
-#define ENCODER_BUGFIX                   1      ///< L0167: encoder bug fix for inter mode
 #define CHROMA_UPSAMPLING                1      ///< L0335: Chroma upsampling with 5 bits coefficients
 
@@ -129,8 +129,4 @@
 #endif
 #endif
-#else
-#define ILP_DECODED_PICTURE              0
-#define SYNTAX_OUTPUT                    0
-#endif
 
 #define FAST_INTRA_SHVC                  1      ///< M0115: reduction number of intra modes in the EL (encoder only)
@@ -139,47 +135,21 @@
 #endif
 
+#define RC_SHVC_HARMONIZATION            1  ///< JCTVC-M0037, rate control for SHVC
+
+#else
+#define ILP_DECODED_PICTURE              0
+#define SYNTAX_OUTPUT                    0
+#endif // SVC_EXTENSION
+
+
 //! \ingroup TLibCommon
 //! \{
 
-#define FIX1071 1 ///< Temporary fix for issue #1071
-
-
-#define M0043_LAYERS_PRESENT_SEI      0 ///< M0043: add layers present SEI
-#define L0208_SOP_DESCRIPTION_SEI     1 ///< L0208: add SOP descrioption SEI
+#define FIX1071 1 ///< fix for issue #1071
+
 #define MAX_NUM_PICS_IN_SOP           1024
 
-#define K0180_SCALABLE_NESTING_SEI  1   ///JCTVC-K0180 scalable nesting sei message
 #define MAX_NESTING_NUM_OPS         1024
 #define MAX_NESTING_NUM_LAYER       64
-
-#define J0149_TONE_MAPPING_SEI        1 ///< J0149: Tone mapping information SEI
-#define L0363_DU_BIT_RATE             1 ///< L0363: add bit_rate_du_value_minus1 to HRD parameters
-#define L0328_SPLICING                1 ///< L0328: splicing support in HRD
-#define L0044_DU_DPB_OUTPUT_DELAY_HRD 1 ///< L0044: Include dpb_output_delay_du_length_minus1 in hrd_parameters(), dpb_output_du_delay in
-                                        ///<        picture timing SEI and DU information SEI
-#define L0045_PERSISTENCE_FLAGS  1      ///< L0045: Replace "repetition_period" syntax elements in SEI with "persistence_flag"
-#define L0045_NON_NESTED_SEI_RESTRICTIONS 1 ///< L0045; Include restriction on the order of APS and non-nested BP, PT and DU info SEI messages
-#define L0044_CPB_DPB_DELAY_OFFSET 1  ///< L0044: Include syntax elements cpb_delay_offset and dpb_delay_offset in the BP SEI message
-#define L0047_APS_FLAGS            1  ///< L0047: Include full_random_access_flag and no_param_set_update_flag in the active parameter set SEI message
-#define L0043_TIMING_INFO          1  ///< L0043: Timing information is signalled in VUI outside hrd_parameters()
-#define L0046_RENAME_PROG_SRC_IDC  1  ///< L0046: Rename progressive_source_idc to source_scan_type
-#define L0045_CONDITION_SIGNALLING 1  ///< L0045: Condition the signaling of some syntax elements in picture timing SEI message
-#define L0043_MSS_IDC 1
-#define L0116_ENTRY_POINT 1
-#define L0363_MORE_BITS 1
-#define L0363_MVP_POC 1
-#define L0363_BYTE_ALIGN 1
-#define L0363_SEI_ALLOW_SUFFIX 1
-#define L0323_LIMIT_DEFAULT_LIST_SIZE 1
-#define L0046_CONSTRAINT_FLAGS 1
-#define L0255_MOVE_PPS_FLAGS       1  ///< move some flags to earlier positions in the PPS
-#define L0444_FPA_TYPE             1  ///< allow only FPA types 3, 4 and 5
-#define L0372 1
-#define SIGNAL_BITRATE_PICRATE_IN_VPS               0  ///< K0125: Signal bit_rate and pic_rate in VPS
-#define L0232_RD_PENALTY           1  ///< L0232: RD-penalty for 32x32 TU for intra in non-intra slices
-#define L0386_DB_METRIC            1  ///< L0386: non-normative blockiness metric (automatically configures deblocking parameters in bitstream)
-#define L0323_DPB                     1 ///< L0323: Specification of active reference indices and decoded picture buffer
-
-#define L0034_COMBINED_LIST_CLEANUP 1
 
 #if VPS_EXTN_MASK_AND_DIM_INFO
@@ -195,6 +165,9 @@
 #endif
 #define RATE_CONTROL_LAMBDA_DOMAIN                  1  ///< JCTVC-K0103, rate control by R-lambda model
-#define L0033_RC_BUGFIX                             1  ///< JCTVC-L0033, bug fix for R-lambda model based rate control
-#define RC_SHVC_HARMONIZATION                       1  ///< JCTVC-M0037, rate control for SHVC
+#define M0036_RC_IMPROVEMENT                        1  ///< JCTVC-M0036, improvement for R-lambda model based rate control
+#define TICKET_1090_FIX                             1
+
+#define RC_FIX                                      1  /// suggested fix for M0036
+#define RATE_CONTROL_INTRA                          1  ///< JCTVC-M0257, rate control for intra 
 
 #define MAX_CPB_CNT                     32  ///< Upper bound of (cpb_cnt_minus1 + 1)
@@ -217,6 +190,4 @@
 
 #define REMOVE_SAO_LCU_ENC_CONSTRAINTS_3 1  ///< disable the encoder constraint that conditionally disable SAO for chroma for entire slice in interleaved mode
-
-#define REMOVE_SINGLE_SEI_EXTENSION_FLAGS 1 ///< remove display orientation SEI extension flag (there is a generic SEI extension mechanism now) 
 
 #define SAO_ENCODING_CHOICE              1  ///< I0184: picture early termination
@@ -232,6 +203,4 @@
 #define MAX_NUM_SPS                16
 #define MAX_NUM_PPS                64
-
-
 
 #define WEIGHTED_CHROMA_DISTORTION  1   ///< F386: weighting of chroma for RDO
@@ -522,7 +491,4 @@
   REF_PIC_LIST_0 = 0,   ///< reference list 0
   REF_PIC_LIST_1 = 1,   ///< reference list 1
-#if !L0034_COMBINED_LIST_CLEANUP
-  REF_PIC_LIST_C = 2,   ///< combined reference list for uni-prediction in B-Slices
-#endif
   REF_PIC_LIST_X = 100  ///< special mark
 };
Index: branches/SHM-2.1-dev/source/Lib/TLibDecoder/SEIread.cpp
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibDecoder/SEIread.cpp	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibDecoder/SEIread.cpp	(revision 302)
@@ -90,9 +90,7 @@
     fprintf( g_hTrace, "=========== Decoding Unit Information SEI message ===========\n");
     break;
-#if J0149_TONE_MAPPING_SEI
   case SEI::TONE_MAPPING_INFO:
     fprintf( g_hTrace, "===========Tone Mapping Info SEI message ===========\n");
     break;
-#endif
 #if M0043_LAYERS_PRESENT_SEI
   case SEI::LAYERS_PRESENT:
@@ -100,14 +98,10 @@
     break;
 #endif
-#if L0208_SOP_DESCRIPTION_SEI
   case SEI::SOP_DESCRIPTION:
     fprintf( g_hTrace, "=========== SOP Description SEI message ===========\n");
     break;
-#endif
-#if K0180_SCALABLE_NESTING_SEI
   case SEI::SCALABLE_NESTING:
     fprintf( g_hTrace, "=========== Scalable Nesting SEI message ===========\n");
     break;
-#endif
   default:
     fprintf( g_hTrace, "=========== Unknown SEI message ===========\n");
@@ -251,10 +245,8 @@
       xParseSEIGradualDecodingRefreshInfo((SEIGradualDecodingRefreshInfo&) *sei, payloadSize);
       break;
-#if J0149_TONE_MAPPING_SEI
     case SEI::TONE_MAPPING_INFO:
       sei = new SEIToneMappingInfo;
       xParseSEIToneMappingInfo((SEIToneMappingInfo&) *sei, payloadSize);
       break;
-#endif
 #if M0043_LAYERS_PRESENT_SEI
     case SEI::LAYERS_PRESENT:
@@ -270,11 +262,8 @@
       break;
 #endif
-#if L0208_SOP_DESCRIPTION_SEI
     case SEI::SOP_DESCRIPTION:
       sei = new SEISOPDescription;
       xParseSEISOPDescription((SEISOPDescription&) *sei, payloadSize);
       break;
-#endif
-#if K0180_SCALABLE_NESTING_SEI
     case SEI::SCALABLE_NESTING:
       sei = new SEIScalableNesting;
@@ -285,5 +274,4 @@
 #endif
       break;
-#endif
     default:
       for (UInt i = 0; i < payloadSize; i++)
@@ -299,10 +287,8 @@
     switch (payloadType)
     {
-#if L0363_SEI_ALLOW_SUFFIX
       case SEI::USER_DATA_UNREGISTERED:
         sei = new SEIuserDataUnregistered;
         xParseSEIuserDataUnregistered((SEIuserDataUnregistered&) *sei, payloadSize);
         break;
-#endif
       case SEI::DECODED_PICTURE_HASH:
         sei = new SEIDecodedPictureHash;
@@ -436,8 +422,6 @@
   UInt val; 
   READ_CODE(4, val, "active_vps_id");      sei.activeVPSId = val; 
-#if L0047_APS_FLAGS
   READ_FLAG( val, "full_random_access_flag");  sei.m_fullRandomAccessFlag = val ? true : false;
   READ_FLAG( val, "no_param_set_update_flag"); sei.m_noParamSetUpdateFlag = val ? true : false;
-#endif
   READ_UVLC(   val, "num_sps_ids_minus1"); sei.numSpsIdsMinus1 = val;
 
@@ -472,5 +456,4 @@
     sei.m_duSptCpbRemovalDelay = 0;
   }
-#if L0044_DU_DPB_OUTPUT_DELAY_HRD
   READ_FLAG( val, "dpb_output_du_delay_present_flag"); sei.m_dpbOutputDuDelayPresentFlag = val ? true : false;
   if(sei.m_dpbOutputDuDelayPresentFlag)
@@ -479,5 +462,4 @@
     sei.m_picSptDpbOutputDuDelay = val;
   }
-#endif
   xParseByteAlign();
 }
@@ -496,5 +478,4 @@
     READ_FLAG( code, "rap_cpb_params_present_flag" );                   sei.m_rapCpbParamsPresentFlag = code;
   }
-#if L0328_SPLICING
   //read splicing flag and cpb_removal_delay_delta
   READ_FLAG( code, "concatenation_flag"); 
@@ -502,6 +483,4 @@
   READ_CODE( ( pHRD->getCpbRemovalDelayLengthMinus1() + 1 ), code, "au_cpb_removal_delay_delta_minus1" );
   sei.m_auCpbRemovalDelayDelta = code + 1;
-#endif
-#if L0044_CPB_DPB_DELAY_OFFSET
   if( sei.m_rapCpbParamsPresentFlag )
   {
@@ -509,5 +488,4 @@
     READ_CODE( pHRD->getDpbOutputDelayLengthMinus1()  + 1, code, "dpb_delay_offset" );      sei.m_dpbDelayOffset = code;
   }
-#endif
   for( nalOrVcl = 0; nalOrVcl < 2; nalOrVcl ++ )
   {
@@ -541,27 +519,13 @@
   TComHRD *hrd = vui->getHrdParameters();
 
-#if !L0045_CONDITION_SIGNALLING
-  // This condition was probably OK before the pic_struct, progressive_source_idc, duplicate_flag were added
-  if( !hrd->getNalHrdParametersPresentFlag() && !hrd->getVclHrdParametersPresentFlag() )
-  {
-    return;
-  }
-#endif
-
   if( vui->getFrameFieldInfoPresentFlag() )
   {
     READ_CODE( 4, code, "pic_struct" );             sei.m_picStruct            = code;
-#if L0046_RENAME_PROG_SRC_IDC
     READ_CODE( 2, code, "source_scan_type" );       sei.m_sourceScanType = code;
-#else
-    READ_CODE( 2, code, "progressive_source_idc" ); sei.m_progressiveSourceIdc = code;
-#endif
     READ_FLAG(    code, "duplicate_flag" );         sei.m_duplicateFlag        = ( code == 1 ? true : false );
   }
 
-#if L0045_CONDITION_SIGNALLING
   if( hrd->getCpbDpbDelaysPresentFlag())
   {
-#endif
     READ_CODE( ( hrd->getCpbRemovalDelayLengthMinus1() + 1 ), code, "au_cpb_removal_delay_minus1" );
     sei.m_auCpbRemovalDelay = code + 1;
@@ -569,5 +533,4 @@
     sei.m_picDpbOutputDelay = code;
 
-#if L0044_DU_DPB_OUTPUT_DELAY_HRD
     if(hrd->getSubPicCpbParamsPresentFlag())
     {
@@ -575,5 +538,4 @@
       sei.m_picDpbOutputDuDelay = code;
     }
-#endif
     if( hrd->getSubPicCpbParamsPresentFlag() && hrd->getSubPicCpbParamsInPicTimingSEIFlag() )
     {
@@ -609,7 +571,5 @@
       }
     }
-#if L0045_CONDITION_SIGNALLING
-  }
-#endif
+  }
   xParseByteAlign();
 }
@@ -632,7 +592,5 @@
   {
     READ_CODE( 7, val, "frame_packing_arrangement_type" );          sei.m_arrangementType = val;
-#if L0444_FPA_TYPE
     assert((sei.m_arrangementType > 2) && (sei.m_arrangementType < 6) );
-#endif
     READ_FLAG( val, "quincunx_sampling_flag" );                     sei.m_quincunxSamplingFlag = val;
 
@@ -654,9 +612,5 @@
 
     READ_CODE( 8, val, "frame_packing_arrangement_reserved_byte" );   sei.m_arrangementReservedByte = val;
-#if L0045_PERSISTENCE_FLAGS
     READ_FLAG( val,  "frame_packing_arrangement_persistence_flag" );  sei.m_arrangementPersistenceFlag = val ? true : false;
-#else
-    READ_UVLC( val, "frame_packing_arrangement_repetition_period" );  sei.m_arrangementRepetetionPeriod = val;
-#endif
   }
   READ_FLAG( val, "upsampled_aspect_ratio" );                       sei.m_upsampledAspectRatio = val;
@@ -674,13 +628,5 @@
     READ_FLAG( val,     "ver_flip" );                              sei.verFlip               = val;
     READ_CODE( 16, val, "anticlockwise_rotation" );                sei.anticlockwiseRotation = val;
-#if L0045_PERSISTENCE_FLAGS
     READ_FLAG( val,     "display_orientation_persistence_flag" );  sei.persistenceFlag       = val;
-#else
-    READ_UVLC( val,     "display_orientation_repetition_period" ); sei.repetitionPeriod      = val;
-#endif
-#if !REMOVE_SINGLE_SEI_EXTENSION_FLAGS
-    READ_FLAG( val,     "display_orientation_extension_flag" );    sei.extensionFlag         = val;
-    assert( !sei.extensionFlag );
-#endif
   }
   xParseByteAlign();
@@ -702,5 +648,4 @@
 }
 
-#if J0149_TONE_MAPPING_SEI
 Void SEIReader::xParseSEIToneMappingInfo(SEIToneMappingInfo& sei, UInt /*payloadSize*/)
 {
@@ -783,5 +728,4 @@
   xParseByteAlign();
 }
-#endif
 
 #if M0043_LAYERS_PRESENT_SEI
@@ -806,5 +750,4 @@
 #endif
 
-#if L0208_SOP_DESCRIPTION_SEI
 Void SEIReader::xParseSEISOPDescription(SEISOPDescription &sei, UInt payloadSize)
 {
@@ -830,8 +773,5 @@
   xParseByteAlign();
 }
-#endif
-
-
-#if K0180_SCALABLE_NESTING_SEI
+
 #if M0043_LAYERS_PRESENT_SEI
 Void SEIReader::xParseSEIScalableNesting(SEIScalableNesting& sei, const NalUnitType nalUnitType, UInt payloadSize, TComVPS *vps, TComSPS *sps)
@@ -888,5 +828,4 @@
 
 }
-#endif
 
 Void SEIReader::xParseByteAlign()
Index: branches/SHM-2.1-dev/source/Lib/TLibDecoder/SEIread.h
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibDecoder/SEIread.h	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibDecoder/SEIread.h	(revision 302)
@@ -78,19 +78,11 @@
   Void xParseSEITemporalLevel0Index   (SEITemporalLevel0Index &sei, UInt payloadSize);
   Void xParseSEIGradualDecodingRefreshInfo (SEIGradualDecodingRefreshInfo &sei, UInt payloadSize);
-#if J0149_TONE_MAPPING_SEI
   Void xParseSEIToneMappingInfo       (SEIToneMappingInfo& sei, UInt payloadSize);
-#endif
+  Void xParseSEISOPDescription        (SEISOPDescription &sei, UInt payloadSize);
 #if M0043_LAYERS_PRESENT_SEI
   Void xParseSEILayersPresent         (SEILayersPresent &sei, UInt payloadSize, TComVPS *vps);
-#endif
-#if L0208_SOP_DESCRIPTION_SEI
-  Void xParseSEISOPDescription        (SEISOPDescription &sei, UInt payloadSize);
-#endif
-#if K0180_SCALABLE_NESTING_SEI
-#if M0043_LAYERS_PRESENT_SEI
   Void xParseSEIScalableNesting       (SEIScalableNesting& sei, const NalUnitType nalUnitType, UInt payloadSize, TComVPS *vps, TComSPS *sps);
 #else
   Void xParseSEIScalableNesting       (SEIScalableNesting& sei, const NalUnitType nalUnitType, UInt payloadSize, TComSPS *sps);
-#endif
 #endif
   Void xParseByteAlign();
Index: branches/SHM-2.1-dev/source/Lib/TLibDecoder/TDecBinCoder.h
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibDecoder/TDecBinCoder.h	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibDecoder/TDecBinCoder.h	(revision 302)
@@ -54,5 +54,4 @@
   virtual Void  start             ()                                          = 0;
   virtual Void  finish            ()                                          = 0;
-  virtual Void  flush            ()                                           = 0;
 
   virtual Void  decodeBin         ( UInt& ruiBin, ContextModel& rcCtxModel )  = 0;
@@ -61,6 +60,4 @@
   virtual Void  decodeBinTrm      ( UInt& ruiBin                           )  = 0;
   
-  virtual Void  resetBac          ()                                          = 0;
-  virtual Void  decodePCMAlignBits()                                          = 0;
   virtual Void  xReadPCMCode      ( UInt uiLength, UInt& ruiCode)              = 0;
 
Index: branches/SHM-2.1-dev/source/Lib/TLibDecoder/TDecBinCoderCABAC.cpp
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibDecoder/TDecBinCoderCABAC.cpp	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibDecoder/TDecBinCoderCABAC.cpp	(revision 302)
@@ -75,15 +75,9 @@
 TDecBinCABAC::finish()
 {
-}
-
-Void 
-TDecBinCABAC::flush()
-{
-  while (m_pcTComBitstream->getNumBitsLeft() > 0 && m_pcTComBitstream->getNumBitsUntilByteAligned() != 0)
-  {
-    UInt uiBits;
-    m_pcTComBitstream->read ( 1, uiBits );
-  }
-  start();
+  UInt lastByte;
+
+  m_pcTComBitstream->peekPreviousByte( lastByte );
+  // Check for proper stop/alignment pattern
+  assert( ((lastByte << (8 + m_bitsNeeded)) & 0xff) == 0x80 );
 }
 
@@ -241,25 +235,4 @@
 }
 
-/** Reset BAC register values.
- * \returns Void
- */
-Void TDecBinCABAC::resetBac()
-{
-  m_uiRange    = 510;
-  m_bitsNeeded = -8;
-  m_uiValue    = m_pcTComBitstream->read( 16 );
-}
-
-/** Decode PCM alignment zero bits.
- * \returns Void
- */
-Void TDecBinCABAC::decodePCMAlignBits()
-{
-  Int iNum = m_pcTComBitstream->getNumBitsUntilByteAligned();
-  
-  UInt uiBit = 0;
-  m_pcTComBitstream->read( iNum, uiBit );
-}
-
 /** Read a PCM code.
  * \param uiLength code bit-depth
Index: branches/SHM-2.1-dev/source/Lib/TLibDecoder/TDecBinCoderCABAC.h
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibDecoder/TDecBinCoderCABAC.h	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibDecoder/TDecBinCoderCABAC.h	(revision 302)
@@ -56,5 +56,4 @@
   Void  start             ();
   Void  finish            ();
-  Void  flush             ();
   
   Void  decodeBin         ( UInt& ruiBin, ContextModel& rcCtxModel );
@@ -63,6 +62,4 @@
   Void  decodeBinTrm      ( UInt& ruiBin                           );
   
-  Void  resetBac          ();
-  Void  decodePCMAlignBits();
   Void  xReadPCMCode      ( UInt uiLength, UInt& ruiCode );
   
Index: branches/SHM-2.1-dev/source/Lib/TLibDecoder/TDecCAVLC.cpp
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibDecoder/TDecCAVLC.cpp	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibDecoder/TDecCAVLC.cpp	(revision 302)
@@ -175,32 +175,4 @@
 }
 
-/** copy SAO parameter
-* \param dst
-* \param src
-*/
-inline Void copySaoOneLcuParam(SaoLcuParam* dst,  SaoLcuParam* src)
-{
-  Int i;
-  dst->partIdx = src->partIdx;
-  dst->typeIdx = src->typeIdx;
-  if (dst->typeIdx != -1)
-  {
-    dst->subTypeIdx = src->subTypeIdx ;
-    dst->length  = src->length;
-    for (i=0;i<dst->length;i++)
-    {
-      dst->offset[i] = src->offset[i];
-    }
-  }
-  else
-  {
-    dst->length  = 0;
-    for (i=0;i<SAO_BO_LEN;i++)
-    {
-      dst->offset[i] = 0;
-    }
-  }
-}
-
 Void TDecCavlc::parsePPS(TComPPS* pcPPS)
 {
@@ -212,17 +184,20 @@
   Int   iCode;
 
-  READ_UVLC( uiCode, "pps_pic_parameter_set_id");                     pcPPS->setPPSId (uiCode);
-  READ_UVLC( uiCode, "pps_seq_parameter_set_id");                     pcPPS->setSPSId (uiCode);
+  READ_UVLC( uiCode, "pps_pic_parameter_set_id");
+  assert(uiCode <= 63);
+  pcPPS->setPPSId (uiCode);
+  
+  READ_UVLC( uiCode, "pps_seq_parameter_set_id");
+  assert(uiCode <= 15);
+  pcPPS->setSPSId (uiCode);
+  
   READ_FLAG( uiCode, "dependent_slice_segments_enabled_flag"    );    pcPPS->setDependentSliceSegmentsEnabledFlag   ( uiCode == 1 );
-#if L0255_MOVE_PPS_FLAGS
   READ_FLAG( uiCode, "output_flag_present_flag" );                    pcPPS->setOutputFlagPresentFlag( uiCode==1 );
 
   READ_CODE(3, uiCode, "num_extra_slice_header_bits");                pcPPS->setNumExtraSliceHeaderBits(uiCode);
-#endif
   READ_FLAG ( uiCode, "sign_data_hiding_flag" ); pcPPS->setSignHideFlag( uiCode );
 
   READ_FLAG( uiCode,   "cabac_init_present_flag" );            pcPPS->setCabacInitPresentFlag( uiCode ? true : false );
 
-#if L0323_LIMIT_DEFAULT_LIST_SIZE
   READ_UVLC(uiCode, "num_ref_idx_l0_default_active_minus1");
   assert(uiCode <= 14);
@@ -232,8 +207,4 @@
   assert(uiCode <= 14);
   pcPPS->setNumRefIdxL1DefaultActive(uiCode+1);
-#else
-  READ_UVLC(uiCode, "num_ref_idx_l0_default_active_minus1");       pcPPS->setNumRefIdxL0DefaultActive(uiCode+1);
-  READ_UVLC(uiCode, "num_ref_idx_l1_default_active_minus1");       pcPPS->setNumRefIdxL1DefaultActive(uiCode+1);
-#endif
 
   READ_SVLC(iCode, "init_qp_minus26" );                            pcPPS->setPicInitQPMinus26(iCode);
@@ -270,8 +241,4 @@
   pcPPS->setWPBiPred( uiCode==1 );
 
-#if !L0255_MOVE_PPS_FLAGS
-  READ_FLAG( uiCode, "output_flag_present_flag" );
-  pcPPS->setOutputFlagPresentFlag( uiCode==1 );
-#endif
   READ_FLAG( uiCode, "transquant_bypass_enable_flag");
   pcPPS->setTransquantBypassEnableFlag(uiCode ? true : false);
@@ -335,8 +302,4 @@
   pcPPS->setLog2ParallelMergeLevelMinus2 (uiCode);
 
-#if !L0255_MOVE_PPS_FLAGS
-  READ_CODE(3, uiCode, "num_extra_slice_header_bits");
-  pcPPS->setNumExtraSliceHeaderBits(uiCode);
-#endif
   READ_FLAG( uiCode, "slice_segment_header_extension_present_flag");
   pcPPS->setSliceHeaderExtensionPresentFlag(uiCode);
@@ -400,5 +363,4 @@
 
   READ_FLAG(     uiCode, "field_seq_flag");                           pcVUI->setFieldSeqFlag(uiCode);
-  assert(pcVUI->getFieldSeqFlag() == false);        // not supported yet
 
   READ_FLAG(uiCode, "frame_field_info_present_flag");                 pcVUI->setFrameFieldInfoPresentFlag(uiCode);
@@ -413,5 +375,4 @@
     READ_UVLC(   uiCode, "def_disp_win_bottom_offset" );              defDisp.setWindowBottomOffset( uiCode * TComSPS::getWinUnitY( pcSPS->getChromaFormatIdc()) );
   }
-#if L0043_TIMING_INFO
   TimingInfo *timingInfo = pcVUI->getTimingInfo();
   READ_FLAG(       uiCode, "vui_timing_info_present_flag");         timingInfo->setTimingInfoPresentFlag      (uiCode ? true : false);
@@ -425,5 +386,4 @@
       READ_UVLC(   uiCode, "vui_num_ticks_poc_diff_one_minus1");    timingInfo->setNumTicksPocDiffOneMinus1   (uiCode);
     }
-#endif
   READ_FLAG(     uiCode, "hrd_parameters_present_flag");              pcVUI->setHrdParametersPresentFlag(uiCode);
   if( pcVUI->getHrdParametersPresentFlag() )
@@ -431,14 +391,5 @@
     parseHrdParameters( pcVUI->getHrdParameters(), 1, pcSPS->getMaxTLayers() - 1 );
   }
-#if L0043_TIMING_INFO
-  }
-#endif
-#if !L0043_TIMING_INFO
-  READ_FLAG( uiCode, "poc_proportional_to_timing_flag" ); pcVUI->setPocProportionalToTimingFlag(uiCode ? true : false);
-  if( pcVUI->getPocProportionalToTimingFlag() && pcVUI->getHrdParameters()->getTimingInfoPresentFlag() )
-  {
-    READ_UVLC( uiCode, "num_ticks_poc_diff_one_minus1" ); pcVUI->setNumTicksPocDiffOneMinus1(uiCode);
-  }
-#endif
+  }
   READ_FLAG(     uiCode, "bitstream_restriction_flag");               pcVUI->setBitstreamRestrictionFlag(uiCode);
   if (pcVUI->getBitstreamRestrictionFlag())
@@ -453,10 +404,6 @@
     READ_FLAG(   uiCode, "motion_vectors_over_pic_boundaries_flag");  pcVUI->setMotionVectorsOverPicBoundariesFlag(uiCode);
     READ_FLAG(   uiCode, "restricted_ref_pic_lists_flag");            pcVUI->setRestrictedRefPicListsFlag(uiCode);
-#if L0043_MSS_IDC
     READ_UVLC( uiCode, "min_spatial_segmentation_idc");            pcVUI->setMinSpatialSegmentationIdc(uiCode);
     assert(uiCode < 4096);
-#else
-    READ_CODE( 8, uiCode, "min_spatial_segmentation_idc");            pcVUI->setMinSpatialSegmentationIdc(uiCode);
-#endif
     READ_UVLC(   uiCode, "max_bytes_per_pic_denom" );                 pcVUI->setMaxBytesPerPicDenom(uiCode);
     READ_UVLC(   uiCode, "max_bits_per_mincu_denom" );                pcVUI->setMaxBitsPerMinCuDenom(uiCode);
@@ -471,12 +418,4 @@
   if( commonInfPresentFlag )
   {
-#if !L0043_TIMING_INFO
-    READ_FLAG( uiCode, "timing_info_present_flag" );                  hrd->setTimingInfoPresentFlag( uiCode == 1 ? true : false );
-    if( hrd->getTimingInfoPresentFlag() )
-    {
-      READ_CODE( 32, uiCode, "num_units_in_tick" );                   hrd->setNumUnitsInTick( uiCode );
-      READ_CODE( 32, uiCode, "time_scale" );                          hrd->setTimeScale( uiCode );
-    }
-#endif
     READ_FLAG( uiCode, "nal_hrd_parameters_present_flag" );           hrd->setNalHrdParametersPresentFlag( uiCode == 1 ? true : false );
     READ_FLAG( uiCode, "vcl_hrd_parameters_present_flag" );           hrd->setVclHrdParametersPresentFlag( uiCode == 1 ? true : false );
@@ -489,7 +428,5 @@
         READ_CODE( 5, uiCode, "du_cpb_removal_delay_length_minus1" ); hrd->setDuCpbRemovalDelayLengthMinus1( uiCode );
         READ_FLAG( uiCode, "sub_pic_cpb_params_in_pic_timing_sei_flag" ); hrd->setSubPicCpbParamsInPicTimingSEIFlag( uiCode == 1 ? true : false );
-#if L0044_DU_DPB_OUTPUT_DELAY_HRD
         READ_CODE( 5, uiCode, "dpb_output_delay_du_length_minus1"  ); hrd->setDpbOutputDelayDuLengthMinus1( uiCode );
-#endif
       }
       READ_CODE( 4, uiCode, "bit_rate_scale" );                       hrd->setBitRateScale( uiCode );
@@ -516,13 +453,10 @@
       hrd->setFixedPicRateWithinCvsFlag( i, true );
     }
-#if L0372
     hrd->setLowDelayHrdFlag( i, 0 ); // Infered to be 0 when not present
     hrd->setCpbCntMinus1   ( i, 0 ); // Infered to be 0 when not present
-#endif
     if( hrd->getFixedPicRateWithinCvsFlag( i ) )
     {
       READ_UVLC( uiCode, "elemental_duration_in_tc_minus1" );             hrd->setPicDurationInTcMinus1( i, uiCode );
     }
-#if L0372
     else
     {
@@ -533,8 +467,4 @@
       READ_UVLC( uiCode, "cpb_cnt_minus1" );                          hrd->setCpbCntMinus1( i, uiCode );
     }
-#else
-    READ_FLAG( uiCode, "low_delay_hrd_flag" );                      hrd->setLowDelayHrdFlag( i, uiCode == 1 ? true : false  );
-    READ_UVLC( uiCode, "cpb_cnt_minus1" );                          hrd->setCpbCntMinus1( i, uiCode );
-#endif
     for( nalOrVcl = 0; nalOrVcl < 2; nalOrVcl ++ )
     {
@@ -548,8 +478,6 @@
           if( hrd->getSubPicCpbParamsPresentFlag() )
           {
-#if L0363_DU_BIT_RATE
+            READ_UVLC( uiCode, "cpb_size_du_value_minus1" );       hrd->setDuCpbSizeValueMinus1( i, j, nalOrVcl, uiCode );
             READ_UVLC( uiCode, "bit_rate_du_value_minus1" );       hrd->setDuBitRateValueMinus1( i, j, nalOrVcl, uiCode );
-#endif
-            READ_UVLC( uiCode, "cpb_size_du_value_minus1" );       hrd->setDuCpbSizeValueMinus1( i, j, nalOrVcl, uiCode );
           }
           READ_FLAG( uiCode, "cbr_flag" );                          hrd->setCbrFlag( i, j, nalOrVcl, uiCode == 1 ? true : false  );
@@ -577,4 +505,6 @@
 #endif
     READ_CODE( 3,  uiCode, "sps_max_sub_layers_minus1" );          pcSPS->setMaxTLayers   ( uiCode+1 );
+    assert(uiCode <= 6);
+  
     READ_FLAG( uiCode, "sps_temporal_id_nesting_flag" );               pcSPS->setTemporalIdNestingFlag ( uiCode > 0 ? true : false );
 #if SPS_SUB_LAYER_INFO
@@ -598,5 +528,8 @@
   parsePTL(pcSPS->getPTL(), 1, pcSPS->getMaxTLayers() - 1);
   READ_UVLC(     uiCode, "sps_seq_parameter_set_id" );           pcSPS->setSPSId( uiCode );
+  assert(uiCode <= 15);
+  
   READ_UVLC(     uiCode, "chroma_format_idc" );                  pcSPS->setChromaFormatIdc( uiCode );
+  assert(uiCode <= 3);
   // in the first version we only support chroma_format_idc equal to 1 (4:2:0), so separate_colour_plane_flag cannot appear in the bitstream
   assert (uiCode == 1);
@@ -619,27 +552,26 @@
 
   READ_UVLC(     uiCode, "bit_depth_luma_minus8" );
+  assert(uiCode <= 6);
   pcSPS->setBitDepthY( uiCode + 8 );
   pcSPS->setQpBDOffsetY( (Int) (6*uiCode) );
 
   READ_UVLC( uiCode,    "bit_depth_chroma_minus8" );
+  assert(uiCode <= 6);
   pcSPS->setBitDepthC( uiCode + 8 );
   pcSPS->setQpBDOffsetC( (Int) (6*uiCode) );
 
   READ_UVLC( uiCode,    "log2_max_pic_order_cnt_lsb_minus4" );   pcSPS->setBitsForPOC( 4 + uiCode );
+  assert(uiCode <= 12);
 
   UInt subLayerOrderingInfoPresentFlag;
   READ_FLAG(subLayerOrderingInfoPresentFlag, "sps_sub_layer_ordering_info_present_flag");
+  
   for(UInt i=0; i <= pcSPS->getMaxTLayers()-1; i++)
   {
-#if L0323_DPB
     READ_UVLC ( uiCode, "sps_max_dec_pic_buffering_minus1");
     pcSPS->setMaxDecPicBuffering( uiCode + 1, i);
-#else
-    READ_UVLC ( uiCode, "sps_max_dec_pic_buffering");
-    pcSPS->setMaxDecPicBuffering( uiCode, i);
-#endif
     READ_UVLC ( uiCode, "sps_num_reorder_pics" );
     pcSPS->setNumReorderPics(uiCode, i);
-    READ_UVLC ( uiCode, "sps_max_latency_increase");
+    READ_UVLC ( uiCode, "sps_max_latency_increase_plus1");
     pcSPS->setMaxLatencyIncrease( uiCode, i );
 
@@ -698,4 +630,5 @@
 
   READ_UVLC( uiCode, "num_short_term_ref_pic_sets" );
+  assert(uiCode <= 64);
   pcSPS->createRPSList(uiCode);
 
@@ -823,18 +756,11 @@
   READ_CODE( 16, uiCode,  "vps_reserved_ffff_16bits" );           assert(uiCode == 0xffff);
   parsePTL ( pcVPS->getPTL(), true, pcVPS->getMaxTLayers()-1);
-#if SIGNAL_BITRATE_PICRATE_IN_VPS
-  parseBitratePicRateInfo( pcVPS->getBitratePicrateInfo(), 0, pcVPS->getMaxTLayers() - 1);
-#endif
   UInt subLayerOrderingInfoPresentFlag;
   READ_FLAG(subLayerOrderingInfoPresentFlag, "vps_sub_layer_ordering_info_present_flag");
   for(UInt i = 0; i <= pcVPS->getMaxTLayers()-1; i++)
   {
-#if L0323_DPB
     READ_UVLC( uiCode,  "vps_max_dec_pic_buffering_minus1[i]" );     pcVPS->setMaxDecPicBuffering( uiCode + 1, i );
-#else
-    READ_UVLC( uiCode,  "vps_max_dec_pic_buffering[i]" );     pcVPS->setMaxDecPicBuffering( uiCode, i );
-#endif
     READ_UVLC( uiCode,  "vps_num_reorder_pics[i]" );          pcVPS->setNumReorderPics( uiCode, i );
-    READ_UVLC( uiCode,  "vps_max_latency_increase[i]" );      pcVPS->setMaxLatencyIncrease( uiCode, i );
+    READ_UVLC( uiCode,  "vps_max_latency_increase_plus1[i]" );      pcVPS->setMaxLatencyIncrease( uiCode, i );
 
     if (!subLayerOrderingInfoPresentFlag)
@@ -876,5 +802,4 @@
   pcVPS->deriveLayerIdListVariables();
 #endif
-#if L0043_TIMING_INFO
   TimingInfo *timingInfo = pcVPS->getTimingInfo();
   READ_FLAG(       uiCode, "vps_timing_info_present_flag");         timingInfo->setTimingInfoPresentFlag      (uiCode ? true : false);
@@ -888,5 +813,4 @@
       READ_UVLC(   uiCode, "vps_num_ticks_poc_diff_one_minus1");    timingInfo->setNumTicksPocDiffOneMinus1   (uiCode);
     }
-#endif
     READ_UVLC( uiCode, "vps_num_hrd_parameters" );                  pcVPS->setNumHrdParameters( uiCode );
 
@@ -904,7 +828,5 @@
       parseHrdParameters(pcVPS->getHrdParameters(i), pcVPS->getCprmsPresentFlag( i ), pcVPS->getMaxTLayers() - 1);
     }
-#if L0043_TIMING_INFO
-  }
-#endif
+  }
   READ_FLAG( uiCode,  "vps_extension_flag" );
   if (uiCode)
@@ -1353,5 +1275,5 @@
           uiCode = 0;
         }
-        memcpy(rps,sps->getRPSList()->getReferencePictureSet(uiCode),sizeof(TComReferencePictureSet));
+        *rps = *(sps->getRPSList()->getReferencePictureSet(uiCode));
       }
       if(sps->getLongTermRefsPresent())
@@ -1446,6 +1368,4 @@
         rpcSlice->setRPS(rps);
       }
-
-
       if (rpcSlice->getSPS()->getTMVPFlagsPresent())
       {
@@ -1794,11 +1714,6 @@
     for (UInt idx=0; idx<numEntryPointOffsets; idx++)
     {
-#if L0116_ENTRY_POINT
       READ_CODE(offsetLenMinus1+1, uiCode, "entry_point_offset_minus1");
       entryPointOffset[ idx ] = uiCode + 1;
-#else
-      READ_CODE(offsetLenMinus1+1, uiCode, "entry_point_offset");
-      entryPointOffset[ idx ] = uiCode;
-#endif
     }
   }
@@ -1822,4 +1737,14 @@
   {
     Int endOfSliceHeaderLocation = m_pcBitstream->getByteLocation();
+    
+    // Adjust endOfSliceHeaderLocation to account for emulation prevention bytes in the slice segment header
+    for ( UInt curByteIdx  = 0; curByteIdx<m_pcBitstream->numEmulationPreventionBytesRead(); curByteIdx++ )
+    {
+      if ( m_pcBitstream->getEmulationPreventionByteLocation( curByteIdx ) < endOfSliceHeaderLocation )
+      {
+        endOfSliceHeaderLocation++;
+      }
+    }
+
     Int  curEntryPointOffset     = 0;
     Int  prevEntryPointOffset    = 0;
@@ -1889,5 +1814,4 @@
   READ_CODE( 8, uiCode, "general_level_idc" );    rpcPTL->getGeneralPTL()->setLevelIdc(uiCode);
 
-#if L0363_BYTE_ALIGN
   for (Int i = 0; i < maxNumSubLayersMinus1; i++)
   {
@@ -1907,15 +1831,7 @@
     }
   }
-#endif
 
   for(Int i = 0; i < maxNumSubLayersMinus1; i++)
   {
-#if !L0363_BYTE_ALIGN
-    if(profilePresentFlag)
-    {
-      READ_FLAG( uiCode, "sub_layer_profile_present_flag[i]" ); rpcPTL->setSubLayerProfilePresentFlag(i, uiCode);
-    }
-    READ_FLAG( uiCode, "sub_layer_level_present_flag[i]"   ); rpcPTL->setSubLayerLevelPresentFlag  (i, uiCode);
-#endif
     if( profilePresentFlag && rpcPTL->getSubLayerProfilePresentFlag(i) )
     {
@@ -1939,5 +1855,4 @@
     READ_FLAG(  uiCode, "XXX_profile_compatibility_flag[][j]");   ptl->setProfileCompatibilityFlag(j, uiCode ? 1 : 0);
   }
-#if L0046_CONSTRAINT_FLAGS
   READ_FLAG(uiCode, "general_progressive_source_flag");
   ptl->setProgressiveSourceFlag(uiCode ? true : false);
@@ -1955,33 +1870,6 @@
   READ_CODE(16, uiCode, "XXX_reserved_zero_44bits[16..31]");
   READ_CODE(12, uiCode, "XXX_reserved_zero_44bits[32..43]");
-#elif L0363_MORE_BITS
-  READ_CODE(16, uiCode, "XXX_reserved_zero_48bits[0..15]");
-  READ_CODE(16, uiCode, "XXX_reserved_zero_48bits[16..31]");
-  READ_CODE(16, uiCode, "XXX_reserved_zero_48bits[32..47]");
-#else
-  READ_CODE(16, uiCode, "XXX_reserved_zero_16bits[]");  assert( uiCode == 0 );
-#endif
-}
-#if SIGNAL_BITRATE_PICRATE_IN_VPS
-Void TDecCavlc::parseBitratePicRateInfo(TComBitRatePicRateInfo *info, Int tempLevelLow, Int tempLevelHigh)
-{
-  UInt uiCode;
-  for(Int i = tempLevelLow; i <= tempLevelHigh; i++)
-  {
-    READ_FLAG( uiCode, "bit_rate_info_present_flag[i]" ); info->setBitRateInfoPresentFlag(i, uiCode ? true : false);
-    READ_FLAG( uiCode, "pic_rate_info_present_flag[i]" ); info->setPicRateInfoPresentFlag(i, uiCode ? true : false);
-    if(info->getBitRateInfoPresentFlag(i))
-    {
-      READ_CODE( 16, uiCode, "avg_bit_rate[i]" ); info->setAvgBitRate(i, uiCode);
-      READ_CODE( 16, uiCode, "max_bit_rate[i]" ); info->setMaxBitRate(i, uiCode);
-    }
-    if(info->getPicRateInfoPresentFlag(i))
-    {
-      READ_CODE(  2, uiCode,  "constant_pic_rate_idc[i]" ); info->setConstantPicRateIdc(i, uiCode);
-      READ_CODE( 16, uiCode,  "avg_pic_rate[i]"          ); info->setAvgPicRate(i, uiCode);
-    }
-  }
-}
-#endif
+}
+
 Void TDecCavlc::parseTerminatingBit( UInt& ruiBit )
 {
Index: branches/SHM-2.1-dev/source/Lib/TLibDecoder/TDecCAVLC.h
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibDecoder/TDecCAVLC.h	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibDecoder/TDecCAVLC.h	(revision 302)
@@ -88,7 +88,4 @@
   Void  parsePTL            ( TComPTL *rpcPTL, Bool profilePresentFlag, Int maxNumSubLayersMinus1 );
   Void  parseProfileTier    (ProfileTierLevel *ptl);
-#if SIGNAL_BITRATE_PICRATE_IN_VPS
-  Void  parseBitratePicRateInfo(TComBitRatePicRateInfo *info, Int tempLevelLow, Int tempLevelHigh);
-#endif
   Void  parseHrdParameters  (TComHRD *hrd, Bool cprms_present_flag, UInt tempLevelHigh);
   Void  parseSliceHeader    ( TComSlice*& rpcSlice, ParameterSetManagerDecoder *parameterSetManager);
Index: branches/SHM-2.1-dev/source/Lib/TLibDecoder/TDecEntropy.cpp
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibDecoder/TDecEntropy.cpp	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibDecoder/TDecEntropy.cpp	(revision 302)
@@ -188,14 +188,4 @@
       decodeMergeIndex( pcCU, uiPartIdx, uiSubPartIdx, uiDepth );
       UInt uiMergeIndex = pcCU->getMergeIndex(uiSubPartIdx);
-#if 0 //REF_IDX_FRAMEWORK  // HM bug fix
-      if(uiPartIdx)
-      {
-        for(UInt ui=0; ui<uiMergeIndex+1; ui++)
-        {
-          cMvFieldNeighbours[(ui<<1)].setMvField(TComMv(), NOT_VALID);
-          cMvFieldNeighbours[(ui<<1)+1].setMvField(TComMv(), NOT_VALID);
-        }
-      }
-#endif
       if ( pcCU->getSlice()->getPPS()->getLog2ParallelMergeLevelMinus2() && ePartSize != SIZE_2Nx2N && pcSubCU->getWidth( 0 ) <= 8 ) 
       {
Index: branches/SHM-2.1-dev/source/Lib/TLibDecoder/TDecSbac.cpp
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibDecoder/TDecSbac.cpp	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibDecoder/TDecSbac.cpp	(revision 302)
@@ -158,4 +158,5 @@
   UInt uiBit;
   m_pcTDecBinIf->decodeBinTrm(uiBit);
+  assert(uiBit); // end_of_sub_stream_one_bit must be equal to 1
   m_pcTDecBinIf->finish();  
   m_pcBitstream->readOutTrailingBits();
@@ -196,4 +197,8 @@
 {
   m_pcTDecBinIf->decodeBinTrm( ruiBit );
+  if ( ruiBit )
+  {
+    m_pcTDecBinIf->finish();
+  }
 }
 
@@ -318,5 +323,4 @@
 {
   UInt uiSymbol;
-  Bool readPCMSampleFlag = false;
 
     m_pcTDecBinIf->decodeBinTrm(uiSymbol);
@@ -324,10 +328,4 @@
     if (uiSymbol)
     {
-      readPCMSampleFlag = true;
-      m_pcTDecBinIf->decodePCMAlignBits();
-    }
-
-  if (readPCMSampleFlag == true)
-  {
     Bool bIpcmFlag = true;
 
@@ -395,5 +393,5 @@
     }
 
-      m_pcTDecBinIf->resetBac();
+    m_pcTDecBinIf->start();
   }
 }
@@ -681,5 +679,4 @@
     else
     {
-      intraPredMode = 0;
       m_pcTDecBinIf->decodeBinsEP( symbol, 5 );
       intraPredMode = symbol;
@@ -917,5 +914,4 @@
   else 
   {
-    iDQp=0;
     qp = pcCU->getRefQP(uiAbsPartIdx);
   }
@@ -1102,5 +1098,5 @@
 
   //===== decode significance flags =====
-  UInt uiScanPosLast = uiBlkPosLast;
+  UInt uiScanPosLast;
   const UInt *scan   = g_auiSigLastScan[ uiScanIdx ][ uiLog2BlockSize-1 ];
   for( uiScanPosLast = 0; uiScanPosLast < uiMaxNumCoeffM1; uiScanPosLast++ )
Index: branches/SHM-2.1-dev/source/Lib/TLibDecoder/TDecSlice.cpp
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibDecoder/TDecSlice.cpp	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibDecoder/TDecSlice.cpp	(revision 302)
@@ -384,4 +384,14 @@
     pcSbacDecoders[uiSubStrm].load(pcSbacDecoder);
 
+    if ( uiCol == rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(iCUAddr))->getRightEdgePosInCU()
+        && pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag()
+        && !uiIsLast )
+    {
+      // Parse end_of_substream_one_bit for WPP case
+      UInt binVal;
+      pcSbacDecoder->parseTerminatingBit( binVal );
+      assert( binVal );
+    }
+
     //Store probabilities of second LCU in line into buffer
     if ( (uiCol == uiTileLCUX+1)&& (depSliceSegmentsEnabled || (pcSlice->getPPS()->getNumSubstreams() > 1)) && (pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag()) )
Index: branches/SHM-2.1-dev/source/Lib/TLibDecoder/TDecTop.cpp
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibDecoder/TDecTop.cpp	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibDecoder/TDecTop.cpp	(revision 302)
@@ -241,9 +241,5 @@
   }
 
-#if L0323_DPB
-  m_iMaxRefPicNum = pcSlice->getSPS()->getMaxDecPicBuffering(pcSlice->getTLayer())+pcSlice->getSPS()->getNumReorderPics(pcSlice->getTLayer());     // m_uiMaxDecPicBuffering has the space for the picture currently being decoded
-#else
-  m_iMaxRefPicNum = pcSlice->getSPS()->getMaxDecPicBuffering(pcSlice->getTLayer())+pcSlice->getSPS()->getNumReorderPics(pcSlice->getTLayer()) + 1; // +1 to have space for the picture currently being decoded
-#endif
+  m_iMaxRefPicNum = pcSlice->getSPS()->getMaxDecPicBuffering(pcSlice->getTLayer());     // m_uiMaxDecPicBuffering has the space for the picture currently being decoded
   if (m_cListPic.size() < (UInt)m_iMaxRefPicNum)
   {
@@ -476,5 +472,4 @@
   m_apcSlicePilot->setPPS(pps);
   m_apcSlicePilot->setSPS(sps);
-
   pps->setSPS(sps);
   pps->setNumSubstreams(pps->getEntropyCodingSyncEnabledFlag() ? ((sps->getPicHeightInLumaSamples() + sps->getMaxCUHeight() - 1) / sps->getMaxCUHeight()) * (pps->getNumColumnsMinus1() + 1) : 1);
@@ -991,22 +986,4 @@
     //---------------
     pcSlice->setRefPOCList();
-#if !L0034_COMBINED_LIST_CLEANUP
-    pcSlice->setNoBackPredFlag( false );
-    if ( pcSlice->getSliceType() == B_SLICE )
-    {
-      if ( pcSlice->getNumRefIdx(RefPicList( 0 ) ) == pcSlice->getNumRefIdx(RefPicList( 1 ) ) )
-      {
-        pcSlice->setNoBackPredFlag( true );
-        for ( i=0; i < pcSlice->getNumRefIdx(RefPicList( 1 ) ); i++ )
-        {
-          if ( pcSlice->getRefPOC(RefPicList(1), i) != pcSlice->getRefPOC(RefPicList(0), i) ) 
-          {
-            pcSlice->setNoBackPredFlag( false );
-            break;
-          }
-        }
-      }
-    }
-#endif
   }
 
Index: branches/SHM-2.1-dev/source/Lib/TLibEncoder/SEIwrite.cpp
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibEncoder/SEIwrite.cpp	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibEncoder/SEIwrite.cpp	(revision 302)
@@ -84,9 +84,7 @@
     fprintf( g_hTrace, "=========== Decoding Unit Information SEI message ===========\n");
     break;
-#if J0149_TONE_MAPPING_SEI
   case SEI::TONE_MAPPING_INFO:
     fprintf( g_hTrace, "=========== Tone Mapping Info SEI message ===========\n");
     break;
-#endif
 #if M0043_LAYERS_PRESENT_SEI
   case SEI::LAYERS_PRESENT:
@@ -94,14 +92,10 @@
     break;
 #endif
-#if L0208_SOP_DESCRIPTION_SEI
   case SEI::SOP_DESCRIPTION:
     fprintf( g_hTrace, "=========== SOP Description SEI message ===========\n");
     break;
-#endif
-#if K0180_SCALABLE_NESTING_SEI
   case SEI::SCALABLE_NESTING:
     fprintf( g_hTrace, "=========== Scalable Nesting SEI message ===========\n");
     break;
-#endif
   default:
     fprintf( g_hTrace, "=========== Unknown SEI message ===========\n");
@@ -111,9 +105,5 @@
 #endif
 
-#if K0180_SCALABLE_NESTING_SEI
 void SEIWriter::xWriteSEIpayloadData(TComBitIf& bs, const SEI& sei, TComSPS *sps)
-#else
-void SEIWriter::xWriteSEIpayloadData(const SEI& sei, TComSPS *sps)
-#endif
 {
   switch (sei.payloadType())
@@ -152,9 +142,7 @@
     xWriteSEIGradualDecodingRefreshInfo(*static_cast<const SEIGradualDecodingRefreshInfo*>(&sei));
     break;
-#if J0149_TONE_MAPPING_SEI
   case SEI::TONE_MAPPING_INFO:
     xWriteSEIToneMappingInfo(*static_cast<const SEIToneMappingInfo*>(&sei));
     break;
-#endif
 #if M0043_LAYERS_PRESENT_SEI
   case SEI::LAYERS_PRESENT:
@@ -162,14 +150,10 @@
     break;
 #endif
-#if L0208_SOP_DESCRIPTION_SEI
   case SEI::SOP_DESCRIPTION:
     xWriteSEISOPDescription(*static_cast<const SEISOPDescription*>(&sei));
     break;
-#endif
-#if K0180_SCALABLE_NESTING_SEI
   case SEI::SCALABLE_NESTING:
     xWriteSEIScalableNesting(bs, *static_cast<const SEIScalableNesting*>(&sei), sps);
     break;
-#endif
   default:
     assert(!"Unhandled SEI message");
@@ -190,6 +174,4 @@
 
 
-#if K0180_SCALABLE_NESTING_SEI
-
 #if ENC_DEC_TRACE
   Bool traceEnable = g_HLSTraceEnable;
@@ -201,16 +183,4 @@
 #endif
 
-#else
-
-#if ENC_DEC_TRACE
-  g_HLSTraceEnable = false;
-#endif
-  xWriteSEIpayloadData(sei, sps);
-#if ENC_DEC_TRACE
-  g_HLSTraceEnable = true;
-#endif
-
-#endif
-
   UInt payload_data_num_bits = bs_count.getNumberOfWrittenBits();
   assert(0 == payload_data_num_bits % 8);
@@ -219,7 +189,5 @@
 
 #if ENC_DEC_TRACE
-#if K0180_SCALABLE_NESTING_SEI
   if (g_HLSTraceEnable)
-#endif
   xTraceSEIHeader();
 #endif
@@ -241,15 +209,9 @@
   /* payloadData */
 #if ENC_DEC_TRACE
-#if K0180_SCALABLE_NESTING_SEI
   if (g_HLSTraceEnable)
-#endif
   xTraceSEIMessageType(sei.payloadType());
 #endif
 
-#if K0180_SCALABLE_NESTING_SEI
   xWriteSEIpayloadData(bs, sei, sps);
-#else
-  xWriteSEIpayloadData(sei, sps);
-#endif
 }
 
@@ -306,8 +268,6 @@
 {
   WRITE_CODE(sei.activeVPSId,     4, "active_vps_id");
-#if L0047_APS_FLAGS
   WRITE_FLAG(sei.m_fullRandomAccessFlag, "full_random_access_flag");
   WRITE_FLAG(sei.m_noParamSetUpdateFlag, "no_param_set_update_flag");
-#endif
   WRITE_UVLC(sei.numSpsIdsMinus1,    "num_sps_ids_minus1");
 
@@ -340,5 +300,4 @@
     WRITE_CODE( sei.m_duSptCpbRemovalDelay, (vui->getHrdParameters()->getDuCpbRemovalDelayLengthMinus1() + 1), "du_spt_cpb_removal_delay");
   }
-#if L0044_DU_DPB_OUTPUT_DELAY_HRD
   WRITE_FLAG( sei.m_dpbOutputDuDelayPresentFlag, "dpb_output_du_delay_present_flag");
   if(sei.m_dpbOutputDuDelayPresentFlag)
@@ -346,5 +305,4 @@
     WRITE_CODE(sei.m_picSptDpbOutputDuDelay, vui->getHrdParameters()->getDpbOutputDelayDuLengthMinus1() + 1, "pic_spt_dpb_output_du_delay");
   }
-#endif
   xWriteByteAlign();
 }
@@ -361,9 +319,6 @@
     WRITE_FLAG( sei.m_rapCpbParamsPresentFlag, "rap_cpb_params_present_flag" );
   }
-#if L0328_SPLICING
   WRITE_FLAG( sei.m_concatenationFlag, "concatenation_flag");
   WRITE_CODE( sei.m_auCpbRemovalDelayDelta - 1, ( hrd->getCpbRemovalDelayLengthMinus1() + 1 ), "au_cpb_removal_delay_delta_minus1" );
-#endif
-#if L0044_CPB_DPB_DELAY_OFFSET
   if( sei.m_rapCpbParamsPresentFlag )
   {
@@ -371,5 +326,4 @@
     WRITE_CODE( sei.m_dpbDelayOffset, hrd->getDpbOutputDelayLengthMinus1()  + 1, "dpb_delay_offset" );
   }
-#endif
   for( nalOrVcl = 0; nalOrVcl < 2; nalOrVcl ++ )
   {
@@ -397,32 +351,19 @@
   TComHRD *hrd = vui->getHrdParameters();
 
-#if !L0045_CONDITION_SIGNALLING
-  // This condition was probably OK before the pic_struct, progressive_source_idc, duplicate_flag were added
-  if( !hrd->getNalHrdParametersPresentFlag() && !hrd->getVclHrdParametersPresentFlag() )
-    return;
-#endif
   if( vui->getFrameFieldInfoPresentFlag() )
   {
     WRITE_CODE( sei.m_picStruct, 4,              "pic_struct" );
-#if L0046_RENAME_PROG_SRC_IDC
     WRITE_CODE( sei.m_sourceScanType, 2,         "source_scan_type" );
-#else
-    WRITE_CODE( sei.m_progressiveSourceIdc, 2,   "progressive_source_idc" );
-#endif
     WRITE_FLAG( sei.m_duplicateFlag ? 1 : 0,     "duplicate_flag" );
   }
 
-#if L0045_CONDITION_SIGNALLING
   if( hrd->getCpbDpbDelaysPresentFlag() )
   {
-#endif
     WRITE_CODE( sei.m_auCpbRemovalDelay - 1, ( hrd->getCpbRemovalDelayLengthMinus1() + 1 ),                                         "au_cpb_removal_delay_minus1" );
     WRITE_CODE( sei.m_picDpbOutputDelay, ( hrd->getDpbOutputDelayLengthMinus1() + 1 ),                                          "pic_dpb_output_delay" );
-#if L0044_DU_DPB_OUTPUT_DELAY_HRD
     if(hrd->getSubPicCpbParamsPresentFlag())
     {
       WRITE_CODE(sei.m_picDpbOutputDuDelay, hrd->getDpbOutputDelayDuLengthMinus1()+1, "pic_dpb_output_du_delay" );
     }
-#endif
     if( hrd->getSubPicCpbParamsPresentFlag() && hrd->getSubPicCpbParamsInPicTimingSEIFlag() )
     {
@@ -442,7 +383,5 @@
       }
     }
-#if L0045_CONDITION_SIGNALLING
-  }
-#endif
+  }
   xWriteByteAlign();
 }
@@ -481,9 +420,5 @@
 
     WRITE_CODE( sei.m_arrangementReservedByte, 8,   "frame_packing_arrangement_reserved_byte" );
-#if L0045_PERSISTENCE_FLAGS
     WRITE_FLAG( sei.m_arrangementPersistenceFlag,   "frame_packing_arrangement_persistence_flag" );
-#else
-    WRITE_UVLC( sei.m_arrangementRepetetionPeriod,  "frame_packing_arrangement_repetition_period" );
-#endif
   }
 
@@ -493,5 +428,4 @@
 }
 
-#if J0149_TONE_MAPPING_SEI
 Void SEIWriter::xWriteSEIToneMappingInfo(const SEIToneMappingInfo& sei)
 {
@@ -565,5 +499,4 @@
   xWriteByteAlign();
 }
-#endif
 
 Void SEIWriter::xWriteSEIDisplayOrientation(const SEIDisplayOrientation &sei)
@@ -575,13 +508,5 @@
     WRITE_FLAG( sei.verFlip,                   "ver_flip" );
     WRITE_CODE( sei.anticlockwiseRotation, 16, "anticlockwise_rotation" );
-#if L0045_PERSISTENCE_FLAGS
     WRITE_FLAG( sei.persistenceFlag,          "display_orientation_persistence_flag" );
-#else
-    WRITE_UVLC( sei.repetitionPeriod,          "display_orientation_repetition_period" );
-#endif
-#if !REMOVE_SINGLE_SEI_EXTENSION_FLAGS
-    WRITE_FLAG( sei.extensionFlag,             "display_orientation_extension_flag" );
-    assert( !sei.extensionFlag );
-#endif
   }
   xWriteByteAlign();
@@ -613,5 +538,4 @@
 #endif
 
-#if L0208_SOP_DESCRIPTION_SEI
 Void SEIWriter::xWriteSEISOPDescription(const SEISOPDescription& sei)
 {
@@ -634,7 +558,5 @@
   xWriteByteAlign();
 }
-#endif
-
-#if K0180_SCALABLE_NESTING_SEI
+
 Void SEIWriter::xWriteSEIScalableNesting(TComBitIf& bs, const SEIScalableNesting& sei, TComSPS *sps)
 {
@@ -678,5 +600,4 @@
   }
 }
-#endif
 
 Void SEIWriter::xWriteByteAlign()
Index: branches/SHM-2.1-dev/source/Lib/TLibEncoder/SEIwrite.h
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibEncoder/SEIwrite.h	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibEncoder/SEIwrite.h	(revision 302)
@@ -50,9 +50,5 @@
 
 protected:
-#if K0180_SCALABLE_NESTING_SEI
   Void xWriteSEIpayloadData(TComBitIf& bs, const SEI& sei, TComSPS *sps);
-#else
-  Void xWriteSEIpayloadData(const SEI& sei, TComSPS *sps);
-#endif
   Void xWriteSEIuserDataUnregistered(const SEIuserDataUnregistered &sei);
   Void xWriteSEIActiveParameterSets(const SEIActiveParameterSets& sei);
@@ -67,16 +63,10 @@
   Void xWriteSEITemporalLevel0Index(const SEITemporalLevel0Index &sei);
   Void xWriteSEIGradualDecodingRefreshInfo(const SEIGradualDecodingRefreshInfo &sei);
-#if J0149_TONE_MAPPING_SEI
   Void xWriteSEIToneMappingInfo(const SEIToneMappingInfo& sei);
-#endif
 #if M0043_LAYERS_PRESENT_SEI
   Void xWriteSEILayersPresent(const SEILayersPresent& sei);
 #endif
-#if L0208_SOP_DESCRIPTION_SEI
   Void xWriteSEISOPDescription(const SEISOPDescription& sei);
-#endif
-#if K0180_SCALABLE_NESTING_SEI
   Void xWriteSEIScalableNesting(TComBitIf& bs, const SEIScalableNesting& sei, TComSPS *sps);
-#endif
   Void xWriteByteAlign();
 };
Index: branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncCavlc.cpp
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 302)
@@ -39,5 +39,5 @@
 #include "TEncCavlc.h"
 #include "SEIwrite.h"
-#include <iostream>
+
 //! \ingroup TLibEncoder
 //! \{
@@ -163,8 +163,6 @@
   WRITE_UVLC( pcPPS->getSPSId(),                             "pps_seq_parameter_set_id" );
   WRITE_FLAG( pcPPS->getDependentSliceSegmentsEnabledFlag()    ? 1 : 0, "dependent_slice_segments_enabled_flag" );
-#if L0255_MOVE_PPS_FLAGS
   WRITE_FLAG( pcPPS->getOutputFlagPresentFlag() ? 1 : 0,     "output_flag_present_flag" );
   WRITE_CODE( pcPPS->getNumExtraSliceHeaderBits(), 3,        "num_extra_slice_header_bits");
-#endif
   WRITE_FLAG( pcPPS->getSignHideFlag(), "sign_data_hiding_flag" );
   WRITE_FLAG( pcPPS->getCabacInitPresentFlag() ? 1 : 0,   "cabac_init_present_flag" );
@@ -186,7 +184,4 @@
   WRITE_FLAG( pcPPS->getUseWP() ? 1 : 0,  "weighted_pred_flag" );   // Use of Weighting Prediction (P_SLICE)
   WRITE_FLAG( pcPPS->getWPBiPred() ? 1 : 0, "weighted_bipred_flag" );  // Use of Weighting Bi-Prediction (B_SLICE)
-#if !L0255_MOVE_PPS_FLAGS
-  WRITE_FLAG( pcPPS->getOutputFlagPresentFlag() ? 1 : 0,  "output_flag_present_flag" );
-#endif
   WRITE_FLAG( pcPPS->getTransquantBypassEnableFlag() ? 1 : 0, "transquant_bypass_enable_flag" );
   WRITE_FLAG( pcPPS->getTilesEnabledFlag()             ? 1 : 0, "tiles_enabled_flag" );
@@ -235,7 +230,4 @@
   WRITE_FLAG( pcPPS->getListsModificationPresentFlag(), "lists_modification_present_flag");
   WRITE_UVLC( pcPPS->getLog2ParallelMergeLevelMinus2(), "log2_parallel_merge_level_minus2");
-#if !L0255_MOVE_PPS_FLAGS
-  WRITE_CODE( pcPPS->getNumExtraSliceHeaderBits(), 3, "num_extra_slice_header_bits");
-#endif
   WRITE_FLAG( pcPPS->getSliceHeaderExtensionPresentFlag() ? 1 : 0, "slice_segment_header_extension_present_flag");
   WRITE_FLAG( 0, "pps_extension_flag" );
@@ -296,5 +288,4 @@
     WRITE_UVLC(defaultDisplayWindow.getWindowBottomOffset(),    "def_disp_win_bottom_offset");
   }
-#if L0043_TIMING_INFO
   TimingInfo *timingInfo = pcVUI->getTimingInfo();
   WRITE_FLAG(timingInfo->getTimingInfoPresentFlag(),          "vui_timing_info_present_flag");
@@ -308,5 +299,4 @@
       WRITE_UVLC(timingInfo->getNumTicksPocDiffOneMinus1(),   "vui_num_ticks_poc_diff_one_minus1");
     }
-#endif
   WRITE_FLAG(pcVUI->getHrdParametersPresentFlag(),              "hrd_parameters_present_flag");
   if( pcVUI->getHrdParametersPresentFlag() )
@@ -314,14 +304,5 @@
     codeHrdParameters(pcVUI->getHrdParameters(), 1, pcSPS->getMaxTLayers() - 1 );
   }
-#if L0043_TIMING_INFO
-  }
-#endif
-#if !L0043_TIMING_INFO
-  WRITE_FLAG( pcVUI->getPocProportionalToTimingFlag(), "poc_proportional_to_timing_flag" );
-  if( pcVUI->getPocProportionalToTimingFlag() && pcVUI->getHrdParameters()->getTimingInfoPresentFlag() )
-  {
-    WRITE_UVLC( pcVUI->getNumTicksPocDiffOneMinus1(), "num_ticks_poc_diff_one_minus1" );
-  }
-#endif
+  }
 
   WRITE_FLAG(pcVUI->getBitstreamRestrictionFlag(),              "bitstream_restriction_flag");
@@ -337,9 +318,5 @@
     WRITE_FLAG(pcVUI->getMotionVectorsOverPicBoundariesFlag(),  "motion_vectors_over_pic_boundaries_flag");
     WRITE_FLAG(pcVUI->getRestrictedRefPicListsFlag(),           "restricted_ref_pic_lists_flag");
-#if L0043_MSS_IDC
     WRITE_UVLC(pcVUI->getMinSpatialSegmentationIdc(),           "min_spatial_segmentation_idc");
-#else
-    WRITE_CODE(pcVUI->getMinSpatialSegmentationIdc(),        8, "min_spatial_segmentation_idc");
-#endif
     WRITE_UVLC(pcVUI->getMaxBytesPerPicDenom(),                 "max_bytes_per_pic_denom");
     WRITE_UVLC(pcVUI->getMaxBitsPerMinCuDenom(),                "max_bits_per_mincu_denom");
@@ -353,12 +330,4 @@
   if( commonInfPresentFlag )
   {
-#if !L0043_TIMING_INFO
-    WRITE_FLAG( hrd->getTimingInfoPresentFlag() ? 1 : 0,        "timing_info_present_flag" );
-    if( hrd->getTimingInfoPresentFlag() )
-    {
-      WRITE_CODE( hrd->getNumUnitsInTick(), 32,                  "num_units_in_tick" );
-      WRITE_CODE( hrd->getTimeScale(),      32,                  "time_scale" );
-    }
-#endif
     WRITE_FLAG( hrd->getNalHrdParametersPresentFlag() ? 1 : 0 ,  "nal_hrd_parameters_present_flag" );
     WRITE_FLAG( hrd->getVclHrdParametersPresentFlag() ? 1 : 0 ,  "vcl_hrd_parameters_present_flag" );
@@ -371,7 +340,5 @@
         WRITE_CODE( hrd->getDuCpbRemovalDelayLengthMinus1(), 5,  "du_cpb_removal_delay_length_minus1" );
         WRITE_FLAG( hrd->getSubPicCpbParamsInPicTimingSEIFlag() ? 1 : 0, "sub_pic_cpb_params_in_pic_timing_sei_flag" );
-#if L0044_DU_DPB_OUTPUT_DELAY_HRD
         WRITE_CODE( hrd->getDpbOutputDelayDuLengthMinus1(), 5,   "dpb_output_delay_du_length_minus1"  );
-#endif
       }
       WRITE_CODE( hrd->getBitRateScale(), 4,                     "bit_rate_scale" );
@@ -402,5 +369,4 @@
       WRITE_UVLC( hrd->getPicDurationInTcMinus1( i ),           "elemental_duration_in_tc_minus1");
     }
-#if L0372
     else
     {
@@ -411,8 +377,4 @@
       WRITE_UVLC( hrd->getCpbCntMinus1( i ),                      "cpb_cnt_minus1");
     }
-#else
-    WRITE_FLAG( hrd->getLowDelayHrdFlag( i ) ? 1 : 0,           "low_delay_hrd_flag");
-    WRITE_UVLC( hrd->getCpbCntMinus1( i ),                      "cpb_cnt_minus1");
-#endif
     
     for( nalOrVcl = 0; nalOrVcl < 2; nalOrVcl ++ )
@@ -427,8 +389,6 @@
           if( hrd->getSubPicCpbParamsPresentFlag() )
           {
-#if L0363_DU_BIT_RATE
+            WRITE_UVLC( hrd->getDuCpbSizeValueMinus1( i, j, nalOrVcl ), "cpb_size_du_value_minus1");  
             WRITE_UVLC( hrd->getDuBitRateValueMinus1( i, j, nalOrVcl ), "bit_rate_du_value_minus1");
-#endif
-            WRITE_UVLC( hrd->getDuCpbSizeValueMinus1( i, j, nalOrVcl ), "cpb_size_du_value_minus1");  
           }
           WRITE_FLAG( hrd->getCbrFlag( i, j, nalOrVcl ) ? 1 : 0, "cbr_flag");
@@ -486,11 +446,7 @@
   for(UInt i=0; i <= pcSPS->getMaxTLayers()-1; i++)
   {
-#if L0323_DPB
     WRITE_UVLC( pcSPS->getMaxDecPicBuffering(i) - 1,       "sps_max_dec_pic_buffering_minus1[i]" );
-#else
-    WRITE_UVLC( pcSPS->getMaxDecPicBuffering(i),           "sps_max_dec_pic_buffering[i]" );
-#endif
     WRITE_UVLC( pcSPS->getNumReorderPics(i),               "sps_num_reorder_pics[i]" );
-    WRITE_UVLC( pcSPS->getMaxLatencyIncrease(i),           "sps_max_latency_increase[i]" );
+    WRITE_UVLC( pcSPS->getMaxLatencyIncrease(i),           "sps_max_latency_increase_plus1[i]" );
     if (!subLayerOrderingInfoPresentFlag)
     {
@@ -639,18 +595,11 @@
   WRITE_CODE( 0xffff,                              16,        "vps_reserved_ffff_16bits" );
   codePTL( pcVPS->getPTL(), true, pcVPS->getMaxTLayers() - 1 );
-#if SIGNAL_BITRATE_PICRATE_IN_VPS
-  codeBitratePicRateInfo(pcVPS->getBitratePicrateInfo(), 0, pcVPS->getMaxTLayers() - 1);
-#endif  
   const Bool subLayerOrderingInfoPresentFlag = 1;
   WRITE_FLAG(subLayerOrderingInfoPresentFlag,              "vps_sub_layer_ordering_info_present_flag");
   for(UInt i=0; i <= pcVPS->getMaxTLayers()-1; i++)
   {
-#if L0323_DPB
     WRITE_UVLC( pcVPS->getMaxDecPicBuffering(i) - 1,       "vps_max_dec_pic_buffering_minus1[i]" );
-#else
-    WRITE_UVLC( pcVPS->getMaxDecPicBuffering(i),           "vps_max_dec_pic_buffering[i]" );
-#endif
     WRITE_UVLC( pcVPS->getNumReorderPics(i),               "vps_num_reorder_pics[i]" );
-    WRITE_UVLC( pcVPS->getMaxLatencyIncrease(i),           "vps_max_latency_increase[i]" );
+    WRITE_UVLC( pcVPS->getMaxLatencyIncrease(i),           "vps_max_latency_increase_plus1[i]" );
     if (!subLayerOrderingInfoPresentFlag)
     {
@@ -693,5 +642,4 @@
   pcVPS->deriveLayerIdListVariables();
 #endif
-#if L0043_TIMING_INFO
   TimingInfo *timingInfo = pcVPS->getTimingInfo();
   WRITE_FLAG(timingInfo->getTimingInfoPresentFlag(),          "vps_timing_info_present_flag");
@@ -705,5 +653,4 @@
       WRITE_UVLC(timingInfo->getNumTicksPocDiffOneMinus1(),   "vps_num_ticks_poc_diff_one_minus1");
     }
-#endif
     pcVPS->setNumHrdParameters( 0 );
     WRITE_UVLC( pcVPS->getNumHrdParameters(),                 "vps_num_hrd_parameters" );
@@ -724,7 +671,5 @@
       codeHrdParameters(pcVPS->getHrdParameters(i), pcVPS->getCprmsPresentFlag( i ), pcVPS->getMaxTLayers() - 1);
     }
-#if L0043_TIMING_INFO
-  }
-#endif
+  }
 #if !VPS_EXTNS
   WRITE_FLAG( 0,                     "vps_extension_flag" );
@@ -994,33 +939,20 @@
       
 #if FIX1071
-      // Deal with bitstream restriction stating that:
-      // – If the current picture is a BLA or CRA picture, the value of NumPocTotalCurr shall be equal to 0.
+      // check for bitstream restriction stating that:
+      // If the current picture is a BLA or CRA picture, the value of NumPocTotalCurr shall be equal to 0.
       // Ideally this process should not be repeated for each slice in a picture
-      TComReferencePictureSet altRps;
-      Bool useAltRps = false;
 #if SVC_EXTENSION
       if( pcSlice->getLayerId() == 0 )
 #endif
-      if (pcSlice->getRapPicFlag())
-      {
-        for (Int picIdx = 0; !useAltRps && picIdx < rps->getNumberOfPictures(); picIdx++)
-        {
-          useAltRps = rps->getUsed(picIdx);
-        }
-        if (useAltRps)
-        {
-          memcpy(&altRps, rps, sizeof(TComReferencePictureSet));
-          rps = &altRps;
-          for (Int picIdx = 0; picIdx < rps->getNumberOfPictures(); picIdx++)
-          {
-            rps->setUsed(picIdx, false);
-          }
-        }
-      }
-
-      if(pcSlice->getRPSidx() < 0 || useAltRps)
-#else
+      if (pcSlice->isIRAP())
+      {
+        for (Int picIdx = 0; picIdx < rps->getNumberOfPictures(); picIdx++)
+        {
+          assert (!rps->getUsed(picIdx));
+        }
+      }
+#endif
+
       if(pcSlice->getRPSidx() < 0)
-#endif
       {
         WRITE_FLAG( 0, "short_term_ref_pic_set_sps_flag");
@@ -1114,5 +1046,4 @@
         }
       }
-
       if (pcSlice->getSPS()->getTMVPFlagsPresent())
       {
@@ -1326,5 +1257,4 @@
     }
   }
-
   if(pcSlice->getPPS()->getSliceHeaderExtensionPresentFlag())
   {
@@ -1341,5 +1271,4 @@
   WRITE_CODE( pcPTL->getGeneralPTL()->getLevelIdc(), 8, "general_level_idc" );
 
-#if L0363_BYTE_ALIGN
   for (Int i = 0; i < maxNumSubLayersMinus1; i++)
   {
@@ -1359,16 +1288,7 @@
     }
   }
-#endif
   
   for(Int i = 0; i < maxNumSubLayersMinus1; i++)
   {
-#if !L0363_BYTE_ALIGN
-    if(profilePresentFlag)
-    {
-      WRITE_FLAG( pcPTL->getSubLayerProfilePresentFlag(i), "sub_layer_profile_present_flag[i]" );
-    }
-
-    WRITE_FLAG( pcPTL->getSubLayerLevelPresentFlag(i),   "sub_layer_level_present_flag[i]" );
-#endif
     if( profilePresentFlag && pcPTL->getSubLayerProfilePresentFlag(i) )
     {
@@ -1391,5 +1311,4 @@
   }
 
-#if L0046_CONSTRAINT_FLAGS
   WRITE_FLAG(ptl->getProgressiveSourceFlag(),   "general_progressive_source_flag");
   WRITE_FLAG(ptl->getInterlacedSourceFlag(),    "general_interlaced_source_flag");
@@ -1400,32 +1319,6 @@
   WRITE_CODE(0 , 16, "XXX_reserved_zero_44bits[16..31]");
   WRITE_CODE(0 , 12, "XXX_reserved_zero_44bits[32..43]");
-#elif L0363_MORE_BITS
-  WRITE_CODE(0 , 16, "XXX_reserved_zero_48bits[0..15]");
-  WRITE_CODE(0 , 16, "XXX_reserved_zero_48bits[16..31]");
-  WRITE_CODE(0 , 16, "XXX_reserved_zero_48bits[32..47]");
-#else
-  WRITE_CODE(0 , 16, "XXX_reserved_zero_16bits[]");
-#endif
-}
-#if SIGNAL_BITRATE_PICRATE_IN_VPS
-Void TEncCavlc::codeBitratePicRateInfo(TComBitRatePicRateInfo *info, Int tempLevelLow, Int tempLevelHigh)
-{
-  for(Int i = tempLevelLow; i <= tempLevelHigh; i++)
-  {
-    WRITE_FLAG( info->getBitRateInfoPresentFlag(i),  "bit_rate_info_present_flag[i]" );
-    WRITE_FLAG( info->getPicRateInfoPresentFlag(i),  "pic_rate_info_present_flag[i]" );
-    if(info->getBitRateInfoPresentFlag(i))
-    {
-      WRITE_CODE( info->getAvgBitRate(i), 16, "avg_bit_rate[i]" );
-      WRITE_CODE( info->getMaxBitRate(i), 16, "max_bit_rate[i]" );
-    }
-    if(info->getPicRateInfoPresentFlag(i))
-    {
-      WRITE_CODE( info->getConstantPicRateIdc(i),  2, "constant_pic_rate_idc[i]" );
-      WRITE_CODE( info->getAvgPicRate(i),         16, "avg_pic_rate[i]"          );
-    }
-  }
-}
-#endif  
+}
+
 /**
  - write wavefront substreams sizes for the slice header.
@@ -1497,9 +1390,5 @@
   for (UInt idx=0; idx<numEntryPointOffsets; idx++)
   {
-#if L0116_ENTRY_POINT
     WRITE_CODE(entryPointOffset[ idx ]-1, offsetLenMinus1+1, "entry_point_offset_minus1");
-#else
-    WRITE_CODE(entryPointOffset[ idx ], offsetLenMinus1+1, "entry_point_offset");
-#endif
   }
 
Index: branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncCavlc.h
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncCavlc.h	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncCavlc.h	(revision 302)
@@ -96,7 +96,4 @@
   Void  codePTL                 ( TComPTL* pcPTL, Bool profilePresentFlag, Int maxNumSubLayersMinus1);
   Void  codeProfileTier         ( ProfileTierLevel* ptl );
-#if SIGNAL_BITRATE_PICRATE_IN_VPS
-  Void codeBitratePicRateInfo(TComBitRatePicRateInfo *info, Int tempLevelLow, Int tempLevelHigh);
-#endif
   Void  codeHrdParameters       ( TComHRD *hrd, Bool commonInfPresentFlag, UInt maxNumSubLayersMinus1 );
   Void  codeTilesWPPEntryPoint( TComSlice* pSlice );
Index: branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncCfg.h
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncCfg.h	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncCfg.h	(revision 302)
@@ -116,10 +116,8 @@
   Level::Tier   m_levelTier;
   Level::Name   m_level;
-#if L0046_CONSTRAINT_FLAGS
   Bool m_progressiveSourceFlag;
   Bool m_interlacedSourceFlag;
   Bool m_nonPackedConstraintFlag;
   Bool m_frameOnlyConstraintFlag;
-#endif
 
   //====== Coding Structure ========
@@ -169,7 +167,5 @@
   Int       m_loopFilterTcOffsetDiv2;
   Bool      m_DeblockingFilterControlPresent;
-#if L0386_DB_METRIC
   Bool      m_DeblockingFilterMetric;
-#endif
   Bool      m_bUseSAO;
   Int       m_maxNumOffsetsPerPic;
@@ -202,12 +198,7 @@
   Bool      m_bUseASR;
   Bool      m_bUseHADME;
-#if !L0034_COMBINED_LIST_CLEANUP
-  Bool      m_bUseLComb;
-#endif
   Bool      m_useRDOQ;
   Bool      m_useRDOQTS;
-#if L0232_RD_PENALTY
   UInt      m_rdPenalty;
-#endif
   Bool      m_bUseFastEnc;
   Bool      m_bUseEarlyCU;
@@ -253,5 +244,4 @@
   Int       m_pictureTimingSEIEnabled;
   Int       m_recoveryPointSEIEnabled;
-#if J0149_TONE_MAPPING_SEI
   Bool      m_toneMappingInfoSEIEnabled;
   Int       m_toneMapId;
@@ -279,5 +269,4 @@
   Int*      m_codedPivotValue;
   Int*      m_targetPivotValue;
-#endif
   Int       m_framePackingSEIEnabled;
   Int       m_framePackingSEIType;
@@ -292,10 +281,6 @@
   Int       m_layersPresentSEIEnabled;
 #endif
-#if L0208_SOP_DESCRIPTION_SEI
   Int       m_SOPDescriptionSEIEnabled;
-#endif
-#if K0180_SCALABLE_NESTING_SEI
   Int       m_scalableNestingSEIEnabled;
-#endif
   //====== Weighted Prediction ========
   Bool      m_useWeightedPred;       //< Use of Weighting Prediction (P_SLICE)
@@ -310,5 +295,9 @@
   Bool      m_RCEnableRateControl;
   Int       m_RCTargetBitrate;
+#if M0036_RC_IMPROVEMENT
+  Int       m_RCKeepHierarchicalBit;
+#else
   Bool      m_RCKeepHierarchicalBit;
+#endif
   Bool      m_RCLCULevelRC;
   Bool      m_RCUseLCUSeparateModel;
@@ -463,7 +452,5 @@
   Void      setLoopFilterTcOffset           ( Int   i )      { m_loopFilterTcOffsetDiv2    = i; }
   Void      setDeblockingFilterControlPresent ( Bool b ) { m_DeblockingFilterControlPresent = b; }
-#if L0386_DB_METRIC
   Void      setDeblockingFilterMetric       ( Bool  b )      { m_DeblockingFilterMetric = b; }
-#endif
 
   //====== Motion search ========
@@ -520,7 +507,5 @@
   Int       getLoopFilterTcOffset           ()      { return m_loopFilterTcOffsetDiv2; }
   Bool      getDeblockingFilterControlPresent()  { return  m_DeblockingFilterControlPresent; }
-#if L0386_DB_METRIC
   Bool      getDeblockingFilterMetric       ()      { return m_DeblockingFilterMetric; }
-#endif
 
   //==== Motion search ========
@@ -540,12 +525,7 @@
   Void      setUseASR                       ( Bool  b )     { m_bUseASR     = b; }
   Void      setUseHADME                     ( Bool  b )     { m_bUseHADME   = b; }
-#if !L0034_COMBINED_LIST_CLEANUP
-  Void      setUseLComb                     ( Bool  b )     { m_bUseLComb   = b; }
-#endif
   Void      setUseRDOQ                      ( Bool  b )     { m_useRDOQ    = b; }
   Void      setUseRDOQTS                    ( Bool  b )     { m_useRDOQTS  = b; }
-#if L0232_RD_PENALTY
   Void      setRDpenalty                 ( UInt  b )     { m_rdPenalty  = b; }
-#endif
   Void      setUseFastEnc                   ( Bool  b )     { m_bUseFastEnc = b; }
   Void      setUseEarlyCU                   ( Bool  b )     { m_bUseEarlyCU = b; }
@@ -567,12 +547,7 @@
   Bool      getUseASR                       ()      { return m_bUseASR;     }
   Bool      getUseHADME                     ()      { return m_bUseHADME;   }
-#if !L0034_COMBINED_LIST_CLEANUP
-  Bool      getUseLComb                     ()      { return m_bUseLComb;   }
-#endif
   Bool      getUseRDOQ                      ()      { return m_useRDOQ;    }
   Bool      getUseRDOQTS                    ()      { return m_useRDOQTS;  }
-#if L0232_RD_PENALTY
   Int      getRDpenalty                  ()      { return m_rdPenalty;  }
-#endif
   Bool      getUseFastEnc                   ()      { return m_bUseFastEnc; }
   Bool      getUseEarlyCU                   ()      { return m_bUseEarlyCU; }
@@ -669,5 +644,4 @@
   Void  setRecoveryPointSEIEnabled(Int b)                { m_recoveryPointSEIEnabled = b; }
   Int   getRecoveryPointSEIEnabled()                     { return m_recoveryPointSEIEnabled; }
-#if J0149_TONE_MAPPING_SEI
   Void  setToneMappingInfoSEIEnabled(Bool b)                 {  m_toneMappingInfoSEIEnabled = b;  }
   Bool  getToneMappingInfoSEIEnabled()                       {  return m_toneMappingInfoSEIEnabled;  }
@@ -720,5 +694,4 @@
   Void  setTMISEIExtendedWhiteLevelLumaCodeValue(Int b)      {  m_extendedWhiteLevelLumaCodeValue =b;  }
   Int   getTMISEIExtendedWhiteLevelLumaCodeValue()           {  return m_extendedWhiteLevelLumaCodeValue;  }
-#endif
   Void  setFramePackingArrangementSEIEnabled(Int b)      { m_framePackingSEIEnabled = b; }
   Int   getFramePackingArrangementSEIEnabled()           { return m_framePackingSEIEnabled; }
@@ -743,12 +716,8 @@
   Int   getLayersPresentSEIEnabled()                     { return m_layersPresentSEIEnabled; }
 #endif
-#if L0208_SOP_DESCRIPTION_SEI
   Void  setSOPDescriptionSEIEnabled(Int b)                { m_SOPDescriptionSEIEnabled = b; }
   Int   getSOPDescriptionSEIEnabled()                     { return m_SOPDescriptionSEIEnabled; }
-#endif
-#if K0180_SCALABLE_NESTING_SEI
   Void  setScalableNestingSEIEnabled(Int b)                { m_scalableNestingSEIEnabled = b; }
   Int   getScalableNestingSEIEnabled()                     { return m_scalableNestingSEIEnabled; }
-#endif
   Void      setUseWP               ( Bool b )    { m_useWeightedPred   = b;    }
   Void      setWPBiPred            ( Bool b )    { m_useWeightedBiPred = b;    }
@@ -772,6 +741,11 @@
   Int       getTargetBitrate       ()              { return m_RCTargetBitrate;       }
   Void      setTargetBitrate       ( Int bitrate ) { m_RCTargetBitrate  = bitrate;   }
+#if M0036_RC_IMPROVEMENT
+  Int       getKeepHierBit         ()              { return m_RCKeepHierarchicalBit; }
+  Void      setKeepHierBit         ( Int i )       { m_RCKeepHierarchicalBit = i;    }
+#else
   Bool      getKeepHierBit         ()              { return m_RCKeepHierarchicalBit; }
   Void      setKeepHierBit         ( Bool b )      { m_RCKeepHierarchicalBit = b;    }
+#endif
   Bool      getLCULevelRC          ()              { return m_RCLCULevelRC; }
   Void      setLCULevelRC          ( Bool b )      { m_RCLCULevelRC = b; }
@@ -865,5 +839,4 @@
   Void      setLog2MaxMvLengthVertical(Int i)             { m_log2MaxMvLengthVertical = i; }
   
-#if L0046_CONSTRAINT_FLAGS
   Bool getProgressiveSourceFlag() const { return m_progressiveSourceFlag; }
   Void setProgressiveSourceFlag(Bool b) { m_progressiveSourceFlag = b; }
@@ -877,5 +850,4 @@
   Bool getFrameOnlyConstraintFlag() const { return m_frameOnlyConstraintFlag; }
   Void setFrameOnlyConstraintFlag(Bool b) { m_frameOnlyConstraintFlag = b; }
-#endif
 
 #if SVC_EXTENSION
Index: branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncCu.cpp
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncCu.cpp	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncCu.cpp	(revision 302)
@@ -95,5 +95,5 @@
   
   m_bEncodeDQP = false;
-#if RATE_CONTROL_LAMBDA_DOMAIN
+#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
   m_LCUPredictionSAD = 0;
   m_addSADDepth      = 0;
@@ -108,5 +108,4 @@
   // initialize conversion matrix from partition index to pel
   initRasterToPelXY( uiMaxWidth, uiMaxHeight, m_uhTotalDepth );
-
 }
 
@@ -245,5 +244,5 @@
   m_ppcTempCU[0]->initCU( rpcCU->getPic(), rpcCU->getAddr() );
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
+#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
   m_addSADDepth      = 0;
   m_LCUPredictionSAD = 0;
@@ -548,5 +547,5 @@
     }
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
+#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
     if ( uiDepth <= m_addSADDepth )
     {
@@ -822,5 +821,5 @@
   {
     bBoundary = true;
-#if RATE_CONTROL_LAMBDA_DOMAIN
+#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
     m_addSADDepth++;
 #endif
@@ -1252,4 +1251,121 @@
 }
 
+#if RATE_CONTROL_INTRA
+Int xCalcHADs8x8_ISlice(Pel *piOrg, Int iStrideOrg) 
+{
+  Int k, i, j, jj;
+  Int diff[64], m1[8][8], m2[8][8], m3[8][8], iSumHad = 0;
+
+  for( k = 0; k < 64; k += 8 )
+  {
+    diff[k+0] = piOrg[0] ;
+    diff[k+1] = piOrg[1] ;
+    diff[k+2] = piOrg[2] ;
+    diff[k+3] = piOrg[3] ;
+    diff[k+4] = piOrg[4] ;
+    diff[k+5] = piOrg[5] ;
+    diff[k+6] = piOrg[6] ;
+    diff[k+7] = piOrg[7] ;
+ 
+    piOrg += iStrideOrg;
+  }
+  
+  //horizontal
+  for (j=0; j < 8; j++)
+  {
+    jj = j << 3;
+    m2[j][0] = diff[jj  ] + diff[jj+4];
+    m2[j][1] = diff[jj+1] + diff[jj+5];
+    m2[j][2] = diff[jj+2] + diff[jj+6];
+    m2[j][3] = diff[jj+3] + diff[jj+7];
+    m2[j][4] = diff[jj  ] - diff[jj+4];
+    m2[j][5] = diff[jj+1] - diff[jj+5];
+    m2[j][6] = diff[jj+2] - diff[jj+6];
+    m2[j][7] = diff[jj+3] - diff[jj+7];
+    
+    m1[j][0] = m2[j][0] + m2[j][2];
+    m1[j][1] = m2[j][1] + m2[j][3];
+    m1[j][2] = m2[j][0] - m2[j][2];
+    m1[j][3] = m2[j][1] - m2[j][3];
+    m1[j][4] = m2[j][4] + m2[j][6];
+    m1[j][5] = m2[j][5] + m2[j][7];
+    m1[j][6] = m2[j][4] - m2[j][6];
+    m1[j][7] = m2[j][5] - m2[j][7];
+    
+    m2[j][0] = m1[j][0] + m1[j][1];
+    m2[j][1] = m1[j][0] - m1[j][1];
+    m2[j][2] = m1[j][2] + m1[j][3];
+    m2[j][3] = m1[j][2] - m1[j][3];
+    m2[j][4] = m1[j][4] + m1[j][5];
+    m2[j][5] = m1[j][4] - m1[j][5];
+    m2[j][6] = m1[j][6] + m1[j][7];
+    m2[j][7] = m1[j][6] - m1[j][7];
+  }
+  
+  //vertical
+  for (i=0; i < 8; i++)
+  {
+    m3[0][i] = m2[0][i] + m2[4][i];
+    m3[1][i] = m2[1][i] + m2[5][i];
+    m3[2][i] = m2[2][i] + m2[6][i];
+    m3[3][i] = m2[3][i] + m2[7][i];
+    m3[4][i] = m2[0][i] - m2[4][i];
+    m3[5][i] = m2[1][i] - m2[5][i];
+    m3[6][i] = m2[2][i] - m2[6][i];
+    m3[7][i] = m2[3][i] - m2[7][i];
+    
+    m1[0][i] = m3[0][i] + m3[2][i];
+    m1[1][i] = m3[1][i] + m3[3][i];
+    m1[2][i] = m3[0][i] - m3[2][i];
+    m1[3][i] = m3[1][i] - m3[3][i];
+    m1[4][i] = m3[4][i] + m3[6][i];
+    m1[5][i] = m3[5][i] + m3[7][i];
+    m1[6][i] = m3[4][i] - m3[6][i];
+    m1[7][i] = m3[5][i] - m3[7][i];
+    
+    m2[0][i] = m1[0][i] + m1[1][i];
+    m2[1][i] = m1[0][i] - m1[1][i];
+    m2[2][i] = m1[2][i] + m1[3][i];
+    m2[3][i] = m1[2][i] - m1[3][i];
+    m2[4][i] = m1[4][i] + m1[5][i];
+    m2[5][i] = m1[4][i] - m1[5][i];
+    m2[6][i] = m1[6][i] + m1[7][i];
+    m2[7][i] = m1[6][i] - m1[7][i];
+  }
+  
+  for (i = 0; i < 8; i++)
+  {
+    for (j = 0; j < 8; j++)
+    {
+      iSumHad += abs(m2[i][j]);
+    }
+  }
+  iSumHad -= abs(m2[0][0]);
+  iSumHad =(iSumHad+2)>>2;
+  return(iSumHad);
+}
+
+Int  TEncCu::updateLCUDataISlice(TComDataCU* pcCU, Int LCUIdx, Int width, Int height)
+{
+  Int  xBl, yBl; 
+  const Int iBlkSize = 8;
+
+  Pel* pOrgInit   = pcCU->getPic()->getPicYuvOrg()->getLumaAddr(pcCU->getAddr(), 0);
+  Int  iStrideOrig = pcCU->getPic()->getPicYuvOrg()->getStride();
+  Pel  *pOrg;
+
+  Int iSumHad = 0;
+  for ( yBl=0; (yBl+iBlkSize)<=height; yBl+= iBlkSize)
+  {
+    for ( xBl=0; (xBl+iBlkSize)<=width; xBl+= iBlkSize)
+    {
+      pOrg = pOrgInit + iStrideOrig*yBl + xBl; 
+      iSumHad += xCalcHADs8x8_ISlice(pOrg, iStrideOrig);
+    }
+  }
+  return(iSumHad);
+}
+#endif
+
 /** check RD costs for a CU block encoded with merge
  * \param rpcBestCU
@@ -1260,5 +1376,5 @@
 {
   assert( rpcTempCU->getSlice()->getSliceType() != I_SLICE );
-  TComMvField  cMvFieldNeighbours[MRG_MAX_NUM_CANDS << 1]; // double length for mv of both lists
+  TComMvField  cMvFieldNeighbours[ 2 * MRG_MAX_NUM_CANDS ]; // double length for mv of both lists
   UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS];
   Int numValidMergeCand = 0;
@@ -1274,5 +1390,5 @@
 
   Int mergeCandBuffer[MRG_MAX_NUM_CANDS];
-  for( UInt ui = 0; ui < rpcTempCU->getSlice()->getMaxNumMergeCand(); ++ui )
+  for( UInt ui = 0; ui < numValidMergeCand; ++ui )
   {
     mergeCandBuffer[ui] = 0;
@@ -1300,7 +1416,6 @@
       {
 #endif
-        if(!(uiNoResidual==1 && mergeCandBuffer[uiMergeCand]==1))
-        {
-
+      if(!(uiNoResidual==1 && mergeCandBuffer[uiMergeCand]==1))
+      {
         if( !(bestIsSkip && uiNoResidual == 0) )
         {
@@ -1314,42 +1429,38 @@
           rpcTempCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( cMvFieldNeighbours[0 + 2*uiMergeCand], SIZE_2Nx2N, 0, 0 ); // interprets depth relative to rpcTempCU level
           rpcTempCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMvFieldNeighbours[1 + 2*uiMergeCand], SIZE_2Nx2N, 0, 0 ); // interprets depth relative to rpcTempCU level
-
-       // do MC
-       m_pcPredSearch->motionCompensation ( rpcTempCU, m_ppcPredYuvTemp[uhDepth] );
-       // estimate residual and encode everything
-       m_pcPredSearch->encodeResAndCalcRdInterCU( rpcTempCU,
-         m_ppcOrigYuv    [uhDepth],
-         m_ppcPredYuvTemp[uhDepth],
-         m_ppcResiYuvTemp[uhDepth],
-         m_ppcResiYuvBest[uhDepth],
-         m_ppcRecoYuvTemp[uhDepth],
-         (uiNoResidual? true:false));
-
-
-       if(uiNoResidual==0)
-       {
-         if(rpcTempCU->getQtRootCbf(0) == 0)
-         {
-           mergeCandBuffer[uiMergeCand] = 1;
-         }
-       }
-
-       rpcTempCU->setSkipFlagSubParts( rpcTempCU->getQtRootCbf(0) == 0, 0, uhDepth );
+          
+          // do MC
+          m_pcPredSearch->motionCompensation ( rpcTempCU, m_ppcPredYuvTemp[uhDepth] );
+          // estimate residual and encode everything
+          m_pcPredSearch->encodeResAndCalcRdInterCU( rpcTempCU,
+                                                    m_ppcOrigYuv    [uhDepth],
+                                                    m_ppcPredYuvTemp[uhDepth],
+                                                    m_ppcResiYuvTemp[uhDepth],
+                                                    m_ppcResiYuvBest[uhDepth],
+                                                    m_ppcRecoYuvTemp[uhDepth],
+                                                    (uiNoResidual? true:false));
+          
+          
+          if ( uiNoResidual == 0 && rpcTempCU->getQtRootCbf(0) == 0 )
+          {
+            // If no residual when allowing for one, then set mark to not try case where residual is forced to 0
+            mergeCandBuffer[uiMergeCand] = 1;
+          }
+          
+          rpcTempCU->setSkipFlagSubParts( rpcTempCU->getQtRootCbf(0) == 0, 0, uhDepth );
           Int orgQP = rpcTempCU->getQP( 0 );
           xCheckDQP( rpcTempCU );
           xCheckBestMode(rpcBestCU, rpcTempCU, uhDepth);
           rpcTempCU->initEstData( uhDepth, orgQP );
-
-
-      if( m_pcEncCfg->getUseFastDecisionForMerge() && !bestIsSkip )
-      {
-        bestIsSkip = rpcBestCU->getQtRootCbf(0) == 0;
-      }
-
-    }
-    }
+          
+          if( m_pcEncCfg->getUseFastDecisionForMerge() && !bestIsSkip )
+          {
+            bestIsSkip = rpcBestCU->getQtRootCbf(0) == 0;
+          }
+        }
 #if REF_IDX_ME_ZEROMV 
-   }
-#endif
+        }
+#endif
+      }
   }
 
@@ -1417,5 +1528,5 @@
 #endif
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
+#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
   if ( m_pcEncCfg->getUseRateCtrl() && m_pcEncCfg->getLCULevelRC() && ePartSize == SIZE_2Nx2N && uhDepth <= m_addSADDepth )
   {
Index: branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncCu.h
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncCu.h	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncCu.h	(revision 302)
@@ -106,5 +106,5 @@
   Bool                    m_bUseSBACRD;
   TEncRateCtrl*           m_pcRateCtrl;
-#if RATE_CONTROL_LAMBDA_DOMAIN
+#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
   UInt                    m_LCUPredictionSAD;
   Int                     m_addSADDepth;
@@ -128,6 +128,9 @@
   
   Void setBitCounter        ( TComBitCounter* pcBitCounter ) { m_pcBitCounter = pcBitCounter; }
-#if RATE_CONTROL_LAMBDA_DOMAIN
+#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
   UInt getLCUPredictionSAD() { return m_LCUPredictionSAD; }
+#endif
+#if RATE_CONTROL_INTRA
+  Int   updateLCUDataISlice ( TComDataCU* pcCU, Int LCUIdx, Int width, Int height );
 #endif
 #if INTRA_BL 
Index: branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncGOP.cpp
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 302)
@@ -94,10 +94,6 @@
   m_cpbRemovalDelay   = 0;
   m_lastBPSEI         = 0;
-#if L0045_NON_NESTED_SEI_RESTRICTIONS
   xResetNonNestedSEIPresentFlags();
-#if K0180_SCALABLE_NESTING_SEI
   xResetNestedSEIPresentFlags();
-#endif
-#endif
 #if SVC_UPSAMPLING
   m_pcPredSearch        = NULL;
@@ -163,8 +159,6 @@
   SEIActiveParameterSets *seiActiveParameterSets = new SEIActiveParameterSets(); 
   seiActiveParameterSets->activeVPSId = m_pcCfg->getVPS()->getVPSId(); 
-#if L0047_APS_FLAGS
   seiActiveParameterSets->m_fullRandomAccessFlag = false;
   seiActiveParameterSets->m_noParamSetUpdateFlag = false;
-#endif
   seiActiveParameterSets->numSpsIdsMinus1 = 0;
   seiActiveParameterSets->activeSeqParamSetId.resize(seiActiveParameterSets->numSpsIdsMinus1 + 1); 
@@ -198,7 +192,5 @@
   seiFramePacking->m_arrangementCancelFlag = 0;
   seiFramePacking->m_arrangementType = m_pcCfg->getFramePackingArrangementSEIType();
-#if L0444_FPA_TYPE
   assert((seiFramePacking->m_arrangementType > 2) && (seiFramePacking->m_arrangementType < 6) );
-#endif
   seiFramePacking->m_quincunxSamplingFlag = m_pcCfg->getFramePackingArrangementSEIQuincunx();
   seiFramePacking->m_contentInterpretationType = m_pcCfg->getFramePackingArrangementSEIInterpretation();
@@ -214,9 +206,5 @@
   seiFramePacking->m_frame1GridPositionY = 0;
   seiFramePacking->m_arrangementReservedByte = 0;
-#if L0045_PERSISTENCE_FLAGS
   seiFramePacking->m_arrangementPersistenceFlag = true;
-#else
-  seiFramePacking->m_arrangementRepetetionPeriod = 1;
-#endif
   seiFramePacking->m_upsampledAspectRatio = 0;
   return seiFramePacking;
@@ -233,5 +221,4 @@
 }
 
-#if J0149_TONE_MAPPING_SEI
 SEIToneMappingInfo*  TEncGOP::xCreateSEIToneMappingInfo()
 {
@@ -244,5 +231,5 @@
   assert(seiToneMappingInfo->m_codedDataBitDepth >= 8 && seiToneMappingInfo->m_codedDataBitDepth <= 14);
   seiToneMappingInfo->m_targetBitDepth = m_pcCfg->getTMISEITargetBitDepth();
-  assert( (seiToneMappingInfo->m_targetBitDepth >= 1 && seiToneMappingInfo->m_targetBitDepth <= 17) || (seiToneMappingInfo->m_targetBitDepth  == 255) );
+  assert( seiToneMappingInfo->m_targetBitDepth >= 1 && seiToneMappingInfo->m_targetBitDepth <= 17 );
   seiToneMappingInfo->m_modelId = m_pcCfg->getTMISEIModelID();
   assert(seiToneMappingInfo->m_modelId >=0 &&seiToneMappingInfo->m_modelId<=4);
@@ -319,5 +306,5 @@
   return seiToneMappingInfo;
 }
-#endif
+
 Void TEncGOP::xCreateLeadingSEIMessages (/*SEIMessages seiMessages,*/ AccessUnit &accessUnit, TComSPS *sps)
 {
@@ -334,7 +321,5 @@
     accessUnit.push_back(new NALUnitEBSP(nalu));
     delete sei;
-#if L0045_NON_NESTED_SEI_RESTRICTIONS
     m_activeParameterSetSEIPresentInAU = true;
-#endif
   }
 
@@ -373,5 +358,4 @@
     delete sei;
   }
-#if J0149_TONE_MAPPING_SEI
   if(m_pcCfg->getToneMappingInfoSEIEnabled())
   {
@@ -385,5 +369,4 @@
     delete sei;
   }
-#endif
 }
 
@@ -411,8 +394,5 @@
   m_iNumPicCoded = 0;
   SEIPictureTiming pictureTimingSEI;
-#if L0208_SOP_DESCRIPTION_SEI
   Bool writeSOP = m_pcCfg->getSOPDescriptionSEIEnabled();
-#endif
-#if K0180_SCALABLE_NESTING_SEI
   // Initialize Scalable Nesting SEI with single layer values
   SEIScalableNesting scalableNestingSEI;
@@ -425,8 +405,5 @@
   scalableNestingSEI.m_nestingLayerId[0]             = 0;
   scalableNestingSEI.m_callerOwnsSEIs                = true;
-#endif
-#if L0044_DU_DPB_OUTPUT_DELAY_HRD
   Int picSptDpbOutputDuDelay = 0;
-#endif
   UInt *accumBitsDU = NULL;
   UInt *accumNalsDU = NULL;
@@ -706,8 +683,15 @@
     pcSlice->getRPS()->setNumberOfLongtermPictures(0);
 
+#if FIX1071
+    if ((pcSlice->checkThatAllRefPicsAreAvailable(rcListPic, pcSlice->getRPS(), false) != 0) || (pcSlice->isIRAP()))
+    {
+      pcSlice->createExplicitReferencePictureSetFromReference(rcListPic, pcSlice->getRPS(), pcSlice->isIRAP());
+    }
+#else
     if(pcSlice->checkThatAllRefPicsAreAvailable(rcListPic, pcSlice->getRPS(), false) != 0)
     {
       pcSlice->createExplicitReferencePictureSetFromReference(rcListPic, pcSlice->getRPS());
     }
+#endif
     pcSlice->applyReferencePictureSet(rcListPic, pcSlice->getRPS());
 
@@ -921,17 +905,4 @@
       pcSlice->setSliceType ( P_SLICE );
     }
-#if !L0034_COMBINED_LIST_CLEANUP
-    if (pcSlice->getSliceType() != B_SLICE || !pcSlice->getSPS()->getUseLComb())
-    {
-      pcSlice->setNumRefIdx(REF_PIC_LIST_C, 0);
-      pcSlice->setRefPicListCombinationFlag(false);
-      pcSlice->setRefPicListModificationFlagLC(false);
-    }
-    else
-    {
-      pcSlice->setRefPicListCombinationFlag(pcSlice->getSPS()->getUseLComb());
-      pcSlice->setNumRefIdx(REF_PIC_LIST_C, pcSlice->getNumRefIdx(REF_PIC_LIST_0));
-    }
-#endif
 
 #if M0457_IL_SAMPLE_PRED_ONLY_FLAG
@@ -975,31 +946,5 @@
     pcSlice->setRefPOCList();
 
-#if L0034_COMBINED_LIST_CLEANUP
     pcSlice->setList1IdxToList0Idx();
-#else
-    pcSlice->setNoBackPredFlag( false );
-    if ( pcSlice->getSliceType() == B_SLICE && !pcSlice->getRefPicListCombinationFlag())
-    {
-      if ( pcSlice->getNumRefIdx(RefPicList( 0 ) ) == pcSlice->getNumRefIdx(RefPicList( 1 ) ) )
-      {
-        pcSlice->setNoBackPredFlag( true );
-        Int i;
-        for ( i=0; i < pcSlice->getNumRefIdx(RefPicList( 1 ) ); i++ )
-        {
-          if ( pcSlice->getRefPOC(RefPicList(1), i) != pcSlice->getRefPOC(RefPicList(0), i) ) 
-          {
-            pcSlice->setNoBackPredFlag( false );
-            break;
-          }
-        }
-      }
-    }
-
-    if(pcSlice->getNoBackPredFlag())
-    {
-      pcSlice->setNumRefIdx(REF_PIC_LIST_C, 0);
-    }
-    pcSlice->generateCombinedList();
-#endif
 
     if (m_pcEncTop->getTMVPModeId() == 2)
@@ -1068,5 +1013,4 @@
 
 #if RATE_CONTROL_LAMBDA_DOMAIN
-    Int sliceQP              = pcSlice->getSliceQp();
     Double lambda            = 0.0;
     Int actualHeadBits       = 0;
@@ -1084,7 +1028,7 @@
       estimatedBits = m_pcRateCtrl->getRCPic()->getTargetBits();
 
+      Int sliceQP = m_pcCfg->getInitialQP();
       if ( ( pcSlice->getPOC() == 0 && m_pcCfg->getInitialQP() > 0 ) || ( frameLevel == 0 && m_pcCfg->getForceIntraQP() ) ) // QP is specified
       {
-        sliceQP              = m_pcCfg->getInitialQP();
         Int    NumberBFrames = ( m_pcCfg->getGOPSize() - 1 );
         Double dLambda_scale = 1.0 - Clip3( 0.0, 0.5, 0.05*(Double)NumberBFrames );
@@ -1097,8 +1041,15 @@
       else if ( frameLevel == 0 )   // intra case, but use the model
       {
+#if RATE_CONTROL_INTRA
+        m_pcSliceEncoder->calCostSliceI(pcPic);
+#endif
         if ( m_pcCfg->getIntraPeriod() != 1 )   // do not refine allocated bits for all intra case
         {
           Int bits = m_pcRateCtrl->getRCSeq()->getLeftAverageBits();
+#if RATE_CONTROL_INTRA
+          bits = m_pcRateCtrl->getRCPic()->getRefineBitsForIntra( bits );
+#else
           bits = m_pcRateCtrl->getRCSeq()->getRefineBitsForIntra( bits );
+#endif
           if ( bits < 200 )
           {
@@ -1109,5 +1060,10 @@
 
         list<TEncRCPic*> listPreviousPicture = m_pcRateCtrl->getPicList();
+#if RATE_CONTROL_INTRA
+        m_pcRateCtrl->getRCPic()->getLCUInitTargetBits();
+        lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambda( listPreviousPicture, pcSlice->getSliceType());
+#else
         lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambda( listPreviousPicture );
+#endif
         sliceQP = m_pcRateCtrl->getRCPic()->estimatePicQP( lambda, listPreviousPicture );
       }
@@ -1115,5 +1071,9 @@
       {
         list<TEncRCPic*> listPreviousPicture = m_pcRateCtrl->getPicList();
+#if RATE_CONTROL_INTRA
+        lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambda( listPreviousPicture, pcSlice->getSliceType());
+#else
         lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambda( listPreviousPicture );
+#endif
         sliceQP = m_pcRateCtrl->getRCPic()->estimatePicQP( lambda, listPreviousPicture );
       }
@@ -1324,10 +1284,8 @@
     Bool bLFCrossTileBoundary = pcSlice->getPPS()->getLoopFilterAcrossTilesEnabledFlag();
     m_pcLoopFilter->setCfg(bLFCrossTileBoundary);
-#if L0386_DB_METRIC
     if ( m_pcCfg->getDeblockingFilterMetric() )
     {
       dblMetric(pcPic, uiNumSlices);
     }
-#endif
     m_pcLoopFilter->loopFilterPic( pcPic );
 
@@ -1400,5 +1358,5 @@
         UInt maxCU = m_pcCfg->getSliceArgument() >> ( pcSlice->getSPS()->getMaxCUDepth() << 1);
         UInt numDU = ( m_pcCfg->getSliceMode() == 1 ) ? ( pcPic->getNumCUsInFrame() / maxCU ) : ( 0 );
-        if( pcPic->getNumCUsInFrame() % maxCU != 0 )
+        if( pcPic->getNumCUsInFrame() % maxCU != 0 || numDU == 0 )
         {
           numDU ++;
@@ -1436,5 +1394,4 @@
     }
 
-#if L0208_SOP_DESCRIPTION_SEI
     if (writeSOP) // write SOP description SEI (if enabled) at the beginning of GOP
     {
@@ -1474,5 +1431,4 @@
       writeSOP = false;
     }
-#endif
 
     if( ( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() ) &&
@@ -1506,5 +1462,4 @@
       pictureTimingSEI.m_auCpbRemovalDelay = std::max<Int>(1, m_totalCoded - m_lastBPSEI); // Syntax element signalled as minus, hence the .
       pictureTimingSEI.m_picDpbOutputDelay = pcSlice->getSPS()->getNumReorderPics(0) + pcSlice->getPOC() - m_totalCoded;
-#if L0044_DU_DPB_OUTPUT_DELAY_HRD
       Int factor = pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getTickDivisorMinus2() + 2;
       pictureTimingSEI.m_picDpbOutputDuDelay = factor * pictureTimingSEI.m_picDpbOutputDelay;
@@ -1513,5 +1468,4 @@
         picSptDpbOutputDuDelay = factor * pictureTimingSEI.m_picDpbOutputDelay;
       }
-#endif
     }
 
@@ -1533,9 +1487,5 @@
       sei_buffering_period.m_initialCpbRemovalDelayOffset[0][1]     = uiInitialCpbRemovalDelay;
 
-#if L0043_TIMING_INFO
       Double dTmp = (Double)pcSlice->getSPS()->getVuiParameters()->getTimingInfo()->getNumUnitsInTick() / (Double)pcSlice->getSPS()->getVuiParameters()->getTimingInfo()->getTimeScale();
-#else
-      Double dTmp = (Double)pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNumUnitsInTick() / (Double)pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getTimeScale();
-#endif
 
       UInt uiTmp = (UInt)( dTmp * 90000.0 ); 
@@ -1548,18 +1498,13 @@
 
       sei_buffering_period.m_rapCpbParamsPresentFlag              = 0;
-#if L0328_SPLICING
       //for the concatenation, it can be set to one during splicing.
       sei_buffering_period.m_concatenationFlag = 0;
       //since the temporal layer HRD is not ready, we assumed it is fixed
       sei_buffering_period.m_auCpbRemovalDelayDelta = 1;
-#endif
-#if L0044_CPB_DPB_DELAY_OFFSET
       sei_buffering_period.m_cpbDelayOffset = 0;
       sei_buffering_period.m_dpbDelayOffset = 0;
-#endif
 
       m_seiWriter.writeSEImessage( nalu.m_Bitstream, sei_buffering_period, pcSlice->getSPS());
       writeRBSPTrailingBits(nalu.m_Bitstream);
-#if L0045_NON_NESTED_SEI_RESTRICTIONS
       {
       UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
@@ -1573,9 +1518,5 @@
       m_bufferingPeriodSEIPresentInAU = true;
       }
-#else
-      accessUnit.push_back(new NALUnitEBSP(nalu));
-#endif
-
-#if K0180_SCALABLE_NESTING_SEI
+
       if (m_pcCfg->getScalableNestingSEIEnabled())
       {
@@ -1587,5 +1528,4 @@
         m_seiWriter.writeSEImessage( naluTmp.m_Bitstream, scalableNestingSEI, pcSlice->getSPS());
         writeRBSPTrailingBits(naluTmp.m_Bitstream);
-#if L0045_NON_NESTED_SEI_RESTRICTIONS
         UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
         UInt offsetPosition = m_activeParameterSetSEIPresentInAU + m_bufferingPeriodSEIPresentInAU + m_pictureTimingSEIPresentInAU;   // Insert BP SEI after non-nested APS, BP and PT SEIs
@@ -1597,9 +1537,5 @@
         accessUnit.insert(it, new NALUnitEBSP(naluTmp));
         m_nestedBufferingPeriodSEIPresentInAU = true;
-#else
-        accessUnit.push_back(new NALUnitEBSP(naluTmp));
-#endif
-      }
-#endif
+      }
 
       m_lastBPSEI = m_totalCoded;
@@ -2065,5 +2001,7 @@
       if ( m_pcCfg->getUseRateCtrl() )
       {
+#if !M0036_RC_IMPROVEMENT
         Double effectivePercentage = m_pcRateCtrl->getRCPic()->getEffectivePercentage();
+#endif
         Double avgQP     = m_pcRateCtrl->getRCPic()->calAverageQP();
         Double avgLambda = m_pcRateCtrl->getRCPic()->calAverageLambda();
@@ -2072,5 +2010,13 @@
           avgLambda = lambda;
         }
+#if M0036_RC_IMPROVEMENT
+#if RATE_CONTROL_INTRA
+        m_pcRateCtrl->getRCPic()->updateAfterPicture( actualHeadBits, actualTotalBits, avgQP, avgLambda, pcSlice->getSliceType());
+#else
+        m_pcRateCtrl->getRCPic()->updateAfterPicture( actualHeadBits, actualTotalBits, avgQP, avgLambda );
+#endif
+#else
         m_pcRateCtrl->getRCPic()->updateAfterPicture( actualHeadBits, actualTotalBits, avgQP, avgLambda, effectivePercentage );
+#endif
         m_pcRateCtrl->getRCPic()->addToPictureLsit( m_pcRateCtrl->getPicList() );
 
@@ -2092,4 +2038,5 @@
       }
 #endif
+
       if( ( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() ) &&
           ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) &&
@@ -2126,9 +2073,5 @@
             for( i = ( numDU - 2 ); i >= 0; i -- )
             {
-#if L0043_TIMING_INFO
               ui64Tmp = ( ( ( accumBitsDU[ numDU - 1 ]  - accumBitsDU[ i ] ) * ( vui->getTimingInfo()->getTimeScale() / vui->getTimingInfo()->getNumUnitsInTick() ) * ( hrd->getTickDivisorMinus2() + 2 ) ) / ( m_pcCfg->getTargetBitrate() ) );
-#else
-              ui64Tmp = ( ( ( accumBitsDU[ numDU - 1 ]  - accumBitsDU[ i ] ) * ( hrd->getTimeScale() / hrd->getNumUnitsInTick() ) * ( hrd->getTickDivisorMinus2() + 2 ) ) / ( m_pcCfg->getTargetBitrate() ) );
-#endif
               if( (UInt)ui64Tmp > maxDiff )
               {
@@ -2142,9 +2085,5 @@
             {
               flag = 0;
-#if L0043_TIMING_INFO
               ui64Tmp = ( ( ( accumBitsDU[ numDU - 1 ]  - accumBitsDU[ i ] ) * ( vui->getTimingInfo()->getTimeScale() / vui->getTimingInfo()->getNumUnitsInTick() ) * ( hrd->getTickDivisorMinus2() + 2 ) ) / ( m_pcCfg->getTargetBitrate() ) );
-#else
-              ui64Tmp = ( ( ( accumBitsDU[ numDU - 1 ]  - accumBitsDU[ i ] ) * ( hrd->getTimeScale() / hrd->getNumUnitsInTick() ) * ( hrd->getTickDivisorMinus2() + 2 ) ) / ( m_pcCfg->getTargetBitrate() ) );
-#endif
 
               if( (UInt)ui64Tmp > maxDiff )
@@ -2178,5 +2117,4 @@
           m_seiWriter.writeSEImessage(nalu.m_Bitstream, pictureTimingSEI, pcSlice->getSPS());
           writeRBSPTrailingBits(nalu.m_Bitstream);
-#if L0045_NON_NESTED_SEI_RESTRICTIONS
           UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
           UInt offsetPosition = m_activeParameterSetSEIPresentInAU 
@@ -2189,10 +2127,5 @@
           accessUnit.insert(it, new NALUnitEBSP(nalu));
           m_pictureTimingSEIPresentInAU = true;
-#else
-          AccessUnit::iterator it = find_if(accessUnit.begin(), accessUnit.end(), mem_fun(&NALUnit::isSlice));
-          accessUnit.insert(it, new NALUnitEBSP(nalu));
-#endif
-        }
-#if K0180_SCALABLE_NESTING_SEI
+        }
           if ( m_pcCfg->getScalableNestingSEIEnabled() ) // put picture timing SEI into scalable nesting SEI
           {
@@ -2203,5 +2136,4 @@
             m_seiWriter.writeSEImessage(nalu.m_Bitstream, scalableNestingSEI, pcSlice->getSPS());
             writeRBSPTrailingBits(nalu.m_Bitstream);
-#if L0045_NON_NESTED_SEI_RESTRICTIONS
             UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
             UInt offsetPosition = m_activeParameterSetSEIPresentInAU 
@@ -2214,11 +2146,5 @@
             accessUnit.insert(it, new NALUnitEBSP(nalu));
             m_nestedPictureTimingSEIPresentInAU = true;
-#else
-            AccessUnit::iterator it = find_if(accessUnit.begin(), accessUnit.end(), mem_fun(&NALUnit::isSlice));
-            accessUnit.insert(it, new NALUnitEBSP(nalu));
-#endif
           }
-#endif
-
         }
         if( m_pcCfg->getDecodingUnitInfoSEIEnabled() && hrd->getSubPicCpbParamsPresentFlag() )
@@ -2232,8 +2158,6 @@
             tempSEI.m_decodingUnitIdx = i;
             tempSEI.m_duSptCpbRemovalDelay = pictureTimingSEI.m_duCpbRemovalDelayMinus1[i] + 1;
-#if L0044_DU_DPB_OUTPUT_DELAY_HRD
             tempSEI.m_dpbOutputDuDelayPresentFlag = false;
             tempSEI.m_picSptDpbOutputDuDelay = picSptDpbOutputDuDelay;
-#endif
 
             AccessUnit::iterator it;
@@ -2245,5 +2169,4 @@
               writeRBSPTrailingBits(nalu.m_Bitstream);
 
-#if L0045_NON_NESTED_SEI_RESTRICTIONS
               UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
               UInt offsetPosition = m_activeParameterSetSEIPresentInAU 
@@ -2255,8 +2178,4 @@
               }
               accessUnit.insert(it, new NALUnitEBSP(nalu));
-#else
-              it = find_if(accessUnit.begin(), accessUnit.end(), mem_fun(&NALUnit::isSlice));
-              accessUnit.insert(it, new NALUnitEBSP(nalu)); 
-#endif
             }
             else
@@ -2284,10 +2203,6 @@
         }
       }
-#if L0045_NON_NESTED_SEI_RESTRICTIONS
       xResetNonNestedSEIPresentFlags();
-#if K0180_SCALABLE_NESTING_SEI
       xResetNestedSEIPresentFlags();
-#endif
-#endif
       pcPic->getPicYuvRec()->copyToPic(pcPicYuvRecOut);
 
@@ -2445,5 +2360,6 @@
   }
   
-  assert (rpcPic->getPOC() == pocCurr);
+  assert( rpcPic != NULL );
+  assert( rpcPic->getPOC() == pocCurr );
   
   return;
@@ -2945,5 +2861,4 @@
 }
 
-#if L0045_NON_NESTED_SEI_RESTRICTIONS
 /** Function for finding the position to insert the first of APS and non-nested BP, PT, DU info SEI messages.
  * \param accessUnit Access Unit of the current picture
@@ -2965,7 +2880,5 @@
   return seiStartPos;
 }
-#endif
-
-#if L0386_DB_METRIC
+
 Void TEncGOP::dblMetric( TComPic* pcPic, UInt uiNumSlices )
 {
@@ -2981,4 +2894,6 @@
   const UInt noCol = (picWidth>>log2maxTB);
   const UInt noRows = (picHeight>>log2maxTB);
+  assert(noCol > 1);
+  assert(noRows > 1);
   UInt64 *colSAD = (UInt64*)malloc(noCol*sizeof(UInt64));
   UInt64 *rowSAD = (UInt64*)malloc(noRows*sizeof(UInt64));
@@ -3089,5 +3004,4 @@
   free(rowSAD);
 }
-#endif
 
 #if M0457_COL_PICTURE_SIGNALING
Index: branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncGOP.h
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncGOP.h	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncGOP.h	(revision 302)
@@ -127,13 +127,9 @@
   UInt                    m_tl0Idx;
   UInt                    m_rapIdx;
-#if L0045_NON_NESTED_SEI_RESTRICTIONS
   Bool                    m_activeParameterSetSEIPresentInAU;
   Bool                    m_bufferingPeriodSEIPresentInAU;
   Bool                    m_pictureTimingSEIPresentInAU;
-#if K0180_SCALABLE_NESTING_SEI
   Bool                    m_nestedBufferingPeriodSEIPresentInAU;
   Bool                    m_nestedPictureTimingSEIPresentInAU;
-#endif
-#endif
 public:
   TEncGOP();
@@ -186,10 +182,7 @@
   SEIDisplayOrientation*  xCreateSEIDisplayOrientation();
 
-#if J0149_TONE_MAPPING_SEI
   SEIToneMappingInfo*     xCreateSEIToneMappingInfo();
-#endif
 
   Void xCreateLeadingSEIMessages (/*SEIMessages seiMessages,*/ AccessUnit &accessUnit, TComSPS *sps);
-#if L0045_NON_NESTED_SEI_RESTRICTIONS
   Int xGetFirstSeiLocation (AccessUnit &accessUnit);
   Void xResetNonNestedSEIPresentFlags()
@@ -199,5 +192,4 @@
     m_pictureTimingSEIPresentInAU      = false;
   }
-#if K0180_SCALABLE_NESTING_SEI
   Void xResetNestedSEIPresentFlags()
   {
@@ -205,9 +197,5 @@
     m_nestedPictureTimingSEIPresentInAU      = false;
   }
-#endif
-#endif
-#if L0386_DB_METRIC
   Void dblMetric( TComPic* pcPic, UInt uiNumSlices );
-#endif
 #if M0457_COL_PICTURE_SIGNALING
   TComPic* getMotionPredIlp(TComSlice* pcSlice);
Index: branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncRateCtrl.cpp
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncRateCtrl.cpp	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncRateCtrl.cpp	(revision 302)
@@ -67,4 +67,8 @@
   m_bitsLeft            = 0;
   m_useLCUSeparateModel = false;
+#if M0036_RC_IMPROVEMENT
+  m_adaptiveBit         = 0;
+  m_lastLambda          = 0.0;
+#endif
 }
 
@@ -74,5 +78,9 @@
 }
 
+#if M0036_RC_IMPROVEMENT
+Void TEncRCSeq::create( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Int numberOfLevel, Bool useLCUSeparateModel, Int adaptiveBit )
+#else
 Void TEncRCSeq::create( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Int numberOfLevel, Bool useLCUSeparateModel )
+#endif
 {
   destroy();
@@ -101,9 +109,27 @@
     m_betaUpdate  = 0.025;
   }
-  else
+#if M0036_RC_IMPROVEMENT
+  else if ( m_seqTargetBpp < 0.2 )
   {
     m_alphaUpdate = 0.1;
     m_betaUpdate  = 0.05;
   }
+  else if ( m_seqTargetBpp < 0.5 )
+  {
+    m_alphaUpdate = 0.2;
+    m_betaUpdate  = 0.1;
+  }
+  else
+  {
+    m_alphaUpdate = 0.4;
+    m_betaUpdate  = 0.2;
+  }
+#else
+  else
+  {
+    m_alphaUpdate = 0.1;
+    m_betaUpdate  = 0.05;
+  }
+#endif
   m_averageBits     = (Int)(m_targetBits / totalFrames);
   Int picWidthInBU  = ( m_picWidth  % m_LCUWidth  ) == 0 ? m_picWidth  / m_LCUWidth  : m_picWidth  / m_LCUWidth  + 1;
@@ -146,4 +172,8 @@
   m_framesLeft = m_totalFrames;
   m_bitsLeft   = m_targetBits;
+#if M0036_RC_IMPROVEMENT
+  m_adaptiveBit = adaptiveBit;
+  m_lastLambda = 0.0;
+#endif
 }
 
@@ -203,7 +233,20 @@
     for ( Int i=0; i<m_numberOfLevel; i++ )
     {
+#if RATE_CONTROL_INTRA
+      if (i>0)
+      {
       m_picPara[i].m_alpha = 3.2003;
       m_picPara[i].m_beta  = -1.367;
     }
+      else
+      {
+        m_picPara[i].m_alpha = ALPHA;   
+        m_picPara[i].m_beta  = BETA2;
+      }
+#else
+      m_picPara[i].m_alpha = 3.2003;
+      m_picPara[i].m_beta  = -1.367;
+#endif
+    }
   }
   else
@@ -228,6 +271,11 @@
       for ( Int j=0; j<m_numberOfLCU; j++)
       {
+#if RATE_CONTROL_INTRA
+        m_LCUPara[i][j].m_alpha = m_picPara[i].m_alpha;
+        m_LCUPara[i][j].m_beta  = m_picPara[i].m_beta;
+#else
         m_LCUPara[i][j].m_alpha = 3.2003;
         m_LCUPara[i][j].m_beta  = -1.367;
+#endif
       }
     }
@@ -251,4 +299,5 @@
 }
 
+#if !RATE_CONTROL_INTRA
 Int TEncRCSeq::getRefineBitsForIntra( Int orgBits )
 {
@@ -264,4 +313,18 @@
   return orgBits * 10;
 }
+#endif
+
+#if M0036_RC_IMPROVEMENT
+Void TEncRCSeq::setAllBitRatio( Double basicLambda, Double* equaCoeffA, Double* equaCoeffB )
+{
+  Int* bitsRatio = new Int[m_GOPSize];
+  for ( Int i=0; i<m_GOPSize; i++ )
+  {
+    bitsRatio[i] = (Int)( equaCoeffA[i] * pow( basicLambda, equaCoeffB[i] ) * m_numberOfPixel );
+  }
+  initBitsRatio( bitsRatio );
+  delete[] bitsRatio;
+}
+#endif
 
 //GOP level
@@ -286,4 +349,66 @@
   Int targetBits = xEstGOPTargetBits( encRCSeq, numPic );
 
+#if M0036_RC_IMPROVEMENT
+  if ( encRCSeq->getAdaptiveBits() > 0 && encRCSeq->getLastLambda() > 0.1 )
+  {
+    Double targetBpp = (Double)targetBits / encRCSeq->getNumPixel();
+    Double basicLambda = 0.0;
+    Double* lambdaRatio = new Double[encRCSeq->getGOPSize()];
+    Double* equaCoeffA = new Double[encRCSeq->getGOPSize()];
+    Double* equaCoeffB = new Double[encRCSeq->getGOPSize()];
+
+    if ( encRCSeq->getAdaptiveBits() == 1 )   // for GOP size =4, low delay case
+    {
+      if ( encRCSeq->getLastLambda() < 120.0 )
+      {
+        lambdaRatio[1] = 0.725 * log( encRCSeq->getLastLambda() ) + 0.5793;
+        lambdaRatio[0] = 1.3 * lambdaRatio[1];
+        lambdaRatio[2] = 1.3 * lambdaRatio[1];
+        lambdaRatio[3] = 1.0;
+      }
+      else
+      {
+        lambdaRatio[0] = 5.0;
+        lambdaRatio[1] = 4.0;
+        lambdaRatio[2] = 5.0;
+        lambdaRatio[3] = 1.0;
+      }
+    }
+    else if ( encRCSeq->getAdaptiveBits() == 2 )  // for GOP size = 8, random access case
+    {
+      if ( encRCSeq->getLastLambda() < 90.0 )
+      {
+        lambdaRatio[0] = 1.0;
+        lambdaRatio[1] = 0.725 * log( encRCSeq->getLastLambda() ) + 0.7963;
+        lambdaRatio[2] = 1.3 * lambdaRatio[1];
+        lambdaRatio[3] = 3.25 * lambdaRatio[1];
+        lambdaRatio[4] = 3.25 * lambdaRatio[1];
+        lambdaRatio[5] = 1.3  * lambdaRatio[1];
+        lambdaRatio[6] = 3.25 * lambdaRatio[1];
+        lambdaRatio[7] = 3.25 * lambdaRatio[1];
+      }
+      else
+      {
+        lambdaRatio[0] = 1.0;
+        lambdaRatio[1] = 4.0;
+        lambdaRatio[2] = 5.0;
+        lambdaRatio[3] = 12.3;
+        lambdaRatio[4] = 12.3;
+        lambdaRatio[5] = 5.0;
+        lambdaRatio[6] = 12.3;
+        lambdaRatio[7] = 12.3;
+      }
+    }
+
+    xCalEquaCoeff( encRCSeq, lambdaRatio, equaCoeffA, equaCoeffB, encRCSeq->getGOPSize() );
+    basicLambda = xSolveEqua( targetBpp, equaCoeffA, equaCoeffB, encRCSeq->getGOPSize() );
+    encRCSeq->setAllBitRatio( basicLambda, equaCoeffA, equaCoeffB );
+
+    delete []lambdaRatio;
+    delete []equaCoeffA;
+    delete []equaCoeffB;
+  }
+#endif
+
   m_picTargetBitInGOP = new Int[numPic];
   Int i;
@@ -297,5 +422,9 @@
   {
     currPicRatio = encRCSeq->getBitRatio( i );
+#if M0036_RC_IMPROVEMENT
+    m_picTargetBitInGOP[i] = (Int)( ((Double)targetBits) * currPicRatio / totalPicRatio );
+#else
     m_picTargetBitInGOP[i] = targetBits * currPicRatio / totalPicRatio;
+#endif
   }
 
@@ -306,4 +435,52 @@
   m_bitsLeft     = m_targetBits;
 }
+
+#if M0036_RC_IMPROVEMENT
+Void TEncRCGOP::xCalEquaCoeff( TEncRCSeq* encRCSeq, Double* lambdaRatio, Double* equaCoeffA, Double* equaCoeffB, Int GOPSize )
+{
+  for ( Int i=0; i<GOPSize; i++ )
+  {
+    Int frameLevel = encRCSeq->getGOPID2Level(i);
+    Double alpha   = encRCSeq->getPicPara(frameLevel).m_alpha;
+    Double beta    = encRCSeq->getPicPara(frameLevel).m_beta;
+    equaCoeffA[i] = pow( 1.0/alpha, 1.0/beta ) * pow( lambdaRatio[i], 1.0/beta );
+    equaCoeffB[i] = 1.0/beta;
+  }
+}
+
+Double TEncRCGOP::xSolveEqua( Double targetBpp, Double* equaCoeffA, Double* equaCoeffB, Int GOPSize )
+{
+  Double solution = 100.0;
+  Double minNumber = 0.1;
+  Double maxNumber = 10000.0;
+  for ( Int i=0; i<g_RCIterationNum; i++ )
+  { 
+    Double fx = 0.0;
+    for ( Int j=0; j<GOPSize; j++ )
+    {
+      fx += equaCoeffA[j] * pow( solution, equaCoeffB[j] );
+    }
+
+    if ( fabs( fx - targetBpp ) < 0.000001 )
+    {
+      break;
+    }
+
+    if ( fx > targetBpp )
+    {
+      minNumber = solution;
+      solution = ( solution + maxNumber ) / 2.0;
+    }
+    else
+    {
+      maxNumber = solution;
+      solution = ( solution + minNumber ) / 2.0;
+    }
+  }
+
+  solution = Clip3( 0.1, 10000.0, solution );
+  return solution;
+}
+#endif
 
 Void TEncRCGOP::destroy()
@@ -357,7 +534,11 @@
 
   m_LCUs         = NULL;
+#if !M0036_RC_IMPROVEMENT
   m_lastPicture  = NULL;
+#endif
   m_picActualHeaderBits = 0;
+#if !M0036_RC_IMPROVEMENT
   m_totalMAD            = 0.0;
+#endif
   m_picActualBits       = 0;
   m_picQP               = 0;
@@ -384,5 +565,9 @@
   }
 
+#if M0036_RC_IMPROVEMENT
+  targetBits  = Int( ((Double)GOPbitsLeft) * currPicRatio / totalPicRatio );
+#else
   targetBits  = Int( GOPbitsLeft * currPicRatio / totalPicRatio );
+#endif
 
   if ( targetBits < 100 )
@@ -480,5 +665,9 @@
       m_LCUs[LCUIdx].m_lambda     = 0.0;
       m_LCUs[LCUIdx].m_targetBits = 0;
+#if M0036_RC_IMPROVEMENT
+      m_LCUs[LCUIdx].m_bitWeight  = 1.0;
+#else
       m_LCUs[LCUIdx].m_MAD        = 0.0;
+#endif
       Int currWidth  = ( (i == picWidthInLCU -1) ? picWidth  - LCUWidth *(picWidthInLCU -1) : LCUWidth  );
       Int currHeight = ( (j == picHeightInLCU-1) ? picHeight - LCUHeight*(picHeightInLCU-1) : LCUHeight );
@@ -487,9 +676,12 @@
   }
   m_picActualHeaderBits = 0;
+#if !M0036_RC_IMPROVEMENT
   m_totalMAD            = 0.0;
+#endif
   m_picActualBits       = 0;
   m_picQP               = 0;
   m_picLambda           = 0.0;
 
+#if !M0036_RC_IMPROVEMENT
   m_lastPicture = NULL;
   list<TEncRCPic*>::reverse_iterator it;
@@ -502,4 +694,5 @@
     }
   }
+#endif
 }
 
@@ -515,10 +708,28 @@
 }
 
+
+#if RATE_CONTROL_INTRA
+Double TEncRCPic::estimatePicLambda( list<TEncRCPic*>& listPreviousPictures, SliceType eSliceType)
+#else
 Double TEncRCPic::estimatePicLambda( list<TEncRCPic*>& listPreviousPictures )
+#endif
 {
   Double alpha         = m_encRCSeq->getPicPara( m_frameLevel ).m_alpha;
   Double beta          = m_encRCSeq->getPicPara( m_frameLevel ).m_beta;
   Double bpp       = (Double)m_targetBits/(Double)m_numberOfPixel;
+#if RATE_CONTROL_INTRA
+  Double estLambda;
+  if (eSliceType == I_SLICE)
+  {
+    estLambda = calculateLambdaIntra(alpha, beta, pow(m_totalCostIntra/(Double)m_numberOfPixel, BETA1), bpp); 
+  }
+  else
+  {
+    estLambda = alpha * pow( bpp, beta );
+  }
+#else
   Double estLambda = alpha * pow( bpp, beta );
+#endif  
+  
   Double lastLevelLambda = -1.0;
   Double lastPicLambda   = -1.0;
@@ -566,4 +777,42 @@
 
   m_estPicLambda = estLambda;
+
+#if M0036_RC_IMPROVEMENT
+  Double totalWeight = 0.0;
+  // initial BU bit allocation weight
+  for ( Int i=0; i<m_numberOfLCU; i++ )
+  {
+#if RC_FIX
+    Double alphaLCU, betaLCU;
+    if ( m_encRCSeq->getUseLCUSeparateModel() )
+    {
+      alphaLCU = m_encRCSeq->getLCUPara( m_frameLevel, i ).m_alpha;
+      betaLCU  = m_encRCSeq->getLCUPara( m_frameLevel, i ).m_beta;
+    }
+    else
+    {
+      alphaLCU = m_encRCSeq->getPicPara( m_frameLevel ).m_alpha;
+      betaLCU  = m_encRCSeq->getPicPara( m_frameLevel ).m_beta;
+    }
+#else
+    Double alphaLCU = m_encRCSeq->getLCUPara( m_frameLevel, i ).m_alpha;
+    Double betaLCU  = m_encRCSeq->getLCUPara( m_frameLevel, i ).m_beta;
+#endif
+
+    m_LCUs[i].m_bitWeight =  m_LCUs[i].m_numberOfPixel * pow( estLambda/alphaLCU, 1.0/betaLCU );
+
+    if ( m_LCUs[i].m_bitWeight < 0.01 )
+    {
+      m_LCUs[i].m_bitWeight = 0.01;
+    }
+    totalWeight += m_LCUs[i].m_bitWeight;
+  }
+  for ( Int i=0; i<m_numberOfLCU; i++ )
+  {
+    Double BUTargetBits = m_targetBits * m_LCUs[i].m_bitWeight / totalWeight;
+    m_LCUs[i].m_bitWeight = BUTargetBits;
+  }
+#endif
+
   return estLambda;
 }
@@ -607,12 +856,47 @@
 }
 
+#if RATE_CONTROL_INTRA
+Double TEncRCPic::getLCUTargetBpp(SliceType eSliceType)  
+#else 
 Double TEncRCPic::getLCUTargetBpp()
+#endif
 {
   Int   LCUIdx    = getLCUCoded();
   Double bpp      = -1.0;
   Int avgBits     = 0;
+#if !M0036_RC_IMPROVEMENT
   Double totalMAD = -1.0;
   Double MAD      = -1.0;
-
+#endif
+
+#if RATE_CONTROL_INTRA
+  if (eSliceType == I_SLICE){
+    Int noOfLCUsLeft = m_numberOfLCU - LCUIdx + 1;
+    Int bitrateWindow = min(4,noOfLCUsLeft);
+    Double MAD      = getLCU(LCUIdx).m_costIntra;
+
+    if (m_remainingCostIntra > 0.1 )
+    {
+      Double weightedBitsLeft = (m_bitsLeft*bitrateWindow+(m_bitsLeft-getLCU(LCUIdx).m_targetBitsLeft)*noOfLCUsLeft)/(Double)bitrateWindow;
+      avgBits = Int( MAD*weightedBitsLeft/m_remainingCostIntra );
+    }
+    else
+    {
+      avgBits = Int( m_bitsLeft / m_LCULeft );
+    }
+    m_remainingCostIntra -= MAD;
+  }
+  else
+  {
+#endif
+#if M0036_RC_IMPROVEMENT
+  Double totalWeight = 0;
+  for ( Int i=LCUIdx; i<m_numberOfLCU; i++ )
+  {
+    totalWeight += m_LCUs[i].m_bitWeight;
+  }
+  Int realInfluenceLCU = min( g_RCLCUSmoothWindowSize, getLCULeft() );
+  avgBits = (Int)( m_LCUs[LCUIdx].m_bitWeight - ( totalWeight - m_bitsLeft ) / realInfluenceLCU + 0.5 );
+#else
   if ( m_lastPicture == NULL )
   {
@@ -637,16 +921,13 @@
     }
   }
-
-#if L0033_RC_BUGFIX
+#endif
+#if RATE_CONTROL_INTRA
+  }
+#endif
+
   if ( avgBits < 1 )
   {
     avgBits = 1;
   }
-#else
-  if ( avgBits < 5 )
-  {
-    avgBits = 5;
-  }
-#endif
 
   bpp = ( Double )avgBits/( Double )m_LCUs[ LCUIdx ].m_numberOfPixel;
@@ -716,9 +997,5 @@
   //for Lambda clip, LCU level clip
   Int clipNeighbourQP = g_RCInvalidQPValue;
-#if L0033_RC_BUGFIX
   for ( int i=LCUIdx - 1; i>=0; i-- )
-#else
-  for ( int i=LCUIdx; i>=0; i-- )
-#endif
   {
     if ( (getLCU(i)).m_QP > g_RCInvalidQPValue )
@@ -773,6 +1050,11 @@
     beta  *= ( 1.0 - m_encRCSeq->getBetaUpdate() / 2.0 );
 
+#if M0036_RC_IMPROVEMENT
+    alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha );
+    beta  = Clip3( g_RCBetaMinValue,  g_RCBetaMaxValue,  beta  );
+#else
     alpha = Clip3( 0.05, 20.0, alpha );
     beta  = Clip3( -3.0, -0.1, beta  );
+#endif
 
     TRCParameter rcPara;
@@ -787,9 +1069,18 @@
   alpha += m_encRCSeq->getAlphaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * alpha;
   double lnbpp = log( bpp );
+#if M0036_RC_IMPROVEMENT
+  lnbpp = Clip3( -5.0, -0.1, lnbpp );
+#else
   lnbpp = Clip3( -5.0, 1.0, lnbpp );
+#endif
   beta  += m_encRCSeq->getBetaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * lnbpp;
 
+#if M0036_RC_IMPROVEMENT
+  alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha );
+  beta  = Clip3( g_RCBetaMinValue,  g_RCBetaMaxValue,  beta  );
+#else
   alpha = Clip3( 0.05, 20.0, alpha );
   beta  = Clip3( -3.0, -0.1, beta  );
+#endif
   TRCParameter rcPara;
   rcPara.m_alpha = alpha;
@@ -799,4 +1090,5 @@
 }
 
+#if !M0036_RC_IMPROVEMENT
 Double TEncRCPic::getEffectivePercentage()
 {
@@ -816,4 +1108,5 @@
   return effectivePixelPercentage;
 }
+#endif
 
 Double TEncRCPic::calAverageQP()
@@ -871,5 +1164,13 @@
 }
 
+#if M0036_RC_IMPROVEMENT
+#if RATE_CONTROL_INTRA
+Void TEncRCPic::updateAfterPicture( Int actualHeaderBits, Int actualTotalBits, Double averageQP, Double averageLambda, SliceType eSliceType)
+#else
+Void TEncRCPic::updateAfterPicture( Int actualHeaderBits, Int actualTotalBits, Double averageQP, Double averageLambda )
+#endif
+#else
 Void TEncRCPic::updateAfterPicture( Int actualHeaderBits, Int actualTotalBits, Double averageQP, Double averageLambda, Double effectivePercentage )
+#endif
 {
   m_picActualHeaderBits = actualHeaderBits;
@@ -884,12 +1185,21 @@
   }
   m_picLambda           = averageLambda;
+#if !M0036_RC_IMPROVEMENT
   for ( Int i=0; i<m_numberOfLCU; i++ )
   {
     m_totalMAD += m_LCUs[i].m_MAD;
   }
+#endif
 
   Double alpha = m_encRCSeq->getPicPara( m_frameLevel ).m_alpha;
   Double beta  = m_encRCSeq->getPicPara( m_frameLevel ).m_beta;
-
+#if RATE_CONTROL_INTRA
+  if (eSliceType == I_SLICE)
+  {
+    updateAlphaBetaIntra(&alpha, &beta);
+  }
+  else
+  {
+#endif
   // update parameters
   Double picActualBits = ( Double )m_picActualBits;
@@ -898,11 +1208,20 @@
   Double inputLambda   = m_picLambda;
 
+#if M0036_RC_IMPROVEMENT
+  if ( inputLambda < 0.01 || calLambda < 0.01 || picActualBpp < 0.0001 )
+#else
   if ( inputLambda < 0.01 || calLambda < 0.01 || picActualBpp < 0.0001 || effectivePercentage < 0.05 )
+#endif
   {
     alpha *= ( 1.0 - m_encRCSeq->getAlphaUpdate() / 2.0 );
     beta  *= ( 1.0 - m_encRCSeq->getBetaUpdate() / 2.0 );
 
+#if M0036_RC_IMPROVEMENT
+    alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha );
+    beta  = Clip3( g_RCBetaMinValue,  g_RCBetaMaxValue,  beta  );
+#else
     alpha = Clip3( 0.05, 20.0, alpha );
     beta  = Clip3( -3.0, -0.1, beta  );
+#endif
     TRCParameter rcPara;
     rcPara.m_alpha = alpha;
@@ -916,9 +1235,21 @@
   alpha += m_encRCSeq->getAlphaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * alpha;
   double lnbpp = log( picActualBpp );
+#if M0036_RC_IMPROVEMENT
+  lnbpp = Clip3( -5.0, -0.1, lnbpp );
+#else
   lnbpp = Clip3( -5.0, 1.0, lnbpp );
+#endif
   beta  += m_encRCSeq->getBetaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * lnbpp;
 
+#if M0036_RC_IMPROVEMENT
+  alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha );
+  beta  = Clip3( g_RCBetaMinValue,  g_RCBetaMaxValue,  beta  );
+#else
   alpha = Clip3( 0.05, 20.0, alpha );
   beta  = Clip3( -3.0, -0.1, beta  );
+#endif
+#if RATE_CONTROL_INTRA
+  }
+#endif
 
   TRCParameter rcPara;
@@ -927,5 +1258,105 @@
 
   m_encRCSeq->setPicPara( m_frameLevel, rcPara );
-}
+
+#if M0036_RC_IMPROVEMENT
+  if ( m_frameLevel == 1 )
+  {
+    Double currLambda = Clip3( 0.1, 10000.0, m_picLambda );
+    Double updateLastLambda = g_RCWeightHistoryLambda * m_encRCSeq->getLastLambda() + g_RCWeightCurrentLambda * currLambda;
+    m_encRCSeq->setLastLambda( updateLastLambda );
+  }
+#endif
+}
+
+#if RATE_CONTROL_INTRA
+Int TEncRCPic::getRefineBitsForIntra( Int orgBits )
+{
+  Double alpha=0.25, beta=0.5582;
+  Int iIntraBits;
+
+  if (orgBits*40 < m_numberOfPixel)
+  {
+    alpha=0.25;
+  }
+  else
+  {
+    alpha=0.30;
+  }
+
+  iIntraBits = (Int)(alpha* pow(m_totalCostIntra*4.0/(Double)orgBits, beta)*(Double)orgBits+0.5);
+  
+  return iIntraBits;
+}
+
+Double TEncRCPic::calculateLambdaIntra(double alpha, double beta, double MADPerPixel, double bitsPerPixel)
+{
+  return ( (alpha/256.0) * pow( MADPerPixel/bitsPerPixel, beta ) );
+}
+
+Void TEncRCPic::updateAlphaBetaIntra(double *alpha, double *beta)
+{
+  Double lnbpp = log(pow(m_totalCostIntra / (Double)m_numberOfPixel, BETA1));
+  Double diffLambda = (*beta)*(log((Double)m_picActualBits)-log((Double)m_targetBits));
+
+  diffLambda = Clip3(-0.125, 0.125, 0.25*diffLambda);
+  *alpha    =  (*alpha) * exp(diffLambda);
+  *beta     =  (*beta) + diffLambda / lnbpp;
+}
+
+
+Void TEncRCPic::getLCUInitTargetBits()  
+{
+  Int iAvgBits     = 0;
+
+  m_remainingCostIntra = m_totalCostIntra;
+  for (Int i=m_numberOfLCU-1; i>=0; i--)
+  {
+    iAvgBits += Int(m_targetBits * getLCU(i).m_costIntra/m_totalCostIntra);
+    getLCU(i).m_targetBitsLeft = iAvgBits;
+  }
+}
+
+
+Double TEncRCPic::getLCUEstLambdaAndQP(Double bpp, Int clipPicQP, Int *estQP) 
+{
+  Int   LCUIdx = getLCUCoded();
+
+  Double   alpha = m_encRCSeq->getPicPara( m_frameLevel ).m_alpha;
+  Double   beta  = m_encRCSeq->getPicPara( m_frameLevel ).m_beta;
+
+  Double costPerPixel = getLCU(LCUIdx).m_costIntra/(Double)getLCU(LCUIdx).m_numberOfPixel;
+  costPerPixel = pow(costPerPixel, BETA1);
+  Double estLambda = calculateLambdaIntra(alpha, beta, costPerPixel, bpp);
+
+  Int clipNeighbourQP = g_RCInvalidQPValue;
+  for (int i=LCUIdx-1; i>=0; i--)
+  {
+    if ((getLCU(i)).m_QP > g_RCInvalidQPValue)
+    {
+      clipNeighbourQP = getLCU(i).m_QP;
+      break;
+    }
+  }
+
+  Int minQP = clipPicQP - 2;
+  Int maxQP = clipPicQP + 2;
+
+  if ( clipNeighbourQP > g_RCInvalidQPValue )
+  {
+    maxQP = min(clipNeighbourQP + 1, maxQP); 
+    minQP = max(clipNeighbourQP - 1, minQP); 
+  }
+
+  Double maxLambda=exp(((Double)(maxQP+0.49)-13.7122)/4.2005);
+  Double minLambda=exp(((Double)(minQP-0.49)-13.7122)/4.2005);
+
+  estLambda = Clip3(minLambda, maxLambda, estLambda);
+
+  *estQP = Int( 4.2005 * log(estLambda) + 13.7122 + 0.5 );
+  *estQP = Clip3(minQP, maxQP, *estQP);
+
+  return estLambda;
+}
+#endif
 
 TEncRateCtrl::TEncRateCtrl()
@@ -961,5 +1392,9 @@
 }
 
+#if M0036_RC_IMPROVEMENT
+Void TEncRateCtrl::init( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Int keepHierBits, Bool useLCUSeparateModel, GOPEntry  GOPList[MAX_GOP] )
+#else
 Void TEncRateCtrl::init( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Bool keepHierBits, Bool useLCUSeparateModel, GOPEntry  GOPList[MAX_GOP] )
+#endif
 {
   destroy();
@@ -976,5 +1411,10 @@
 
   Int numberOfLevel = 1;
+#if M0036_RC_IMPROVEMENT
+  Int adaptiveBit = 0;
+  if ( keepHierBits > 0 )
+#else
   if ( keepHierBits )
+#endif
   {
     numberOfLevel = Int( log((Double)GOPSize)/log(2.0) + 0.5 ) + 1;
@@ -998,5 +1438,10 @@
     }
   }
+
+#if M0036_RC_IMPROVEMENT
+  if ( keepHierBits > 0 )
+#else
   if ( keepHierBits )
+#endif
   {
     Double bpp = (Double)( targetBitrate / (Double)( frameRate*picWidth*picHeight ) );
@@ -1031,4 +1476,10 @@
         bitsRatio[3] = 14;
       }
+#if M0036_RC_IMPROVEMENT
+      if ( keepHierBits == 2 )
+      {
+        adaptiveBit = 1;
+      }
+#endif
     }
     else if ( GOPSize == 8 && !isLowdelay )
@@ -1078,8 +1529,18 @@
         bitsRatio[7] = 1;
       }
+#if M0036_RC_IMPROVEMENT
+      if ( keepHierBits == 2 )
+      {
+        adaptiveBit = 2;
+      }
+#endif
     }
     else
     {
+#if M0036_RC_IMPROVEMENT
+      printf( "\n hierarchical bit allocation is not support for the specified coding structure currently.\n" );
+#else
       printf( "\n hierarchical bit allocation is not support for the specified coding structure currently." );
+#endif
     }
   }
@@ -1094,5 +1555,9 @@
     }
   }
+#if M0036_RC_IMPROVEMENT
+  if ( keepHierBits > 0 )
+#else
   if ( keepHierBits )
+#endif
   {
     if ( GOPSize == 4 && isLowdelay )
@@ -1129,5 +1594,9 @@
 
   m_encRCSeq = new TEncRCSeq;
+#if M0036_RC_IMPROVEMENT
+  m_encRCSeq->create( totalFrames, targetBitrate, frameRate, GOPSize, picWidth, picHeight, LCUWidth, LCUHeight, numberOfLevel, useLCUSeparateModel, adaptiveBit );
+#else
   m_encRCSeq->create( totalFrames, targetBitrate, frameRate, GOPSize, picWidth, picHeight, LCUWidth, LCUHeight, numberOfLevel, useLCUSeparateModel );
+#endif
   m_encRCSeq->initBitsRatio( bitsRatio );
   m_encRCSeq->initGOPID2Level( GOPID2Level );
Index: branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncRateCtrl.h
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncRateCtrl.h	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncRateCtrl.h	(revision 302)
@@ -65,4 +65,20 @@
 const Double g_RCWeightPicTargetBitInGOP    = 0.9;
 const Double g_RCWeightPicRargetBitInBuffer = 1.0 - g_RCWeightPicTargetBitInGOP;
+#if M0036_RC_IMPROVEMENT
+const Int g_RCIterationNum = 20;
+const Double g_RCWeightHistoryLambda = 0.5;
+const Double g_RCWeightCurrentLambda = 1.0 - g_RCWeightHistoryLambda;
+const Int g_RCLCUSmoothWindowSize = 4;
+const Double g_RCAlphaMinValue = 0.05;
+const Double g_RCAlphaMaxValue = 500.0;
+const Double g_RCBetaMinValue  = -3.0;
+const Double g_RCBetaMaxValue  = -0.1;
+#endif
+
+#if RATE_CONTROL_INTRA
+#define ALPHA     6.7542;
+#define BETA1     1.2517
+#define BETA2     1.7860
+#endif
 
 struct TRCLCU
@@ -72,6 +88,14 @@
   Int m_targetBits;
   Double m_lambda;
+#if M0036_RC_IMPROVEMENT
+  Double m_bitWeight;
+#else
   Double m_MAD;
+#endif
   Int m_numberOfPixel;
+#if RATE_CONTROL_INTRA
+  Double m_costIntra;
+  Int m_targetBitsLeft;
+#endif
 };
 
@@ -89,5 +113,9 @@
 
 public:
+#if M0036_RC_IMPROVEMENT
+  Void create( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Int numberOfLevel, Bool useLCUSeparateModel, Int adaptiveBit );
+#else
   Void create( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Int numberOfLevel, Bool useLCUSeparateModel );
+#endif
   Void destroy();
   Void initBitsRatio( Int bitsRatio[] );
@@ -96,5 +124,10 @@
   Void initLCUPara( TRCParameter** LCUPara = NULL );    // NULL to initial with default value
   Void updateAfterPic ( Int bits );
+#if !RATE_CONTROL_INTRA
   Int  getRefineBitsForIntra( Int orgBits );
+#endif
+#if M0036_RC_IMPROVEMENT
+  Void setAllBitRatio( Double basicLambda, Double* equaCoeffA, Double* equaCoeffB );
+#endif
 
 public:
@@ -134,4 +167,10 @@
   Double getBetaUpdate()                { return m_betaUpdate; }
 
+#if M0036_RC_IMPROVEMENT
+  Int    getAdaptiveBits()              { return m_adaptiveBit;  }
+  Double getLastLambda()                { return m_lastLambda;   }
+  Void   setLastLambda( Double lamdba ) { m_lastLambda = lamdba; }
+#endif
+
 private:
   Int m_totalFrames;
@@ -160,4 +199,9 @@
   Double m_betaUpdate;
   Bool m_useLCUSeparateModel;
+
+#if M0036_RC_IMPROVEMENT
+  Int m_adaptiveBit;
+  Double m_lastLambda;
+#endif
 };
 
@@ -175,4 +219,8 @@
 private:
   Int  xEstGOPTargetBits( TEncRCSeq* encRCSeq, Int GOPSize );
+#if M0036_RC_IMPROVEMENT
+  Void   xCalEquaCoeff( TEncRCSeq* encRCSeq, Double* lambdaRatio, Double* equaCoeffA, Double* equaCoeffB, Int GOPSize );
+  Double xSolveEqua( Double targetBpp, Double* equaCoeffA, Double* equaCoeffB, Int GOPSize );
+#endif
 
 public:
@@ -203,15 +251,38 @@
   Void destroy();
 
+#if !RATE_CONTROL_INTRA
   Double estimatePicLambda( list<TEncRCPic*>& listPreviousPictures );
+#endif
   Int    estimatePicQP    ( Double lambda, list<TEncRCPic*>& listPreviousPictures );
+#if RATE_CONTROL_INTRA
+  Int    getRefineBitsForIntra(Int orgBits);
+  Double calculateLambdaIntra(double alpha, double beta, double MADPerPixel, double bitsPerPixel);
+  Double estimatePicLambda( list<TEncRCPic*>& listPreviousPictures, SliceType eSliceType);
+
+  Void   updateAlphaBetaIntra(double *alpha, double *beta);
+
+  Double getLCUTargetBpp(SliceType eSliceType);
+  Double getLCUEstLambdaAndQP(Double bpp, Int clipPicQP, Int *estQP);
+#else
   Double getLCUTargetBpp();
+#endif
   Double getLCUEstLambda( Double bpp );
   Int    getLCUEstQP( Double lambda, Int clipPicQP );
 
   Void updateAfterLCU( Int LCUIdx, Int bits, Int QP, Double lambda, Bool updateLCUParameter = true );
+#if M0036_RC_IMPROVEMENT
+#if RATE_CONTROL_INTRA
+  Void updateAfterPicture( Int actualHeaderBits, Int actualTotalBits, Double averageQP, Double averageLambda, SliceType eSliceType);
+#else
+  Void updateAfterPicture( Int actualHeaderBits, Int actualTotalBits, Double averageQP, Double averageLambda );
+#endif
+#else
   Void updateAfterPicture( Int actualHeaderBits, Int actualTotalBits, Double averageQP, Double averageLambda, Double effectivePercentage );
+#endif
 
   Void addToPictureLsit( list<TEncRCPic*>& listPreviousPictures );
+#if !M0036_RC_IMPROVEMENT
   Double getEffectivePercentage();
+#endif
   Double calAverageQP();
   Double calAverageLambda();
@@ -229,5 +300,7 @@
   Int  getNumberOfLCU()                                   { return m_numberOfLCU; }
   Int  getTargetBits()                                    { return m_targetBits; }
+#if !RATE_CONTROL_INTRA 
   Void setTargetBits( Int bits )                          { m_targetBits = bits; }
+#endif
   Int  getEstHeaderBits()                                 { return m_estHeaderBits; }
   Int  getLCULeft()                                       { return m_LCULeft; }
@@ -239,6 +312,14 @@
   TRCLCU& getLCU( Int LCUIdx )                            { return m_LCUs[LCUIdx]; }
   Int  getPicActualHeaderBits()                           { return m_picActualHeaderBits; }
+#if !M0036_RC_IMPROVEMENT
   Double getTotalMAD()                                    { return m_totalMAD; }
   Void   setTotalMAD( Double MAD )                        { m_totalMAD = MAD; }
+#endif
+#if RATE_CONTROL_INTRA
+  Void setTargetBits( Int bits )                          { m_targetBits = bits; m_bitsLeft = bits;}
+  Void setTotalIntraCost(Double cost)                     { m_totalCostIntra = cost; }
+  Void getLCUInitTargetBits();
+#endif
+
   Int  getPicActualBits()                                 { return m_picActualBits; }
   Int  getPicActualQP()                                   { return m_picQP; }
@@ -267,9 +348,17 @@
   TRCLCU* m_LCUs;
   Int m_picActualHeaderBits;    // only SH and potential APS
+#if !M0036_RC_IMPROVEMENT
   Double m_totalMAD;
+#endif
+#if RATE_CONTROL_INTRA
+  Double m_totalCostIntra; 
+  Double m_remainingCostIntra;
+#endif
   Int m_picActualBits;          // the whole picture, including header
   Int m_picQP;                  // in integer form
   Double m_picLambda;
+#if !M0036_RC_IMPROVEMENT
   TEncRCPic* m_lastPicture;
+#endif
 };
 
@@ -281,5 +370,9 @@
 
 public:
+#if M0036_RC_IMPROVEMENT
+  Void init( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Int keepHierBits, Bool useLCUSeparateModel, GOPEntry GOPList[MAX_GOP] );
+#else
   Void init( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Bool keepHierBits, Bool useLCUSeparateModel, GOPEntry GOPList[MAX_GOP] );
+#endif
   Void destroy();
   Void initRCPic( Int frameLevel );
Index: branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp	(revision 302)
@@ -299,5 +299,7 @@
         m_iTypePartBest[iPartIdx] = -1;
         if( m_bUseSBACRD )
+        {
           m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[pOnePart->PartLevel][CI_TEMP_BEST] );
+        }
       }
     }
Index: branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncSearch.cpp
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncSearch.cpp	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncSearch.cpp	(revision 302)
@@ -1410,5 +1410,4 @@
   
 #if HHI_RQT_INTRA_SPEEDUP
-#if L0232_RD_PENALTY
   Int maxTuSize = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize();
   Int isIntraSlice = (pcCU->getSlice()->getSliceType() == I_SLICE);
@@ -1427,12 +1426,8 @@
   }
   if( bCheckFirst && noSplitIntraMaxTuSize )
+  {
+    bCheckSplit = false;
+  }
 #else
-  if( bCheckFirst && bCheckFull )
-#endif
-  {
-    bCheckSplit = false;
-  }
-#else
-#if L0232_RD_PENALTY
   Int maxTuSize = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize();
   Int isIntraSlice = (pcCU->getSlice()->getSliceType() == I_SLICE);
@@ -1442,5 +1437,4 @@
     bCheckFull    = ( uiLog2TrSize  <= min(maxTuSize,4));
   }
-#endif
 #endif
   Double  dSingleCost   = MAX_DOUBLE;
@@ -1617,10 +1611,8 @@
       //----- determine rate and r-d cost -----
       UInt uiSingleBits = xGetIntraBitsQT( pcCU, uiTrDepth, uiAbsPartIdx, true, !bLumaOnly, false );
-#if L0232_RD_PENALTY
       if(m_pcEncCfg->getRDpenalty() && (uiLog2TrSize==5) && !isIntraSlice)
       {
         uiSingleBits=uiSingleBits*4; 
       }
-#endif
       dSingleCost       = m_pcRdCost->calcRdCost( uiSingleBits, uiSingleDistY + uiSingleDistC );
     }
@@ -3096,12 +3088,4 @@
   Int iHeight = 0; 
 
-#if 0 //REF_IDX_FRAMEWORK  // HM bug fix
-  for( UInt uiMergeCand = 0; uiMergeCand < pcCU->getSlice()->getMaxNumMergeCand(); ++uiMergeCand )
-  {
-    uhInterDirNeighbours[uiMergeCand] = 0;
-    cMvFieldNeighbours[0 + 2*uiMergeCand].setMvField(TComMv(), NOT_VALID);
-    cMvFieldNeighbours[1 + 2*uiMergeCand].setMvField(TComMv(), NOT_VALID);
-  }
-#endif
   pcCU->getPartIndexAndSize( iPUIdx, uiAbsPartIdx, iWidth, iHeight );
   UInt uiDepth = pcCU->getDepth( uiAbsPartIdx );
@@ -3280,10 +3264,8 @@
     UInt          uiBitsTempL0[MAX_NUM_REF];
 
-#if L0034_COMBINED_LIST_CLEANUP
     TComMv        mvValidList1;
     Int           refIdxValidList1 = 0;
     UInt          bitsValidList1 = MAX_UINT;
     UInt          costValidList1 = MAX_UINT;
-#endif
 
     xGetBlkBits( ePartSize, pcCU->getSlice()->isInterP(), iPartIdx, uiLastMode, uiMbBits);
@@ -3349,10 +3331,5 @@
         uiBitsTemp += m_auiMVPIdxCost[aaiMvpIdx[iRefList][iRefIdxTemp]][AMVP_MAX_NUM_CANDS];
 #if ZERO_MVD_EST
-#if L0034_COMBINED_LIST_CLEANUP
         if ( iRefList == 0 || pcCU->getSlice()->getList1IdxToList0Idx( iRefIdxTemp ) < 0 )
-#else
-        if ((iRefList != 1 || !pcCU->getSlice()->getNoBackPredFlag()) &&
-            (pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) <= 0 || pcCU->getSlice()->getRefIdxOfLC(eRefPicList, iRefIdxTemp)>=0))
-#endif
         {
           uiZeroMvdBitsTemp = uiBitsTemp;
@@ -3374,5 +3351,4 @@
         
 #if GPB_SIMPLE_UNI
-#if L0034_COMBINED_LIST_CLEANUP
         if ( iRefList == 1 )    // list 1
         {
@@ -3399,47 +3375,4 @@
         }
 #else
-        if ( pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0)
-        {
-          if ( iRefList && ( pcCU->getSlice()->getNoBackPredFlag() || (pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0 && !pcCU->getSlice()->getNoBackPredFlag() && pcCU->getSlice()->getRefIdxOfL0FromRefIdxOfL1(iRefIdxTemp)>=0 ) ) )
-            {
-              if ( pcCU->getSlice()->getNoBackPredFlag() )
-              {
-                cMvTemp[1][iRefIdxTemp] = cMvTemp[0][iRefIdxTemp];
-                uiCostTemp = uiCostTempL0[iRefIdxTemp];
-                /*first subtract the bit-rate part of the cost of the other list*/
-                uiCostTemp -= m_pcRdCost->getCost( uiBitsTempL0[iRefIdxTemp] );
-              }
-              else
-              {
-                cMvTemp[1][iRefIdxTemp] = cMvTemp[0][pcCU->getSlice()->getRefIdxOfL0FromRefIdxOfL1(iRefIdxTemp)]; 
-                uiCostTemp = uiCostTempL0[pcCU->getSlice()->getRefIdxOfL0FromRefIdxOfL1(iRefIdxTemp)];
-                /*first subtract the bit-rate part of the cost of the other list*/
-                uiCostTemp -= m_pcRdCost->getCost( uiBitsTempL0[pcCU->getSlice()->getRefIdxOfL0FromRefIdxOfL1(iRefIdxTemp)] );
-              }
-              /*correct the bit-rate part of the current ref*/
-              m_pcRdCost->setPredictor  ( cMvPred[iRefList][iRefIdxTemp] );
-              uiBitsTemp += m_pcRdCost->getBits( cMvTemp[1][iRefIdxTemp].getHor(), cMvTemp[1][iRefIdxTemp].getVer() );
-              /*calculate the correct cost*/
-              uiCostTemp += m_pcRdCost->getCost( uiBitsTemp );
-            }
-            else
-            {
-              xMotionEstimation ( pcCU, pcOrgYuv, iPartIdx, eRefPicList, &cMvPred[iRefList][iRefIdxTemp], iRefIdxTemp, cMvTemp[iRefList][iRefIdxTemp], uiBitsTemp, uiCostTemp );
-            }
-        }
-        else
-        {
-          if (iRefList && pcCU->getSlice()->getNoBackPredFlag())
-          {
-            uiCostTemp = MAX_UINT;
-            cMvTemp[1][iRefIdxTemp] = cMvTemp[0][iRefIdxTemp];
-          }
-          else
-          { 
-            xMotionEstimation ( pcCU, pcOrgYuv, iPartIdx, eRefPicList, &cMvPred[iRefList][iRefIdxTemp], iRefIdxTemp, cMvTemp[iRefList][iRefIdxTemp], uiBitsTemp, uiCostTemp );
-          }        
-        }
-#endif
-#else
         xMotionEstimation ( pcCU, pcOrgYuv, iPartIdx, eRefPicList, &cMvPred[iRefList][iRefIdxTemp], iRefIdxTemp, cMvTemp[iRefList][iRefIdxTemp], uiBitsTemp, uiCostTemp );
 #endif
@@ -3447,5 +3380,4 @@
         xCheckBestMVP(pcCU, eRefPicList, cMvTemp[iRefList][iRefIdxTemp], cMvPred[iRefList][iRefIdxTemp], aaiMvpIdx[iRefList][iRefIdxTemp], uiBitsTemp, uiCostTemp);
 
-#if L0034_COMBINED_LIST_CLEANUP
         if ( iRefList == 0 )
         {
@@ -3472,61 +3404,4 @@
           refIdxValidList1 = iRefIdxTemp;
         }
-#else
-        if(pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0 && !pcCU->getSlice()->getNoBackPredFlag())
-        {
-          if(iRefList==REF_PIC_LIST_0)
-          {
-            uiCostTempL0[iRefIdxTemp] = uiCostTemp;
-            uiBitsTempL0[iRefIdxTemp] = uiBitsTemp;
-            if(pcCU->getSlice()->getRefIdxOfLC(REF_PIC_LIST_0, iRefIdxTemp)<0)
-            {
-              uiCostTemp = MAX_UINT;
-            }
-          }
-          else
-          {
-            if(pcCU->getSlice()->getRefIdxOfLC(REF_PIC_LIST_1, iRefIdxTemp)<0)
-            {
-              uiCostTemp = MAX_UINT;
-            }           
-          }
-        }
-
-#if ENCODER_BUGFIX
-        if ( ( iRefList == 0 && uiCostTemp < uiCost[iRefList] ) ||
-            ( iRefList == 1 &&  pcCU->getSlice()->getNoBackPredFlag() && iRefIdxTemp == iRefIdx[0] ) ||
-            ( iRefList == 1 && !pcCU->getSlice()->getNoBackPredFlag() && uiCostTemp < uiCost[iRefList] ) )
-#else
-        if ( ( iRefList == 0 && uiCostTemp < uiCost[iRefList] ) ||
-            ( iRefList == 1 &&  pcCU->getSlice()->getNoBackPredFlag() && iRefIdxTemp == iRefIdx[0] ) ||
-            ( iRefList == 1 && (pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0) && (iRefIdxTemp==0 || iRefIdxTemp == iRefIdx[0]) && !pcCU->getSlice()->getNoBackPredFlag() && (iRefIdxTemp == pcCU->getSlice()->getRefIdxOfL0FromRefIdxOfL1(iRefIdxTemp)) ) ||
-            ( iRefList == 1 && !pcCU->getSlice()->getNoBackPredFlag() && uiCostTemp < uiCost[iRefList] ) )
-#endif
-          {
-            uiCost[iRefList] = uiCostTemp;
-            uiBits[iRefList] = uiBitsTemp; // storing for bi-prediction
-            
-            // set motion
-            cMv[iRefList]     = cMvTemp[iRefList][iRefIdxTemp];
-            iRefIdx[iRefList] = iRefIdxTemp;
-            pcCU->getCUMvField(eRefPicList)->setAllMv( cMv[iRefList], ePartSize, uiPartAddr, 0, iPartIdx );
-            pcCU->getCUMvField(eRefPicList)->setAllRefIdx( iRefIdx[iRefList], ePartSize, uiPartAddr, 0, iPartIdx );
-
-            if(!pcCU->getSlice()->getMvdL1ZeroFlag())
-            {
-              // storing list 1 prediction signal for iterative bi-directional prediction
-              if ( eRefPicList == REF_PIC_LIST_1 )
-              {
-                TComYuv*  pcYuvPred = &m_acYuvPred[iRefList];
-                motionCompensation ( pcCU, pcYuvPred, eRefPicList, iPartIdx );
-              }
-              if ( (pcCU->getSlice()->getNoBackPredFlag() || (pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0 && pcCU->getSlice()->getRefIdxOfL0FromRefIdxOfL1(0)==0 )) && eRefPicList == REF_PIC_LIST_0 )
-              {
-                TComYuv*  pcYuvPred = &m_acYuvPred[iRefList];
-                motionCompensation ( pcCU, pcYuvPred, eRefPicList, iPartIdx );
-              }
-            }
-          }
-#endif
       }
     }
@@ -3596,5 +3471,4 @@
         
         Int         iRefList    = iIter % 2;
-#if L0034_COMBINED_LIST_CLEANUP
         if ( m_pcEncCfg->getUseFastEnc() )
         {
@@ -3619,10 +3493,4 @@
           motionCompensation ( pcCU, pcYuvPred, RefPicList(1-iRefList), iPartIdx );
         }
-#else
-        if ( m_pcEncCfg->getUseFastEnc() && (pcCU->getSlice()->getNoBackPredFlag() || (pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0 && pcCU->getSlice()->getRefIdxOfL0FromRefIdxOfL1(0)==0 )) )
-        {
-          iRefList = 1;
-        }
-#endif
         RefPicList  eRefPicList = ( iRefList ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
 
@@ -3785,15 +3653,8 @@
     UInt uiMEBits = 0;
     // Set Motion Field_
-#if L0034_COMBINED_LIST_CLEANUP
     cMv[1] = mvValidList1;
     iRefIdx[1] = refIdxValidList1;
     uiBits[1] = bitsValidList1;
     uiCost[1] = costValidList1;
-#else
-    if ( pcCU->getSlice()->getNoBackPredFlag() || (pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0 && pcCU->getSlice()->getRefIdxOfL0FromRefIdxOfL1(0)==0 ) )
-    {
-      uiCost[1] = MAX_UINT;
-    }
-#endif
 #if AMP_MRG
     if (bTestNormalMC)
Index: branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncSlice.cpp
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 302)
@@ -425,5 +425,4 @@
   rpcSlice->setNumRefIdx(REF_PIC_LIST_1,m_pcCfg->getGOPEntry(iGOPid).m_numRefPicsActive);
   
-#if L0386_DB_METRIC
   if ( m_pcCfg->getDeblockingFilterMetric() )
   {
@@ -433,5 +432,4 @@
     rpcSlice->setDeblockingFilterTcOffsetDiv2( 0 );
   } else
-#endif
   if (rpcSlice->getPPS()->getDeblockingFilterControlPresentFlag())
   {
@@ -519,7 +517,5 @@
   // store lambda
   slice->setSliceQp( sliceQP );
-#if L0033_RC_BUGFIX
   slice->setSliceQpBase ( sliceQP );
-#endif
   m_pcRdCost ->setLambda( lambda );
 #if WEIGHTED_CHROMA_DISTORTION
@@ -828,4 +824,40 @@
 /** \param rpcPic   picture class
  */
+#if RATE_CONTROL_INTRA
+Void TEncSlice::calCostSliceI(TComPic*& rpcPic)
+{
+  UInt    uiCUAddr;
+  UInt    uiStartCUAddr;
+  UInt    uiBoundingCUAddr;
+  Int     iSumHad, shift = g_bitDepthY-8, offset = (shift>0)?(1<<(shift-1)):0;;
+  Double  iSumHadSlice = 0;
+
+  rpcPic->getSlice(getSliceIdx())->setSliceSegmentBits(0);
+  TComSlice* pcSlice            = rpcPic->getSlice(getSliceIdx());
+  xDetermineStartAndBoundingCUAddr ( uiStartCUAddr, uiBoundingCUAddr, rpcPic, false );
+
+  UInt uiEncCUOrder;
+  uiCUAddr = rpcPic->getPicSym()->getCUOrderMap( uiStartCUAddr /rpcPic->getNumPartInCU()); 
+  for( uiEncCUOrder = uiStartCUAddr/rpcPic->getNumPartInCU();
+       uiEncCUOrder < (uiBoundingCUAddr+(rpcPic->getNumPartInCU()-1))/rpcPic->getNumPartInCU();
+       uiCUAddr = rpcPic->getPicSym()->getCUOrderMap(++uiEncCUOrder) )
+  {
+    // initialize CU encoder
+    TComDataCU*& pcCU = rpcPic->getCU( uiCUAddr );
+    pcCU->initCU( rpcPic, uiCUAddr );
+
+    Int height  = min( pcSlice->getSPS()->getMaxCUHeight(),pcSlice->getSPS()->getPicHeightInLumaSamples() - uiCUAddr / rpcPic->getFrameWidthInCU() * pcSlice->getSPS()->getMaxCUHeight() );
+    Int width   = min( pcSlice->getSPS()->getMaxCUWidth(),pcSlice->getSPS()->getPicWidthInLumaSamples() - uiCUAddr % rpcPic->getFrameWidthInCU() * pcSlice->getSPS()->getMaxCUWidth() );
+
+    iSumHad = m_pcCuEncoder->updateLCUDataISlice(pcCU, uiCUAddr, width, height);
+
+    (m_pcRateCtrl->getRCPic()->getLCU(uiCUAddr)).m_costIntra=(iSumHad+offset)>>shift;
+    iSumHadSlice += (m_pcRateCtrl->getRCPic()->getLCU(uiCUAddr)).m_costIntra;
+
+  }
+  m_pcRateCtrl->getRCPic()->setTotalIntraCost(iSumHadSlice);
+}
+#endif
+
 Void TEncSlice::compressSlice( TComPic*& rpcPic )
 {
@@ -1091,5 +1123,9 @@
         Double bpp       = -1.0;
 
+#if M0036_RC_IMPROVEMENT
+        if ( ( rpcPic->getSlice( 0 )->getSliceType() == I_SLICE && m_pcCfg->getForceIntraQP() ) || !m_pcCfg->getLCULevelRC() )
+#else
         if ( rpcPic->getSlice( 0 )->getSliceType() == I_SLICE || !m_pcCfg->getLCULevelRC() )
+#endif
         {
           estQP = pcSlice->getSliceQp();
@@ -1097,16 +1133,37 @@
         else
         {
+#if RATE_CONTROL_INTRA
+          bpp = m_pcRateCtrl->getRCPic()->getLCUTargetBpp(pcSlice->getSliceType());
+          if ( rpcPic->getSlice( 0 )->getSliceType() == I_SLICE)
+          {
+            estLambda = m_pcRateCtrl->getRCPic()->getLCUEstLambdaAndQP(bpp, pcSlice->getSliceQp(), &estQP);
+          }
+          else
+          {
+            estLambda = m_pcRateCtrl->getRCPic()->getLCUEstLambda( bpp );
+            estQP     = m_pcRateCtrl->getRCPic()->getLCUEstQP    ( estLambda, pcSlice->getSliceQp() );
+          }
+#else
           bpp       = m_pcRateCtrl->getRCPic()->getLCUTargetBpp();
           estLambda = m_pcRateCtrl->getRCPic()->getLCUEstLambda( bpp );
           estQP     = m_pcRateCtrl->getRCPic()->getLCUEstQP    ( estLambda, pcSlice->getSliceQp() );
+#endif
+
           estQP     = Clip3( -pcSlice->getSPS()->getQpBDOffsetY(), MAX_QP, estQP );
 
           m_pcRdCost->setLambda(estLambda);
+#if M0036_RC_IMPROVEMENT
+#if RDOQ_CHROMA_LAMBDA
+          // set lambda for RDOQ
+          Double weight=m_pcRdCost->getChromaWeight();
+          m_pcTrQuant->setLambda( estLambda, estLambda / weight );
+#else
+          m_pcTrQuant->setLambda( estLambda );
+#endif
+#endif
         }
 
         m_pcRateCtrl->setRCQP( estQP );
-#if L0033_RC_BUGFIX
         pcCU->getSlice()->setSliceQpBase( estQP );
-#endif
       }
 #endif
@@ -1115,7 +1172,9 @@
       m_pcCuEncoder->compressCU( pcCU );
 
+#if !TICKET_1090_FIX
 #if RATE_CONTROL_LAMBDA_DOMAIN
       if ( m_pcCfg->getUseRateCtrl() )
       {
+#if !M0036_RC_IMPROVEMENT
         UInt SAD    = m_pcCuEncoder->getLCUPredictionSAD();
         Int height  = min( pcSlice->getSPS()->getMaxCUHeight(),pcSlice->getSPS()->getPicHeightInLumaSamples() - uiCUAddr / rpcPic->getFrameWidthInCU() * pcSlice->getSPS()->getMaxCUHeight() );
@@ -1124,4 +1183,5 @@
         MAD = MAD * MAD;
         ( m_pcRateCtrl->getRCPic()->getLCU(uiCUAddr) ).m_MAD = MAD;
+#endif
 
         Int actualQP        = g_RCInvalidQPValue;
@@ -1147,7 +1207,12 @@
         }
         m_pcRdCost->setLambda(oldLambda);
-
+#if RATE_CONTROL_INTRA
+        m_pcRateCtrl->getRCPic()->updateAfterLCU( m_pcRateCtrl->getRCPic()->getLCUCoded(), actualBits, actualQP, actualLambda, 
+          pcCU->getSlice()->getSliceType() == I_SLICE ? 0 : m_pcCfg->getLCULevelRC() );
+#else
         m_pcRateCtrl->getRCPic()->updateAfterLCU( m_pcRateCtrl->getRCPic()->getLCUCoded(), actualBits, actualQP, actualLambda, m_pcCfg->getLCULevelRC() );
-      }
+#endif
+      }
+#endif
 #endif
       
@@ -1183,4 +1248,50 @@
         }
       }
+
+#if TICKET_1090_FIX
+#if RATE_CONTROL_LAMBDA_DOMAIN
+      if ( m_pcCfg->getUseRateCtrl() )
+      {
+#if !M0036_RC_IMPROVEMENT
+        UInt SAD    = m_pcCuEncoder->getLCUPredictionSAD();
+        Int height  = min( pcSlice->getSPS()->getMaxCUHeight(),pcSlice->getSPS()->getPicHeightInLumaSamples() - uiCUAddr / rpcPic->getFrameWidthInCU() * pcSlice->getSPS()->getMaxCUHeight() );
+        Int width   = min( pcSlice->getSPS()->getMaxCUWidth(),pcSlice->getSPS()->getPicWidthInLumaSamples() - uiCUAddr % rpcPic->getFrameWidthInCU() * pcSlice->getSPS()->getMaxCUWidth() );
+        Double MAD = (Double)SAD / (Double)(height * width);
+        MAD = MAD * MAD;
+        ( m_pcRateCtrl->getRCPic()->getLCU(uiCUAddr) ).m_MAD = MAD;
+#endif
+
+        Int actualQP        = g_RCInvalidQPValue;
+        Double actualLambda = m_pcRdCost->getLambda();
+        Int actualBits      = pcCU->getTotalBits();
+        Int numberOfEffectivePixels    = 0;
+        for ( Int idx = 0; idx < rpcPic->getNumPartInCU(); idx++ )
+        {
+          if ( pcCU->getPredictionMode( idx ) != MODE_NONE && ( !pcCU->isSkipped( idx ) ) )
+          {
+            numberOfEffectivePixels = numberOfEffectivePixels + 16;
+            break;
+          }
+        }
+
+        if ( numberOfEffectivePixels == 0 )
+        {
+          actualQP = g_RCInvalidQPValue;
+        }
+        else
+        {
+          actualQP = pcCU->getQP( 0 );
+        }
+        m_pcRdCost->setLambda(oldLambda);
+
+#if RATE_CONTROL_INTRA
+        m_pcRateCtrl->getRCPic()->updateAfterLCU( m_pcRateCtrl->getRCPic()->getLCUCoded(), actualBits, actualQP, actualLambda, 
+          pcCU->getSlice()->getSliceType() == I_SLICE ? 0 : m_pcCfg->getLCULevelRC() );
+#else
+        m_pcRateCtrl->getRCPic()->updateAfterLCU( m_pcRateCtrl->getRCPic()->getLCUCoded(), actualBits, actualQP, actualLambda, m_pcCfg->getLCULevelRC() );
+#endif
+      }
+#endif
+#endif
     }
     // other case: encodeCU is not called
Index: branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncSlice.h
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncSlice.h	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncSlice.h	(revision 302)
@@ -132,4 +132,7 @@
   Void    precompressSlice    ( TComPic*& rpcPic                                );      ///< precompress slice for multi-loop opt.
   Void    compressSlice       ( TComPic*& rpcPic                                );      ///< analysis stage of slice
+#if RATE_CONTROL_INTRA
+  Void    calCostSliceI       ( TComPic*& rpcPic );
+#endif
   Void    encodeSlice         ( TComPic*& rpcPic, TComOutputBitstream* pcSubstreams  );
   
Index: branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncTop.cpp
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncTop.cpp	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncTop.cpp	(revision 302)
@@ -313,7 +313,5 @@
   /* set the VPS profile information */
   *m_cVPS.getPTL() = *m_cSPS.getPTL();
-#if L0043_TIMING_INFO
   m_cVPS.getTimingInfo()->setTimingInfoPresentFlag       ( false );
-#endif
   // initialize PPS
   m_cPPS.setSPS(&m_cSPS);
@@ -615,10 +613,8 @@
   profileTierLevel.setProfileIdc(m_profile);
   profileTierLevel.setProfileCompatibilityFlag(m_profile, 1);
-#if L0046_CONSTRAINT_FLAGS
   profileTierLevel.setProgressiveSourceFlag(m_progressiveSourceFlag);
   profileTierLevel.setInterlacedSourceFlag(m_interlacedSourceFlag);
   profileTierLevel.setNonPackedConstraintFlag(m_nonPackedConstraintFlag);
   profileTierLevel.setFrameOnlyConstraintFlag(m_frameOnlyConstraintFlag);
-#endif
   
   if (m_profile == Profile::MAIN10 && g_bitDepthY == 8 && g_bitDepthC == 8)
@@ -670,7 +666,4 @@
 
   m_cSPS.setMaxTrSize   ( 1 << m_uiQuadtreeTULog2MaxSize );
-#if !L0034_COMBINED_LIST_CLEANUP
-  m_cSPS.setUseLComb    ( m_bUseLComb           );
-#endif
   
   Int i;
@@ -737,11 +730,6 @@
     pcVUI->setFieldSeqFlag(false);
     pcVUI->setHrdParametersPresentFlag(false);
-#if L0043_TIMING_INFO
     pcVUI->getTimingInfo()->setPocProportionalToTimingFlag(getPocProportionalToTimingFlag());
     pcVUI->getTimingInfo()->setNumTicksPocDiffOneMinus1   (getNumTicksPocDiffOneMinus1()   );
-#else
-    pcVUI->setPocProportionalToTimingFlag(getPocProportionalToTimingFlag());
-    pcVUI->setNumTicksPocDiffOneMinus1   (getNumTicksPocDiffOneMinus1()   );
-#endif
     pcVUI->setBitstreamRestrictionFlag(getBitstreamRestrictionFlag());
     pcVUI->setTilesFixedStructureFlag(getTilesFixedStructureFlag());
@@ -816,5 +804,4 @@
   m_cPPS.setOutputFlagPresentFlag( false );
   m_cPPS.setSignHideFlag(getSignHideFlag());
-#if L0386_DB_METRIC
   if ( getDeblockingFilterMetric() )
   {
@@ -829,7 +816,4 @@
   m_cPPS.setDeblockingFilterControlPresentFlag (m_DeblockingFilterControlPresent );
   }
-#else
-  m_cPPS.setDeblockingFilterControlPresentFlag (m_DeblockingFilterControlPresent );
-#endif
   m_cPPS.setLog2ParallelMergeLevelMinus2   (m_log2ParallelMergeLevelMinus2 );
   m_cPPS.setCabacInitPresentFlag(CABAC_INIT_PRESENT_FLAG);
@@ -855,7 +839,5 @@
     }
   }
-#if L0323_LIMIT_DEFAULT_LIST_SIZE
   assert(bestPos <= 15);
-#endif
   m_cPPS.setNumRefIdxL0DefaultActive(bestPos);
   m_cPPS.setNumRefIdxL1DefaultActive(bestPos);
@@ -1104,5 +1086,4 @@
 }
 
-#if L0208_SOP_DESCRIPTION_SEI
 Int TEncTop::getReferencePictureSetIdxForSOP(TComSlice* slice, Int POCCurr, Int GOPid )
 {
@@ -1134,5 +1115,4 @@
   return rpsIdx;
 }
-#endif
 
 Void  TEncTop::xInitPPSforTiles()
Index: branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncTop.h
===================================================================
--- branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncTop.h	(revision 300)
+++ branches/SHM-2.1-dev/source/Lib/TLibEncoder/TEncTop.h	(revision 302)
@@ -199,7 +199,5 @@
   TComPPS*                getPPS                () { return  &m_cPPS;                 }
   Void selectReferencePictureSet(TComSlice* slice, Int POCCurr, Int GOPid );
-#if L0208_SOP_DESCRIPTION_SEI
   Int getReferencePictureSetIdxForSOP(TComSlice* slice, Int POCCurr, Int GOPid );
-#endif
   TComScalingList*        getScalingList        () { return  &m_scalingList;         }
 #if SVC_EXTENSION
