Index: trunk/source/Lib/TLibEncoder/TEncGOP.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 1196)
+++ trunk/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 1313)
@@ -2,7 +2,7 @@
  * License, included below. This software may be subject to other third party
  * and contributor rights, including patent rights, and no such rights are
- * granted under this license.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -50,5 +50,7 @@
 #include <math.h>
 
+#include <deque>
 using namespace std;
+
 //! \ingroup TLibEncoder
 //! \{
@@ -75,19 +77,17 @@
   m_iNumPicCoded        = 0; //Niko
   m_bFirst              = true;
-#if ALLOW_RECOVERY_POINT_AS_RAP
   m_iLastRecoveryPicPOC = 0;
-#endif
-  
+
   m_pcCfg               = NULL;
   m_pcSliceEncoder      = NULL;
   m_pcListPic           = NULL;
-  
+
   m_pcEntropyCoder      = NULL;
   m_pcCavlcCoder        = NULL;
   m_pcSbacCoder         = NULL;
   m_pcBinCABAC          = NULL;
-  
+
   m_bSeqFirst           = true;
-  
+
   m_bRefreshPending     = 0;
   m_pocCRA            = 0;
@@ -95,21 +95,17 @@
   ::memset(m_ltRefPicPocLsbSps, 0, sizeof(m_ltRefPicPocLsbSps));
   ::memset(m_ltRefPicUsedByCurrPicFlag, 0, sizeof(m_ltRefPicUsedByCurrPicFlag));
-  m_cpbRemovalDelay   = 0;
   m_lastBPSEI         = 0;
-  xResetNonNestedSEIPresentFlags();
-  xResetNestedSEIPresentFlags();
-#if H_MV
+  m_bufferingPeriodSEIPresentInAU = false;
+#if NH_MV
   m_layerId      = 0;
   m_viewId       = 0;
   m_pocLastCoded = -1; 
-#if H_3D
+#if NH_3D
   m_viewIndex  =   0; 
   m_isDepth = false;
 #endif
 #endif
-#if FIX1172
   m_associatedIRAPType = NAL_UNIT_CODED_SLICE_IDR_N_LP;
   m_associatedIRAPPOC  = 0;
-#endif
   return;
 }
@@ -119,5 +115,5 @@
 }
 
-/** Create list to contain pointers to LCU start addresses of slice.
+/** Create list to contain pointers to CTU start addresses of slice.
  */
 Void  TEncGOP::create()
@@ -135,7 +131,8 @@
   m_pcEncTop     = pcTEncTop;
   m_pcCfg                = pcTEncTop;
+  m_seiEncoder.init(m_pcCfg, pcTEncTop, this);
   m_pcSliceEncoder       = pcTEncTop->getSliceEncoder();
   m_pcListPic            = pcTEncTop->getListPic();
-  
+
   m_pcEntropyCoder       = pcTEncTop->getEntropyCoder();
   m_pcCavlcCoder         = pcTEncTop->getCavlcCoder();
@@ -143,7 +140,5 @@
   m_pcBinCABAC           = pcTEncTop->getBinCABAC();
   m_pcLoopFilter         = pcTEncTop->getLoopFilter();
-  m_pcBitCounter         = pcTEncTop->getBitCounter();
-  
-  //--Adaptive Loop filter
+
   m_pcSAO                = pcTEncTop->getSAO();
   m_pcRateCtrl           = pcTEncTop->getRateCtrl();
@@ -151,14 +146,14 @@
   m_totalCoded         = 0;
 
-#if H_MV
+#if NH_MV
   m_ivPicLists           = pcTEncTop->getIvPicLists(); 
   m_layerId              = pcTEncTop->getLayerId();
   m_viewId               = pcTEncTop->getViewId();
-#if H_3D
+#if NH_3D
   m_viewIndex            = pcTEncTop->getViewIndex();
   m_isDepth              = pcTEncTop->getIsDepth();
 #endif
 #endif
-#if H_3D_IC
+#if NH_3D_IC
   m_aICEnableCandidate   = pcTEncTop->getICEnableCandidate(); 
   m_aICEnableNum         = pcTEncTop->getICEnableNum(); 
@@ -169,222 +164,893 @@
 }
 
-SEIActiveParameterSets* TEncGOP::xCreateSEIActiveParameterSets (TComSPS *sps)
-{
-  SEIActiveParameterSets *seiActiveParameterSets = new SEIActiveParameterSets(); 
-  seiActiveParameterSets->activeVPSId = m_pcCfg->getVPS()->getVPSId(); 
-  seiActiveParameterSets->m_selfContainedCvsFlag = false;
-  seiActiveParameterSets->m_noParameterSetUpdateFlag = false;
-  seiActiveParameterSets->numSpsIdsMinus1 = 0;
-  seiActiveParameterSets->activeSeqParameterSetId.resize(seiActiveParameterSets->numSpsIdsMinus1 + 1); 
-  seiActiveParameterSets->activeSeqParameterSetId[0] = sps->getSPSId();
-  return seiActiveParameterSets;
-}
-
-SEIFramePacking* TEncGOP::xCreateSEIFramePacking()
-{
-  SEIFramePacking *seiFramePacking = new SEIFramePacking();
-  seiFramePacking->m_arrangementId = m_pcCfg->getFramePackingArrangementSEIId();
-  seiFramePacking->m_arrangementCancelFlag = 0;
-  seiFramePacking->m_arrangementType = m_pcCfg->getFramePackingArrangementSEIType();
-  assert((seiFramePacking->m_arrangementType > 2) && (seiFramePacking->m_arrangementType < 6) );
-  seiFramePacking->m_quincunxSamplingFlag = m_pcCfg->getFramePackingArrangementSEIQuincunx();
-  seiFramePacking->m_contentInterpretationType = m_pcCfg->getFramePackingArrangementSEIInterpretation();
-  seiFramePacking->m_spatialFlippingFlag = 0;
-  seiFramePacking->m_frame0FlippedFlag = 0;
-  seiFramePacking->m_fieldViewsFlag = (seiFramePacking->m_arrangementType == 2);
-  seiFramePacking->m_currentFrameIsFrame0Flag = ((seiFramePacking->m_arrangementType == 5) && m_iNumPicCoded&1);
-  seiFramePacking->m_frame0SelfContainedFlag = 0;
-  seiFramePacking->m_frame1SelfContainedFlag = 0;
-  seiFramePacking->m_frame0GridPositionX = 0;
-  seiFramePacking->m_frame0GridPositionY = 0;
-  seiFramePacking->m_frame1GridPositionX = 0;
-  seiFramePacking->m_frame1GridPositionY = 0;
-  seiFramePacking->m_arrangementReservedByte = 0;
-  seiFramePacking->m_arrangementPersistenceFlag = true;
-  seiFramePacking->m_upsampledAspectRatio = 0;
-  return seiFramePacking;
-}
-
-SEIDisplayOrientation* TEncGOP::xCreateSEIDisplayOrientation()
-{
-  SEIDisplayOrientation *seiDisplayOrientation = new SEIDisplayOrientation();
-  seiDisplayOrientation->cancelFlag = false;
-  seiDisplayOrientation->horFlip = false;
-  seiDisplayOrientation->verFlip = false;
-  seiDisplayOrientation->anticlockwiseRotation = m_pcCfg->getDisplayOrientationSEIAngle();
-  return seiDisplayOrientation;
-}
-
-SEIToneMappingInfo*  TEncGOP::xCreateSEIToneMappingInfo()
-{
-  SEIToneMappingInfo *seiToneMappingInfo = new SEIToneMappingInfo();
-  seiToneMappingInfo->m_toneMapId = m_pcCfg->getTMISEIToneMapId();
-  seiToneMappingInfo->m_toneMapCancelFlag = m_pcCfg->getTMISEIToneMapCancelFlag();
-  seiToneMappingInfo->m_toneMapPersistenceFlag = m_pcCfg->getTMISEIToneMapPersistenceFlag();
-
-  seiToneMappingInfo->m_codedDataBitDepth = m_pcCfg->getTMISEICodedDataBitDepth();
-  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_modelId = m_pcCfg->getTMISEIModelID();
-  assert(seiToneMappingInfo->m_modelId >=0 &&seiToneMappingInfo->m_modelId<=4);
-
-  switch( seiToneMappingInfo->m_modelId)
-  {
-  case 0:
-    {
-      seiToneMappingInfo->m_minValue = m_pcCfg->getTMISEIMinValue();
-      seiToneMappingInfo->m_maxValue = m_pcCfg->getTMISEIMaxValue();
-      break;
-    }
-  case 1:
-    {
-      seiToneMappingInfo->m_sigmoidMidpoint = m_pcCfg->getTMISEISigmoidMidpoint();
-      seiToneMappingInfo->m_sigmoidWidth = m_pcCfg->getTMISEISigmoidWidth();
-      break;
-    }
-  case 2:
-    {
-      UInt num = 1u<<(seiToneMappingInfo->m_targetBitDepth);
-      seiToneMappingInfo->m_startOfCodedInterval.resize(num);
-      Int* ptmp = m_pcCfg->getTMISEIStartOfCodedInterva();
-      if(ptmp)
-      {
-        for(int i=0; i<num;i++)
-        {
-          seiToneMappingInfo->m_startOfCodedInterval[i] = ptmp[i];
-        }
-      }
-      break;
-    }
-  case 3:
-    {
-      seiToneMappingInfo->m_numPivots = m_pcCfg->getTMISEINumPivots();
-      seiToneMappingInfo->m_codedPivotValue.resize(seiToneMappingInfo->m_numPivots);
-      seiToneMappingInfo->m_targetPivotValue.resize(seiToneMappingInfo->m_numPivots);
-      Int* ptmpcoded = m_pcCfg->getTMISEICodedPivotValue();
-      Int* ptmptarget = m_pcCfg->getTMISEITargetPivotValue();
-      if(ptmpcoded&&ptmptarget)
-      {
-        for(int i=0; i<(seiToneMappingInfo->m_numPivots);i++)
-        {
-          seiToneMappingInfo->m_codedPivotValue[i]=ptmpcoded[i];
-          seiToneMappingInfo->m_targetPivotValue[i]=ptmptarget[i];
-         }
-       }
-       break;
-     }
-  case 4:
-     {
-       seiToneMappingInfo->m_cameraIsoSpeedIdc = m_pcCfg->getTMISEICameraIsoSpeedIdc();
-       seiToneMappingInfo->m_cameraIsoSpeedValue = m_pcCfg->getTMISEICameraIsoSpeedValue();
-       assert( seiToneMappingInfo->m_cameraIsoSpeedValue !=0 );
-       seiToneMappingInfo->m_exposureIndexIdc = m_pcCfg->getTMISEIExposurIndexIdc();
-       seiToneMappingInfo->m_exposureIndexValue = m_pcCfg->getTMISEIExposurIndexValue();
-       assert( seiToneMappingInfo->m_exposureIndexValue !=0 );
-       seiToneMappingInfo->m_exposureCompensationValueSignFlag = m_pcCfg->getTMISEIExposureCompensationValueSignFlag();
-       seiToneMappingInfo->m_exposureCompensationValueNumerator = m_pcCfg->getTMISEIExposureCompensationValueNumerator();
-       seiToneMappingInfo->m_exposureCompensationValueDenomIdc = m_pcCfg->getTMISEIExposureCompensationValueDenomIdc();
-       seiToneMappingInfo->m_refScreenLuminanceWhite = m_pcCfg->getTMISEIRefScreenLuminanceWhite();
-       seiToneMappingInfo->m_extendedRangeWhiteLevel = m_pcCfg->getTMISEIExtendedRangeWhiteLevel();
-       assert( seiToneMappingInfo->m_extendedRangeWhiteLevel >= 100 );
-       seiToneMappingInfo->m_nominalBlackLevelLumaCodeValue = m_pcCfg->getTMISEINominalBlackLevelLumaCodeValue();
-       seiToneMappingInfo->m_nominalWhiteLevelLumaCodeValue = m_pcCfg->getTMISEINominalWhiteLevelLumaCodeValue();
-       assert( seiToneMappingInfo->m_nominalWhiteLevelLumaCodeValue > seiToneMappingInfo->m_nominalBlackLevelLumaCodeValue );
-       seiToneMappingInfo->m_extendedWhiteLevelLumaCodeValue = m_pcCfg->getTMISEIExtendedWhiteLevelLumaCodeValue();
-       assert( seiToneMappingInfo->m_extendedWhiteLevelLumaCodeValue >= seiToneMappingInfo->m_nominalWhiteLevelLumaCodeValue );
-       break;
-    }
-  default:
-    {
-      assert(!"Undefined SEIToneMapModelId");
-      break;
-    }
-  }
-  return seiToneMappingInfo;
-}
-
-#if H_MV
-SEISubBitstreamProperty *TEncGOP::xCreateSEISubBitstreamProperty( TComSPS *sps)
-{
-  SEISubBitstreamProperty *seiSubBitstreamProperty = new SEISubBitstreamProperty();
-
-  seiSubBitstreamProperty->m_activeVpsId = sps->getVPSId();
-  /* These values can be determined by the encoder; for now we will use the input parameter */
-  TEncTop *encTop = this->m_pcEncTop;
-  seiSubBitstreamProperty->m_numAdditionalSubStreams = encTop->getNumAdditionalSubStreams();
-  seiSubBitstreamProperty->m_subBitstreamMode        = encTop->getSubBitstreamMode();
-  seiSubBitstreamProperty->m_outputLayerSetIdxToVps  = encTop->getOutputLayerSetIdxToVps();
-  seiSubBitstreamProperty->m_highestSublayerId       = encTop->getHighestSublayerId();
-  seiSubBitstreamProperty->m_avgBitRate              = encTop->getAvgBitRate();
-  seiSubBitstreamProperty->m_maxBitRate              = encTop->getMaxBitRate();
-
-  return seiSubBitstreamProperty;
-}
-#endif
-
-Void TEncGOP::xCreateLeadingSEIMessages (/*SEIMessages seiMessages,*/ AccessUnit &accessUnit, TComSPS *sps)
-{
+Int TEncGOP::xWriteVPS (AccessUnit &accessUnit, const TComVPS *vps)
+{
+  OutputNALUnit nalu(NAL_UNIT_VPS);
+  m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+  m_pcEntropyCoder->encodeVPS(vps);
+  accessUnit.push_back(new NALUnitEBSP(nalu));
+  return (Int)(accessUnit.back()->m_nalUnitData.str().size()) * 8;
+}
+
+Int TEncGOP::xWriteSPS (AccessUnit &accessUnit, const TComSPS *sps)
+{
+#if NH_MV
+  OutputNALUnit nalu(NAL_UNIT_SPS, 0, getLayerId() );
+#else
+  OutputNALUnit nalu(NAL_UNIT_SPS);
+#endif
+  m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+  m_pcEntropyCoder->encodeSPS(sps);
+  accessUnit.push_back(new NALUnitEBSP(nalu));
+  return (Int)(accessUnit.back()->m_nalUnitData.str().size()) * 8;
+
+}
+
+Int TEncGOP::xWritePPS (AccessUnit &accessUnit, const TComPPS *pps)
+{
+#if NH_MV
+  OutputNALUnit nalu(NAL_UNIT_PPS, 0, getLayerId() );
+#else
+  OutputNALUnit nalu(NAL_UNIT_PPS);
+#endif
+  m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+  m_pcEntropyCoder->encodePPS(pps);
+  accessUnit.push_back(new NALUnitEBSP(nalu));
+  return (Int)(accessUnit.back()->m_nalUnitData.str().size()) * 8;
+}
+
+
+Int TEncGOP::xWriteParameterSets (AccessUnit &accessUnit, TComSlice *slice)
+{
+  Int actualTotalBits = 0;
+
+#if NH_MV
+  if ( getLayerId() == 0 )
+  {  
+    actualTotalBits += xWriteVPS(accessUnit, m_pcEncTop->getVPS());
+  }
+#else
+  actualTotalBits += xWriteVPS(accessUnit, m_pcEncTop->getVPS());
+#endif
+  actualTotalBits += xWriteSPS(accessUnit, slice->getSPS());
+  actualTotalBits += xWritePPS(accessUnit, slice->getPPS());
+
+  return actualTotalBits;
+}
+
+// write SEI list into one NAL unit and add it to the Access unit at auPos
+Void TEncGOP::xWriteSEI (NalUnitType naluType, SEIMessages& seiMessages, AccessUnit &accessUnit, AccessUnit::iterator &auPos, Int temporalId, const TComSPS *sps)
+{
+  // don't do anything, if we get an empty list
+  if (seiMessages.empty())
+  {
+    return;
+  }
+#if NH_MV
+  OutputNALUnit nalu(naluType, temporalId, getLayerId() );
+#else
+  OutputNALUnit nalu(naluType, temporalId);
+#endif
+  m_seiWriter.writeSEImessages(nalu.m_Bitstream, seiMessages, sps, false);
+  auPos = accessUnit.insert(auPos, new NALUnitEBSP(nalu));
+  auPos++;
+}
+
+Void TEncGOP::xWriteSEISeparately (NalUnitType naluType, SEIMessages& seiMessages, AccessUnit &accessUnit, AccessUnit::iterator &auPos, Int temporalId, const TComSPS *sps)
+{
+  // don't do anything, if we get an empty list
+  if (seiMessages.empty())
+  {
+    return;
+  }
+  for (SEIMessages::const_iterator sei = seiMessages.begin(); sei!=seiMessages.end(); sei++ )
+  {
+    SEIMessages tmpMessages;
+    tmpMessages.push_back(*sei);
+#if NH_MV
+    OutputNALUnit nalu(naluType, temporalId, getLayerId() );
+#else
+    OutputNALUnit nalu(naluType, temporalId);
+#endif
+    m_seiWriter.writeSEImessages(nalu.m_Bitstream, tmpMessages, sps, false);
+    auPos = accessUnit.insert(auPos, new NALUnitEBSP(nalu));
+    auPos++;
+  }
+}
+
+Void TEncGOP::xClearSEIs(SEIMessages& seiMessages, Bool deleteMessages)
+{
+  if (deleteMessages)
+  {
+    deleteSEIs(seiMessages);
+  }
+  else
+  {
+    seiMessages.clear();
+  }
+}
+
+// write SEI messages as separate NAL units ordered
+Void TEncGOP::xWriteLeadingSEIOrdered (SEIMessages& seiMessages, SEIMessages& duInfoSeiMessages, AccessUnit &accessUnit, Int temporalId, const TComSPS *sps, Bool testWrite)
+{
+  AccessUnit::iterator itNalu = accessUnit.begin();
+
+  while ( (itNalu!=accessUnit.end())&&
+    ( (*itNalu)->m_nalUnitType==NAL_UNIT_ACCESS_UNIT_DELIMITER 
+    || (*itNalu)->m_nalUnitType==NAL_UNIT_VPS
+    || (*itNalu)->m_nalUnitType==NAL_UNIT_SPS
+    || (*itNalu)->m_nalUnitType==NAL_UNIT_PPS
+    ))
+  {
+    itNalu++;
+  }
+
+  SEIMessages localMessages = seiMessages;
+  SEIMessages currentMessages;
+  
+#if ENC_DEC_TRACE
+  g_HLSTraceEnable = !testWrite;
+#endif
+  // The case that a specific SEI is not present is handled in xWriteSEI (empty list)
+
+  // Active parameter sets SEI must always be the first SEI
+  currentMessages = extractSeisByType(localMessages, SEI::ACTIVE_PARAMETER_SETS);
+  assert (currentMessages.size() <= 1);
+  xWriteSEI(NAL_UNIT_PREFIX_SEI, currentMessages, accessUnit, itNalu, temporalId, sps);
+  xClearSEIs(currentMessages, !testWrite);
+  
+  // Buffering period SEI must always be following active parameter sets
+  currentMessages = extractSeisByType(localMessages, SEI::BUFFERING_PERIOD);
+  assert (currentMessages.size() <= 1);
+  xWriteSEI(NAL_UNIT_PREFIX_SEI, currentMessages, accessUnit, itNalu, temporalId, sps);
+  xClearSEIs(currentMessages, !testWrite);
+
+  // Picture timing SEI must always be following buffering period
+  currentMessages = extractSeisByType(localMessages, SEI::PICTURE_TIMING);
+  assert (currentMessages.size() <= 1);
+  xWriteSEI(NAL_UNIT_PREFIX_SEI, currentMessages, accessUnit, itNalu, temporalId, sps);
+  xClearSEIs(currentMessages, !testWrite);
+
+  // Decoding unit info SEI must always be following picture timing
+  if (!duInfoSeiMessages.empty())
+  {
+    currentMessages.push_back(duInfoSeiMessages.front());
+    if (!testWrite)
+    {
+      duInfoSeiMessages.pop_front();
+    }
+    xWriteSEI(NAL_UNIT_PREFIX_SEI, currentMessages, accessUnit, itNalu, temporalId, sps);
+    xClearSEIs(currentMessages, !testWrite);
+  }
+
+  // Scalable nesting SEI must always be the following DU info
+  currentMessages = extractSeisByType(localMessages, SEI::SCALABLE_NESTING);
+  xWriteSEISeparately(NAL_UNIT_PREFIX_SEI, currentMessages, accessUnit, itNalu, temporalId, sps);
+  xClearSEIs(currentMessages, !testWrite);
+
+  // And finally everything else one by one
+  xWriteSEISeparately(NAL_UNIT_PREFIX_SEI, localMessages, accessUnit, itNalu, temporalId, sps);
+  xClearSEIs(localMessages, !testWrite);
+
+  if (!testWrite)
+  {
+    seiMessages.clear();
+  }
+}
+
+
+Void TEncGOP::xWriteLeadingSEIMessages (SEIMessages& seiMessages, SEIMessages& duInfoSeiMessages, AccessUnit &accessUnit, Int temporalId, const TComSPS *sps, std::deque<DUData> &duData)
+{
+  AccessUnit testAU;
+  SEIMessages picTimingSEIs = getSeisByType(seiMessages, SEI::PICTURE_TIMING);
+  assert (picTimingSEIs.size() < 2);
+  SEIPictureTiming * picTiming = picTimingSEIs.empty() ? NULL : (SEIPictureTiming*) picTimingSEIs.front();
+
+  // test writing
+  xWriteLeadingSEIOrdered(seiMessages, duInfoSeiMessages, testAU, temporalId, sps, true);
+  // update Timing and DU info SEI
+  xUpdateDuData(testAU, duData);
+  xUpdateTimingSEI(picTiming, duData, sps);
+  xUpdateDuInfoSEI(duInfoSeiMessages, picTiming);
+  // actual writing
+  xWriteLeadingSEIOrdered(seiMessages, duInfoSeiMessages, accessUnit, temporalId, sps, false);
+
+  // testAU will automatically be cleaned up when losing scope
+}
+
+Void TEncGOP::xWriteTrailingSEIMessages (SEIMessages& seiMessages, AccessUnit &accessUnit, Int temporalId, const TComSPS *sps)
+{
+  // Note: using accessUnit.end() works only as long as this function is called after slice coding and before EOS/EOB NAL units
+  AccessUnit::iterator pos = accessUnit.end();
+  xWriteSEISeparately(NAL_UNIT_SUFFIX_SEI, seiMessages, accessUnit, pos, temporalId, sps);
+  deleteSEIs(seiMessages);
+}
+
+Void TEncGOP::xWriteDuSEIMessages (SEIMessages& duInfoSeiMessages, AccessUnit &accessUnit, Int temporalId, const TComSPS *sps, std::deque<DUData> &duData)
+{
+  const TComHRD *hrd = sps->getVuiParameters()->getHrdParameters();
+
+  if( m_pcCfg->getDecodingUnitInfoSEIEnabled() && hrd->getSubPicCpbParamsPresentFlag() )
+  {
+    Int naluIdx = 0;
+    AccessUnit::iterator nalu = accessUnit.begin();
+
+    // skip over first DU, we have a DU info SEI there already
+    while (naluIdx < duData[0].accumNalsDU && nalu!=accessUnit.end())
+    {
+      naluIdx++;
+      nalu++;
+    }
+
+    SEIMessages::iterator duSEI = duInfoSeiMessages.begin();
+    // loop over remaining DUs
+    for (Int duIdx = 1; duIdx < duData.size(); duIdx++)
+    {
+      if (duSEI == duInfoSeiMessages.end())
+      {
+        // if the number of generated SEIs matches the number of DUs, this should not happen
+        assert (false);
+        return;
+      }
+      // write the next SEI
+      SEIMessages tmpSEI;
+      tmpSEI.push_back(*duSEI);
+      xWriteSEI(NAL_UNIT_PREFIX_SEI, tmpSEI, accessUnit, nalu, temporalId, sps);
+      // nalu points to the position after the SEI, so we have to increase the index as well
+      naluIdx++;
+      while ((naluIdx < duData[duIdx].accumNalsDU) && nalu!=accessUnit.end())
+      {
+        naluIdx++;
+        nalu++;
+      }
+      duSEI++;
+    }
+  }
+  deleteSEIs(duInfoSeiMessages);
+}
+
+Void TEncGOP::xCreateIRAPLeadingSEIMessages (SEIMessages& seiMessages, const TComSPS *sps, const TComPPS *pps)
+{
+#if NH_MV
+  OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI, 0, getLayerId());
+#else
   OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
-
+#endif
   if(m_pcCfg->getActiveParameterSetsSEIEnabled())
   {
-    SEIActiveParameterSets *sei = xCreateSEIActiveParameterSets (sps);
-
-    //nalu = NALUnit(NAL_UNIT_SEI); 
-    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
-    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps); 
-    writeRBSPTrailingBits(nalu.m_Bitstream);
-    accessUnit.push_back(new NALUnitEBSP(nalu));
-    delete sei;
-    m_activeParameterSetSEIPresentInAU = true;
+    SEIActiveParameterSets *sei = new SEIActiveParameterSets;
+    m_seiEncoder.initSEIActiveParameterSets (sei, m_pcCfg->getVPS(), sps);
+    seiMessages.push_back(sei);
   }
 
   if(m_pcCfg->getFramePackingArrangementSEIEnabled())
   {
-    SEIFramePacking *sei = xCreateSEIFramePacking ();
-
-    nalu = NALUnit(NAL_UNIT_PREFIX_SEI);
-    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
-    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps);
-    writeRBSPTrailingBits(nalu.m_Bitstream);
-    accessUnit.push_back(new NALUnitEBSP(nalu));
-    delete sei;
-  }
+    SEIFramePacking *sei = new SEIFramePacking;
+    m_seiEncoder.initSEIFramePacking (sei, m_iNumPicCoded);
+    seiMessages.push_back(sei);
+  }
+
+  if(m_pcCfg->getSegmentedRectFramePackingArrangementSEIEnabled())
+  {
+    SEISegmentedRectFramePacking *sei = new SEISegmentedRectFramePacking;
+    m_seiEncoder.initSEISegmentedRectFramePacking(sei);
+    seiMessages.push_back(sei);
+  }
+
   if (m_pcCfg->getDisplayOrientationSEIAngle())
   {
-    SEIDisplayOrientation *sei = xCreateSEIDisplayOrientation();
-
-    nalu = NALUnit(NAL_UNIT_PREFIX_SEI); 
-    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
-    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps); 
-    writeRBSPTrailingBits(nalu.m_Bitstream);
-    accessUnit.push_back(new NALUnitEBSP(nalu));
-    delete sei;
-  }
+    SEIDisplayOrientation *sei = new SEIDisplayOrientation;
+    m_seiEncoder.initSEIDisplayOrientation(sei);
+    seiMessages.push_back(sei);
+  }
+
   if(m_pcCfg->getToneMappingInfoSEIEnabled())
   {
-    SEIToneMappingInfo *sei = xCreateSEIToneMappingInfo ();
-      
-    nalu = NALUnit(NAL_UNIT_PREFIX_SEI); 
-    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
-    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps); 
-    writeRBSPTrailingBits(nalu.m_Bitstream);
-    accessUnit.push_back(new NALUnitEBSP(nalu));
-    delete sei;
-  }
-#if H_MV
-  if( m_pcCfg->getSubBitstreamPropSEIEnabled() )
-  {
-    SEISubBitstreamProperty *sei = xCreateSEISubBitstreamProperty ( sps );
-
-    nalu = NALUnit(NAL_UNIT_PREFIX_SEI); 
-    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
-    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps); 
-    writeRBSPTrailingBits(nalu.m_Bitstream);
-    accessUnit.push_back(new NALUnitEBSP(nalu));
-    delete sei;
-  }
-#endif
+    SEIToneMappingInfo *sei = new SEIToneMappingInfo;
+    m_seiEncoder.initSEIToneMappingInfo (sei);
+    seiMessages.push_back(sei);
+  }
+
+  if(m_pcCfg->getTMCTSSEIEnabled())
+  {
+    SEITempMotionConstrainedTileSets *sei = new SEITempMotionConstrainedTileSets;
+    m_seiEncoder.initSEITempMotionConstrainedTileSets(sei, pps);
+    seiMessages.push_back(sei);
+  }
+
+  if(m_pcCfg->getTimeCodeSEIEnabled())
+  {
+    SEITimeCode *seiTimeCode = new SEITimeCode;
+    m_seiEncoder.initSEITimeCode(seiTimeCode);
+    seiMessages.push_back(seiTimeCode);
+  }
+
+  if(m_pcCfg->getKneeSEIEnabled())
+  {
+    SEIKneeFunctionInfo *sei = new SEIKneeFunctionInfo;
+    m_seiEncoder.initSEIKneeFunctionInfo(sei);
+    seiMessages.push_back(sei);
+  }
+    
+  if(m_pcCfg->getMasteringDisplaySEI().colourVolumeSEIEnabled)
+  {
+    const TComSEIMasteringDisplay &seiCfg=m_pcCfg->getMasteringDisplaySEI();
+    SEIMasteringDisplayColourVolume *sei = new SEIMasteringDisplayColourVolume;
+    sei->values = seiCfg;
+    seiMessages.push_back(sei);
+  }
+
+#if NH_MV
+  if( m_pcCfg->getSubBitstreamPropSEIEnabled() && ( getLayerId() == 0 ) )
+  {
+    SEISubBitstreamProperty *sei = new SEISubBitstreamProperty;
+    m_seiEncoder.initSEISubBitstreamProperty( sei, sps );   
+    seiMessages.push_back(sei);
+  }
+#endif
+}
+
+Void TEncGOP::xCreatePerPictureSEIMessages (Int picInGOP, SEIMessages& seiMessages, SEIMessages& nestedSeiMessages, TComSlice *slice)
+{
+  if( ( m_pcCfg->getBufferingPeriodSEIEnabled() ) && ( slice->getSliceType() == I_SLICE ) &&
+    ( slice->getSPS()->getVuiParametersPresentFlag() ) &&
+    ( ( slice->getSPS()->getVuiParameters()->getHrdParameters()->getNalHrdParametersPresentFlag() )
+    || ( slice->getSPS()->getVuiParameters()->getHrdParameters()->getVclHrdParametersPresentFlag() ) ) )
+  {
+    SEIBufferingPeriod *bufferingPeriodSEI = new SEIBufferingPeriod();
+    m_seiEncoder.initSEIBufferingPeriod(bufferingPeriodSEI, slice);
+    seiMessages.push_back(bufferingPeriodSEI);
+    m_bufferingPeriodSEIPresentInAU = true;
+
+    if (m_pcCfg->getScalableNestingSEIEnabled())
+    {
+      SEIBufferingPeriod *bufferingPeriodSEIcopy = new SEIBufferingPeriod();
+      bufferingPeriodSEI->copyTo(*bufferingPeriodSEIcopy);
+      nestedSeiMessages.push_back(bufferingPeriodSEIcopy);
+    }
+  }
+
+  if (picInGOP ==0 && m_pcCfg->getSOPDescriptionSEIEnabled() ) // write SOP description SEI (if enabled) at the beginning of GOP
+  {
+    SEISOPDescription* sopDescriptionSEI = new SEISOPDescription();
+    m_seiEncoder.initSEISOPDescription(sopDescriptionSEI, slice, picInGOP, m_iLastIDR, m_iGopSize);
+    seiMessages.push_back(sopDescriptionSEI);
+  }
+
+  if( ( m_pcEncTop->getRecoveryPointSEIEnabled() ) && ( slice->getSliceType() == I_SLICE ) )
+  {
+    if( m_pcEncTop->getGradualDecodingRefreshInfoEnabled() && !slice->getRapPicFlag() )
+    {
+      // Gradual decoding refresh SEI
+      SEIGradualDecodingRefreshInfo *gradualDecodingRefreshInfoSEI = new SEIGradualDecodingRefreshInfo();
+      gradualDecodingRefreshInfoSEI->m_gdrForegroundFlag = true; // Indicating all "foreground"
+      seiMessages.push_back(gradualDecodingRefreshInfoSEI);
+    }
+    // Recovery point SEI
+    SEIRecoveryPoint *recoveryPointSEI = new SEIRecoveryPoint();
+    m_seiEncoder.initSEIRecoveryPoint(recoveryPointSEI, slice);
+    seiMessages.push_back(recoveryPointSEI);
+  }
+  if (m_pcCfg->getTemporalLevel0IndexSEIEnabled())
+  {
+    SEITemporalLevel0Index *temporalLevel0IndexSEI = new SEITemporalLevel0Index();
+    m_seiEncoder.initTemporalLevel0IndexSEI(temporalLevel0IndexSEI, slice);
+    seiMessages.push_back(temporalLevel0IndexSEI);
+  }
+
+  if(slice->getSPS()->getVuiParametersPresentFlag() && m_pcCfg->getChromaSamplingFilterHintEnabled() && ( slice->getSliceType() == I_SLICE ))
+  {
+    SEIChromaSamplingFilterHint *seiChromaSamplingFilterHint = new SEIChromaSamplingFilterHint;
+    m_seiEncoder.initSEIChromaSamplingFilterHint(seiChromaSamplingFilterHint, m_pcCfg->getChromaSamplingHorFilterIdc(), m_pcCfg->getChromaSamplingVerFilterIdc());
+    seiMessages.push_back(seiChromaSamplingFilterHint);
+  }
+
+  if( m_pcEncTop->getNoDisplaySEITLayer() && ( slice->getTLayer() >= m_pcEncTop->getNoDisplaySEITLayer() ) )
+  {
+    SEINoDisplay *seiNoDisplay = new SEINoDisplay;
+    seiNoDisplay->m_noDisplay = true;
+    seiMessages.push_back(seiNoDisplay);
+  }
+}
+
+Void TEncGOP::xCreateScalableNestingSEI (SEIMessages& seiMessages, SEIMessages& nestedSeiMessages)
+{
+  SEIMessages tmpMessages;
+  while (!nestedSeiMessages.empty())
+  {
+    SEI* sei=nestedSeiMessages.front();
+    nestedSeiMessages.pop_front();
+    tmpMessages.push_back(sei);
+    SEIScalableNesting *nestingSEI = new SEIScalableNesting();
+    m_seiEncoder.initSEIScalableNesting(nestingSEI, tmpMessages);
+    seiMessages.push_back(nestingSEI);
+    tmpMessages.clear();
+  }
+}
+
+Void TEncGOP::xCreatePictureTimingSEI  (Int IRAPGOPid, SEIMessages& seiMessages, SEIMessages& nestedSeiMessages, SEIMessages& duInfoSeiMessages, TComSlice *slice, Bool isField, std::deque<DUData> &duData)
+{
+  Int picSptDpbOutputDuDelay = 0;
+#if !NH_MV
+  SEIPictureTiming *pictureTimingSEI = new SEIPictureTiming();
+#endif
+
+  const TComVUI *vui = slice->getSPS()->getVuiParameters();
+  const TComHRD *hrd = vui->getHrdParameters();
+
+  // update decoding unit parameters
+  if( ( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() ) &&
+    ( slice->getSPS()->getVuiParametersPresentFlag() ) &&
+    (  hrd->getNalHrdParametersPresentFlag() || hrd->getVclHrdParametersPresentFlag() ) )
+  {
+#if NH_MV
+    // Preliminary fix to avoid memory leak.
+    SEIPictureTiming *pictureTimingSEI = new SEIPictureTiming();
+#endif
+
+    // DU parameters
+    if( hrd->getSubPicCpbParamsPresentFlag() )
+    {
+      UInt numDU = (UInt) duData.size();
+      pictureTimingSEI->m_numDecodingUnitsMinus1     = ( numDU - 1 );
+      pictureTimingSEI->m_duCommonCpbRemovalDelayFlag = false;
+      pictureTimingSEI->m_numNalusInDuMinus1.resize( numDU );
+      pictureTimingSEI->m_duCpbRemovalDelayMinus1.resize( numDU );
+    }
+    pictureTimingSEI->m_auCpbRemovalDelay = std::min<Int>(std::max<Int>(1, m_totalCoded - m_lastBPSEI), static_cast<Int>(pow(2, static_cast<Double>(hrd->getCpbRemovalDelayLengthMinus1()+1)))); // Syntax element signalled as minus, hence the .
+    pictureTimingSEI->m_picDpbOutputDelay = slice->getSPS()->getNumReorderPics(slice->getSPS()->getMaxTLayers()-1) + slice->getPOC() - m_totalCoded;
+    if(m_pcCfg->getEfficientFieldIRAPEnabled() && IRAPGOPid > 0 && IRAPGOPid < m_iGopSize)
+    {
+      // if pictures have been swapped there is likely one more picture delay on their tid. Very rough approximation
+      pictureTimingSEI->m_picDpbOutputDelay ++;
+    }
+    Int factor = hrd->getTickDivisorMinus2() + 2;
+    pictureTimingSEI->m_picDpbOutputDuDelay = factor * pictureTimingSEI->m_picDpbOutputDelay;
+    if( m_pcCfg->getDecodingUnitInfoSEIEnabled() )
+    {
+      picSptDpbOutputDuDelay = factor * pictureTimingSEI->m_picDpbOutputDelay;
+    }
+    if (m_bufferingPeriodSEIPresentInAU)
+    {
+      m_lastBPSEI = m_totalCoded;
+    }
+
+    if( hrd->getSubPicCpbParamsPresentFlag() )
+    {
+      Int i;
+      UInt64 ui64Tmp;
+      UInt uiPrev = 0;
+      UInt numDU = ( pictureTimingSEI->m_numDecodingUnitsMinus1 + 1 );
+      std::vector<UInt> &rDuCpbRemovalDelayMinus1 = pictureTimingSEI->m_duCpbRemovalDelayMinus1;
+      UInt maxDiff = ( hrd->getTickDivisorMinus2() + 2 ) - 1;
+
+      for( i = 0; i < numDU; i ++ )
+      {
+        pictureTimingSEI->m_numNalusInDuMinus1[ i ]       = ( i == 0 ) ? ( duData[i].accumNalsDU - 1 ) : ( duData[i].accumNalsDU- duData[i-1].accumNalsDU - 1 );
+      }
+
+      if( numDU == 1 )
+      {
+        rDuCpbRemovalDelayMinus1[ 0 ] = 0; /* don't care */
+      }
+      else
+      {
+        rDuCpbRemovalDelayMinus1[ numDU - 1 ] = 0;/* by definition */
+        UInt tmp = 0;
+        UInt accum = 0;
+
+        for( i = ( numDU - 2 ); i >= 0; i -- )
+        {
+          ui64Tmp = ( ( ( duData[numDU - 1].accumBitsDU  - duData[i].accumBitsDU ) * ( vui->getTimingInfo()->getTimeScale() / vui->getTimingInfo()->getNumUnitsInTick() ) * ( hrd->getTickDivisorMinus2() + 2 ) ) / ( m_pcCfg->getTargetBitrate() ) );
+          if( (UInt)ui64Tmp > maxDiff )
+          {
+            tmp ++;
+          }
+        }
+        uiPrev = 0;
+
+        UInt flag = 0;
+        for( i = ( numDU - 2 ); i >= 0; i -- )
+        {
+          flag = 0;
+          ui64Tmp = ( ( ( duData[numDU - 1].accumBitsDU  - duData[i].accumBitsDU ) * ( vui->getTimingInfo()->getTimeScale() / vui->getTimingInfo()->getNumUnitsInTick() ) * ( hrd->getTickDivisorMinus2() + 2 ) ) / ( m_pcCfg->getTargetBitrate() ) );
+
+          if( (UInt)ui64Tmp > maxDiff )
+          {
+            if(uiPrev >= maxDiff - tmp)
+            {
+              ui64Tmp = uiPrev + 1;
+              flag = 1;
+            }
+            else                            ui64Tmp = maxDiff - tmp + 1;
+          }
+          rDuCpbRemovalDelayMinus1[ i ] = (UInt)ui64Tmp - uiPrev - 1;
+          if( (Int)rDuCpbRemovalDelayMinus1[ i ] < 0 )
+          {
+            rDuCpbRemovalDelayMinus1[ i ] = 0;
+          }
+          else if (tmp > 0 && flag == 1)
+          {
+            tmp --;
+          }
+          accum += rDuCpbRemovalDelayMinus1[ i ] + 1;
+          uiPrev = accum;
+        }
+      }
+    }
+    
+    if( m_pcCfg->getPictureTimingSEIEnabled() )
+    {
+      pictureTimingSEI->m_picStruct = (isField && slice->getPic()->isTopField())? 1 : isField? 2 : 0;
+      seiMessages.push_back(pictureTimingSEI);
+
+      if ( m_pcCfg->getScalableNestingSEIEnabled() ) // put picture timing SEI into scalable nesting SEI
+      {
+          SEIPictureTiming *pictureTimingSEIcopy = new SEIPictureTiming();
+          pictureTimingSEI->copyTo(*pictureTimingSEIcopy);
+          nestedSeiMessages.push_back(pictureTimingSEIcopy);
+        }
+    }
+
+    if( m_pcCfg->getDecodingUnitInfoSEIEnabled() && hrd->getSubPicCpbParamsPresentFlag() )
+    {
+      for( Int i = 0; i < ( pictureTimingSEI->m_numDecodingUnitsMinus1 + 1 ); i ++ )
+      {
+        SEIDecodingUnitInfo *duInfoSEI = new SEIDecodingUnitInfo();
+        duInfoSEI->m_decodingUnitIdx = i;
+        duInfoSEI->m_duSptCpbRemovalDelay = pictureTimingSEI->m_duCpbRemovalDelayMinus1[i] + 1;
+        duInfoSEI->m_dpbOutputDuDelayPresentFlag = false;
+        duInfoSEI->m_picSptDpbOutputDuDelay = picSptDpbOutputDuDelay;
+
+        duInfoSeiMessages.push_back(duInfoSEI);
+      }
+    }
+  }
+}
+
+Void TEncGOP::xUpdateDuData(AccessUnit &testAU, std::deque<DUData> &duData)
+{
+  if (duData.empty())
+  {
+    return;
+  }
+  // fix first 
+  UInt numNalUnits = (UInt)testAU.size();
+  UInt numRBSPBytes = 0;
+  for (AccessUnit::const_iterator it = testAU.begin(); it != testAU.end(); it++)
+  {
+    numRBSPBytes += UInt((*it)->m_nalUnitData.str().size());
+  }
+  duData[0].accumBitsDU += ( numRBSPBytes << 3 );
+  duData[0].accumNalsDU += numNalUnits;
+
+  // adapt cumulative sums for all following DUs
+  // and add one DU info SEI, if enabled
+  for (Int i=1; i<duData.size(); i++)
+  {
+    if (m_pcCfg->getDecodingUnitInfoSEIEnabled())
+    {
+      numNalUnits  += 1;
+      numRBSPBytes += ( 5 << 3 );
+    }
+    duData[i].accumBitsDU += numRBSPBytes; // probably around 5 bytes
+    duData[i].accumNalsDU += numNalUnits;
+  }
+
+  // The last DU may have a trailing SEI
+  if (m_pcCfg->getDecodedPictureHashSEIEnabled())
+  {
+    duData.back().accumBitsDU += ( 20 << 3 ); // probably around 20 bytes - should be further adjusted, e.g. by type
+    duData.back().accumNalsDU += 1;
+  }
+
+}
+Void TEncGOP::xUpdateTimingSEI(SEIPictureTiming *pictureTimingSEI, std::deque<DUData> &duData, const TComSPS *sps)
+{
+  if (!pictureTimingSEI)
+  {
+    return;
+  }
+  const TComVUI *vui = sps->getVuiParameters();
+  const TComHRD *hrd = vui->getHrdParameters();
+  if( hrd->getSubPicCpbParamsPresentFlag() )
+  {
+    Int i;
+    UInt64 ui64Tmp;
+    UInt uiPrev = 0;
+    UInt numDU = ( pictureTimingSEI->m_numDecodingUnitsMinus1 + 1 );
+    std::vector<UInt> &rDuCpbRemovalDelayMinus1 = pictureTimingSEI->m_duCpbRemovalDelayMinus1;
+    UInt maxDiff = ( hrd->getTickDivisorMinus2() + 2 ) - 1;
+
+    for( i = 0; i < numDU; i ++ )
+    {
+      pictureTimingSEI->m_numNalusInDuMinus1[ i ]       = ( i == 0 ) ? ( duData[i].accumNalsDU - 1 ) : ( duData[i].accumNalsDU- duData[i-1].accumNalsDU - 1 );
+    }
+
+    if( numDU == 1 )
+    {
+      rDuCpbRemovalDelayMinus1[ 0 ] = 0; /* don't care */
+    }
+    else
+    {
+      rDuCpbRemovalDelayMinus1[ numDU - 1 ] = 0;/* by definition */
+      UInt tmp = 0;
+      UInt accum = 0;
+
+      for( i = ( numDU - 2 ); i >= 0; i -- )
+      {
+        ui64Tmp = ( ( ( duData[numDU - 1].accumBitsDU  - duData[i].accumBitsDU ) * ( vui->getTimingInfo()->getTimeScale() / vui->getTimingInfo()->getNumUnitsInTick() ) * ( hrd->getTickDivisorMinus2() + 2 ) ) / ( m_pcCfg->getTargetBitrate() ) );
+        if( (UInt)ui64Tmp > maxDiff )
+        {
+          tmp ++;
+        }
+      }
+      uiPrev = 0;
+
+      UInt flag = 0;
+      for( i = ( numDU - 2 ); i >= 0; i -- )
+      {
+        flag = 0;
+        ui64Tmp = ( ( ( duData[numDU - 1].accumBitsDU  - duData[i].accumBitsDU ) * ( vui->getTimingInfo()->getTimeScale() / vui->getTimingInfo()->getNumUnitsInTick() ) * ( hrd->getTickDivisorMinus2() + 2 ) ) / ( m_pcCfg->getTargetBitrate() ) );
+
+        if( (UInt)ui64Tmp > maxDiff )
+        {
+          if(uiPrev >= maxDiff - tmp)
+          {
+            ui64Tmp = uiPrev + 1;
+            flag = 1;
+          }
+          else                            ui64Tmp = maxDiff - tmp + 1;
+        }
+        rDuCpbRemovalDelayMinus1[ i ] = (UInt)ui64Tmp - uiPrev - 1;
+        if( (Int)rDuCpbRemovalDelayMinus1[ i ] < 0 )
+        {
+          rDuCpbRemovalDelayMinus1[ i ] = 0;
+        }
+        else if (tmp > 0 && flag == 1)
+        {
+          tmp --;
+        }
+        accum += rDuCpbRemovalDelayMinus1[ i ] + 1;
+        uiPrev = accum;
+      }
+    }
+  }
+}
+Void TEncGOP::xUpdateDuInfoSEI(SEIMessages &duInfoSeiMessages, SEIPictureTiming *pictureTimingSEI)
+{
+  if (duInfoSeiMessages.empty() || (pictureTimingSEI == NULL))
+  {
+    return;
+  }
+
+  Int i=0;
+
+  for (SEIMessages::iterator du = duInfoSeiMessages.begin(); du!= duInfoSeiMessages.end(); du++)
+  {
+    SEIDecodingUnitInfo *duInfoSEI = (SEIDecodingUnitInfo*) (*du);
+    duInfoSEI->m_decodingUnitIdx = i;
+    duInfoSEI->m_duSptCpbRemovalDelay = pictureTimingSEI->m_duCpbRemovalDelayMinus1[i] + 1;
+    duInfoSEI->m_dpbOutputDuDelayPresentFlag = false;
+    i++;
+  }
+}
+
+static Void
+cabac_zero_word_padding(TComSlice *const pcSlice, TComPic *const pcPic, const std::size_t binCountsInNalUnits, const std::size_t numBytesInVclNalUnits, std::ostringstream &nalUnitData, const Bool cabacZeroWordPaddingEnabled)
+{
+  const TComSPS &sps=*(pcSlice->getSPS());
+  const Int log2subWidthCxsubHeightC = (pcPic->getComponentScaleX(COMPONENT_Cb)+pcPic->getComponentScaleY(COMPONENT_Cb));
+  const Int minCuWidth  = pcPic->getMinCUWidth();
+  const Int minCuHeight = pcPic->getMinCUHeight();
+  const Int paddedWidth = ((sps.getPicWidthInLumaSamples()  + minCuWidth  - 1) / minCuWidth) * minCuWidth;
+  const Int paddedHeight= ((sps.getPicHeightInLumaSamples() + minCuHeight - 1) / minCuHeight) * minCuHeight;
+  const Int rawBits = paddedWidth * paddedHeight *
+                         (sps.getBitDepth(CHANNEL_TYPE_LUMA) + 2*(sps.getBitDepth(CHANNEL_TYPE_CHROMA)>>log2subWidthCxsubHeightC));
+  const std::size_t threshold = (32/3)*numBytesInVclNalUnits + (rawBits/32);
+  if (binCountsInNalUnits >= threshold)
+  {
+    // need to add additional cabac zero words (each one accounts for 3 bytes (=00 00 03)) to increase numBytesInVclNalUnits
+    const std::size_t targetNumBytesInVclNalUnits = ((binCountsInNalUnits - (rawBits/32))*3+31)/32;
+
+    if (targetNumBytesInVclNalUnits>numBytesInVclNalUnits) // It should be!
+    {
+      const std::size_t numberOfAdditionalBytesNeeded=targetNumBytesInVclNalUnits - numBytesInVclNalUnits;
+      const std::size_t numberOfAdditionalCabacZeroWords=(numberOfAdditionalBytesNeeded+2)/3;
+      const std::size_t numberOfAdditionalCabacZeroBytes=numberOfAdditionalCabacZeroWords*3;
+      if (cabacZeroWordPaddingEnabled)
+      {
+        std::vector<Char> zeroBytesPadding(numberOfAdditionalCabacZeroBytes, Char(0));
+        for(std::size_t i=0; i<numberOfAdditionalCabacZeroWords; i++)
+        {
+          zeroBytesPadding[i*3+2]=3;  // 00 00 03
+        }
+        nalUnitData.write(&(zeroBytesPadding[0]), numberOfAdditionalCabacZeroBytes);
+        printf("Adding %d bytes of padding\n", UInt(numberOfAdditionalCabacZeroWords*3));
+      }
+      else
+      {
+        printf("Standard would normally require adding %d bytes of padding\n", UInt(numberOfAdditionalCabacZeroWords*3));
+      }
+    }
+  }
+}
+
+class EfficientFieldIRAPMapping
+{
+  private:
+    Int  IRAPGOPid;
+    Bool IRAPtoReorder;
+    Bool swapIRAPForward;
+
+  public:
+    EfficientFieldIRAPMapping() :
+      IRAPGOPid(-1),
+      IRAPtoReorder(false),
+      swapIRAPForward(false)
+    { }
+
+    Void initialize(const Bool isField, const Int gopSize, const Int POCLast, const Int numPicRcvd, const Int lastIDR, TEncGOP *pEncGop, TEncCfg *pCfg);
+
+    Int adjustGOPid(const Int gopID);
+    Int restoreGOPid(const Int gopID);
+    Int GetIRAPGOPid() const { return IRAPGOPid; }
+};
+
+Void EfficientFieldIRAPMapping::initialize(const Bool isField, const Int gopSize, const Int POCLast, const Int numPicRcvd, const Int lastIDR, TEncGOP *pEncGop, TEncCfg *pCfg )
+{
+  if(isField)
+  {
+    Int pocCurr;
+    for ( Int iGOPid=0; iGOPid < gopSize; iGOPid++ )
+    {
+      // determine actual POC
+      if(POCLast == 0) //case first frame or first top field
+      {
+        pocCurr=0;
+      }
+      else if(POCLast == 1 && isField) //case first bottom field, just like the first frame, the poc computation is not right anymore, we set the right value
+      {
+        pocCurr = 1;
+      }
+      else
+      {
+        pocCurr = POCLast - numPicRcvd + pCfg->getGOPEntry(iGOPid).m_POC - isField;
+      }
+
+      // check if POC corresponds to IRAP
+      NalUnitType tmpUnitType = pEncGop->getNalUnitType(pocCurr, lastIDR, isField);
+      if(tmpUnitType >= NAL_UNIT_CODED_SLICE_BLA_W_LP && tmpUnitType <= NAL_UNIT_CODED_SLICE_CRA) // if picture is an IRAP
+      {
+        if(pocCurr%2 == 0 && iGOPid < gopSize-1 && pCfg->getGOPEntry(iGOPid).m_POC == pCfg->getGOPEntry(iGOPid+1).m_POC-1)
+        { // if top field and following picture in enc order is associated bottom field
+          IRAPGOPid = iGOPid;
+          IRAPtoReorder = true;
+          swapIRAPForward = true; 
+          break;
+        }
+        if(pocCurr%2 != 0 && iGOPid > 0 && pCfg->getGOPEntry(iGOPid).m_POC == pCfg->getGOPEntry(iGOPid-1).m_POC+1)
+        {
+          // if picture is an IRAP remember to process it first
+          IRAPGOPid = iGOPid;
+          IRAPtoReorder = true;
+          swapIRAPForward = false; 
+          break;
+        }
+      }
+    }
+  }
+}
+
+Int EfficientFieldIRAPMapping::adjustGOPid(const Int GOPid)
+{
+  if(IRAPtoReorder)
+  {
+    if(swapIRAPForward)
+    {
+      if(GOPid == IRAPGOPid)
+      {
+        return IRAPGOPid +1;
+      }
+      else if(GOPid == IRAPGOPid +1)
+      {
+        return IRAPGOPid;
+      }
+    }
+    else
+    {
+      if(GOPid == IRAPGOPid -1)
+      {
+        return IRAPGOPid;
+      }
+      else if(GOPid == IRAPGOPid)
+      {
+        return IRAPGOPid -1;
+      }
+    }
+  }
+  return GOPid;
+}
+
+Int EfficientFieldIRAPMapping::restoreGOPid(const Int GOPid)
+{
+  if(IRAPtoReorder)
+  {
+    if(swapIRAPForward)
+    {
+      if(GOPid == IRAPGOPid)
+      {
+        IRAPtoReorder = false;
+        return IRAPGOPid +1;
+      }
+      else if(GOPid == IRAPGOPid +1)
+      {
+        return GOPid -1;
+      }
+    }
+    else
+    {
+      if(GOPid == IRAPGOPid)
+      {
+        return IRAPGOPid -1;
+      }
+      else if(GOPid == IRAPGOPid -1)
+      {
+        IRAPtoReorder = false;
+        return IRAPGOPid;
+      }
+    }
+  }
+  return GOPid;
+}
+
+
+static UInt calculateCollocatedFromL1Flag(TEncCfg *pCfg, const Int GOPid, const Int gopSize)
+{
+  Int iCloseLeft=1, iCloseRight=-1;
+  for(Int i = 0; i<pCfg->getGOPEntry(GOPid).m_numRefPics; i++)
+  {
+    Int iRef = pCfg->getGOPEntry(GOPid).m_referencePics[i];
+    if(iRef>0&&(iRef<iCloseRight||iCloseRight==-1))
+    {
+      iCloseRight=iRef;
+    }
+    else if(iRef<0&&(iRef>iCloseLeft||iCloseLeft==1))
+    {
+      iCloseLeft=iRef;
+    }
+  }
+  if(iCloseRight>-1)
+  {
+    iCloseRight=iCloseRight+pCfg->getGOPEntry(GOPid).m_POC-1;
+  }
+  if(iCloseLeft<1)
+  {
+    iCloseLeft=iCloseLeft+pCfg->getGOPEntry(GOPid).m_POC-1;
+    while(iCloseLeft<0)
+    {
+      iCloseLeft+=gopSize;
+    }
+  }
+  Int iLeftQP=0, iRightQP=0;
+  for(Int i=0; i<gopSize; i++)
+  {
+    if(pCfg->getGOPEntry(i).m_POC==(iCloseLeft%gopSize)+1)
+    {
+      iLeftQP= pCfg->getGOPEntry(i).m_QPOffset;
+    }
+    if (pCfg->getGOPEntry(i).m_POC==(iCloseRight%gopSize)+1)
+    {
+      iRightQP=pCfg->getGOPEntry(i).m_QPOffset;
+    }
+  }
+  if(iCloseRight>-1&&iRightQP<iLeftQP)
+  {
+    return 0;
+  }
+  else
+  {
+    return 1;
+  }
 }
 
@@ -392,18 +1058,24 @@
 // Public member functions
 // ====================================================================================================================
-#if H_MV
+#if NH_MV
 Void TEncGOP::initGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP)
 {
-  xInitGOP( iPOCLast, iNumPicRcvd, rcListPic, rcListPicYuvRecOut, false );
+  xInitGOP( iPOCLast, iNumPicRcvd, false );
   m_iNumPicCoded = 0;
 }
 #endif
-#if H_MV
-Void TEncGOP::compressPicInGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP, Int iGOPid, bool isField, bool isTff)
+#if NH_MV
+Void TEncGOP::compressPicInGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, 
+                                TComList<TComPicYuv*>& rcListPicYuvRecOut,  std::list<AccessUnit>& accessUnitsInGOP, 
+                                Bool isField, Bool isTff, const InputColourSpaceConversion snr_conversion, const Bool printFrameMSE, Int iGOPid )
 #else
-Void TEncGOP::compressGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP, bool isField, bool isTff)
-#endif
-{
-  TComPic*        pcPic;
+Void TEncGOP::compressGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic,
+                           TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP,
+                           Bool isField, Bool isTff, const InputColourSpaceConversion snr_conversion, const Bool printFrameMSE )
+#endif
+{
+  // TODO: Split this function up.
+
+  TComPic*        pcPic = NULL;
   TComPicYuv*     pcPicYuvRecOut;
   TComSlice*      pcSlice;
@@ -411,160 +1083,46 @@
   pcBitstreamRedirect = new TComOutputBitstream;
   AccessUnit::iterator  itLocationToPushSliceHeaderNALU; // used to store location where NALU containing slice header is to be inserted
-  UInt                  uiOneBitstreamPerSliceLength = 0;
-  TEncSbac* pcSbacCoders = NULL;
-  TComOutputBitstream* pcSubstreamsOut = NULL;
-
-#if !H_MV
-  xInitGOP( iPOCLast, iNumPicRcvd, rcListPic, rcListPicYuvRecOut, isField );
-
-  
+#if !NH_MV
+  xInitGOP( iPOCLast, iNumPicRcvd, isField );
+#endif
+
   m_iNumPicCoded = 0;
-#endif
-  SEIPictureTiming pictureTimingSEI;
-  Bool writeSOP = m_pcCfg->getSOPDescriptionSEIEnabled();
-  // Initialize Scalable Nesting SEI with single layer values
-  SEIScalableNesting scalableNestingSEI;
-  scalableNestingSEI.m_bitStreamSubsetFlag           = 1;      // If the nested SEI messages are picture buffereing SEI mesages, picure timing SEI messages or sub-picture timing SEI messages, bitstream_subset_flag shall be equal to 1
-  scalableNestingSEI.m_nestingOpFlag                 = 0;
-  scalableNestingSEI.m_nestingNumOpsMinus1           = 0;      //nesting_num_ops_minus1
-  scalableNestingSEI.m_allLayersFlag                 = 0;
-  scalableNestingSEI.m_nestingNoOpMaxTemporalIdPlus1 = 6 + 1;  //nesting_no_op_max_temporal_id_plus1
-  scalableNestingSEI.m_nestingNumLayersMinus1        = 1 - 1;  //nesting_num_layers_minus1
-  scalableNestingSEI.m_nestingLayerId[0]             = 0;
-  scalableNestingSEI.m_callerOwnsSEIs                = true;
-  Int picSptDpbOutputDuDelay = 0;
-  UInt *accumBitsDU = NULL;
-  UInt *accumNalsDU = NULL;
+  SEIMessages leadingSeiMessages;
+  SEIMessages nestedSeiMessages;
+  SEIMessages duInfoSeiMessages;
+  SEIMessages trailingSeiMessages;
+  std::deque<DUData> duData;
   SEIDecodingUnitInfo decodingUnitInfoSEI;
-#if EFFICIENT_FIELD_IRAP
-  Int IRAPGOPid = -1;
-  Bool IRAPtoReorder = false;
-  Bool swapIRAPForward = false;
-  if(isField)
-  {
-    Int pocCurr;
-#if !H_MV
-    for ( Int iGOPid=0; iGOPid < m_iGopSize; iGOPid++ )
-#endif
-    {
-      // determine actual POC
-      if(iPOCLast == 0) //case first frame or first top field
-      {
-        pocCurr=0;
-      }
-      else if(iPOCLast == 1 && isField) //case first bottom field, just like the first frame, the poc computation is not right anymore, we set the right value
-      {
-        pocCurr = 1;
-      }
-      else
-      {
-        pocCurr = iPOCLast - iNumPicRcvd + m_pcCfg->getGOPEntry(iGOPid).m_POC - isField;
-      }
-
-      // check if POC corresponds to IRAP
-      NalUnitType tmpUnitType = getNalUnitType(pocCurr, m_iLastIDR, isField);
-      if(tmpUnitType >= NAL_UNIT_CODED_SLICE_BLA_W_LP && tmpUnitType <= NAL_UNIT_CODED_SLICE_CRA) // if picture is an IRAP
-      {
-        if(pocCurr%2 == 0 && iGOPid < m_iGopSize-1 && m_pcCfg->getGOPEntry(iGOPid).m_POC == m_pcCfg->getGOPEntry(iGOPid+1).m_POC-1)
-        { // if top field and following picture in enc order is associated bottom field
-          IRAPGOPid = iGOPid;
-          IRAPtoReorder = true;
-          swapIRAPForward = true; 
-          break;
-        }
-        if(pocCurr%2 != 0 && iGOPid > 0 && m_pcCfg->getGOPEntry(iGOPid).m_POC == m_pcCfg->getGOPEntry(iGOPid-1).m_POC+1)
-        {
-          // if picture is an IRAP remember to process it first
-          IRAPGOPid = iGOPid;
-          IRAPtoReorder = true;
-          swapIRAPForward = false; 
-          break;
-        }
-      }
-    }
-  }
-#endif
-#if !H_MV
+
+  EfficientFieldIRAPMapping effFieldIRAPMap;
+  if (m_pcCfg->getEfficientFieldIRAPEnabled())
+  {
+   effFieldIRAPMap.initialize(isField, m_iGopSize, iPOCLast, iNumPicRcvd, m_iLastIDR, this, m_pcCfg);
+  }
+
+  // reset flag indicating whether pictures have been encoded
+#if !NH_MV
   for ( Int iGOPid=0; iGOPid < m_iGopSize; iGOPid++ )
 #endif
   {
-#if EFFICIENT_FIELD_IRAP
-    if(IRAPtoReorder)
-    {
-      if(swapIRAPForward)
-      {
-        if(iGOPid == IRAPGOPid)
-        {
-          iGOPid = IRAPGOPid +1;
-        }
-        else if(iGOPid == IRAPGOPid +1)
-        {
-          iGOPid = IRAPGOPid;
-        }
-      }
-      else
-      {
-        if(iGOPid == IRAPGOPid -1)
-        {
-          iGOPid = IRAPGOPid;
-        }
-        else if(iGOPid == IRAPGOPid)
-        {
-          iGOPid = IRAPGOPid -1;
-        }
-      }
-    }
-#endif
-    UInt uiColDir = 1;
+    m_pcCfg->setEncodedFlag(iGOPid, false);
+  }
+#if !NH_MV
+  for ( Int iGOPid=0; iGOPid < m_iGopSize; iGOPid++ )
+#endif
+  {
+    if (m_pcCfg->getEfficientFieldIRAPEnabled())
+    {
+      iGOPid=effFieldIRAPMap.adjustGOPid(iGOPid);
+    }
+
     //-- For time output for each slice
-    long iBeforeTime = clock();
-
-    //select uiColDir
-    Int iCloseLeft=1, iCloseRight=-1;
-    for(Int i = 0; i<m_pcCfg->getGOPEntry(iGOPid).m_numRefPics; i++) 
-    {
-      Int iRef = m_pcCfg->getGOPEntry(iGOPid).m_referencePics[i];
-      if(iRef>0&&(iRef<iCloseRight||iCloseRight==-1))
-      {
-        iCloseRight=iRef;
-      }
-      else if(iRef<0&&(iRef>iCloseLeft||iCloseLeft==1))
-      {
-        iCloseLeft=iRef;
-      }
-    }
-    if(iCloseRight>-1)
-    {
-      iCloseRight=iCloseRight+m_pcCfg->getGOPEntry(iGOPid).m_POC-1;
-    }
-    if(iCloseLeft<1) 
-    {
-      iCloseLeft=iCloseLeft+m_pcCfg->getGOPEntry(iGOPid).m_POC-1;
-      while(iCloseLeft<0)
-      {
-        iCloseLeft+=m_iGopSize;
-      }
-    }
-    Int iLeftQP=0, iRightQP=0;
-    for(Int i=0; i<m_iGopSize; i++)
-    {
-      if(m_pcCfg->getGOPEntry(i).m_POC==(iCloseLeft%m_iGopSize)+1)
-      {
-        iLeftQP= m_pcCfg->getGOPEntry(i).m_QPOffset;
-      }
-      if (m_pcCfg->getGOPEntry(i).m_POC==(iCloseRight%m_iGopSize)+1)
-      {
-        iRightQP=m_pcCfg->getGOPEntry(i).m_QPOffset;
-      }
-    }
-    if(iCloseRight>-1&&iRightQP<iLeftQP)
-    {
-      uiColDir=0;
-    }
+    clock_t iBeforeTime = clock();
+
+    UInt uiColDir = calculateCollocatedFromL1Flag(m_pcCfg, iGOPid, m_iGopSize);
 
     /////////////////////////////////////////////////////////////////////////////////////////////////// Initial to start encoding
     Int iTimeOffset;
     Int pocCurr;
-    
     if(iPOCLast == 0) //case first frame or first top field
     {
@@ -579,39 +1137,15 @@
     else
     {
-      pocCurr = iPOCLast - iNumPicRcvd + m_pcCfg->getGOPEntry(iGOPid).m_POC - isField;
+      pocCurr = iPOCLast - iNumPicRcvd + m_pcCfg->getGOPEntry(iGOPid).m_POC - ((isField && m_iGopSize>1) ? 1:0);
       iTimeOffset = m_pcCfg->getGOPEntry(iGOPid).m_POC;
     }
+
     if(pocCurr>=m_pcCfg->getFramesToBeEncoded())
     {
-#if EFFICIENT_FIELD_IRAP
-      if(IRAPtoReorder)
-      {
-        if(swapIRAPForward)
-        {
-          if(iGOPid == IRAPGOPid)
-          {
-            iGOPid = IRAPGOPid +1;
-            IRAPtoReorder = false;
-          }
-          else if(iGOPid == IRAPGOPid +1)
-          {
-            iGOPid --;
-          }
-        }
-        else
-        {
-          if(iGOPid == IRAPGOPid)
-          {
-            iGOPid = IRAPGOPid -1;
-          }
-          else if(iGOPid == IRAPGOPid -1)
-          {
-            iGOPid = IRAPGOPid;
-            IRAPtoReorder = false;
-          }
-        }
-      }
-#endif
-#if H_MV
+      if (m_pcCfg->getEfficientFieldIRAPEnabled())
+      {
+        iGOPid=effFieldIRAPMap.restoreGOPid(iGOPid);
+      }
+#if NH_MV
       delete pcBitstreamRedirect;
       return;
@@ -624,23 +1158,21 @@
     {
       m_iLastIDR = pocCurr;
-    }        
+    }
     // start a new access unit: create an entry in the list of output access units
     accessUnitsInGOP.push_back(AccessUnit());
     AccessUnit& accessUnit = accessUnitsInGOP.back();
-    xGetBuffer( rcListPic, rcListPicYuvRecOut, iNumPicRcvd, iTimeOffset, pcPic, pcPicYuvRecOut, pocCurr, isField);
+    xGetBuffer( rcListPic, rcListPicYuvRecOut, iNumPicRcvd, iTimeOffset, pcPic, pcPicYuvRecOut, pocCurr, isField );
 
     //  Slice data initialization
     pcPic->clearSliceBuffer();
-    assert(pcPic->getNumAllocatedSlice() == 1);
+    pcPic->allocateNewSlice();
     m_pcSliceEncoder->setSliceIdx(0);
     pcPic->setCurrSliceIdx(0);
-
-
-#if H_MV
-    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, pocCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getVPS(), m_pcEncTop->getSPS(), m_pcEncTop->getPPS(), getLayerId(), isField  );     
+#if NH_MV
+    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, pocCurr, iGOPid, pcSlice, m_pcEncTop->getVPS(), getLayerId(), isField  );     
 #else
-    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, pocCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getSPS(), m_pcEncTop->getPPS(), isField  );
-#endif
-    
+    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, pocCurr, iGOPid, pcSlice, isField );
+#endif
+
     //Set Frame/Field coding
     pcSlice->getPic()->setField(isField);
@@ -648,9 +1180,9 @@
     pcSlice->setLastIDR(m_iLastIDR);
     pcSlice->setSliceIdx(0);
-#if H_MV
+#if NH_MV
     pcSlice->setRefPicSetInterLayer ( &m_refPicSetInterLayer0, &m_refPicSetInterLayer1 ); 
     pcPic  ->setLayerId     ( getLayerId()   );
     pcPic  ->setViewId      ( getViewId()    );    
-#if !H_3D
+#if !NH_3D
     pcSlice->setLayerId     ( getLayerId() );
     pcSlice->setViewId      ( getViewId()  );    
@@ -664,39 +1196,5 @@
     //set default slice level flag to the same as SPS level flag
     pcSlice->setLFCrossSliceBoundaryFlag(  pcSlice->getPPS()->getLoopFilterAcrossSlicesEnabledFlag()  );
-    pcSlice->setScalingList ( m_pcEncTop->getScalingList()  );
-    if(m_pcEncTop->getUseScalingListId() == SCALING_LIST_OFF)
-    {
-      m_pcEncTop->getTrQuant()->setFlatScalingList();
-      m_pcEncTop->getTrQuant()->setUseScalingList(false);
-      m_pcEncTop->getSPS()->setScalingListPresentFlag(false);
-      m_pcEncTop->getPPS()->setScalingListPresentFlag(false);
-    }
-    else if(m_pcEncTop->getUseScalingListId() == SCALING_LIST_DEFAULT)
-    {
-      pcSlice->setDefaultScalingList ();
-      m_pcEncTop->getSPS()->setScalingListPresentFlag(false);
-      m_pcEncTop->getPPS()->setScalingListPresentFlag(false);
-      m_pcEncTop->getTrQuant()->setScalingList(pcSlice->getScalingList());
-      m_pcEncTop->getTrQuant()->setUseScalingList(true);
-    }
-    else if(m_pcEncTop->getUseScalingListId() == SCALING_LIST_FILE_READ)
-    {
-      if(pcSlice->getScalingList()->xParseScalingList(m_pcCfg->getScalingListFile()))
-      {
-        pcSlice->setDefaultScalingList ();
-      }
-      pcSlice->getScalingList()->checkDcOfMatrix();
-      m_pcEncTop->getSPS()->setScalingListPresentFlag(pcSlice->checkDefaultScalingList());
-      m_pcEncTop->getPPS()->setScalingListPresentFlag(false);
-      m_pcEncTop->getTrQuant()->setScalingList(pcSlice->getScalingList());
-      m_pcEncTop->getTrQuant()->setUseScalingList(true);
-    }
-    else
-    {
-      printf("error : ScalingList == %d no support\n",m_pcEncTop->getUseScalingListId());
-      assert(0);
-    }
-
-#if H_MV
+#if NH_MV
     // Set the nal unit type
     pcSlice->setNalUnitType(getNalUnitType(pocCurr, m_iLastIDR, isField));
@@ -718,4 +1216,5 @@
     }
 #else
+
     if(pcSlice->getSliceType()==B_SLICE&&m_pcCfg->getGOPEntry(iGOPid).m_sliceType=='P')
     {
@@ -747,7 +1246,6 @@
       }
     }
-
-#if EFFICIENT_FIELD_IRAP
-#if FIX1172
+    if (m_pcCfg->getEfficientFieldIRAPEnabled())
+    {
     if ( pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
       || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
@@ -762,13 +1260,10 @@
     pcSlice->setAssociatedIRAPType(m_associatedIRAPType);
     pcSlice->setAssociatedIRAPPOC(m_associatedIRAPPOC);
-#endif
-#endif
-    // Do decoding refresh marking if any 
-    pcSlice->decodingRefreshMarking(m_pocCRA, m_bRefreshPending, rcListPic);
+    }
+    // Do decoding refresh marking if any
+    pcSlice->decodingRefreshMarking(m_pocCRA, m_bRefreshPending, rcListPic, m_pcCfg->getEfficientFieldIRAPEnabled());
     m_pcEncTop->selectReferencePictureSet(pcSlice, pocCurr, iGOPid);
-    pcSlice->getRPS()->setNumberOfLongtermPictures(0);
-#if EFFICIENT_FIELD_IRAP
-#else
-#if FIX1172
+    if (!m_pcCfg->getEfficientFieldIRAPEnabled())
+    {
     if ( pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
       || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
@@ -783,22 +1278,12 @@
     pcSlice->setAssociatedIRAPType(m_associatedIRAPType);
     pcSlice->setAssociatedIRAPPOC(m_associatedIRAPPOC);
-#endif
-#endif
-
-#if ALLOW_RECOVERY_POINT_AS_RAP
+    }
     if ((pcSlice->checkThatAllRefPicsAreAvailable(rcListPic, pcSlice->getRPS(), false, m_iLastRecoveryPicPOC, m_pcCfg->getDecodingRefreshType() == 3) != 0) || (pcSlice->isIRAP()) 
-#if EFFICIENT_FIELD_IRAP
-      || (isField && pcSlice->getAssociatedIRAPType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP && pcSlice->getAssociatedIRAPType() <= NAL_UNIT_CODED_SLICE_CRA && pcSlice->getAssociatedIRAPPOC() == pcSlice->getPOC()+1)
-#endif
+      || (m_pcCfg->getEfficientFieldIRAPEnabled() && isField && pcSlice->getAssociatedIRAPType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP && pcSlice->getAssociatedIRAPType() <= NAL_UNIT_CODED_SLICE_CRA && pcSlice->getAssociatedIRAPPOC() == pcSlice->getPOC()+1)
       )
     {
-      pcSlice->createExplicitReferencePictureSetFromReference(rcListPic, pcSlice->getRPS(), pcSlice->isIRAP(), m_iLastRecoveryPicPOC, m_pcCfg->getDecodingRefreshType() == 3);
-    }
-#else
-    if ((pcSlice->checkThatAllRefPicsAreAvailable(rcListPic, pcSlice->getRPS(), false) != 0) || (pcSlice->isIRAP()))
-    {
-      pcSlice->createExplicitReferencePictureSetFromReference(rcListPic, pcSlice->getRPS(), pcSlice->isIRAP());
-    }
-#endif
+      pcSlice->createExplicitReferencePictureSetFromReference(rcListPic, pcSlice->getRPS(), pcSlice->isIRAP(), m_iLastRecoveryPicPOC, m_pcCfg->getDecodingRefreshType() == 3, m_pcCfg->getEfficientFieldIRAPEnabled());
+    }
+
     pcSlice->applyReferencePictureSet(rcListPic, pcSlice->getRPS());
 
@@ -827,10 +1312,10 @@
         {
           Int lTid= m_pcCfg->getGOPEntry(ii).m_temporalId;
-          if(lTid==pcSlice->getTLayer()) 
+          if(lTid==pcSlice->getTLayer())
           {
-            TComReferencePictureSet* nRPS = pcSlice->getSPS()->getRPSList()->getReferencePictureSet(ii);
+            const TComReferencePictureSet* nRPS = pcSlice->getSPS()->getRPSList()->getReferencePictureSet(ii);
             for(Int jj=0;jj<nRPS->getNumberOfPictures();jj++)
             {
-              if(nRPS->getUsed(jj)) 
+              if(nRPS->getUsed(jj))
               {
                 Int tPoc=m_pcCfg->getGOPEntry(ii).m_POC+nRPS->getDeltaPOC(jj);
@@ -839,5 +1324,7 @@
                 {
                   if(m_pcCfg->getGOPEntry(kk).m_POC==tPoc)
+                  {
                     break;
+                  }
                 }
                 Int tTid=m_pcCfg->getGOPEntry(kk).m_temporalId;
@@ -852,5 +1339,5 @@
         }
         if(isSTSA==true)
-        {    
+        {
           if(pcSlice->getTemporalLayerNonReferenceFlag())
           {
@@ -868,5 +1355,5 @@
     refPicListModification->setRefPicListModificationFlagL0(0);
     refPicListModification->setRefPicListModificationFlagL1(0);
-#if H_MV
+#if NH_MV
     if ( pcSlice->getPPS()->getNumExtraSliceHeaderBits() > 0 )
     {
@@ -875,11 +1362,11 @@
     }    
 
-    TComVPS*           vps = pcSlice->getVPS();     
-#if H_3D
+    const TComVPS*           vps = pcSlice->getVPS();     
+#if NH_3D
     Int numDirectRefLayers = vps    ->getNumRefListLayers( getLayerId() ); 
 #else
     Int numDirectRefLayers = vps    ->getNumDirectRefLayers( getLayerId() ); 
 #endif
-#if H_3D
+#if NH_3D
     pcSlice->setIvPicLists( m_ivPicLists );         
 
@@ -902,5 +1389,5 @@
           pcSlice->setNumInterLayerRefPicsMinus1( gopEntry.m_numActiveRefLayerPics - 1 ); 
         }
-#if H_3D
+#if NH_3D
         if ( gopEntry.m_numActiveRefLayerPics != vps->getNumRefListLayers( getLayerId() ) )
 #else
@@ -927,8 +1414,8 @@
     assert( pcSlice->getNumActiveRefLayerPics() == gopEntry.m_numActiveRefLayerPics ); 
     
-#if H_3D
+#if NH_3D
     if ( m_pcEncTop->decProcAnnexI() )
     {    
-      pcSlice->deriveInCmpPredAndCpAvailFlag(); 
+      pcSlice->deriveInCmpPredAndCpAvailFlag( ); 
       if ( pcSlice->getInCmpPredAvailFlag() )
       {      
@@ -953,9 +1440,10 @@
       pcSlice->init3dToolParameters(); 
       pcSlice->checkInCompPredRefLayers(); 
-    }
-    
-
-    // This needs to be done after initilizaiton of 3D tool parameters.
+    }   
+
+#if NH_3D_IV_MERGE
+    // This needs to be done after initialization of 3D tool parameters.
     pcSlice->setMaxNumMergeCand      ( m_pcCfg->getMaxNumMergeCand()   + ( ( pcSlice->getMpiFlag( ) || pcSlice->getIvMvPredFlag( ) || pcSlice->getViewSynthesisPredFlag( )   ) ? 1 : 0 ));
+#endif
 #endif
 
@@ -976,40 +1464,24 @@
     pcSlice->setNumRefIdx(REF_PIC_LIST_1,min(m_pcCfg->getGOPEntry(iGOPid).m_numRefPicsActive,pcSlice->getRPS()->getNumberOfPictures()));
 #endif
-
-#if ADAPTIVE_QP_SELECTION
-    pcSlice->setTrQuant( m_pcEncTop->getTrQuant() );
-#endif      
-
     //  Set reference list
-#if H_MV    
+#if NH_MV    
     pcSlice->setRefPicList( tempRefPicLists, usedAsLongTerm, numPocTotalCurr ); 
 #else
     pcSlice->setRefPicList ( rcListPic );
 #endif
-#if H_3D
+#if NH_3D_NBDV
     pcSlice->setDefaultRefView();
 #endif
-#if H_3D_ARP
+#if NH_3D_ARP
     //GT: This seems to be broken when layerId in vps is not equal to layerId in nuh
     pcSlice->setARPStepNum(m_ivPicLists);
-    if(pcSlice->getARPStepNum() > 1)
-    {
-      for(Int iLayerId = 0; iLayerId < getLayerId(); iLayerId ++ )
-      {
-        Int  iViewIdx =   pcSlice->getVPS()->getViewIndex(iLayerId);
-        Bool bIsDepth = ( pcSlice->getVPS()->getDepthId  ( iLayerId ) == 1 );
-        if( iViewIdx<getViewIndex() && !bIsDepth )
-        {
-          pcSlice->setBaseViewRefPicList( m_ivPicLists->getPicList( iLayerId ), iViewIdx );
-        }
-      }
-    }
-#endif
-#if H_3D_IC
+#endif
+#if NH_3D_IC
     pcSlice->setICEnableCandidate( m_aICEnableCandidate );         
     pcSlice->setICEnableNum( m_aICEnableNum );         
 #endif
+
     //  Slice info. refinement
-#if H_MV
+#if NH_MV
     if ( pcSlice->getSliceType() == B_SLICE )
     {
@@ -1025,4 +1497,6 @@
     }
 #endif
+    pcSlice->setEncCABACTableIdx(m_pcSliceEncoder->getEncCABACTableIdx());
+
     if (pcSlice->getSliceType() == B_SLICE)
     {
@@ -1047,9 +1521,9 @@
       }
 
-      pcSlice->setCheckLDC(bLowDelay);  
+      pcSlice->setCheckLDC(bLowDelay);
     }
     else
     {
-      pcSlice->setCheckLDC(true);  
+      pcSlice->setCheckLDC(true);
     }
 
@@ -1060,8 +1534,9 @@
 
     pcSlice->setList1IdxToList0Idx();
-#if H_3D_TMVP
+#if NH_3D_TMVP
     if(pcSlice->getLayerId())
       pcSlice->generateAlterRefforTMVP();
 #endif
+
     if (m_pcEncTop->getTMVPModeId() == 2)
     {
@@ -1075,17 +1550,14 @@
         pcSlice->setEnableTMVPFlag(1);
       }
-      pcSlice->getSPS()->setTMVPFlagsPresent(1);
     }
     else if (m_pcEncTop->getTMVPModeId() == 1)
     {
-      pcSlice->getSPS()->setTMVPFlagsPresent(1);
       pcSlice->setEnableTMVPFlag(1);
     }
     else
     {
-      pcSlice->getSPS()->setTMVPFlagsPresent(0);
       pcSlice->setEnableTMVPFlag(0);
     }
-#if H_MV
+#if NH_MV
     if( pcSlice->getIdrPicFlag() )
     {
@@ -1094,5 +1566,5 @@
 #endif
 
-#if H_3D_VSO
+#if NH_3D_VSO
   // Should be moved to TEncTop !!! 
   Bool bUseVSO = m_pcEncTop->getUseVSO();
@@ -1128,4 +1600,5 @@
   }
 #endif
+
     /////////////////////////////////////////////////////////////////////////////////////////////////// Compress a slice
     //  Slice compression
@@ -1144,5 +1617,5 @@
         for ( i=0; i < pcSlice->getNumRefIdx(RefPicList( 1 ) ); i++ )
         {
-          if ( pcSlice->getRefPOC(RefPicList(1), i) != pcSlice->getRefPOC(RefPicList(0), i) ) 
+          if ( pcSlice->getRefPOC(RefPicList(1), i) != pcSlice->getRefPOC(RefPicList(0), i) )
           {
             bGPBcheck=false;
@@ -1161,4 +1634,5 @@
     }
     pcPic->getSlice(pcSlice->getSliceIdx())->setMvdL1ZeroFlag(pcSlice->getMvdL1ZeroFlag());
+
 
     Double lambda            = 0.0;
@@ -1167,5 +1641,5 @@
     Int estimatedBits        = 0;
     Int tmpBitsBeforeWriting = 0;
-    if ( m_pcCfg->getUseRateCtrl() )
+    if ( m_pcCfg->getUseRateCtrl() ) // TODO: does this work with multiple slices and slice-segments?
     {
       Int frameLevel = m_pcRateCtrl->getRCSeq()->getGOPID2Level( iGOPid );
@@ -1198,5 +1672,6 @@
       else if ( frameLevel == 0 )   // intra case, but use the model
       {
-        m_pcSliceEncoder->calCostSliceI(pcPic);
+        m_pcSliceEncoder->calCostSliceI(pcPic); // TODO: This only analyses the first slice segment - what about the others?
+
         if ( m_pcCfg->getIntraPeriod() != 1 )   // do not refine allocated bits for all intra case
         {
@@ -1235,5 +1710,5 @@
       }
 
-      sliceQP = Clip3( -pcSlice->getSPS()->getQpBDOffsetY(), MAX_QP, sliceQP );
+      sliceQP = Clip3( -pcSlice->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA), MAX_QP, sliceQP );
       m_pcRateCtrl->getRCPic()->setPicEstQP( sliceQP );
 
@@ -1241,76 +1716,19 @@
     }
 
-    UInt uiNumSlices = 1;
-
-    UInt uiInternalAddress = pcPic->getNumPartInCU()-4;
-    UInt uiExternalAddress = pcPic->getPicSym()->getNumberOfCUsInFrame()-1;
-    UInt uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
-    UInt uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
-    UInt uiWidth = pcSlice->getSPS()->getPicWidthInLumaSamples();
-    UInt uiHeight = pcSlice->getSPS()->getPicHeightInLumaSamples();
-    while(uiPosX>=uiWidth||uiPosY>=uiHeight) 
-    {
-      uiInternalAddress--;
-      uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
-      uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
-    }
-    uiInternalAddress++;
-    if(uiInternalAddress==pcPic->getNumPartInCU()) 
-    {
-      uiInternalAddress = 0;
-      uiExternalAddress++;
-    }
-    UInt uiRealEndAddress = uiExternalAddress*pcPic->getNumPartInCU()+uiInternalAddress;
-
-    Int  p, j;
-    UInt uiEncCUAddr;
-
-    pcPic->getPicSym()->initTiles(pcSlice->getPPS());
-
-    // Allocate some coders, now we know how many tiles there are.
-    Int iNumSubstreams = pcSlice->getPPS()->getNumSubstreams();
-
-    //generate the Coding Order Map and Inverse Coding Order Map
-    for(p=0, uiEncCUAddr=0; p<pcPic->getPicSym()->getNumberOfCUsInFrame(); p++, uiEncCUAddr = pcPic->getPicSym()->xCalculateNxtCUAddr(uiEncCUAddr))
-    {
-      pcPic->getPicSym()->setCUOrderMap(p, uiEncCUAddr);
-      pcPic->getPicSym()->setInverseCUOrderMap(uiEncCUAddr, p);
-    }
-    pcPic->getPicSym()->setCUOrderMap(pcPic->getPicSym()->getNumberOfCUsInFrame(), pcPic->getPicSym()->getNumberOfCUsInFrame());    
-    pcPic->getPicSym()->setInverseCUOrderMap(pcPic->getPicSym()->getNumberOfCUsInFrame(), pcPic->getPicSym()->getNumberOfCUsInFrame());
-
-    // Allocate some coders, now we know how many tiles there are.
-    m_pcEncTop->createWPPCoders(iNumSubstreams);
-    pcSbacCoders = m_pcEncTop->getSbacCoders();
-    pcSubstreamsOut = new TComOutputBitstream[iNumSubstreams];
-
-    UInt startCUAddrSliceIdx = 0; // used to index "m_uiStoredStartCUAddrForEncodingSlice" containing locations of slice boundaries
-    UInt startCUAddrSlice    = 0; // used to keep track of current slice's starting CU addr.
-    pcSlice->setSliceCurStartCUAddr( startCUAddrSlice ); // Setting "start CU addr" for current slice
-    m_storedStartCUAddrForEncodingSlice.clear();
-
-    UInt startCUAddrSliceSegmentIdx = 0; // used to index "m_uiStoredStartCUAddrForEntropyEncodingSlice" containing locations of slice boundaries
-    UInt startCUAddrSliceSegment    = 0; // used to keep track of current Dependent slice's starting CU addr.
-    pcSlice->setSliceSegmentCurStartCUAddr( startCUAddrSliceSegment ); // Setting "start CU addr" for current Dependent slice
-
-    m_storedStartCUAddrForEncodingSliceSegment.clear();
-    UInt nextCUAddr = 0;
-    m_storedStartCUAddrForEncodingSlice.push_back (nextCUAddr);
-    startCUAddrSliceIdx++;
-    m_storedStartCUAddrForEncodingSliceSegment.push_back(nextCUAddr);
-    startCUAddrSliceSegmentIdx++;
-#if H_3D_NBDV
+    UInt uiNumSliceSegments = 1;
+
+#if NH_3D_NBDV
       if(pcSlice->getViewIndex() && !pcSlice->getIsDepth()) //Notes from QC: this condition shall be changed once the configuration is completed, e.g. in pcSlice->getSPS()->getMultiviewMvPredMode() || ARP in prev. HTM. Remove this comment once it is done.
       {
-        Int iColPoc = pcSlice->getRefPOC(RefPicList(1-pcSlice->getColFromL0Flag()), pcSlice->getColRefIdx());
+        Int iColPoc = pcSlice->getRefPOC(RefPicList(1 - pcSlice->getColFromL0Flag()), pcSlice->getColRefIdx());
         pcPic->setNumDdvCandPics(pcPic->getDisCandRefPictures(iColPoc));
       }
 #endif
-#if H_3D
+#if NH_3D
       pcSlice->setDepthToDisparityLUTs(); 
 
 #endif
 
-#if H_3D_NBDV
+#if NH_3D_NBDV
       if(pcSlice->getViewIndex() && !pcSlice->getIsDepth() && !pcSlice->isIntra()) //Notes from QC: this condition shall be changed once the configuration is completed, e.g. in pcSlice->getSPS()->getMultiviewMvPredMode() || ARP in prev. HTM. Remove this comment once it is done.
       {
@@ -1323,64 +1741,58 @@
       }
 #endif
-    while(nextCUAddr<uiRealEndAddress) // determine slice boundaries
-    {
-      pcSlice->setNextSlice       ( false );
-      pcSlice->setNextSliceSegment( false );
-      assert(pcPic->getNumAllocatedSlice() == startCUAddrSliceIdx);
-      m_pcSliceEncoder->precompressSlice( pcPic );
-      m_pcSliceEncoder->compressSlice   ( pcPic );
-
-      Bool bNoBinBitConstraintViolated = (!pcSlice->isNextSlice() && !pcSlice->isNextSliceSegment());
-      if (pcSlice->isNextSlice() || (bNoBinBitConstraintViolated && m_pcCfg->getSliceMode()==FIXED_NUMBER_OF_LCU))
-      {
-        startCUAddrSlice = pcSlice->getSliceCurEndCUAddr();
-        // Reconstruction slice
-        m_storedStartCUAddrForEncodingSlice.push_back(startCUAddrSlice);
-        startCUAddrSliceIdx++;
-        // Dependent slice
-        if (startCUAddrSliceSegmentIdx>0 && m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx-1] != startCUAddrSlice)
-        {
-          m_storedStartCUAddrForEncodingSliceSegment.push_back(startCUAddrSlice);
-          startCUAddrSliceSegmentIdx++;
-        }
-
-        if (startCUAddrSlice < uiRealEndAddress)
-        {
-          pcPic->allocateNewSlice();          
-          pcPic->setCurrSliceIdx                  ( startCUAddrSliceIdx-1 );
-          m_pcSliceEncoder->setSliceIdx           ( startCUAddrSliceIdx-1 );
-          pcSlice = pcPic->getSlice               ( startCUAddrSliceIdx-1 );
-          pcSlice->copySliceInfo                  ( pcPic->getSlice(0)      );
-          pcSlice->setSliceIdx                    ( startCUAddrSliceIdx-1 );
-          pcSlice->setSliceCurStartCUAddr         ( startCUAddrSlice      );
-          pcSlice->setSliceSegmentCurStartCUAddr  ( startCUAddrSlice      );
-          pcSlice->setSliceBits(0);
-          uiNumSlices ++;
-        }
-      }
-      else if (pcSlice->isNextSliceSegment() || (bNoBinBitConstraintViolated && m_pcCfg->getSliceSegmentMode()==FIXED_NUMBER_OF_LCU))
-      {
-        startCUAddrSliceSegment                                                     = pcSlice->getSliceSegmentCurEndCUAddr();
-        m_storedStartCUAddrForEncodingSliceSegment.push_back(startCUAddrSliceSegment);
-        startCUAddrSliceSegmentIdx++;
-        pcSlice->setSliceSegmentCurStartCUAddr( startCUAddrSliceSegment );
-      }
-      else
-      {
-        startCUAddrSlice                                                            = pcSlice->getSliceCurEndCUAddr();
-        startCUAddrSliceSegment                                                     = pcSlice->getSliceSegmentCurEndCUAddr();
-      }        
-
-      nextCUAddr = (startCUAddrSlice > startCUAddrSliceSegment) ? startCUAddrSlice : startCUAddrSliceSegment;
-    }
-    m_storedStartCUAddrForEncodingSlice.push_back( pcSlice->getSliceCurEndCUAddr());
-    startCUAddrSliceIdx++;
-    m_storedStartCUAddrForEncodingSliceSegment.push_back(pcSlice->getSliceCurEndCUAddr());
-    startCUAddrSliceSegmentIdx++;
-
+    // Allocate some coders, now the number of tiles are known.
+    const Int numSubstreamsColumns = (pcSlice->getPPS()->getNumTileColumnsMinus1() + 1);
+    const Int numSubstreamRows     = pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag() ? pcPic->getFrameHeightInCtus() : (pcSlice->getPPS()->getNumTileRowsMinus1() + 1);
+    const Int numSubstreams        = numSubstreamRows * numSubstreamsColumns;
+    std::vector<TComOutputBitstream> substreamsOut(numSubstreams);
+
+    // now compress (trial encode) the various slice segments (slices, and dependent slices)
+    {
+      const UInt numberOfCtusInFrame=pcPic->getPicSym()->getNumberOfCtusInFrame();
+      pcSlice->setSliceCurStartCtuTsAddr( 0 );
+      pcSlice->setSliceSegmentCurStartCtuTsAddr( 0 );
+
+      for(UInt nextCtuTsAddr = 0; nextCtuTsAddr < numberOfCtusInFrame; )
+      {
+        m_pcSliceEncoder->precompressSlice( pcPic );
+        m_pcSliceEncoder->compressSlice   ( pcPic, false, false );
+
+        const UInt curSliceSegmentEnd = pcSlice->getSliceSegmentCurEndCtuTsAddr();
+        if (curSliceSegmentEnd < numberOfCtusInFrame)
+        {
+          const Bool bNextSegmentIsDependentSlice=curSliceSegmentEnd<pcSlice->getSliceCurEndCtuTsAddr();
+          const UInt sliceBits=pcSlice->getSliceBits();
+          pcPic->allocateNewSlice();
+          // prepare for next slice
+          pcPic->setCurrSliceIdx                    ( uiNumSliceSegments );
+          m_pcSliceEncoder->setSliceIdx             ( uiNumSliceSegments   );
+          pcSlice = pcPic->getSlice                 ( uiNumSliceSegments   );
+          assert(pcSlice->getPPS()!=0);
+          pcSlice->copySliceInfo                    ( pcPic->getSlice(uiNumSliceSegments-1)  );
+          pcSlice->setSliceIdx                      ( uiNumSliceSegments   );
+          if (bNextSegmentIsDependentSlice)
+          {
+            pcSlice->setSliceBits(sliceBits);
+          }
+          else
+          {
+            pcSlice->setSliceCurStartCtuTsAddr      ( curSliceSegmentEnd );
+            pcSlice->setSliceBits(0);
+          }
+          pcSlice->setDependentSliceSegmentFlag(bNextSegmentIsDependentSlice);
+          pcSlice->setSliceSegmentCurStartCtuTsAddr ( curSliceSegmentEnd );
+          // TODO: optimise cabac_init during compress slice to improve multi-slice operation
+          // pcSlice->setEncCABACTableIdx(m_pcSliceEncoder->getEncCABACTableIdx());
+          uiNumSliceSegments ++;
+        }
+        nextCtuTsAddr = curSliceSegmentEnd;
+      }
+    }
+
+    duData.clear();
     pcSlice = pcPic->getSlice(0);
 
-    // SAO parameter estimation using non-deblocked pixels for LCU bottom and right boundary areas
-    if( pcSlice->getSPS()->getUseSAO() && m_pcCfg->getSaoLcuBoundary() )
+    // SAO parameter estimation using non-deblocked pixels for CTU bottom and right boundary areas
+    if( pcSlice->getSPS()->getUseSAO() && m_pcCfg->getSaoCtuBoundary() )
     {
       m_pcSAO->getPreDBFStatistics(pcPic);
@@ -1392,5 +1804,5 @@
     if ( m_pcCfg->getDeblockingFilterMetric() )
     {
-      dblMetric(pcPic, uiNumSlices);
+      applyDeblockingFilterMetric(pcPic, uiNumSliceSegments);
     }
     m_pcLoopFilter->loopFilterPic( pcPic );
@@ -1398,1022 +1810,315 @@
     /////////////////////////////////////////////////////////////////////////////////////////////////// File writing
     // Set entropy coder
-    m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder, pcSlice );
-
-    /* write various header sets. */
+    m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder );
     if ( m_bSeqFirst )
     {
-      OutputNALUnit nalu(NAL_UNIT_VPS);
-#if H_MV
-      if( getLayerId() == 0 )
-      {
+      // write various parameter sets
+      actualTotalBits += xWriteParameterSets(accessUnit, pcSlice);
+#if PPS_FIX_DEPTH
+      if(!pcSlice->getIsDepth() || !pcSlice->getViewIndex() )
+      {
+#endif
+#if PPS_FIX_DEPTH
+      }
+#endif
+
+
+      // create prefix SEI messages at the beginning of the sequence
+      assert(leadingSeiMessages.empty());
+      xCreateIRAPLeadingSEIMessages(leadingSeiMessages, pcSlice->getSPS(), pcSlice->getPPS());
+
+      m_bSeqFirst = false;
+    }
+
+    // reset presence of BP SEI indication
+    m_bufferingPeriodSEIPresentInAU = false;
+    // create prefix SEI associated with a picture
+    xCreatePerPictureSEIMessages(iGOPid, leadingSeiMessages, nestedSeiMessages, pcSlice);
+
+    /* use the main bitstream buffer for storing the marshalled picture */
+    m_pcEntropyCoder->setBitstream(NULL);
+
+    pcSlice = pcPic->getSlice(0);
+
+    if (pcSlice->getSPS()->getUseSAO())
+    {
+      Bool sliceEnabled[MAX_NUM_COMPONENT];
+      TComBitCounter tempBitCounter;
+      tempBitCounter.resetBits();
+      m_pcEncTop->getRDGoOnSbacCoder()->setBitstream(&tempBitCounter);
+      m_pcSAO->initRDOCabacCoder(m_pcEncTop->getRDGoOnSbacCoder(), pcSlice);
+      m_pcSAO->SAOProcess(pcPic, sliceEnabled, pcPic->getSlice(0)->getLambdas(), m_pcCfg->getTestSAODisableAtPictureLevel(), m_pcCfg->getSaoEncodingRate(), m_pcCfg->getSaoEncodingRateChroma(), m_pcCfg->getSaoCtuBoundary());
+      m_pcSAO->PCMLFDisableProcess(pcPic);
+      m_pcEncTop->getRDGoOnSbacCoder()->setBitstream(NULL);
+
+      //assign SAO slice header
+      for(Int s=0; s< uiNumSliceSegments; s++)
+      {
+        pcPic->getSlice(s)->setSaoEnabledFlag(CHANNEL_TYPE_LUMA, sliceEnabled[COMPONENT_Y]);
+        assert(sliceEnabled[COMPONENT_Cb] == sliceEnabled[COMPONENT_Cr]);
+        pcPic->getSlice(s)->setSaoEnabledFlag(CHANNEL_TYPE_CHROMA, sliceEnabled[COMPONENT_Cb]);
+      }
+    }
+
+    // pcSlice is currently slice 0.
+    std::size_t binCountsInNalUnits   = 0; // For implementation of cabac_zero_word stuffing (section 7.4.3.10)
+    std::size_t numBytesInVclNalUnits = 0; // For implementation of cabac_zero_word stuffing (section 7.4.3.10)
+
+    for( UInt sliceSegmentStartCtuTsAddr = 0, sliceIdxCount=0; sliceSegmentStartCtuTsAddr < pcPic->getPicSym()->getNumberOfCtusInFrame(); sliceIdxCount++, sliceSegmentStartCtuTsAddr=pcSlice->getSliceSegmentCurEndCtuTsAddr() )
+    {
+      pcSlice = pcPic->getSlice(sliceIdxCount);
+      if(sliceIdxCount > 0 && pcSlice->getSliceType()!= I_SLICE)
+      {
+        pcSlice->checkColRefIdx(sliceIdxCount, pcPic);
+      }
+      pcPic->setCurrSliceIdx(sliceIdxCount);
+      m_pcSliceEncoder->setSliceIdx(sliceIdxCount);
+
+      pcSlice->setRPS(pcPic->getSlice(0)->getRPS());
+      pcSlice->setRPSidx(pcPic->getSlice(0)->getRPSidx());
+
+      for ( UInt ui = 0 ; ui < numSubstreams; ui++ )
+      {
+        substreamsOut[ui].clear();
+      }
+
+      m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder );
+      m_pcEntropyCoder->resetEntropy      ( pcSlice );
+      /* start slice NALunit */
+#if NH_MV
+      OutputNALUnit nalu( pcSlice->getNalUnitType(), pcSlice->getTLayer(), getLayerId() );
+#else
+      OutputNALUnit nalu( pcSlice->getNalUnitType(), pcSlice->getTLayer() );
 #endif
       m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
-      m_pcEntropyCoder->encodeVPS(m_pcEncTop->getVPS());
-      writeRBSPTrailingBits(nalu.m_Bitstream);
+
+      pcSlice->setNoRaslOutputFlag(false);
+      if (pcSlice->isIRAP())
+      {
+        if (pcSlice->getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP && pcSlice->getNalUnitType() <= NAL_UNIT_CODED_SLICE_IDR_N_LP)
+        {
+          pcSlice->setNoRaslOutputFlag(true);
+        }
+        //the inference for NoOutputPriorPicsFlag
+        // KJS: This cannot happen at the encoder
+        if (!m_bFirst && pcSlice->isIRAP() && pcSlice->getNoRaslOutputFlag())
+        {
+          if (pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA)
+          {
+            pcSlice->setNoOutputPriorPicsFlag(true);
+          }
+        }
+      }
+
+      pcSlice->setEncCABACTableIdx(m_pcSliceEncoder->getEncCABACTableIdx());
+
+      tmpBitsBeforeWriting = m_pcEntropyCoder->getNumberOfWrittenBits();
+      m_pcEntropyCoder->encodeSliceHeader(pcSlice);
+      actualHeadBits += ( m_pcEntropyCoder->getNumberOfWrittenBits() - tmpBitsBeforeWriting );
+
+      pcSlice->setFinalized(true);
+
+      pcSlice->clearSubstreamSizes(  );
+      {
+        UInt numBinsCoded = 0;
+        m_pcSliceEncoder->encodeSlice(pcPic, &(substreamsOut[0]), numBinsCoded);
+        binCountsInNalUnits+=numBinsCoded;
+      }
+
+      {
+        // Construct the final bitstream by concatenating substreams.
+        // The final bitstream is either nalu.m_Bitstream or pcBitstreamRedirect;
+        // Complete the slice header info.
+        m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder );
+        m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+        m_pcEntropyCoder->encodeTilesWPPEntryPoint( pcSlice );
+
+        // Append substreams...
+        TComOutputBitstream *pcOut = pcBitstreamRedirect;
+        const Int numZeroSubstreamsAtStartOfSlice  = pcPic->getSubstreamForCtuAddr(pcSlice->getSliceSegmentCurStartCtuTsAddr(), false, pcSlice);
+        const Int numSubstreamsToCode  = pcSlice->getNumberOfSubstreamSizes()+1;
+        for ( UInt ui = 0 ; ui < numSubstreamsToCode; ui++ )
+        {
+          pcOut->addSubstream(&(substreamsOut[ui+numZeroSubstreamsAtStartOfSlice]));
+        }
+      }
+
+      // If current NALU is the first NALU of slice (containing slice header) and more NALUs exist (due to multiple dependent slices) then buffer it.
+      // If current NALU is the last NALU of slice and a NALU was buffered, then (a) Write current NALU (b) Update an write buffered NALU at approproate location in NALU list.
+      Bool bNALUAlignedWrittenToList    = false; // used to ensure current NALU is not written more than once to the NALU list.
+      xAttachSliceDataToNalUnit(nalu, pcBitstreamRedirect);
       accessUnit.push_back(new NALUnitEBSP(nalu));
       actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
-
-#if H_MV
-      }
-      nalu = NALUnit(NAL_UNIT_SPS, 0, getLayerId());
-#else
-      nalu = NALUnit(NAL_UNIT_SPS);
-#endif
-      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
-      if (m_bSeqFirst)
-      {
-        pcSlice->getSPS()->setNumLongTermRefPicSPS(m_numLongTermRefPicSPS);
-        for (Int k = 0; k < m_numLongTermRefPicSPS; k++)
-        {
-          pcSlice->getSPS()->setLtRefPicPocLsbSps(k, m_ltRefPicPocLsbSps[k]);
-          pcSlice->getSPS()->setUsedByCurrPicLtSPSFlag(k, m_ltRefPicUsedByCurrPicFlag[k]);
-        }
-      }
-      if( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() )
-      {
-        UInt maxCU = m_pcCfg->getSliceArgument() >> ( pcSlice->getSPS()->getMaxCUDepth() << 1);
-        UInt numDU = ( m_pcCfg->getSliceMode() == 1 ) ? ( pcPic->getNumCUsInFrame() / maxCU ) : ( 0 );
-        if( pcPic->getNumCUsInFrame() % maxCU != 0 || numDU == 0 )
-        {
-          numDU ++;
-        }
-        pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->setNumDU( numDU );
-        pcSlice->getSPS()->setHrdParameters( m_pcCfg->getFrameRate(), numDU, m_pcCfg->getTargetBitrate(), ( m_pcCfg->getIntraPeriod() > 0 ) );
-      }
-      if( m_pcCfg->getBufferingPeriodSEIEnabled() || m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() )
-      {
-        pcSlice->getSPS()->getVuiParameters()->setHrdParametersPresentFlag( true );
-      }
-      m_pcEntropyCoder->encodeSPS(pcSlice->getSPS());
-      writeRBSPTrailingBits(nalu.m_Bitstream);
-      accessUnit.push_back(new NALUnitEBSP(nalu));
-      actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
-
-#if H_MV
-      nalu = NALUnit(NAL_UNIT_PPS, 0, getLayerId());
-#else
-      nalu = NALUnit(NAL_UNIT_PPS);
-#endif
-#if PPS_FIX_DEPTH
-      if(!pcSlice->getIsDepth() || !pcSlice->getViewIndex() )
-      {
-#endif
-      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
-      m_pcEntropyCoder->encodePPS(pcSlice->getPPS());
-      writeRBSPTrailingBits(nalu.m_Bitstream);
-      accessUnit.push_back(new NALUnitEBSP(nalu));
-      actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
-      
-#if PPS_FIX_DEPTH
-      }
-#endif
-      xCreateLeadingSEIMessages(accessUnit, pcSlice->getSPS());
-
-      m_bSeqFirst = false;
-    }
-
-    if (writeSOP) // write SOP description SEI (if enabled) at the beginning of GOP
-    {
-      Int SOPcurrPOC = pocCurr;
-
-      OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
-      m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
-      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
-
-      SEISOPDescription SOPDescriptionSEI;
-      SOPDescriptionSEI.m_sopSeqParameterSetId = pcSlice->getSPS()->getSPSId();
-
-      UInt i = 0;
-      UInt prevEntryId = iGOPid;
-      for (j = iGOPid; j < m_iGopSize; j++)
-      {
-        Int deltaPOC = m_pcCfg->getGOPEntry(j).m_POC - m_pcCfg->getGOPEntry(prevEntryId).m_POC;
-        if ((SOPcurrPOC + deltaPOC) < m_pcCfg->getFramesToBeEncoded())
-        {
-          SOPcurrPOC += deltaPOC;
-          SOPDescriptionSEI.m_sopDescVclNaluType[i] = getNalUnitType(SOPcurrPOC, m_iLastIDR, isField);
-          SOPDescriptionSEI.m_sopDescTemporalId[i] = m_pcCfg->getGOPEntry(j).m_temporalId;
-          SOPDescriptionSEI.m_sopDescStRpsIdx[i] = m_pcEncTop->getReferencePictureSetIdxForSOP(pcSlice, SOPcurrPOC, j);
-          SOPDescriptionSEI.m_sopDescPocDelta[i] = deltaPOC;
-
-          prevEntryId = j;
-          i++;
-        }
-      }
-
-      SOPDescriptionSEI.m_numPicsInSopMinus1 = i - 1;
-
-      m_seiWriter.writeSEImessage( nalu.m_Bitstream, SOPDescriptionSEI, pcSlice->getSPS());
-      writeRBSPTrailingBits(nalu.m_Bitstream);
-      accessUnit.push_back(new NALUnitEBSP(nalu));
-
-      writeSOP = false;
-    }
-
-    if( ( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() ) &&
-        ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) &&
-        ( ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNalHrdParametersPresentFlag() ) 
-       || ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getVclHrdParametersPresentFlag() ) ) )
-    {
-      if( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getSubPicCpbParamsPresentFlag() )
-      {
-        UInt numDU = pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNumDU();
-        pictureTimingSEI.m_numDecodingUnitsMinus1     = ( numDU - 1 );
-        pictureTimingSEI.m_duCommonCpbRemovalDelayFlag = false;
-
-        if( pictureTimingSEI.m_numNalusInDuMinus1 == NULL )
-        {
-          pictureTimingSEI.m_numNalusInDuMinus1       = new UInt[ numDU ];
-        }
-        if( pictureTimingSEI.m_duCpbRemovalDelayMinus1  == NULL )
-        {
-          pictureTimingSEI.m_duCpbRemovalDelayMinus1  = new UInt[ numDU ];
-        }
-        if( accumBitsDU == NULL )
-        {
-          accumBitsDU                                  = new UInt[ numDU ];
-        }
-        if( accumNalsDU == NULL )
-        {
-          accumNalsDU                                  = new UInt[ numDU ];
-        }
-      }
-      pictureTimingSEI.m_auCpbRemovalDelay = std::min<Int>(std::max<Int>(1, m_totalCoded - m_lastBPSEI), static_cast<Int>(pow(2, static_cast<double>(pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getCpbRemovalDelayLengthMinus1()+1)))); // Syntax element signalled as minus, hence the .
-      pictureTimingSEI.m_picDpbOutputDelay = pcSlice->getSPS()->getNumReorderPics(pcSlice->getSPS()->getMaxTLayers()-1) + pcSlice->getPOC() - m_totalCoded;
-#if EFFICIENT_FIELD_IRAP
-      if(IRAPGOPid > 0 && IRAPGOPid < m_iGopSize)
-      {
-        // if pictures have been swapped there is likely one more picture delay on their tid. Very rough approximation
-        pictureTimingSEI.m_picDpbOutputDelay ++;
-      }
-#endif
-      Int factor = pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getTickDivisorMinus2() + 2;
-      pictureTimingSEI.m_picDpbOutputDuDelay = factor * pictureTimingSEI.m_picDpbOutputDelay;
-      if( m_pcCfg->getDecodingUnitInfoSEIEnabled() )
-      {
-        picSptDpbOutputDuDelay = factor * pictureTimingSEI.m_picDpbOutputDelay;
-      }
-    }
-
-    if( ( m_pcCfg->getBufferingPeriodSEIEnabled() ) && ( pcSlice->getSliceType() == I_SLICE ) &&
-        ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) && 
-        ( ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNalHrdParametersPresentFlag() ) 
-       || ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getVclHrdParametersPresentFlag() ) ) )
-    {
-      OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
-      m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
-      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
-
-      SEIBufferingPeriod sei_buffering_period;
-      
-      UInt uiInitialCpbRemovalDelay = (90000/2);                      // 0.5 sec
-      sei_buffering_period.m_initialCpbRemovalDelay      [0][0]     = uiInitialCpbRemovalDelay;
-      sei_buffering_period.m_initialCpbRemovalDelayOffset[0][0]     = uiInitialCpbRemovalDelay;
-      sei_buffering_period.m_initialCpbRemovalDelay      [0][1]     = uiInitialCpbRemovalDelay;
-      sei_buffering_period.m_initialCpbRemovalDelayOffset[0][1]     = uiInitialCpbRemovalDelay;
-
-      Double dTmp = (Double)pcSlice->getSPS()->getVuiParameters()->getTimingInfo()->getNumUnitsInTick() / (Double)pcSlice->getSPS()->getVuiParameters()->getTimingInfo()->getTimeScale();
-
-      UInt uiTmp = (UInt)( dTmp * 90000.0 ); 
-      uiInitialCpbRemovalDelay -= uiTmp;
-      uiInitialCpbRemovalDelay -= uiTmp / ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getTickDivisorMinus2() + 2 );
-      sei_buffering_period.m_initialAltCpbRemovalDelay      [0][0]  = uiInitialCpbRemovalDelay;
-      sei_buffering_period.m_initialAltCpbRemovalDelayOffset[0][0]  = uiInitialCpbRemovalDelay;
-      sei_buffering_period.m_initialAltCpbRemovalDelay      [0][1]  = uiInitialCpbRemovalDelay;
-      sei_buffering_period.m_initialAltCpbRemovalDelayOffset[0][1]  = uiInitialCpbRemovalDelay;
-
-      sei_buffering_period.m_rapCpbParamsPresentFlag              = 0;
-      //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;
-      sei_buffering_period.m_cpbDelayOffset = 0;
-      sei_buffering_period.m_dpbDelayOffset = 0;
-
-      m_seiWriter.writeSEImessage( nalu.m_Bitstream, sei_buffering_period, pcSlice->getSPS());
-      writeRBSPTrailingBits(nalu.m_Bitstream);
-      {
-      UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
-      UInt offsetPosition = m_activeParameterSetSEIPresentInAU;   // Insert BP SEI after APS SEI
-      AccessUnit::iterator it;
-      for(j = 0, it = accessUnit.begin(); j < seiPositionInAu + offsetPosition; j++)
-      {
-        it++;
-      }
-      accessUnit.insert(it, new NALUnitEBSP(nalu));
-      m_bufferingPeriodSEIPresentInAU = true;
-      }
-
-      if (m_pcCfg->getScalableNestingSEIEnabled())
-      {
-        OutputNALUnit naluTmp(NAL_UNIT_PREFIX_SEI);
-        m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
-        m_pcEntropyCoder->setBitstream(&naluTmp.m_Bitstream);
-        scalableNestingSEI.m_nestedSEIs.clear();
-        scalableNestingSEI.m_nestedSEIs.push_back(&sei_buffering_period);
-        m_seiWriter.writeSEImessage( naluTmp.m_Bitstream, scalableNestingSEI, pcSlice->getSPS());
-        writeRBSPTrailingBits(naluTmp.m_Bitstream);
-        UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
-        UInt offsetPosition = m_activeParameterSetSEIPresentInAU + m_bufferingPeriodSEIPresentInAU + m_pictureTimingSEIPresentInAU;   // Insert BP SEI after non-nested APS, BP and PT SEIs
-        AccessUnit::iterator it;
-        for(j = 0, it = accessUnit.begin(); j < seiPositionInAu + offsetPosition; j++)
-        {
-          it++;
-        }
-        accessUnit.insert(it, new NALUnitEBSP(naluTmp));
-        m_nestedBufferingPeriodSEIPresentInAU = true;
-      }
-
-      m_lastBPSEI = m_totalCoded;
-      m_cpbRemovalDelay = 0;
-    }
-    m_cpbRemovalDelay ++;
-    if( ( m_pcEncTop->getRecoveryPointSEIEnabled() ) && ( pcSlice->getSliceType() == I_SLICE ) )
-    {
-      if( m_pcEncTop->getGradualDecodingRefreshInfoEnabled() && !pcSlice->getRapPicFlag() )
-      {
-        // Gradual decoding refresh SEI 
-        OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
-        m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
-        m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
-
-        SEIGradualDecodingRefreshInfo seiGradualDecodingRefreshInfo;
-        seiGradualDecodingRefreshInfo.m_gdrForegroundFlag = true; // Indicating all "foreground"
-
-        m_seiWriter.writeSEImessage( nalu.m_Bitstream, seiGradualDecodingRefreshInfo, pcSlice->getSPS() );
-        writeRBSPTrailingBits(nalu.m_Bitstream);
+      numBytesInVclNalUnits += (std::size_t)(accessUnit.back()->m_nalUnitData.str().size());
+      bNALUAlignedWrittenToList = true;
+
+      if (!bNALUAlignedWrittenToList)
+      {
+        nalu.m_Bitstream.writeAlignZero();
         accessUnit.push_back(new NALUnitEBSP(nalu));
-      }
-    // Recovery point SEI
-      OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
-      m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
-      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
-
-      SEIRecoveryPoint sei_recovery_point;
-      sei_recovery_point.m_recoveryPocCnt    = 0;
-      sei_recovery_point.m_exactMatchingFlag = ( pcSlice->getPOC() == 0 ) ? (true) : (false);
-      sei_recovery_point.m_brokenLinkFlag    = false;
-#if ALLOW_RECOVERY_POINT_AS_RAP
-      if(m_pcCfg->getDecodingRefreshType() == 3)
-      {
-        m_iLastRecoveryPicPOC = pocCurr;
-      }
-#endif
-
-      m_seiWriter.writeSEImessage( nalu.m_Bitstream, sei_recovery_point, pcSlice->getSPS() );
-      writeRBSPTrailingBits(nalu.m_Bitstream);
-      accessUnit.push_back(new NALUnitEBSP(nalu));
-    }
-
-    /* use the main bitstream buffer for storing the marshalled picture */
-    m_pcEntropyCoder->setBitstream(NULL);
-
-    startCUAddrSliceIdx = 0;
-    startCUAddrSlice    = 0; 
-
-    startCUAddrSliceSegmentIdx = 0;
-    startCUAddrSliceSegment    = 0; 
-    nextCUAddr                 = 0;
-    pcSlice = pcPic->getSlice(startCUAddrSliceIdx);
-
-    Int processingState = (pcSlice->getSPS()->getUseSAO())?(EXECUTE_INLOOPFILTER):(ENCODE_SLICE);
-    Bool skippedSlice=false;
-    while (nextCUAddr < uiRealEndAddress) // Iterate over all slices
-    {
-      switch(processingState)
-      {
-      case ENCODE_SLICE:
-        {
-          pcSlice->setNextSlice       ( false );
-          pcSlice->setNextSliceSegment( false );
-          if (nextCUAddr == m_storedStartCUAddrForEncodingSlice[startCUAddrSliceIdx])
-          {
-            pcSlice = pcPic->getSlice(startCUAddrSliceIdx);
-            if(startCUAddrSliceIdx > 0 && pcSlice->getSliceType()!= I_SLICE)
-            {
-              pcSlice->checkColRefIdx(startCUAddrSliceIdx, pcPic);
-            }
-            pcPic->setCurrSliceIdx(startCUAddrSliceIdx);
-            m_pcSliceEncoder->setSliceIdx(startCUAddrSliceIdx);
-            assert(startCUAddrSliceIdx == pcSlice->getSliceIdx());
-            // Reconstruction slice
-            pcSlice->setSliceCurStartCUAddr( nextCUAddr );  // to be used in encodeSlice() + context restriction
-            pcSlice->setSliceCurEndCUAddr  ( m_storedStartCUAddrForEncodingSlice[startCUAddrSliceIdx+1 ] );
-            // Dependent slice
-            pcSlice->setSliceSegmentCurStartCUAddr( nextCUAddr );  // to be used in encodeSlice() + context restriction
-            pcSlice->setSliceSegmentCurEndCUAddr  ( m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx+1 ] );
-
-            pcSlice->setNextSlice       ( true );
-
-            startCUAddrSliceIdx++;
-            startCUAddrSliceSegmentIdx++;
-          } 
-          else if (nextCUAddr == m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx])
-          {
-            // Dependent slice
-            pcSlice->setSliceSegmentCurStartCUAddr( nextCUAddr );  // to be used in encodeSlice() + context restriction
-            pcSlice->setSliceSegmentCurEndCUAddr  ( m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx+1 ] );
-
-            pcSlice->setNextSliceSegment( true );
-
-            startCUAddrSliceSegmentIdx++;
-          }
-
-          pcSlice->setRPS(pcPic->getSlice(0)->getRPS());
-          pcSlice->setRPSidx(pcPic->getSlice(0)->getRPSidx());
-          UInt uiDummyStartCUAddr;
-          UInt uiDummyBoundingCUAddr;
-          m_pcSliceEncoder->xDetermineStartAndBoundingCUAddr(uiDummyStartCUAddr,uiDummyBoundingCUAddr,pcPic,true);
-
-          uiInternalAddress = pcPic->getPicSym()->getPicSCUAddr(pcSlice->getSliceSegmentCurEndCUAddr()-1) % pcPic->getNumPartInCU();
-          uiExternalAddress = pcPic->getPicSym()->getPicSCUAddr(pcSlice->getSliceSegmentCurEndCUAddr()-1) / pcPic->getNumPartInCU();
-          uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
-          uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
-          uiWidth = pcSlice->getSPS()->getPicWidthInLumaSamples();
-          uiHeight = pcSlice->getSPS()->getPicHeightInLumaSamples();
-          while(uiPosX>=uiWidth||uiPosY>=uiHeight)
-          {
-            uiInternalAddress--;
-            uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
-            uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
-          }
-          uiInternalAddress++;
-          if(uiInternalAddress==pcPic->getNumPartInCU())
-          {
-            uiInternalAddress = 0;
-            uiExternalAddress = pcPic->getPicSym()->getCUOrderMap(pcPic->getPicSym()->getInverseCUOrderMap(uiExternalAddress)+1);
-          }
-          UInt endAddress = pcPic->getPicSym()->getPicSCUEncOrder(uiExternalAddress*pcPic->getNumPartInCU()+uiInternalAddress);
-          if(endAddress<=pcSlice->getSliceSegmentCurStartCUAddr()) 
-          {
-            UInt boundingAddrSlice, boundingAddrSliceSegment;
-            boundingAddrSlice          = m_storedStartCUAddrForEncodingSlice[startCUAddrSliceIdx];          
-            boundingAddrSliceSegment = m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx];          
-            nextCUAddr               = min(boundingAddrSlice, boundingAddrSliceSegment);
-            if(pcSlice->isNextSlice())
-            {
-              skippedSlice=true;
-            }
-            continue;
-          }
-          if(skippedSlice) 
-          {
-            pcSlice->setNextSlice       ( true );
-            pcSlice->setNextSliceSegment( false );
-          }
-          skippedSlice=false;
-          pcSlice->allocSubstreamSizes( iNumSubstreams );
-          for ( UInt ui = 0 ; ui < iNumSubstreams; ui++ )
-          {
-            pcSubstreamsOut[ui].clear();
-          }
-
-          m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder, pcSlice );
-          m_pcEntropyCoder->resetEntropy      ();
-          /* start slice NALunit */
-#if H_MV
-          OutputNALUnit nalu( pcSlice->getNalUnitType(), pcSlice->getTLayer(), getLayerId() );
-#else
-          OutputNALUnit nalu( pcSlice->getNalUnitType(), pcSlice->getTLayer() );
-#endif
-          Bool sliceSegment = (!pcSlice->isNextSlice());
-          if (!sliceSegment)
-          {
-            uiOneBitstreamPerSliceLength = 0; // start of a new slice
-          }
-          m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
-
-#if SETTING_NO_OUT_PIC_PRIOR
-          pcSlice->setNoRaslOutputFlag(false);
-          if (pcSlice->isIRAP())
-          {
-            if (pcSlice->getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP && pcSlice->getNalUnitType() <= NAL_UNIT_CODED_SLICE_IDR_N_LP)
-            {
-              pcSlice->setNoRaslOutputFlag(true);
-            }
-            //the inference for NoOutputPriorPicsFlag
-            // KJS: This cannot happen at the encoder
-            if (!m_bFirst && pcSlice->isIRAP() && pcSlice->getNoRaslOutputFlag())
-            {
-              if (pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA)
-              {
-                pcSlice->setNoOutputPriorPicsFlag(true);
-              }
-            }
-          }
-#endif
-
-          tmpBitsBeforeWriting = m_pcEntropyCoder->getNumberOfWrittenBits();
-          m_pcEntropyCoder->encodeSliceHeader(pcSlice);
-          actualHeadBits += ( m_pcEntropyCoder->getNumberOfWrittenBits() - tmpBitsBeforeWriting );
-
-          // is it needed?
-          {
-            if (!sliceSegment)
-            {
-              pcBitstreamRedirect->writeAlignOne();
-            }
-            else
-            {
-              // We've not completed our slice header info yet, do the alignment later.
-            }
-            m_pcSbacCoder->init( (TEncBinIf*)m_pcBinCABAC );
-            m_pcEntropyCoder->setEntropyCoder ( m_pcSbacCoder, pcSlice );
-            m_pcEntropyCoder->resetEntropy    ();
-            for ( UInt ui = 0 ; ui < pcSlice->getPPS()->getNumSubstreams() ; ui++ )
-            {
-              m_pcEntropyCoder->setEntropyCoder ( &pcSbacCoders[ui], pcSlice );
-              m_pcEntropyCoder->resetEntropy    ();
-            }
-          }
-
-          if(pcSlice->isNextSlice())
-          {
-            // set entropy coder for writing
-            m_pcSbacCoder->init( (TEncBinIf*)m_pcBinCABAC );
-            {
-              for ( UInt ui = 0 ; ui < pcSlice->getPPS()->getNumSubstreams() ; ui++ )
-              {
-                m_pcEntropyCoder->setEntropyCoder ( &pcSbacCoders[ui], pcSlice );
-                m_pcEntropyCoder->resetEntropy    ();
-              }
-              pcSbacCoders[0].load(m_pcSbacCoder);
-              m_pcEntropyCoder->setEntropyCoder ( &pcSbacCoders[0], pcSlice );  //ALF is written in substream #0 with CABAC coder #0 (see ALF param encoding below)
-            }
-            m_pcEntropyCoder->resetEntropy    ();
-            // File writing
-            if (!sliceSegment)
-            {
-              m_pcEntropyCoder->setBitstream(pcBitstreamRedirect);
-            }
-            else
-            {
-              m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
-            }
-            // for now, override the TILES_DECODER setting in order to write substreams.
-            m_pcEntropyCoder->setBitstream    ( &pcSubstreamsOut[0] );
-
-          }
-          pcSlice->setFinalized(true);
-
-          m_pcSbacCoder->load( &pcSbacCoders[0] );
-
-          pcSlice->setTileOffstForMultES( uiOneBitstreamPerSliceLength );
-            pcSlice->setTileLocationCount ( 0 );
-          m_pcSliceEncoder->encodeSlice(pcPic, pcSubstreamsOut);
-
-          {
-            // Construct the final bitstream by flushing and concatenating substreams.
-            // The final bitstream is either nalu.m_Bitstream or pcBitstreamRedirect;
-            UInt* puiSubstreamSizes = pcSlice->getSubstreamSizes();
-            UInt uiTotalCodedSize = 0; // for padding calcs.
-            UInt uiNumSubstreamsPerTile = iNumSubstreams;
-            if (iNumSubstreams > 1)
-            {
-              uiNumSubstreamsPerTile /= pcPic->getPicSym()->getNumTiles();
-            }
-            for ( UInt ui = 0 ; ui < iNumSubstreams; ui++ )
-            {
-              // Flush all substreams -- this includes empty ones.
-              // Terminating bit and flush.
-              m_pcEntropyCoder->setEntropyCoder   ( &pcSbacCoders[ui], pcSlice );
-              m_pcEntropyCoder->setBitstream      (  &pcSubstreamsOut[ui] );
-              m_pcEntropyCoder->encodeTerminatingBit( 1 );
-              m_pcEntropyCoder->encodeSliceFinish();
-
-              pcSubstreamsOut[ui].writeByteAlignment();   // Byte-alignment in slice_data() at end of sub-stream
-              // Byte alignment is necessary between tiles when tiles are independent.
-              uiTotalCodedSize += pcSubstreamsOut[ui].getNumberOfWrittenBits();
-
-              Bool bNextSubstreamInNewTile = ((ui+1) < iNumSubstreams)&& ((ui+1)%uiNumSubstreamsPerTile == 0);
-              if (bNextSubstreamInNewTile)
-              {
-                pcSlice->setTileLocation(ui/uiNumSubstreamsPerTile, pcSlice->getTileOffstForMultES()+(uiTotalCodedSize>>3));
-              }
-              if (ui+1 < pcSlice->getPPS()->getNumSubstreams())
-              {
-                puiSubstreamSizes[ui] = pcSubstreamsOut[ui].getNumberOfWrittenBits() + (pcSubstreamsOut[ui].countStartCodeEmulations()<<3);
-              }
-            }
-
-            // Complete the slice header info.
-            m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder, pcSlice );
-            m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
-            m_pcEntropyCoder->encodeTilesWPPEntryPoint( pcSlice );
-
-            // Substreams...
-            TComOutputBitstream *pcOut = pcBitstreamRedirect;
-          Int offs = 0;
-          Int nss = pcSlice->getPPS()->getNumSubstreams();
-          if (pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag())
-          {
-            // 1st line present for WPP.
-            offs = pcSlice->getSliceSegmentCurStartCUAddr()/pcSlice->getPic()->getNumPartInCU()/pcSlice->getPic()->getFrameWidthInCU();
-            nss  = pcSlice->getNumEntryPointOffsets()+1;
-          }
-          for ( UInt ui = 0 ; ui < nss; ui++ )
-          {
-            pcOut->addSubstream(&pcSubstreamsOut[ui+offs]);
-            }
-          }
-
-          UInt boundingAddrSlice, boundingAddrSliceSegment;
-          boundingAddrSlice        = m_storedStartCUAddrForEncodingSlice[startCUAddrSliceIdx];          
-          boundingAddrSliceSegment = m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx];          
-          nextCUAddr               = min(boundingAddrSlice, boundingAddrSliceSegment);
-          // If current NALU is the first NALU of slice (containing slice header) and more NALUs exist (due to multiple dependent slices) then buffer it.
-          // If current NALU is the last NALU of slice and a NALU was buffered, then (a) Write current NALU (b) Update an write buffered NALU at approproate location in NALU list.
-          Bool bNALUAlignedWrittenToList    = false; // used to ensure current NALU is not written more than once to the NALU list.
-          xAttachSliceDataToNalUnit(nalu, pcBitstreamRedirect);
-          accessUnit.push_back(new NALUnitEBSP(nalu));
-          actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
-          bNALUAlignedWrittenToList = true; 
-          uiOneBitstreamPerSliceLength += nalu.m_Bitstream.getNumberOfWrittenBits(); // length of bitstream after byte-alignment
-
-          if (!bNALUAlignedWrittenToList)
-          {
-            {
-              nalu.m_Bitstream.writeAlignZero();
-            }
-            accessUnit.push_back(new NALUnitEBSP(nalu));
-            uiOneBitstreamPerSliceLength += nalu.m_Bitstream.getNumberOfWrittenBits() + 24; // length of bitstream after byte-alignment + 3 byte startcode 0x000001
-          }
-
-          if( ( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() ) &&
-              ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) &&
-              ( ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNalHrdParametersPresentFlag() ) 
-             || ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getVclHrdParametersPresentFlag() ) ) &&
-              ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getSubPicCpbParamsPresentFlag() ) )
-          {
-              UInt numNalus = 0;
-            UInt numRBSPBytes = 0;
-            for (AccessUnit::const_iterator it = accessUnit.begin(); it != accessUnit.end(); it++)
-            {
-              UInt numRBSPBytes_nal = UInt((*it)->m_nalUnitData.str().size());
-              if ((*it)->m_nalUnitType != NAL_UNIT_PREFIX_SEI && (*it)->m_nalUnitType != NAL_UNIT_SUFFIX_SEI)
-              {
-                numRBSPBytes += numRBSPBytes_nal;
-                numNalus ++;
-              }
-            }
-            accumBitsDU[ pcSlice->getSliceIdx() ] = ( numRBSPBytes << 3 );
-            accumNalsDU[ pcSlice->getSliceIdx() ] = numNalus;   // SEI not counted for bit count; hence shouldn't be counted for # of NALUs - only for consistency
-          }
-          processingState = ENCODE_SLICE;
-          }
-          break;
-        case EXECUTE_INLOOPFILTER:
-          {
-            // set entropy coder for RD
-            m_pcEntropyCoder->setEntropyCoder ( m_pcSbacCoder, pcSlice );
-            if ( pcSlice->getSPS()->getUseSAO() )
-            {
-              m_pcEntropyCoder->resetEntropy();
-              m_pcEntropyCoder->setBitstream( m_pcBitCounter );
-            Bool sliceEnabled[NUM_SAO_COMPONENTS];
-            m_pcSAO->initRDOCabacCoder(m_pcEncTop->getRDGoOnSbacCoder(), pcSlice);
-            m_pcSAO->SAOProcess(pcPic
-              , sliceEnabled
-              , pcPic->getSlice(0)->getLambdas()
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
-              , m_pcCfg->getSaoLcuBoundary()
-#endif
-              );
-              m_pcSAO->PCMLFDisableProcess(pcPic);
-
-#if H_3D_DISABLE_CHROMA
-            if (pcSlice->getIsDepth())
-            {
-              sliceEnabled[SAO_Cb] = false; 
-              sliceEnabled[SAO_Cr] = false; 
-            }
-#endif
-            //assign SAO slice header
-            for(Int s=0; s< uiNumSlices; s++)
-            {
-              pcPic->getSlice(s)->setSaoEnabledFlag(sliceEnabled[SAO_Y]);
-              assert(sliceEnabled[SAO_Cb] == sliceEnabled[SAO_Cr]);
-              pcPic->getSlice(s)->setSaoEnabledFlagChroma(sliceEnabled[SAO_Cb]);
-              }
-            }
-          processingState = ENCODE_SLICE;
-          }
-          break;
-        default:
-          {
-            printf("Not a supported encoding state\n");
-            assert(0);
-            exit(-1);
-          }
-        }
-      } // end iteration over slices
-#if H_3D
-      pcPic->compressMotion(2); 
-#endif
-#if !H_3D
-      pcPic->compressMotion(); 
-#endif
-#if H_MV
-      m_pocLastCoded = pcPic->getPOC();
-#endif
-
-      //-- For time output for each slice
-      Double dEncTime = (Double)(clock()-iBeforeTime) / CLOCKS_PER_SEC;
-
-      const Char* digestStr = NULL;
-      if (m_pcCfg->getDecodedPictureHashSEIEnabled())
-      {
-        /* calculate MD5sum for entire reconstructed picture */
-        SEIDecodedPictureHash sei_recon_picture_digest;
-        if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 1)
-        {
-          sei_recon_picture_digest.method = SEIDecodedPictureHash::MD5;
-          calcMD5(*pcPic->getPicYuvRec(), sei_recon_picture_digest.digest);
-          digestStr = digestToString(sei_recon_picture_digest.digest, 16);
-        }
-        else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 2)
-        {
-          sei_recon_picture_digest.method = SEIDecodedPictureHash::CRC;
-          calcCRC(*pcPic->getPicYuvRec(), sei_recon_picture_digest.digest);
-          digestStr = digestToString(sei_recon_picture_digest.digest, 2);
-        }
-        else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 3)
-        {
-          sei_recon_picture_digest.method = SEIDecodedPictureHash::CHECKSUM;
-          calcChecksum(*pcPic->getPicYuvRec(), sei_recon_picture_digest.digest);
-          digestStr = digestToString(sei_recon_picture_digest.digest, 4);
-        }
-#if H_MV
-        OutputNALUnit nalu(NAL_UNIT_SUFFIX_SEI, pcSlice->getTLayer(), getLayerId() );
-#else
-        OutputNALUnit nalu(NAL_UNIT_SUFFIX_SEI, pcSlice->getTLayer());
-#endif
-
-        /* write the SEI messages */
-        m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
-        m_seiWriter.writeSEImessage(nalu.m_Bitstream, sei_recon_picture_digest, pcSlice->getSPS());
-        writeRBSPTrailingBits(nalu.m_Bitstream);
-
-        accessUnit.insert(accessUnit.end(), new NALUnitEBSP(nalu));
-      }
-      if (m_pcCfg->getTemporalLevel0IndexSEIEnabled())
-      {
-        SEITemporalLevel0Index sei_temporal_level0_index;
-        if (pcSlice->getRapPicFlag())
-        {
-          m_tl0Idx = 0;
-          m_rapIdx = (m_rapIdx + 1) & 0xFF;
-        }
-        else
-        {
-          m_tl0Idx = (m_tl0Idx + (pcSlice->getTLayer() ? 0 : 1)) & 0xFF;
-        }
-        sei_temporal_level0_index.tl0Idx = m_tl0Idx;
-        sei_temporal_level0_index.rapIdx = m_rapIdx;
-
-        OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI); 
-
-        /* write the SEI messages */
-        m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
-        m_seiWriter.writeSEImessage(nalu.m_Bitstream, sei_temporal_level0_index, pcSlice->getSPS());
-        writeRBSPTrailingBits(nalu.m_Bitstream);
-
-        /* insert the SEI message NALUnit before any Slice NALUnits */
-        AccessUnit::iterator it = find_if(accessUnit.begin(), accessUnit.end(), mem_fun(&NALUnit::isSlice));
-        accessUnit.insert(it, new NALUnitEBSP(nalu));
-      }
-
-      xCalculateAddPSNR( pcPic, pcPic->getPicYuvRec(), accessUnit, dEncTime );
-
-    //In case of field coding, compute the interlaced PSNR for both fields
-    if (isField && ((!pcPic->isTopField() && isTff) || (pcPic->isTopField() && !isTff)) && (pcPic->getPOC()%m_iGopSize != 1))
-    {
-      //get complementary top field
-      TComPic* pcPicTop;
-      TComList<TComPic*>::iterator   iterPic = rcListPic.begin();
-      while ((*iterPic)->getPOC() != pcPic->getPOC()-1)
-      {
-        iterPic ++;
-      }
-      pcPicTop = *(iterPic);
-      xCalculateInterlacedAddPSNR(pcPicTop, pcPic, pcPicTop->getPicYuvRec(), pcPic->getPicYuvRec(), accessUnit, dEncTime );
-    }
-    else if (isField && pcPic->getPOC()!= 0 && (pcPic->getPOC()%m_iGopSize == 0))
-    {
-      //get complementary bottom field
-      TComPic* pcPicBottom;
-      TComList<TComPic*>::iterator   iterPic = rcListPic.begin();
-      while ((*iterPic)->getPOC() != pcPic->getPOC()+1)
-      {
-        iterPic ++;
-      }
-      pcPicBottom = *(iterPic);
-      xCalculateInterlacedAddPSNR(pcPic, pcPicBottom, pcPic->getPicYuvRec(), pcPicBottom->getPicYuvRec(), accessUnit, dEncTime );
-    }
-    
-      if (digestStr)
-      {
-        if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 1)
-        {
-          printf(" [MD5:%s]", digestStr);
-        }
-        else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 2)
-        {
-          printf(" [CRC:%s]", digestStr);
-        }
-        else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 3)
-        {
-          printf(" [Checksum:%s]", digestStr);
-        }
-      }
-      if ( m_pcCfg->getUseRateCtrl() )
-      {
-        Double avgQP     = m_pcRateCtrl->getRCPic()->calAverageQP();
-        Double avgLambda = m_pcRateCtrl->getRCPic()->calAverageLambda();
-        if ( avgLambda < 0.0 )
-        {
-          avgLambda = lambda;
-        }
-        m_pcRateCtrl->getRCPic()->updateAfterPicture( actualHeadBits, actualTotalBits, avgQP, avgLambda, pcSlice->getSliceType());
-        m_pcRateCtrl->getRCPic()->addToPictureLsit( m_pcRateCtrl->getPicList() );
-
-        m_pcRateCtrl->getRCSeq()->updateAfterPic( actualTotalBits );
-        if ( pcSlice->getSliceType() != I_SLICE )
-        {
-          m_pcRateCtrl->getRCGOP()->updateAfterPicture( actualTotalBits );
-        }
-        else    // for intra picture, the estimated bits are used to update the current status in the GOP
-        {
-          m_pcRateCtrl->getRCGOP()->updateAfterPicture( estimatedBits );
-        }
       }
 
       if( ( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() ) &&
           ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) &&
-          ( ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNalHrdParametersPresentFlag() ) 
-         || ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getVclHrdParametersPresentFlag() ) ) )
-      {
-        TComVUI *vui = pcSlice->getSPS()->getVuiParameters();
-        TComHRD *hrd = vui->getHrdParameters();
-
-        if( hrd->getSubPicCpbParamsPresentFlag() )
-        {
-          Int i;
-          UInt64 ui64Tmp;
-          UInt uiPrev = 0;
-          UInt numDU = ( pictureTimingSEI.m_numDecodingUnitsMinus1 + 1 );
-          UInt *pCRD = &pictureTimingSEI.m_duCpbRemovalDelayMinus1[0];
-          UInt maxDiff = ( hrd->getTickDivisorMinus2() + 2 ) - 1;
-
-          for( i = 0; i < numDU; i ++ )
-          {
-            pictureTimingSEI.m_numNalusInDuMinus1[ i ]       = ( i == 0 ) ? ( accumNalsDU[ i ] - 1 ) : ( accumNalsDU[ i ] - accumNalsDU[ i - 1] - 1 );
-          }
-
-          if( numDU == 1 )
-          {
-            pCRD[ 0 ] = 0; /* don't care */
-          }
-          else
-          {
-            pCRD[ numDU - 1 ] = 0;/* by definition */
-            UInt tmp = 0;
-            UInt accum = 0;
-
-            for( i = ( numDU - 2 ); i >= 0; i -- )
-            {
-              ui64Tmp = ( ( ( accumBitsDU[ numDU - 1 ]  - accumBitsDU[ i ] ) * ( vui->getTimingInfo()->getTimeScale() / vui->getTimingInfo()->getNumUnitsInTick() ) * ( hrd->getTickDivisorMinus2() + 2 ) ) / ( m_pcCfg->getTargetBitrate() ) );
-              if( (UInt)ui64Tmp > maxDiff )
-              {
-                tmp ++;
-              }
-            }
-            uiPrev = 0;
-
-            UInt flag = 0;
-            for( i = ( numDU - 2 ); i >= 0; i -- )
-            {
-              flag = 0;
-              ui64Tmp = ( ( ( accumBitsDU[ numDU - 1 ]  - accumBitsDU[ i ] ) * ( vui->getTimingInfo()->getTimeScale() / vui->getTimingInfo()->getNumUnitsInTick() ) * ( hrd->getTickDivisorMinus2() + 2 ) ) / ( m_pcCfg->getTargetBitrate() ) );
-
-              if( (UInt)ui64Tmp > maxDiff )
-              {
-                if(uiPrev >= maxDiff - tmp)
-                {
-                  ui64Tmp = uiPrev + 1;
-                  flag = 1;
-                }
-                else                            ui64Tmp = maxDiff - tmp + 1;
-              }
-              pCRD[ i ] = (UInt)ui64Tmp - uiPrev - 1;
-              if( (Int)pCRD[ i ] < 0 )
-              {
-                pCRD[ i ] = 0;
-              }
-              else if (tmp > 0 && flag == 1) 
-              {
-                tmp --;
-              }
-              accum += pCRD[ i ] + 1;
-              uiPrev = accum;
-            }
-          }
-        }
-        if( m_pcCfg->getPictureTimingSEIEnabled() )
-        {
-          {
-            OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI, pcSlice->getTLayer());
-          m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
-          pictureTimingSEI.m_picStruct = (isField && pcSlice->getPic()->isTopField())? 1 : isField? 2 : 0;
-          m_seiWriter.writeSEImessage(nalu.m_Bitstream, pictureTimingSEI, pcSlice->getSPS());
-          writeRBSPTrailingBits(nalu.m_Bitstream);
-          UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
-          UInt offsetPosition = m_activeParameterSetSEIPresentInAU 
-                                    + m_bufferingPeriodSEIPresentInAU;    // Insert PT SEI after APS and BP SEI
-          AccessUnit::iterator it;
-          for(j = 0, it = accessUnit.begin(); j < seiPositionInAu + offsetPosition; j++)
-          {
-            it++;
-          }
-          accessUnit.insert(it, new NALUnitEBSP(nalu));
-          m_pictureTimingSEIPresentInAU = true;
-        }
-          if ( m_pcCfg->getScalableNestingSEIEnabled() ) // put picture timing SEI into scalable nesting SEI
-          {
-            OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI, pcSlice->getTLayer());
-            m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
-            scalableNestingSEI.m_nestedSEIs.clear();
-            scalableNestingSEI.m_nestedSEIs.push_back(&pictureTimingSEI);
-            m_seiWriter.writeSEImessage(nalu.m_Bitstream, scalableNestingSEI, pcSlice->getSPS());
-            writeRBSPTrailingBits(nalu.m_Bitstream);
-            UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
-            UInt offsetPosition = m_activeParameterSetSEIPresentInAU 
-              + m_bufferingPeriodSEIPresentInAU + m_pictureTimingSEIPresentInAU + m_nestedBufferingPeriodSEIPresentInAU;    // Insert PT SEI after APS and BP SEI
-            AccessUnit::iterator it;
-            for(j = 0, it = accessUnit.begin(); j < seiPositionInAu + offsetPosition; j++)
-            {
-              it++;
-            }
-            accessUnit.insert(it, new NALUnitEBSP(nalu));
-            m_nestedPictureTimingSEIPresentInAU = true;
-          }
-        }
-        if( m_pcCfg->getDecodingUnitInfoSEIEnabled() && hrd->getSubPicCpbParamsPresentFlag() )
-        {             
-          m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
-          for( Int i = 0; i < ( pictureTimingSEI.m_numDecodingUnitsMinus1 + 1 ); i ++ )
-          {
-            OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI, pcSlice->getTLayer());
-
-            SEIDecodingUnitInfo tempSEI;
-            tempSEI.m_decodingUnitIdx = i;
-            tempSEI.m_duSptCpbRemovalDelay = pictureTimingSEI.m_duCpbRemovalDelayMinus1[i] + 1;
-            tempSEI.m_dpbOutputDuDelayPresentFlag = false;
-            tempSEI.m_picSptDpbOutputDuDelay = picSptDpbOutputDuDelay;
-
-            AccessUnit::iterator it;
-            // Insert the first one in the right location, before the first slice
-            if(i == 0)
-            {
-              // Insert before the first slice. 
-              m_seiWriter.writeSEImessage(nalu.m_Bitstream, tempSEI, pcSlice->getSPS());
-              writeRBSPTrailingBits(nalu.m_Bitstream);
-
-              UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
-              UInt offsetPosition = m_activeParameterSetSEIPresentInAU 
-                                    + m_bufferingPeriodSEIPresentInAU 
-                                    + m_pictureTimingSEIPresentInAU;  // Insert DU info SEI after APS, BP and PT SEI
-              for(j = 0, it = accessUnit.begin(); j < seiPositionInAu + offsetPosition; j++)
-              {
-                it++;
-              }
-              accessUnit.insert(it, new NALUnitEBSP(nalu));
-            }
-            else
-            {
-              Int ctr;
-              // For the second decoding unit onwards we know how many NALUs are present
-              for (ctr = 0, it = accessUnit.begin(); it != accessUnit.end(); it++)
-              {            
-                if(ctr == accumNalsDU[ i - 1 ])
-                {
-                  // Insert before the first slice. 
-                  m_seiWriter.writeSEImessage(nalu.m_Bitstream, tempSEI, pcSlice->getSPS());
-                  writeRBSPTrailingBits(nalu.m_Bitstream);
-
-                  accessUnit.insert(it, new NALUnitEBSP(nalu));
-                  break;
-                }
-                if ((*it)->m_nalUnitType != NAL_UNIT_PREFIX_SEI && (*it)->m_nalUnitType != NAL_UNIT_SUFFIX_SEI)
-                {
-                  ctr++;
-                }
-              }
-            }            
-          }
-        }
-      }
-      xResetNonNestedSEIPresentFlags();
-      xResetNestedSEIPresentFlags();
-      pcPic->getPicYuvRec()->copyToPic(pcPicYuvRecOut);
-
-      pcPic->setReconMark   ( true );
-#if H_MV
+          ( ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNalHrdParametersPresentFlag() )
+         || ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getVclHrdParametersPresentFlag() ) ) &&
+          ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getSubPicCpbParamsPresentFlag() ) )
+      {
+          UInt numNalus = 0;
+        UInt numRBSPBytes = 0;
+        for (AccessUnit::const_iterator it = accessUnit.begin(); it != accessUnit.end(); it++)
+        {
+          numRBSPBytes += UInt((*it)->m_nalUnitData.str().size());
+          numNalus ++;
+        }
+        duData.push_back(DUData());
+        duData.back().accumBitsDU = ( numRBSPBytes << 3 );
+        duData.back().accumNalsDU = numNalus;
+      }
+    } // end iteration over slices
+
+    // cabac_zero_words processing
+    cabac_zero_word_padding(pcSlice, pcPic, binCountsInNalUnits, numBytesInVclNalUnits, accessUnit.back()->m_nalUnitData, m_pcCfg->getCabacZeroWordPaddingEnabled());
+#if NH_3D
+      pcPic->compressMotion(2); 
+#else
+    pcPic->compressMotion();
+#endif
+#if NH_MV
+      m_pocLastCoded = pcPic->getPOC();
+#endif
+
+    //-- For time output for each slice
+    Double dEncTime = (Double)(clock()-iBeforeTime) / CLOCKS_PER_SEC;
+
+    std::string digestStr;
+    if (m_pcCfg->getDecodedPictureHashSEIEnabled())
+    {
+      SEIDecodedPictureHash *decodedPictureHashSei = new SEIDecodedPictureHash();
+      m_seiEncoder.initDecodedPictureHashSEI(decodedPictureHashSei, pcPic, digestStr, pcSlice->getSPS()->getBitDepths());
+      trailingSeiMessages.push_back(decodedPictureHashSei);
+    }
+    xWriteTrailingSEIMessages(trailingSeiMessages, accessUnit, pcSlice->getTLayer(), pcSlice->getSPS());
+
+    m_pcCfg->setEncodedFlag(iGOPid, true);
+
+    xCalculateAddPSNRs( isField, isTff, iGOPid, pcPic, accessUnit, rcListPic, dEncTime, snr_conversion, printFrameMSE );
+
+    if (!digestStr.empty())
+    {
+      if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 1)
+      {
+        printf(" [MD5:%s]", digestStr.c_str());
+      }
+      else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 2)
+      {
+        printf(" [CRC:%s]", digestStr.c_str());
+      }
+      else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 3)
+      {
+        printf(" [Checksum:%s]", digestStr.c_str());
+      }
+    }
+
+    if ( m_pcCfg->getUseRateCtrl() )
+    {
+      Double avgQP     = m_pcRateCtrl->getRCPic()->calAverageQP();
+      Double avgLambda = m_pcRateCtrl->getRCPic()->calAverageLambda();
+      if ( avgLambda < 0.0 )
+      {
+        avgLambda = lambda;
+      }
+
+      m_pcRateCtrl->getRCPic()->updateAfterPicture( actualHeadBits, actualTotalBits, avgQP, avgLambda, pcSlice->getSliceType());
+      m_pcRateCtrl->getRCPic()->addToPictureLsit( m_pcRateCtrl->getPicList() );
+
+      m_pcRateCtrl->getRCSeq()->updateAfterPic( actualTotalBits );
+      if ( pcSlice->getSliceType() != I_SLICE )
+      {
+        m_pcRateCtrl->getRCGOP()->updateAfterPicture( actualTotalBits );
+      }
+      else    // for intra picture, the estimated bits are used to update the current status in the GOP
+      {
+        m_pcRateCtrl->getRCGOP()->updateAfterPicture( estimatedBits );
+      }
+    }
+
+    xCreatePictureTimingSEI(m_pcCfg->getEfficientFieldIRAPEnabled()?effFieldIRAPMap.GetIRAPGOPid():0, leadingSeiMessages, nestedSeiMessages, duInfoSeiMessages, pcSlice, isField, duData);
+    if (m_pcCfg->getScalableNestingSEIEnabled())
+    {
+      xCreateScalableNestingSEI (leadingSeiMessages, nestedSeiMessages);
+    }
+    xWriteLeadingSEIMessages(leadingSeiMessages, duInfoSeiMessages, accessUnit, pcSlice->getTLayer(), pcSlice->getSPS(), duData);
+    xWriteDuSEIMessages(duInfoSeiMessages, accessUnit, pcSlice->getTLayer(), pcSlice->getSPS(), duData);
+
+    pcPic->getPicYuvRec()->copyToPic(pcPicYuvRecOut);
+
+    pcPic->setReconMark   ( true );
+#if NH_MV
       TComSlice::markIvRefPicsAsShortTerm( m_refPicSetInterLayer0, m_refPicSetInterLayer1 );  
       std::vector<Int> temp; 
       TComSlice::markCurrPic( pcPic ); 
 #endif
-      m_bFirst = false;
-      m_iNumPicCoded++;
-      m_totalCoded ++;
-      /* logging: insert a newline at end of picture period */
-      printf("\n");
-      fflush(stdout);
-
-      delete[] pcSubstreamsOut;
-
-#if EFFICIENT_FIELD_IRAP
-    if(IRAPtoReorder)
-    {
-      if(swapIRAPForward)
-      {
-        if(iGOPid == IRAPGOPid)
-        {
-          iGOPid = IRAPGOPid +1;
-          IRAPtoReorder = false;
-        }
-        else if(iGOPid == IRAPGOPid +1)
-        {
-          iGOPid --;
-        }
-      }
-      else
-      {
-        if(iGOPid == IRAPGOPid)
-        {
-          iGOPid = IRAPGOPid -1;
-        }
-        else if(iGOPid == IRAPGOPid -1)
-        {
-          iGOPid = IRAPGOPid;
-          IRAPtoReorder = false;
-        }
-      }
-    }
-#endif
-  }
+    m_bFirst = false;
+    m_iNumPicCoded++;
+    m_totalCoded ++;
+    /* logging: insert a newline at end of picture period */
+    printf("\n");
+    fflush(stdout);
+
+    if (m_pcCfg->getEfficientFieldIRAPEnabled())
+    {
+    iGOPid=effFieldIRAPMap.restoreGOPid(iGOPid);
+    }
+  } // iGOPid-loop
+
   delete pcBitstreamRedirect;
 
-  if( accumBitsDU != NULL) delete accumBitsDU;
-  if( accumNalsDU != NULL) delete accumNalsDU;
-
-#if !H_MV
-  assert ( (m_iNumPicCoded == iNumPicRcvd) || (isField && iPOCLast == 1) );
-#endif
-}
-
-#if !H_MV
-Void TEncGOP::printOutSummary(UInt uiNumAllPicCoded, bool isField)
+#if !NH_MV
+  assert ( (m_iNumPicCoded == iNumPicRcvd) );
+#endif
+}
+
+Void TEncGOP::printOutSummary(UInt uiNumAllPicCoded, Bool isField, const Bool printMSEBasedSNR, const Bool printSequenceMSE, const BitDepths &bitDepths)
 {
   assert (uiNumAllPicCoded == m_gcAnalyzeAll.getNumPic());
-  
-    
+
+
   //--CFG_KDY
-  if(isField)
-  {
-    m_gcAnalyzeAll.setFrmRate( m_pcCfg->getFrameRate() * 2);
-    m_gcAnalyzeI.setFrmRate( m_pcCfg->getFrameRate() * 2);
-    m_gcAnalyzeP.setFrmRate( m_pcCfg->getFrameRate() * 2);
-    m_gcAnalyzeB.setFrmRate( m_pcCfg->getFrameRate() * 2);
-  }
-  else
-  {
-  m_gcAnalyzeAll.setFrmRate( m_pcCfg->getFrameRate() );
-  m_gcAnalyzeI.setFrmRate( m_pcCfg->getFrameRate() );
-  m_gcAnalyzeP.setFrmRate( m_pcCfg->getFrameRate() );
-  m_gcAnalyzeB.setFrmRate( m_pcCfg->getFrameRate() );
-  }
-  
+  const Int rateMultiplier=(isField?2:1);
+  m_gcAnalyzeAll.setFrmRate( m_pcCfg->getFrameRate()*rateMultiplier );
+  m_gcAnalyzeI.setFrmRate( m_pcCfg->getFrameRate()*rateMultiplier );
+  m_gcAnalyzeP.setFrmRate( m_pcCfg->getFrameRate()*rateMultiplier );
+  m_gcAnalyzeB.setFrmRate( m_pcCfg->getFrameRate()*rateMultiplier );
+  const ChromaFormat chFmt = m_pcCfg->getChromaFormatIdc();
+
   //-- all
+#if NH_MV
+  printf( "\n\nSUMMARY -------------------------------------------- LayerId %2d\n", getLayerId() );   
+#else
   printf( "\n\nSUMMARY --------------------------------------------------------\n" );
-  m_gcAnalyzeAll.printOut('a');
-  
+#endif
+  m_gcAnalyzeAll.printOut('a', chFmt, printMSEBasedSNR, printSequenceMSE, bitDepths);
+
   printf( "\n\nI Slices--------------------------------------------------------\n" );
-  m_gcAnalyzeI.printOut('i');
-  
+  m_gcAnalyzeI.printOut('i', chFmt, printMSEBasedSNR, printSequenceMSE, bitDepths);
+
   printf( "\n\nP Slices--------------------------------------------------------\n" );
-  m_gcAnalyzeP.printOut('p');
-  
+  m_gcAnalyzeP.printOut('p', chFmt, printMSEBasedSNR, printSequenceMSE, bitDepths);
+
   printf( "\n\nB Slices--------------------------------------------------------\n" );
-  m_gcAnalyzeB.printOut('b');
-  
-#if _SUMMARY_OUT_
-  m_gcAnalyzeAll.printSummaryOut();
-#endif
-#if _SUMMARY_PIC_
-  m_gcAnalyzeI.printSummary('I');
-  m_gcAnalyzeP.printSummary('P');
-  m_gcAnalyzeB.printSummary('B');
-#endif
+  m_gcAnalyzeB.printOut('b', chFmt, printMSEBasedSNR, printSequenceMSE, bitDepths);
+
+  if (!m_pcCfg->getSummaryOutFilename().empty())
+  {
+    m_gcAnalyzeAll.printSummary(chFmt, printSequenceMSE, bitDepths, m_pcCfg->getSummaryOutFilename());
+  }
+
+  if (!m_pcCfg->getSummaryPicFilenameBase().empty())
+  {
+    m_gcAnalyzeI.printSummary(chFmt, printSequenceMSE, bitDepths, m_pcCfg->getSummaryPicFilenameBase()+"I.txt");
+    m_gcAnalyzeP.printSummary(chFmt, printSequenceMSE, bitDepths, m_pcCfg->getSummaryPicFilenameBase()+"P.txt");
+    m_gcAnalyzeB.printSummary(chFmt, printSequenceMSE, bitDepths, m_pcCfg->getSummaryPicFilenameBase()+"B.txt");
+  }
 
   if(isField)
@@ -2421,34 +2126,33 @@
     //-- interlaced summary
     m_gcAnalyzeAll_in.setFrmRate( m_pcCfg->getFrameRate());
+    m_gcAnalyzeAll_in.setBits(m_gcAnalyzeAll.getBits());
+    // prior to the above statement, the interlace analyser does not contain the correct total number of bits.
+
     printf( "\n\nSUMMARY INTERLACED ---------------------------------------------\n" );
-    m_gcAnalyzeAll_in.printOutInterlaced('a',  m_gcAnalyzeAll.getBits());
-    
-#if _SUMMARY_OUT_
-    m_gcAnalyzeAll_in.printSummaryOutInterlaced();
-#endif
+    m_gcAnalyzeAll_in.printOut('a', chFmt, printMSEBasedSNR, printSequenceMSE, bitDepths);
+
+    if (!m_pcCfg->getSummaryOutFilename().empty())
+    {
+      m_gcAnalyzeAll_in.printSummary(chFmt, printSequenceMSE, bitDepths, m_pcCfg->getSummaryOutFilename());
+    }
   }
 
   printf("\nRVM: %.3lf\n" , xCalculateRVM());
 }
-#endif
-#if H_3D_VSO
-Void TEncGOP::preLoopFilterPicAll( TComPic* pcPic, Dist64& ruiDist, UInt64& ruiBits )
+
+#if NH_3D_VSO
+Void TEncGOP::preLoopFilterPicAll( TComPic* pcPic, Dist64& ruiDist )
 #else
-Void TEncGOP::preLoopFilterPicAll( TComPic* pcPic, UInt64& ruiDist, UInt64& ruiBits )
-#endif
-{
-  TComSlice* pcSlice = pcPic->getSlice(pcPic->getCurrSliceIdx());
+Void TEncGOP::preLoopFilterPicAll( TComPic* pcPic, UInt64& ruiDist )
+#endif
+{
   Bool bCalcDist = false;
   m_pcLoopFilter->setCfg(m_pcCfg->getLFCrossTileBoundaryFlag());
   m_pcLoopFilter->loopFilterPic( pcPic );
-  
-  m_pcEntropyCoder->setEntropyCoder ( m_pcEncTop->getRDGoOnSbacCoder(), pcSlice );
-  m_pcEntropyCoder->resetEntropy    ();
-  m_pcEntropyCoder->setBitstream    ( m_pcBitCounter );
-  m_pcEntropyCoder->resetEntropy    ();
-  ruiBits += m_pcEntropyCoder->getNumberOfWrittenBits();
-  
+
   if (!bCalcDist)
-    ruiDist = xFindDistortionFrame(pcPic->getPicYuvOrg(), pcPic->getPicYuvRec());
+  {
+    ruiDist = xFindDistortionFrame(pcPic->getPicYuvOrg(), pcPic->getPicYuvRec(), pcPic->getPicSym()->getSPS().getBitDepths());
+  }
 }
 
@@ -2458,5 +2162,5 @@
 
 
-Void TEncGOP::xInitGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, bool isField )
+Void TEncGOP::xInitGOP( Int iPOCLast, Int iNumPicRcvd, Bool isField )
 {
   assert( iNumPicRcvd > 0 );
@@ -2471,7 +2175,8 @@
   }
   assert (m_iGopSize > 0);
-  
+
   return;
 }
+
 
 Void TEncGOP::xGetBuffer( TComList<TComPic*>&      rcListPic,
@@ -2482,35 +2187,22 @@
                          TComPicYuv*&              rpcPicYuvRecOut,
                          Int                       pocCurr,
-                         bool                      isField)
+                         Bool                      isField)
 {
   Int i;
   //  Rec. output
   TComList<TComPicYuv*>::iterator     iterPicYuvRec = rcListPicYuvRecOut.end();
-  
-  if (isField)
-  {
-    for ( i = 0; i < ( (pocCurr == 0 ) || (pocCurr == 1 ) ? (iNumPicRcvd - iTimeOffset + 1) : (iNumPicRcvd - iTimeOffset + 2) ); i++ )
-    {
-      iterPicYuvRec--;
-    }
-  }
-  else
-  {
-    for ( i = 0; i < (iNumPicRcvd - iTimeOffset + 1); i++ )
+
+  if (isField && pocCurr > 1 && m_iGopSize!=1)
+  {
+    iTimeOffset--;
+  }
+
+  for ( i = 0; i < (iNumPicRcvd - iTimeOffset + 1); i++ )
   {
     iterPicYuvRec--;
   }
-  
-  }
-  
-  if (isField)
-  {
-    if(pocCurr == 1)
-    {
-      iterPicYuvRec++;
-    }
-  }
+
   rpcPicYuvRecOut = *(iterPicYuvRec);
-  
+
   //  Current pic.
   TComList<TComPic*>::iterator        iterPic       = rcListPic.begin();
@@ -2526,149 +2218,163 @@
   }
 
-#if !H_MV
-  assert( rpcPic != NULL );
+#if !NH_MV
+  assert (rpcPic != NULL);
 #endif
   assert (rpcPic->getPOC() == pocCurr);
-  
+
   return;
 }
 
-#if H_3D_VSO
-Dist64 TEncGOP::xFindDistortionFrame (TComPicYuv* pcPic0, TComPicYuv* pcPic1)
+#if NH_3D_VSO
+Dist64 TEncGOP::xFindDistortionFrame (TComPicYuv* pcPic0, TComPicYuv* pcPic1, const BitDepths &bitDepths)
 #else
-UInt64 TEncGOP::xFindDistortionFrame (TComPicYuv* pcPic0, TComPicYuv* pcPic1)
-#endif
-{
-  Int     x, y;
-  Pel*  pSrc0   = pcPic0 ->getLumaAddr();
-  Pel*  pSrc1   = pcPic1 ->getLumaAddr();
-  UInt  uiShift = 2 * DISTORTION_PRECISION_ADJUSTMENT(g_bitDepthY-8);
-  Int   iTemp;
-  
-  Int   iStride = pcPic0->getStride();
-  Int   iWidth  = pcPic0->getWidth();
-  Int   iHeight = pcPic0->getHeight();
-  
-#if H_3D_VSO
+UInt64 TEncGOP::xFindDistortionFrame (TComPicYuv* pcPic0, TComPicYuv* pcPic1, const BitDepths &bitDepths)
+#endif
+{
+#if NH_3D_VSO
   Dist64  uiTotalDiff = 0;
 #else
   UInt64  uiTotalDiff = 0;
 #endif
-  
-  for( y = 0; y < iHeight; y++ )
-  {
-    for( x = 0; x < iWidth; x++ )
-    {
-      iTemp = pSrc0[x] - pSrc1[x]; uiTotalDiff += (iTemp*iTemp) >> uiShift;
-    }
-    pSrc0 += iStride;
-    pSrc1 += iStride;
-  }
-  
-  uiShift = 2 * DISTORTION_PRECISION_ADJUSTMENT(g_bitDepthC-8);
-  iHeight >>= 1;
-  iWidth  >>= 1;
-  iStride >>= 1;
-  
-  pSrc0  = pcPic0->getCbAddr();
-  pSrc1  = pcPic1->getCbAddr();
-  
-  for( y = 0; y < iHeight; y++ )
-  {
-    for( x = 0; x < iWidth; x++ )
-    {
-      iTemp = pSrc0[x] - pSrc1[x]; uiTotalDiff += (iTemp*iTemp) >> uiShift;
-    }
-    pSrc0 += iStride;
-    pSrc1 += iStride;
-  }
-  
-  pSrc0  = pcPic0->getCrAddr();
-  pSrc1  = pcPic1->getCrAddr();
-  
-  for( y = 0; y < iHeight; y++ )
-  {
-    for( x = 0; x < iWidth; x++ )
-    {
-      iTemp = pSrc0[x] - pSrc1[x]; uiTotalDiff += (iTemp*iTemp) >> uiShift;
-    }
-    pSrc0 += iStride;
-    pSrc1 += iStride;
-  }
-  
+
+  for(Int chan=0; chan<pcPic0 ->getNumberValidComponents(); chan++)
+  {
+    const ComponentID ch=ComponentID(chan);
+    Pel*  pSrc0   = pcPic0 ->getAddr(ch);
+    Pel*  pSrc1   = pcPic1 ->getAddr(ch);
+    UInt  uiShift     = 2 * DISTORTION_PRECISION_ADJUSTMENT(bitDepths.recon[toChannelType(ch)]-8);
+
+    const Int   iStride = pcPic0->getStride(ch);
+    const Int   iWidth  = pcPic0->getWidth(ch);
+    const Int   iHeight = pcPic0->getHeight(ch);
+
+    for(Int y = 0; y < iHeight; y++ )
+    {
+      for(Int x = 0; x < iWidth; x++ )
+      {
+        Intermediate_Int iTemp = pSrc0[x] - pSrc1[x];
+        uiTotalDiff += UInt64((iTemp*iTemp) >> uiShift);
+      }
+      pSrc0 += iStride;
+      pSrc1 += iStride;
+    }
+  }
+
   return uiTotalDiff;
 }
 
-#if VERBOSE_RATE
-static const Char* nalUnitTypeToString(NalUnitType type)
-{
-  switch (type)
-  {
-    case NAL_UNIT_CODED_SLICE_TRAIL_R: return "TRAIL_R";
-    case NAL_UNIT_CODED_SLICE_TRAIL_N: return "TRAIL_N";
-    case NAL_UNIT_CODED_SLICE_TSA_R:      return "TSA_R";
-    case NAL_UNIT_CODED_SLICE_TSA_N: return "TSA_N";
-    case NAL_UNIT_CODED_SLICE_STSA_R: return "STSA_R";
-    case NAL_UNIT_CODED_SLICE_STSA_N: return "STSA_N";
-    case NAL_UNIT_CODED_SLICE_BLA_W_LP:   return "BLA_W_LP";
-    case NAL_UNIT_CODED_SLICE_BLA_W_RADL: return "BLA_W_RADL";
-    case NAL_UNIT_CODED_SLICE_BLA_N_LP: return "BLA_N_LP";
-    case NAL_UNIT_CODED_SLICE_IDR_W_RADL: return "IDR_W_RADL";
-    case NAL_UNIT_CODED_SLICE_IDR_N_LP: return "IDR_N_LP";
-    case NAL_UNIT_CODED_SLICE_CRA: return "CRA";
-    case NAL_UNIT_CODED_SLICE_RADL_R:     return "RADL_R";
-    case NAL_UNIT_CODED_SLICE_RADL_N:     return "RADL_N";
-    case NAL_UNIT_CODED_SLICE_RASL_R:     return "RASL_R";
-    case NAL_UNIT_CODED_SLICE_RASL_N:     return "RASL_N";
-    case NAL_UNIT_VPS: return "VPS";
-    case NAL_UNIT_SPS: return "SPS";
-    case NAL_UNIT_PPS: return "PPS";
-    case NAL_UNIT_ACCESS_UNIT_DELIMITER: return "AUD";
-    case NAL_UNIT_EOS: return "EOS";
-    case NAL_UNIT_EOB: return "EOB";
-    case NAL_UNIT_FILLER_DATA: return "FILLER";
-    case NAL_UNIT_PREFIX_SEI:             return "SEI";
-    case NAL_UNIT_SUFFIX_SEI:             return "SEI";
-    default: return "UNK";
-  }
-}
-#endif
-
-Void TEncGOP::xCalculateAddPSNR( TComPic* pcPic, TComPicYuv* pcPicD, const AccessUnit& accessUnit, Double dEncTime )
-{
-  Int     x, y;
-  UInt64 uiSSDY  = 0;
-  UInt64 uiSSDU  = 0;
-  UInt64 uiSSDV  = 0;
-  
-  Double  dYPSNR  = 0.0;
-  Double  dUPSNR  = 0.0;
-  Double  dVPSNR  = 0.0;
-  
+Void TEncGOP::xCalculateAddPSNRs( const Bool isField, const Bool isFieldTopFieldFirst, const Int iGOPid, TComPic* pcPic, const AccessUnit&accessUnit, TComList<TComPic*> &rcListPic, const Double dEncTime, const InputColourSpaceConversion snr_conversion, const Bool printFrameMSE )
+{
+  xCalculateAddPSNR( pcPic, pcPic->getPicYuvRec(), accessUnit, dEncTime, snr_conversion, printFrameMSE );
+
+  //In case of field coding, compute the interlaced PSNR for both fields
+  if(isField)
+  {
+    Bool bothFieldsAreEncoded = false;
+    Int correspondingFieldPOC = pcPic->getPOC();
+    Int currentPicGOPPoc = m_pcCfg->getGOPEntry(iGOPid).m_POC;
+    if(pcPic->getPOC() == 0)
+    {
+      // particular case for POC 0 and 1.
+      // If they are not encoded first and separately from other pictures, we need to change this
+      // POC 0 is always encoded first then POC 1 is encoded
+      bothFieldsAreEncoded = false;
+    }
+    else if(pcPic->getPOC() == 1)
+    {
+      // if we are at POC 1, POC 0 has been encoded for sure
+      correspondingFieldPOC = 0;
+      bothFieldsAreEncoded = true;
+    }
+    else
+    {
+      if(pcPic->getPOC()%2 == 1)
+      {
+        correspondingFieldPOC -= 1; // all odd POC are associated with the preceding even POC (e.g poc 1 is associated to poc 0)
+        currentPicGOPPoc      -= 1;
+      }
+      else
+      {
+        correspondingFieldPOC += 1; // all even POC are associated with the following odd POC (e.g poc 0 is associated to poc 1)
+        currentPicGOPPoc      += 1;
+      }
+      for(Int i = 0; i < m_iGopSize; i ++)
+      {
+        if(m_pcCfg->getGOPEntry(i).m_POC == currentPicGOPPoc)
+        {
+          bothFieldsAreEncoded = m_pcCfg->getGOPEntry(i).m_isEncoded;
+          break;
+        }
+      }
+    }
+
+    if(bothFieldsAreEncoded)
+    {
+      //get complementary top field
+      TComList<TComPic*>::iterator   iterPic = rcListPic.begin();
+      while ((*iterPic)->getPOC() != correspondingFieldPOC)
+      {
+        iterPic ++;
+      }
+      TComPic* correspondingFieldPic = *(iterPic);
+
+      if( (pcPic->isTopField() && isFieldTopFieldFirst) || (!pcPic->isTopField() && !isFieldTopFieldFirst))
+      {
+        xCalculateInterlacedAddPSNR(pcPic, correspondingFieldPic, pcPic->getPicYuvRec(), correspondingFieldPic->getPicYuvRec(), snr_conversion, printFrameMSE );
+      }
+      else
+      {
+        xCalculateInterlacedAddPSNR(correspondingFieldPic, pcPic, correspondingFieldPic->getPicYuvRec(), pcPic->getPicYuvRec(), snr_conversion, printFrameMSE );
+      }
+    }
+  }
+}
+
+Void TEncGOP::xCalculateAddPSNR( TComPic* pcPic, TComPicYuv* pcPicD, const AccessUnit& accessUnit, Double dEncTime, const InputColourSpaceConversion conversion, const Bool printFrameMSE )
+{
+  Double  dPSNR[MAX_NUM_COMPONENT];
+
+  for(Int i=0; i<MAX_NUM_COMPONENT; i++)
+  {
+    dPSNR[i]=0.0;
+  }
+
+  TComPicYuv cscd;
+  if (conversion!=IPCOLOURSPACE_UNCHANGED)
+  {
+    cscd.create(pcPicD->getWidth(COMPONENT_Y), pcPicD->getHeight(COMPONENT_Y), pcPicD->getChromaFormat(), pcPicD->getWidth(COMPONENT_Y), pcPicD->getHeight(COMPONENT_Y), 0, false);
+    TVideoIOYuv::ColourSpaceConvert(*pcPicD, cscd, conversion, false);
+  }
+  TComPicYuv &picd=(conversion==IPCOLOURSPACE_UNCHANGED)?*pcPicD : cscd;
+
   //===== calculate PSNR =====
-  Pel*  pOrg    = pcPic ->getPicYuvOrg()->getLumaAddr();
-  Pel*  pRec    = pcPicD->getLumaAddr();
-  Int   iStride = pcPicD->getStride();
-  
-  Int   iWidth;
-  Int   iHeight;
-  
-  iWidth  = pcPicD->getWidth () - m_pcEncTop->getPad(0);
-  iHeight = pcPicD->getHeight() - m_pcEncTop->getPad(1);
-  
-  Int   iSize   = iWidth*iHeight;
-  
-  for( y = 0; y < iHeight; y++ )
-  {
-    for( x = 0; x < iWidth; x++ )
-    {
-      Int iDiff = (Int)( pOrg[x] - pRec[x] );
-      uiSSDY   += iDiff * iDiff;
-    }
-    pOrg += iStride;
-    pRec += iStride;
-  }
-  
-#if H_3D_VSO
+  Double MSEyuvframe[MAX_NUM_COMPONENT] = {0, 0, 0};
+
+  for(Int chan=0; chan<pcPicD->getNumberValidComponents(); chan++)
+  {
+    const ComponentID ch=ComponentID(chan);
+    const TComPicYuv *pOrgPicYuv =(conversion!=IPCOLOURSPACE_UNCHANGED) ? pcPic ->getPicYuvTrueOrg() : pcPic ->getPicYuvOrg();
+    const Pel*  pOrg       = pOrgPicYuv->getAddr(ch);
+    const Int   iOrgStride = pOrgPicYuv->getStride(ch);
+    Pel*  pRec    = picd.getAddr(ch);
+    const Int   iRecStride = picd.getStride(ch);
+
+    const Int   iWidth  = pcPicD->getWidth (ch) - (m_pcEncTop->getPad(0) >> pcPic->getComponentScaleX(ch));
+    const Int   iHeight = pcPicD->getHeight(ch) - ((m_pcEncTop->getPad(1) >> (pcPic->isField()?1:0)) >> pcPic->getComponentScaleY(ch));
+
+    Int   iSize   = iWidth*iHeight;
+
+    UInt64 uiSSDtemp=0;
+    for(Int y = 0; y < iHeight; y++ )
+    {
+      for(Int x = 0; x < iWidth; x++ )
+      {
+        Intermediate_Int iDiff = (Intermediate_Int)( pOrg[x] - pRec[x] );
+        uiSSDtemp   += iDiff * iDiff;
+      }
+      pOrg += iOrgStride;
+      pRec += iRecStride;
+    }
+#if NH_3D_VSO
 #if H_3D_VSO_SYNTH_DIST_OUT
   if ( m_pcRdCost->getUseRenModel() )
@@ -2688,47 +2394,15 @@
 #endif
 #endif
-    iHeight >>= 1;
-  iWidth  >>= 1;
-  iStride >>= 1;
-  pOrg  = pcPic ->getPicYuvOrg()->getCbAddr();
-  pRec  = pcPicD->getCbAddr();
-  
-  for( y = 0; y < iHeight; y++ )
-  {
-    for( x = 0; x < iWidth; x++ )
-    {
-      Int iDiff = (Int)( pOrg[x] - pRec[x] );
-      uiSSDU   += iDiff * iDiff;
-    }
-    pOrg += iStride;
-    pRec += iStride;
-  }
-  
-  pOrg  = pcPic ->getPicYuvOrg()->getCrAddr();
-  pRec  = pcPicD->getCrAddr();
-  
-  for( y = 0; y < iHeight; y++ )
-  {
-    for( x = 0; x < iWidth; x++ )
-    {
-      Int iDiff = (Int)( pOrg[x] - pRec[x] );
-      uiSSDV   += iDiff * iDiff;
-    }
-    pOrg += iStride;
-    pRec += iStride;
-  }
-  
-  Int maxvalY = 255 << (g_bitDepthY-8);
-  Int maxvalC = 255 << (g_bitDepthC-8);
-  Double fRefValueY = (Double) maxvalY * maxvalY * iSize;
-  Double fRefValueC = (Double) maxvalC * maxvalC * iSize / 4.0;
-  dYPSNR            = ( uiSSDY ? 10.0 * log10( fRefValueY / (Double)uiSSDY ) : 99.99 );
-  dUPSNR            = ( uiSSDU ? 10.0 * log10( fRefValueC / (Double)uiSSDU ) : 99.99 );
-  dVPSNR            = ( uiSSDV ? 10.0 * log10( fRefValueC / (Double)uiSSDV ) : 99.99 );
-#if H_3D_VSO
+    const Int maxval = 255 << (pcPic->getPicSym()->getSPS().getBitDepth(toChannelType(ch)) - 8);
+    const Double fRefValue = (Double) maxval * maxval * iSize;
+    dPSNR[ch]         = ( uiSSDtemp ? 10.0 * log10( fRefValue / (Double)uiSSDtemp ) : 999.99 );
+    MSEyuvframe[ch]   = (Double)uiSSDtemp/(iSize);
+  }
+
+#if NH_3D_VSO
 #if H_3D_VSO_SYNTH_DIST_OUT
 }
 #endif 
-#endif
+#endif  
   /* calculate the size of the access unit, excluding:
    *  - any AnnexB contributions (start_code_prefix, zero_byte, etc.,)
@@ -2739,7 +2413,8 @@
   {
     UInt numRBSPBytes_nal = UInt((*it)->m_nalUnitData.str().size());
-#if VERBOSE_RATE
+    if (m_pcCfg->getSummaryVerboseness() > 0)
+    {
     printf("*** %6s numBytesInNALunit: %u\n", nalUnitTypeToString((*it)->m_nalUnitType), numRBSPBytes_nal);
-#endif
+    }
     if ((*it)->m_nalUnitType != NAL_UNIT_PREFIX_SEI && (*it)->m_nalUnitType != NAL_UNIT_SUFFIX_SEI)
     {
@@ -2752,40 +2427,28 @@
 
   //===== add PSNR =====
-#if H_MV
-  m_pcEncTop->getAnalyzeAll()->addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
-#else
-  m_gcAnalyzeAll.addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
-#endif
+  m_gcAnalyzeAll.addResult (dPSNR, (Double)uibits, MSEyuvframe);
+
   TComSlice*  pcSlice = pcPic->getSlice(0);
   if (pcSlice->isIntra())
   {
-#if H_MV
-    m_pcEncTop->getAnalyzeI()->addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
-#else
-    m_gcAnalyzeI.addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
-#endif
+    m_gcAnalyzeI.addResult (dPSNR, (Double)uibits, MSEyuvframe);
   }
   if (pcSlice->isInterP())
   {
-#if H_MV
-    m_pcEncTop->getAnalyzeP()->addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
-#else
-    m_gcAnalyzeP.addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
-#endif
+    m_gcAnalyzeP.addResult (dPSNR, (Double)uibits, MSEyuvframe);
   }
   if (pcSlice->isInterB())
   {
-#if H_MV
-    m_pcEncTop->getAnalyzeB()->addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
-#else
-    m_gcAnalyzeB.addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
-#endif
+    m_gcAnalyzeB.addResult (dPSNR, (Double)uibits, MSEyuvframe);
   }
 
   Char c = (pcSlice->isIntra() ? 'I' : pcSlice->isInterP() ? 'P' : 'B');
-  if (!pcSlice->isReferenced()) c += 32;
+  if (!pcSlice->isReferenced())
+  {
+    c += 32;
+  }
 
 #if ADAPTIVE_QP_SELECTION
-#if H_MV
+#if NH_MV
   printf("Layer %3d   POC %4d TId: %1d ( %c-SLICE, nQP %d QP %d ) %10d  bits",
     pcSlice->getLayerId(),
@@ -2806,5 +2469,5 @@
 #endif
 #else
-#if H_MV
+#if NH_MV
   printf("Layer %3d   POC %4d TId: %1d ( %c-SLICE, QP %d ) %10d bits",
     pcSlice->getLayerId(),
@@ -2823,8 +2486,15 @@
 #endif
 #endif
-
-  printf(" [Y %6.4lf dB    U %6.4lf dB    V %6.4lf dB]", dYPSNR, dUPSNR, dVPSNR );
+#if NH_MV
+  printf(" [Y %8.4lf dB    U %8.4lf dB    V %8.4lf dB]", dPSNR[COMPONENT_Y], dPSNR[COMPONENT_Cb], dPSNR[COMPONENT_Cr] );
+#else
+  printf(" [Y %6.4lf dB    U %6.4lf dB    V %6.4lf dB]", dPSNR[COMPONENT_Y], dPSNR[COMPONENT_Cb], dPSNR[COMPONENT_Cr] );
+#endif
+  if (printFrameMSE)
+  {
+    printf(" [Y MSE %6.4lf  U MSE %6.4lf  V MSE %6.4lf]", MSEyuvframe[COMPONENT_Y], MSEyuvframe[COMPONENT_Cb], MSEyuvframe[COMPONENT_Cr] );
+  }
   printf(" [ET %5.0f ]", dEncTime );
-  
+
   for (Int iRefList = 0; iRefList < 2; iRefList++)
   {
@@ -2832,5 +2502,5 @@
     for (Int iRefIndex = 0; iRefIndex < pcSlice->getNumRefIdx(RefPicList(iRefList)); iRefIndex++)
     {
-#if H_MV
+#if NH_MV
       if( pcSlice->getLayerId() != pcSlice->getRefLayerId( RefPicList(iRefList), iRefIndex ) )
       {
@@ -2841,5 +2511,5 @@
 #endif
       printf ("%d ", pcSlice->getRefPOC(RefPicList(iRefList), iRefIndex)-pcSlice->getLastIDR());
-#if H_MV
+#if NH_MV
       }
 #endif
@@ -2847,172 +2517,107 @@
     printf("]");
   }
-}
-
-
-Void reinterlace(Pel* top, Pel* bottom, Pel* dst, UInt stride, UInt width, UInt height, bool isTff)
-{
-  
-  for (Int y = 0; y < height; y++)
-  {
-    for (Int x = 0; x < width; x++)
-    {
-      dst[x] = isTff ? top[x] : bottom[x];
-      dst[stride+x] = isTff ? bottom[x] : top[x];
-    }
-    top += stride;
-    bottom += stride;
-    dst += stride*2;
-  }
-}
-
-
-Void TEncGOP::xCalculateInterlacedAddPSNR( TComPic* pcPicOrgTop, TComPic* pcPicOrgBottom, TComPicYuv* pcPicRecTop, TComPicYuv* pcPicRecBottom, const AccessUnit& accessUnit, Double dEncTime )
-{
-#if  H_MV
+
+  cscd.destroy();
+}
+
+Void TEncGOP::xCalculateInterlacedAddPSNR( TComPic* pcPicOrgFirstField, TComPic* pcPicOrgSecondField,
+                                           TComPicYuv* pcPicRecFirstField, TComPicYuv* pcPicRecSecondField,
+                                           const InputColourSpaceConversion conversion, const Bool printFrameMSE )
+{
+
+#if  NH_MV
   assert( 0 ); // Field coding and MV need to be aligned. 
 #else
-  Int     x, y;
-  
-  UInt64 uiSSDY_in  = 0;
-  UInt64 uiSSDU_in  = 0;
-  UInt64 uiSSDV_in  = 0;
-  
-  Double  dYPSNR_in  = 0.0;
-  Double  dUPSNR_in  = 0.0;
-  Double  dVPSNR_in  = 0.0;
-  
-  /*------ INTERLACED PSNR -----------*/
-  
-  /* Luma */
-  
-  Pel*  pOrgTop = pcPicOrgTop->getPicYuvOrg()->getLumaAddr();
-  Pel*  pOrgBottom = pcPicOrgBottom->getPicYuvOrg()->getLumaAddr();
-  Pel*  pRecTop = pcPicRecTop->getLumaAddr();
-  Pel*  pRecBottom = pcPicRecBottom->getLumaAddr();
-  
-  Int   iWidth;
-  Int   iHeight;
-  Int iStride;
-  
-  iWidth  = pcPicOrgTop->getPicYuvOrg()->getWidth () - m_pcEncTop->getPad(0);
-  iHeight = pcPicOrgTop->getPicYuvOrg()->getHeight() - m_pcEncTop->getPad(1);
-  iStride = pcPicOrgTop->getPicYuvOrg()->getStride();
-  Int   iSize   = iWidth*iHeight;
-  bool isTff = pcPicOrgTop->isTopField();
-  
-  TComPicYuv* pcOrgInterlaced = new TComPicYuv;
-  pcOrgInterlaced->create( iWidth, iHeight << 1, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
-  
-  TComPicYuv* pcRecInterlaced = new TComPicYuv;
-  pcRecInterlaced->create( iWidth, iHeight << 1, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
-  
-  Pel* pOrgInterlaced = pcOrgInterlaced->getLumaAddr();
-  Pel* pRecInterlaced = pcRecInterlaced->getLumaAddr();
-  
-  //=== Interlace fields ====
-  reinterlace(pOrgTop, pOrgBottom, pOrgInterlaced, iStride, iWidth, iHeight, isTff);
-  reinterlace(pRecTop, pRecBottom, pRecInterlaced, iStride, iWidth, iHeight, isTff);
-  
+
+  const TComSPS &sps=pcPicOrgFirstField->getPicSym()->getSPS();
+  Double  dPSNR[MAX_NUM_COMPONENT];
+  TComPic    *apcPicOrgFields[2]={pcPicOrgFirstField, pcPicOrgSecondField};
+  TComPicYuv *apcPicRecFields[2]={pcPicRecFirstField, pcPicRecSecondField};
+
+  for(Int i=0; i<MAX_NUM_COMPONENT; i++)
+  {
+    dPSNR[i]=0.0;
+  }
+
+  TComPicYuv cscd[2 /* first/second field */];
+  if (conversion!=IPCOLOURSPACE_UNCHANGED)
+  {
+    for(UInt fieldNum=0; fieldNum<2; fieldNum++)
+    {
+      TComPicYuv &reconField=*(apcPicRecFields[fieldNum]);
+      cscd[fieldNum].create(reconField.getWidth(COMPONENT_Y), reconField.getHeight(COMPONENT_Y), reconField.getChromaFormat(), reconField.getWidth(COMPONENT_Y), reconField.getHeight(COMPONENT_Y), 0, false);
+      TVideoIOYuv::ColourSpaceConvert(reconField, cscd[fieldNum], conversion, false);
+      apcPicRecFields[fieldNum]=cscd+fieldNum;
+    }
+  }
+
   //===== calculate PSNR =====
-  for( y = 0; y < iHeight << 1; y++ )
-  {
-    for( x = 0; x < iWidth; x++ )
-    {
-      Int iDiff = (Int)( pOrgInterlaced[x] - pRecInterlaced[x] );
-      uiSSDY_in   += iDiff * iDiff;
-    }
-    pOrgInterlaced += iStride;
-    pRecInterlaced += iStride;
-  }
-  
-  /*Chroma*/
-  
-  iHeight >>= 1;
-  iWidth  >>= 1;
-  iStride >>= 1;
-  
-  pOrgTop = pcPicOrgTop->getPicYuvOrg()->getCbAddr();
-  pOrgBottom = pcPicOrgBottom->getPicYuvOrg()->getCbAddr();
-  pRecTop = pcPicRecTop->getCbAddr();
-  pRecBottom = pcPicRecBottom->getCbAddr();
-  pOrgInterlaced = pcOrgInterlaced->getCbAddr();
-  pRecInterlaced = pcRecInterlaced->getCbAddr();
-  
-  //=== Interlace fields ====
-  reinterlace(pOrgTop, pOrgBottom, pOrgInterlaced, iStride, iWidth, iHeight, isTff);
-  reinterlace(pRecTop, pRecBottom, pRecInterlaced, iStride, iWidth, iHeight, isTff);
-  
-  //===== calculate PSNR =====
-  for( y = 0; y < iHeight << 1; y++ )
-  {
-    for( x = 0; x < iWidth; x++ )
-    {
-      Int iDiff = (Int)( pOrgInterlaced[x] - pRecInterlaced[x] );
-      uiSSDU_in   += iDiff * iDiff;
-    }
-    pOrgInterlaced += iStride;
-    pRecInterlaced += iStride;
-  }
-  
-  pOrgTop = pcPicOrgTop->getPicYuvOrg()->getCrAddr();
-  pOrgBottom = pcPicOrgBottom->getPicYuvOrg()->getCrAddr();
-  pRecTop = pcPicRecTop->getCrAddr();
-  pRecBottom = pcPicRecBottom->getCrAddr();
-  pOrgInterlaced = pcOrgInterlaced->getCrAddr();
-  pRecInterlaced = pcRecInterlaced->getCrAddr();
-  
-  //=== Interlace fields ====
-  reinterlace(pOrgTop, pOrgBottom, pOrgInterlaced, iStride, iWidth, iHeight, isTff);
-  reinterlace(pRecTop, pRecBottom, pRecInterlaced, iStride, iWidth, iHeight, isTff);
-  
-  //===== calculate PSNR =====
-  for( y = 0; y < iHeight << 1; y++ )
-  {
-    for( x = 0; x < iWidth; x++ )
-    {
-      Int iDiff = (Int)( pOrgInterlaced[x] - pRecInterlaced[x] );
-      uiSSDV_in   += iDiff * iDiff;
-    }
-    pOrgInterlaced += iStride;
-    pRecInterlaced += iStride;
-  }
-  
-  Int maxvalY = 255 << (g_bitDepthY-8);
-  Int maxvalC = 255 << (g_bitDepthC-8);
-  Double fRefValueY = (Double) maxvalY * maxvalY * iSize*2;
-  Double fRefValueC = (Double) maxvalC * maxvalC * iSize*2 / 4.0;
-  dYPSNR_in            = ( uiSSDY_in ? 10.0 * log10( fRefValueY / (Double)uiSSDY_in ) : 99.99 );
-  dUPSNR_in            = ( uiSSDU_in ? 10.0 * log10( fRefValueC / (Double)uiSSDU_in ) : 99.99 );
-  dVPSNR_in            = ( uiSSDV_in ? 10.0 * log10( fRefValueC / (Double)uiSSDV_in ) : 99.99 );
-  
-  /* calculate the size of the access unit, excluding:
-   *  - any AnnexB contributions (start_code_prefix, zero_byte, etc.,)
-   *  - SEI NAL units
-   */
-  UInt numRBSPBytes = 0;
-  for (AccessUnit::const_iterator it = accessUnit.begin(); it != accessUnit.end(); it++)
-  {
-    UInt numRBSPBytes_nal = UInt((*it)->m_nalUnitData.str().size());
-    
-    if ((*it)->m_nalUnitType != NAL_UNIT_PREFIX_SEI && (*it)->m_nalUnitType != NAL_UNIT_SUFFIX_SEI)
-      numRBSPBytes += numRBSPBytes_nal;
-  }
-  
-  UInt uibits = numRBSPBytes * 8 ;
-  
+  Double MSEyuvframe[MAX_NUM_COMPONENT] = {0, 0, 0};
+
+  assert(apcPicRecFields[0]->getChromaFormat()==apcPicRecFields[1]->getChromaFormat());
+  const UInt numValidComponents=apcPicRecFields[0]->getNumberValidComponents();
+
+  for(Int chan=0; chan<numValidComponents; chan++)
+  {
+    const ComponentID ch=ComponentID(chan);
+    assert(apcPicRecFields[0]->getWidth(ch)==apcPicRecFields[1]->getWidth(ch));
+    assert(apcPicRecFields[0]->getHeight(ch)==apcPicRecFields[1]->getHeight(ch));
+
+    UInt64 uiSSDtemp=0;
+    const Int   iWidth  = apcPicRecFields[0]->getWidth (ch) - (m_pcEncTop->getPad(0) >> apcPicRecFields[0]->getComponentScaleX(ch));
+    const Int   iHeight = apcPicRecFields[0]->getHeight(ch) - ((m_pcEncTop->getPad(1) >> 1) >> apcPicRecFields[0]->getComponentScaleY(ch));
+
+    Int   iSize   = iWidth*iHeight;
+
+    for(UInt fieldNum=0; fieldNum<2; fieldNum++)
+    {
+      TComPic *pcPic=apcPicOrgFields[fieldNum];
+      TComPicYuv *pcPicD=apcPicRecFields[fieldNum];
+
+      const Pel*  pOrg    = (conversion!=IPCOLOURSPACE_UNCHANGED) ? pcPic ->getPicYuvTrueOrg()->getAddr(ch) : pcPic ->getPicYuvOrg()->getAddr(ch);
+      Pel*  pRec    = pcPicD->getAddr(ch);
+      const Int   iStride = pcPicD->getStride(ch);
+
+
+      for(Int y = 0; y < iHeight; y++ )
+      {
+        for(Int x = 0; x < iWidth; x++ )
+        {
+          Intermediate_Int iDiff = (Intermediate_Int)( pOrg[x] - pRec[x] );
+          uiSSDtemp   += iDiff * iDiff;
+        }
+        pOrg += iStride;
+        pRec += iStride;
+      }
+    }
+    const Int maxval = 255 << (sps.getBitDepth(toChannelType(ch)) - 8);
+    const Double fRefValue = (Double) maxval * maxval * iSize*2;
+    dPSNR[ch]         = ( uiSSDtemp ? 10.0 * log10( fRefValue / (Double)uiSSDtemp ) : 999.99 );
+    MSEyuvframe[ch]   = (Double)uiSSDtemp/(iSize*2);
+  }
+
+  UInt uibits = 0; // the number of bits for the pair is not calculated here - instead the overall total is used elsewhere.
+
   //===== add PSNR =====
-  m_gcAnalyzeAll_in.addResult (dYPSNR_in, dUPSNR_in, dVPSNR_in, (Double)uibits);
-  
-  printf("\n                                      Interlaced frame %d: [Y %6.4lf dB    U %6.4lf dB    V %6.4lf dB]", pcPicOrgBottom->getPOC()/2 , dYPSNR_in, dUPSNR_in, dVPSNR_in );
-  
-  pcOrgInterlaced->destroy();
-  delete pcOrgInterlaced;
-  pcRecInterlaced->destroy();
-  delete pcRecInterlaced;
-#endif
-}
+  m_gcAnalyzeAll_in.addResult (dPSNR, (Double)uibits, MSEyuvframe);
+
+  printf("\n                                      Interlaced frame %d: [Y %6.4lf dB    U %6.4lf dB    V %6.4lf dB]", pcPicOrgSecondField->getPOC()/2 , dPSNR[COMPONENT_Y], dPSNR[COMPONENT_Cb], dPSNR[COMPONENT_Cr] );
+  if (printFrameMSE)
+  {
+    printf(" [Y MSE %6.4lf  U MSE %6.4lf  V MSE %6.4lf]", MSEyuvframe[COMPONENT_Y], MSEyuvframe[COMPONENT_Cb], MSEyuvframe[COMPONENT_Cr] );
+  }
+
+  for(UInt fieldNum=0; fieldNum<2; fieldNum++)
+  {
+    cscd[fieldNum].destroy();
+  }
+#endif
+}
+
 /** Function for deciding the nal_unit_type.
  * \param pocCurr POC of the current picture
- * \returns the nal unit type of the picture
+ * \param lastIDR  POC of the last IDR picture
+ * \param isField  true to indicate field coding
+ * \returns the NAL unit type of the picture
  * This function checks the configuration and returns the appropriate nal_unit_type for the picture.
  */
@@ -3023,17 +2628,12 @@
     return NAL_UNIT_CODED_SLICE_IDR_W_RADL;
   }
-#if EFFICIENT_FIELD_IRAP
-  if(isField && pocCurr == 1)
+
+  if(m_pcCfg->getEfficientFieldIRAPEnabled() && isField && pocCurr == 1)
   {
     // to avoid the picture becoming an IRAP
     return NAL_UNIT_CODED_SLICE_TRAIL_R;
   }
-#endif
-
-#if ALLOW_RECOVERY_POINT_AS_RAP
+
   if(m_pcCfg->getDecodingRefreshType() != 3 && (pocCurr - isField) % m_pcCfg->getIntraPeriod() == 0)
-#else
-  if ((pocCurr - isField) % m_pcCfg->getIntraPeriod() == 0)
-#endif
   {
     if (m_pcCfg->getDecodingRefreshType() == 1)
@@ -3050,8 +2650,8 @@
     if(pocCurr<m_pocCRA)
     {
-      // All leading pictures are being marked as TFD pictures here since current encoder uses all 
-      // reference pictures while encoding leading pictures. An encoder can ensure that a leading 
-      // picture can be still decodable when random accessing to a CRA/CRANT/BLA/BLANT picture by 
-      // controlling the reference pictures used for encoding that leading picture. Such a leading 
+      // All leading pictures are being marked as TFD pictures here since current encoder uses all
+      // reference pictures while encoding leading pictures. An encoder can ensure that a leading
+      // picture can be still decodable when random accessing to a CRA/CRANT/BLA/BLANT picture by
+      // controlling the reference pictures used for encoding that leading picture. Such a leading
       // picture need not be marked as a TFD picture.
       return NAL_UNIT_CODED_SLICE_RASL_R;
@@ -3068,8 +2668,9 @@
 }
 
+
 Double TEncGOP::xCalculateRVM()
 {
   Double dRVM = 0;
-  
+
   if( m_pcCfg->getGOPSize() == 1 && m_pcCfg->getIntraPeriod() != 1 && m_pcCfg->getFramesToBeEncoded() > RVM_VCEGAM10_M * 2 )
   {
@@ -3079,5 +2680,5 @@
     vRL.resize( N );
     vB.resize( N );
-    
+
     Int i;
     Double dRavg = 0 , dBavg = 0;
@@ -3087,5 +2688,7 @@
       vRL[i] = 0;
       for( Int j = i - RVM_VCEGAM10_M ; j <= i + RVM_VCEGAM10_M - 1 ; j++ )
+      {
         vRL[i] += m_vRVM_RP[j];
+      }
       vRL[i] /= ( 2 * RVM_VCEGAM10_M );
       vB[i] = vB[i-1] + m_vRVM_RP[i] - vRL[i];
@@ -3093,8 +2696,8 @@
       dBavg += vB[i];
     }
-    
+
     dRavg /= ( N - 2 * RVM_VCEGAM10_M );
     dBavg /= ( N - 2 * RVM_VCEGAM10_M );
-    
+
     Double dSigamB = 0;
     for( i = RVM_VCEGAM10_M + 1 ; i < N - RVM_VCEGAM10_M + 1 ; i++ )
@@ -3104,13 +2707,12 @@
     }
     dSigamB = sqrt( dSigamB / ( N - 2 * RVM_VCEGAM10_M ) );
-    
+
     Double f = sqrt( 12.0 * ( RVM_VCEGAM10_M - 1 ) / ( RVM_VCEGAM10_M + 1 ) );
-    
+
     dRVM = dSigamB / dRavg * f;
   }
-  
+
   return( dRVM );
 }
-
 /** Attaches the input bitstream to the stream in the output NAL unit
     Updates rNalu to contain concatenated bitstream. rpcBitstreamRedirect is cleared at the end of this function call.
@@ -3118,5 +2720,5 @@
  *  \param rNalu          target NAL unit
  */
-Void TEncGOP::xAttachSliceDataToNalUnit (OutputNALUnit& rNalu, TComOutputBitstream*& codedSliceData)
+Void TEncGOP::xAttachSliceDataToNalUnit (OutputNALUnit& rNalu, TComOutputBitstream* codedSliceData)
 {
   // Byte-align
@@ -3125,5 +2727,5 @@
   // Perform bitstream concatenation
   if (codedSliceData->getNumberOfWrittenBits() > 0)
-    {
+  {
     rNalu.m_Bitstream.addSubstream(codedSliceData);
   }
@@ -3134,13 +2736,15 @@
 }
 
-// Function will arrange the long-term pictures in the decreasing order of poc_lsb_lt, 
+// Function will arrange the long-term pictures in the decreasing order of poc_lsb_lt,
 // and among the pictures with the same lsb, it arranges them in increasing delta_poc_msb_cycle_lt value
 Void TEncGOP::arrangeLongtermPicturesInRPS(TComSlice *pcSlice, TComList<TComPic*>& rcListPic)
 {
-  TComReferencePictureSet *rps = pcSlice->getRPS();
-  if(!rps->getNumberOfLongtermPictures())
+  if(pcSlice->getRPS()->getNumberOfLongtermPictures() == 0)
   {
     return;
   }
+  // we can only modify the local RPS!
+  assert (pcSlice->getRPSidx()==-1);
+  TComReferencePictureSet *rps = pcSlice->getLocalRPS();
 
   // Arrange long-term reference pictures in the correct order of LSB and MSB,
@@ -3155,5 +2759,5 @@
   ::memset(mSBPresentFlag , 0, sizeof(mSBPresentFlag));     // Indicate if MSB needs to be present
 
-  // Get the long-term reference pictures 
+  // Get the long-term reference pictures
   Int offset = rps->getNumberOfNegativePictures() + rps->getNumberOfPositivePictures();
   Int i, ctr = 0;
@@ -3163,5 +2767,5 @@
     longtermPicsPoc[ctr] = rps->getPOC(i);                                  // LTRP POC
     longtermPicsLSB[ctr] = getLSB(longtermPicsPoc[ctr], maxPicOrderCntLSB); // LTRP POC LSB
-    indices[ctr]      = i; 
+    indices[ctr]      = i;
     longtermPicsMSB[ctr] = longtermPicsPoc[ctr] - longtermPicsLSB[ctr];
   }
@@ -3169,5 +2773,5 @@
   assert(ctr == numLongPics);
 
-  // Arrange pictures in decreasing order of MSB; 
+  // Arrange pictures in decreasing order of MSB;
   for(i = 0; i < numLongPics; i++)
   {
@@ -3188,5 +2792,5 @@
     // Check if MSB present flag should be enabled.
     // Check if the buffer contains any pictures that have the same LSB.
-    TComList<TComPic*>::iterator  iterPic = rcListPic.begin();  
+    TComList<TComPic*>::iterator  iterPic = rcListPic.begin();
     TComPic*                      pcPic;
     while ( iterPic != rcListPic.end() )
@@ -3200,5 +2804,5 @@
         break;
       }
-      iterPic++;      
+      iterPic++;
     }
   }
@@ -3214,5 +2818,5 @@
   Int currMSB = 0, currLSB = 0;
   // currPicPoc = currMSB + currLSB
-  currLSB = getLSB(pcSlice->getPOC(), maxPicOrderCntLSB);  
+  currLSB = getLSB(pcSlice->getPOC(), maxPicOrderCntLSB);
   currMSB = pcSlice->getPOC() - currLSB;
 
@@ -3224,5 +2828,5 @@
     rps->setPocLSBLT              (i, longtermPicsLSB[ctr]);
     rps->setDeltaPocMSBCycleLT    (i, (currMSB - (longtermPicsPoc[ctr] - longtermPicsLSB[ctr])) / maxPicOrderCntLSB);
-    rps->setDeltaPocMSBPresentFlag(i, mSBPresentFlag[ctr]);     
+    rps->setDeltaPocMSBPresentFlag(i, mSBPresentFlag[ctr]);
 
     assert(rps->getDeltaPocMSBCycleLT(i) >= 0);   // Non-negative value
@@ -3232,5 +2836,5 @@
     for(Int j = rps->getNumberOfPictures() - 1 - ctr; j >= offset; j--)
     {
-      // Here at the encoder we know that we have set the full POC value for the LTRPs, hence we 
+      // Here at the encoder we know that we have set the full POC value for the LTRPs, hence we
       // don't have to check the MSB present flag values for this constraint.
       assert( rps->getPOC(i) != rps->getPOC(j) ); // If assert fails, LTRP entry repeated in RPS!!!
@@ -3239,35 +2843,15 @@
 }
 
-/** 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
- * This function finds the position to insert the first of APS and non-nested BP, PT, DU info SEI messages.
- */
-Int TEncGOP::xGetFirstSeiLocation(AccessUnit &accessUnit)
-{
-  // Find the location of the first SEI message
-  AccessUnit::iterator it;
-  Int seiStartPos = 0;
-  for(it = accessUnit.begin(); it != accessUnit.end(); it++, seiStartPos++)
-  {
-     if ((*it)->isSei() || (*it)->isVcl())
-     {
-       break;
-     }               
-  }
-//  assert(it != accessUnit.end());  // Triggers with some legit configurations
-  return seiStartPos;
-}
-
-Void TEncGOP::dblMetric( TComPic* pcPic, UInt uiNumSlices )
+Void TEncGOP::applyDeblockingFilterMetric( TComPic* pcPic, UInt uiNumSlices )
 {
   TComPicYuv* pcPicYuvRec = pcPic->getPicYuvRec();
-  Pel* Rec    = pcPicYuvRec->getLumaAddr( 0 );
+  Pel* Rec    = pcPicYuvRec->getAddr(COMPONENT_Y);
   Pel* tempRec = Rec;
-  Int  stride = pcPicYuvRec->getStride();
+  Int  stride = pcPicYuvRec->getStride(COMPONENT_Y);
   UInt log2maxTB = pcPic->getSlice(0)->getSPS()->getQuadtreeTULog2MaxSize();
   UInt maxTBsize = (1<<log2maxTB);
   const UInt minBlockArtSize = 8;
-  const UInt picWidth = pcPicYuvRec->getWidth();
-  const UInt picHeight = pcPicYuvRec->getHeight();
+  const UInt picWidth = pcPicYuvRec->getWidth(COMPONENT_Y);
+  const UInt picHeight = pcPicYuvRec->getHeight(COMPONENT_Y);
   const UInt noCol = (picWidth>>log2maxTB);
   const UInt noRows = (picHeight>>log2maxTB);
@@ -3279,15 +2863,16 @@
   UInt rowIdx = 0;
   Pel p0, p1, p2, q0, q1, q2;
-  
+
   Int qp = pcPic->getSlice(0)->getSliceQp();
-  Int bitdepthScale = 1 << (g_bitDepthY-8);
+  const Int bitDepthLuma=pcPic->getSlice(0)->getSPS()->getBitDepth(CHANNEL_TYPE_LUMA);
+  Int bitdepthScale = 1 << (bitDepthLuma-8);
   Int beta = TComLoopFilter::getBeta( qp ) * bitdepthScale;
   const Int thr2 = (beta>>2);
   const Int thr1 = 2*bitdepthScale;
   UInt a = 0;
-  
+
   memset(colSAD, 0, noCol*sizeof(UInt64));
   memset(rowSAD, 0, noRows*sizeof(UInt64));
-  
+
   if (maxTBsize > minBlockArtSize)
   {
@@ -3313,5 +2898,5 @@
       Rec = tempRec;
     }
-    
+
     // Analyze horizontal artifact edges
     for(Int r = maxTBsize; r < picHeight; r += maxTBsize)
@@ -3334,5 +2919,5 @@
     }
   }
-  
+
   UInt64 colSADsum = 0;
   UInt64 rowSADsum = 0;
@@ -3345,5 +2930,5 @@
     rowSADsum += rowSAD[r];
   }
-  
+
   colSADsum <<= 10;
   rowSADsum <<= 10;
@@ -3352,8 +2937,8 @@
   rowSADsum /= (noRows-1);
   rowSADsum /= picWidth;
-  
+
   UInt64 avgSAD = ((colSADsum + rowSADsum)>>1);
-  avgSAD >>= (g_bitDepthY-8);
-  
+  avgSAD >>= (bitDepthLuma-8);
+
   if ( avgSAD > 2048 )
   {
@@ -3378,10 +2963,10 @@
     }
   }
-  
+
   free(colSAD);
   free(rowSAD);
 }
 
-#if H_MV
+#if NH_MV
 Void TEncGOP::xSetRefPicListModificationsMv( std::vector<TComPic*> tempPicLists[2], TComSlice* pcSlice, UInt iGOPid )
 { 
