Index: branches/SHM-3.1-dev/source/App/TAppDecoder/TAppDecTop.cpp
===================================================================
--- branches/SHM-3.1-dev/source/App/TAppDecoder/TAppDecTop.cpp	(revision 430)
+++ branches/SHM-3.1-dev/source/App/TAppDecoder/TAppDecTop.cpp	(revision 431)
@@ -56,5 +56,4 @@
 TAppDecTop::TAppDecTop()
 {
-  ::memset (m_abDecFlag, 0, sizeof (m_abDecFlag));
   for(UInt layer=0; layer < MAX_LAYERS; layer++)
   {
@@ -67,5 +66,4 @@
 : m_iPOCLastDisplay(-MAX_INT)
 {
-  ::memset (m_abDecFlag, 0, sizeof (m_abDecFlag));
 }
 #endif
@@ -146,8 +144,8 @@
 
   // main decoder loop
-  Bool recon_opened[MAX_LAYERS]; // reconstruction file not yet opened. (must be performed after SPS is seen)
+  Bool openedReconFile[MAX_LAYERS]; // reconstruction file not yet opened. (must be performed after SPS is seen)
   for(UInt layer=0; layer<=m_tgtLayerId; layer++)
   {
-    recon_opened[layer] = false;
+    openedReconFile[layer] = false;
     m_aiPOCLastDisplay[layer] += m_iSkipFrame;      // set the last displayed POC correctly for skip forward.
   }
@@ -235,5 +233,5 @@
     if( pcListPic )
     {
-      if ( m_pchReconFile[curLayerId] && !recon_opened[curLayerId] )
+      if ( m_pchReconFile[curLayerId] && !openedReconFile[curLayerId] )
       {
         if (!m_outputBitDepthY) { m_outputBitDepthY = g_bitDepthY; }        
@@ -242,5 +240,5 @@
         m_acTVideoIOYuvReconFile[curLayerId].open( m_pchReconFile[curLayerId], true, m_outputBitDepthY, m_outputBitDepthC, g_bitDepthY, g_bitDepthC ); // write mode
 
-        recon_opened[curLayerId] = true;
+        openedReconFile[curLayerId] = true;
       }
       if ( bNewPicture && bNewPOC && 
@@ -278,5 +276,7 @@
   pcBLPic.destroy();
 
-  for(UInt layer = 1; layer <= m_tgtLayerId; layer++)
+  UInt layerIdmin = m_acTDecTop[0].getBLReconFile() == NULL ? 0 : 1;
+
+  for(UInt layer = layerIdmin; layer <= m_tgtLayerId; layer++)
 #else
   for(UInt layer = 0; layer <= m_tgtLayerId; layer++)
@@ -310,5 +310,5 @@
 
   // main decoder loop
-  Bool recon_opened = false; // reconstruction file not yet opened. (must be performed after SPS is seen)
+  Bool openedReconFile = false; // reconstruction file not yet opened. (must be performed after SPS is seen)
 
 #if SYNTAX_OUTPUT
@@ -341,5 +341,4 @@
     streampos location = bitstreamFile.tellg();
     AnnexBStats stats = AnnexBStats();
-    Bool bPreviousPictureDecoded = false;
 
     vector<uint8_t> nalUnit;
@@ -363,14 +362,6 @@
       if( (m_iMaxTemporalLayer >= 0 && nalu.m_temporalId > m_iMaxTemporalLayer) || !isNaluWithinTargetDecLayerIdSet(&nalu)  )
       {
-        if(bPreviousPictureDecoded)
-        {
-          bNewPicture = true;
-          bPreviousPictureDecoded = false;
-        }
-        else
-        {
           bNewPicture = false;
         }
-      }
       else
       {
@@ -386,5 +377,4 @@
           bytestream.reset();
         }
-        bPreviousPictureDecoded = true; 
       }
     }
@@ -396,5 +386,5 @@
     if( pcListPic )
     {
-      if ( m_pchReconFile && !recon_opened )
+      if ( m_pchReconFile && !openedReconFile )
       {
         if (!m_outputBitDepthY) { m_outputBitDepthY = g_bitDepthY; }
@@ -402,5 +392,5 @@
 
         m_cTVideoIOYuvReconFile.open( m_pchReconFile, true, m_outputBitDepthY, m_outputBitDepthC, g_bitDepthY, g_bitDepthC ); // write mode
-        recon_opened = true;
+        openedReconFile = true;
       }
       if ( bNewPicture && 
@@ -508,6 +498,6 @@
 
 /** \param pcListPic list of pictures to be written to file
-    \todo            DYN_REF_FREE should be revised
- */
+\todo            DYN_REF_FREE should be revised
+*/
 #if SVC_EXTENSION
 Void TAppDecTop::xWriteOutput( TComList<TComPic*>* pcListPic, UInt layerId, UInt tId )
@@ -517,5 +507,5 @@
 {
   TComList<TComPic*>::iterator iterPic   = pcListPic->begin();
-  Int not_displayed = 0;
+  Int numPicsNotYetDisplayed = 0;
 
   while (iterPic != pcListPic->end())
@@ -528,85 +518,194 @@
 #endif
     {
-       not_displayed++;
+      numPicsNotYetDisplayed++;
     }
     iterPic++;
   }
   iterPic   = pcListPic->begin();
-  
-  while (iterPic != pcListPic->end())
-  {
-    TComPic* pcPic = *(iterPic);
-    
-#if SVC_EXTENSION
-    if ( pcPic->getOutputMark() && (not_displayed >  pcPic->getNumReorderPics(tId) && pcPic->getPOC() > m_aiPOCLastDisplay[layerId]))
-#else
-    if ( pcPic->getOutputMark() && (not_displayed >  pcPic->getNumReorderPics(tId) && pcPic->getPOC() > m_iPOCLastDisplay))
-#endif
-    {
-      // write to file
-       not_displayed--;
-#if SVC_EXTENSION
-      if ( m_pchReconFile[layerId] )
-      {
-        const Window &conf = pcPic->getConformanceWindow();
-        const Window &defDisp = m_respectDefDispWindow ? pcPic->getDefDisplayWindow() : Window();
+  if (numPicsNotYetDisplayed>2)
+  {
+    iterPic++;
+  }
+
+  TComPic* pcPic = *(iterPic);
+  if (numPicsNotYetDisplayed>2 && pcPic->isField()) //Field Decoding
+  {
+    TComList<TComPic*>::iterator endPic   = pcListPic->end();
+    endPic--;
+    iterPic   = pcListPic->begin();
+    while (iterPic != endPic)
+    {
+      TComPic* pcPicTop = *(iterPic);
+      iterPic++;
+      TComPic* pcPicBottom = *(iterPic);
+
+#if SVC_EXTENSION
+      if ( pcPicTop->getOutputMark() && (numPicsNotYetDisplayed >  pcPicTop->getNumReorderPics(tId) && !(pcPicTop->getPOC()%2) && pcPicBottom->getPOC() == pcPicTop->getPOC()+1)
+        && pcPicBottom->getOutputMark() && (numPicsNotYetDisplayed >  pcPicBottom->getNumReorderPics(tId) && (pcPicTop->getPOC() == m_aiPOCLastDisplay[layerId]+1 || m_aiPOCLastDisplay[layerId]<0)))
+#else
+      if ( pcPicTop->getOutputMark() && (numPicsNotYetDisplayed >  pcPicTop->getNumReorderPics(tId) && !(pcPicTop->getPOC()%2) && pcPicBottom->getPOC() == pcPicTop->getPOC()+1)
+        && pcPicBottom->getOutputMark() && (numPicsNotYetDisplayed >  pcPicBottom->getNumReorderPics(tId) && (pcPicTop->getPOC() == m_iPOCLastDisplay+1 || m_iPOCLastDisplay<0)))
+#endif
+      {
+        // write to file
+        numPicsNotYetDisplayed = numPicsNotYetDisplayed-2;
+#if SVC_EXTENSION
+        if ( m_pchReconFile[layerId] )
+        {
+          const Window &conf = pcPicTop->getConformanceWindow();
+          const Window &defDisp = m_respectDefDispWindow ? pcPicTop->getDefDisplayWindow() : Window();
+          const Bool isTff = pcPicTop->isTopField();
 #if REPN_FORMAT_IN_VPS
-        UInt chromaFormatIdc = pcPic->getSlice(0)->getChromaFormatIdc();
-        Int xScal =  TComSPS::getWinUnitX( chromaFormatIdc ), yScal = TComSPS::getWinUnitY( chromaFormatIdc );
-        m_acTVideoIOYuvReconFile[layerId].write( pcPic->getPicYuvRec(),
-                                       conf.getWindowLeftOffset()  * xScal + defDisp.getWindowLeftOffset(),
-                                       conf.getWindowRightOffset() * xScal + defDisp.getWindowRightOffset(),
-                                       conf.getWindowTopOffset()   * yScal + defDisp.getWindowTopOffset(),
-                                       conf.getWindowBottomOffset()* yScal + defDisp.getWindowBottomOffset() );
-
-#else
-        m_acTVideoIOYuvReconFile[layerId].write( pcPic->getPicYuvRec(),
-                                       conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(),
-                                       conf.getWindowRightOffset() + defDisp.getWindowRightOffset(),
-                                       conf.getWindowTopOffset() + defDisp.getWindowTopOffset(),
-                                       conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset() );
-#endif
-      }
-      
-      // update POC of display order
-      m_aiPOCLastDisplay[layerId] = pcPic->getPOC();
-#else
-      if ( m_pchReconFile )
-      {
+          UInt chromaFormatIdc = pcPic->getSlice(0)->getChromaFormatIdc();
+          Int xScal =  TComSPS::getWinUnitX( chromaFormatIdc ), yScal = TComSPS::getWinUnitY( chromaFormatIdc );
+          m_acTVideoIOYuvReconFile[layerId].write( pcPic->getPicYuvRec(),
+            conf.getWindowLeftOffset()  * xScal + defDisp.getWindowLeftOffset(),
+            conf.getWindowRightOffset() * xScal + defDisp.getWindowRightOffset(),
+            conf.getWindowTopOffset()   * yScal + defDisp.getWindowTopOffset(),
+            conf.getWindowBottomOffset()* yScal + defDisp.getWindowBottomOffset() );
+
+#else
+          m_cTVideoIOYuvReconFile.write( pcPicTop->getPicYuvRec(), pcPicBottom->getPicYuvRec(),
+            conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(),
+            conf.getWindowRightOffset() + defDisp.getWindowRightOffset(),
+            conf.getWindowTopOffset() + defDisp.getWindowTopOffset(),
+            conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset(), isTff );
+#endif
+        }
+
+        // update POC of display order
+        m_aiPOCLastDisplay[layerId] = pcPicBottom->getPOC();
+#else
+        if ( m_pchReconFile )
+        {
+          const Window &conf = pcPicTop->getConformanceWindow();
+          const Window &defDisp = m_respectDefDispWindow ? pcPicTop->getDefDisplayWindow() : Window();
+          const Bool isTff = pcPicTop->isTopField();
+          m_cTVideoIOYuvReconFile.write( pcPicTop->getPicYuvRec(), pcPicBottom->getPicYuvRec(),
+            conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(),
+            conf.getWindowRightOffset() + defDisp.getWindowRightOffset(),
+            conf.getWindowTopOffset() + defDisp.getWindowTopOffset(),
+            conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset(), isTff );
+        }
+
+        // update POC of display order
+        m_iPOCLastDisplay = pcPicBottom->getPOC();
+#endif
+
+        // erase non-referenced picture in the reference picture list after display
+        if ( !pcPicTop->getSlice(0)->isReferenced() && pcPicTop->getReconMark() == true )
+        {
+#if !DYN_REF_FREE
+          pcPicTop->setReconMark(false);
+
+          // mark it should be extended later
+          pcPicTop->getPicYuvRec()->setBorderExtension( false );
+
+#else
+          pcPicTop->destroy();
+          pcListPic->erase( iterPic );
+          iterPic = pcListPic->begin(); // to the beginning, non-efficient way, have to be revised!
+          continue;
+#endif
+        }
+        if ( !pcPicBottom->getSlice(0)->isReferenced() && pcPicBottom->getReconMark() == true )
+        {
+#if !DYN_REF_FREE
+          pcPicBottom->setReconMark(false);
+
+          // mark it should be extended later
+          pcPicBottom->getPicYuvRec()->setBorderExtension( false );
+
+#else
+          pcPicBottom->destroy();
+          pcListPic->erase( iterPic );
+          iterPic = pcListPic->begin(); // to the beginning, non-efficient way, have to be revised!
+          continue;
+#endif
+        }
+        pcPicTop->setOutputMark(false);
+        pcPicBottom->setOutputMark(false);
+      }
+    }
+  }
+  else if (!pcPic->isField()) //Frame Decoding
+  {
+    iterPic = pcListPic->begin();
+    while (iterPic != pcListPic->end())
+    {
+      pcPic = *(iterPic);
+
+#if SVC_EXTENSION
+      if ( pcPic->getOutputMark() && (numPicsNotYetDisplayed >  pcPic->getNumReorderPics(tId) && pcPic->getPOC() > m_aiPOCLastDisplay[layerId]))
+#else
+      if ( pcPic->getOutputMark() && (numPicsNotYetDisplayed >  pcPic->getNumReorderPics(tId) && pcPic->getPOC() > m_iPOCLastDisplay))
+#endif
+      {
+        // write to file
+        numPicsNotYetDisplayed--;
+#if SVC_EXTENSION
+        if ( m_pchReconFile[layerId] )
+        {
+          const Window &conf = pcPic->getConformanceWindow();
+          const Window &defDisp = m_respectDefDispWindow ? pcPic->getDefDisplayWindow() : Window();
+#if REPN_FORMAT_IN_VPS
+          UInt chromaFormatIdc = pcPic->getSlice(0)->getChromaFormatIdc();
+          Int xScal =  TComSPS::getWinUnitX( chromaFormatIdc ), yScal = TComSPS::getWinUnitY( chromaFormatIdc );
+          m_acTVideoIOYuvReconFile[layerId].write( pcPic->getPicYuvRec(),
+            conf.getWindowLeftOffset()  * xScal + defDisp.getWindowLeftOffset(),
+            conf.getWindowRightOffset() * xScal + defDisp.getWindowRightOffset(),
+            conf.getWindowTopOffset()   * yScal + defDisp.getWindowTopOffset(),
+            conf.getWindowBottomOffset()* yScal + defDisp.getWindowBottomOffset() );
+
+#else
+          m_acTVideoIOYuvReconFile[layerId].write( pcPic->getPicYuvRec(),
+            conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(),
+            conf.getWindowRightOffset() + defDisp.getWindowRightOffset(),
+            conf.getWindowTopOffset() + defDisp.getWindowTopOffset(),
+            conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset() );
+#endif
+        }
+
+        // update POC of display order
+        m_aiPOCLastDisplay[layerId] = pcPic->getPOC();
+#else
+        if ( m_pchReconFile )
+        {
 #if SYNTAX_OUTPUT
-        const Window &conf = pcPic->getConformanceWindow();
-        const Window &defDisp = m_respectDefDispWindow ? pcPic->getDefDisplayWindow() : Window();
-        m_cTVideoIOYuvReconFile.write( pcPic->getPicYuvRec(),
-                                       conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(),
-                                       conf.getWindowRightOffset() + defDisp.getWindowRightOffset(),
-                                       conf.getWindowTopOffset() + defDisp.getWindowTopOffset(),
-                                       conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset() );
-#endif
-      }
-      
-      // update POC of display order
-      m_iPOCLastDisplay = pcPic->getPOC();
-#endif
-      
-      // erase non-referenced picture in the reference picture list after display
-      if ( !pcPic->getSlice(0)->isReferenced() && pcPic->getReconMark() == true )
-      {
+          const Window &conf = pcPic->getConformanceWindow();
+          const Window &defDisp = m_respectDefDispWindow ? pcPic->getDefDisplayWindow() : Window();
+          m_cTVideoIOYuvReconFile.write( pcPic->getPicYuvRec(),
+            conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(),
+            conf.getWindowRightOffset() + defDisp.getWindowRightOffset(),
+            conf.getWindowTopOffset() + defDisp.getWindowTopOffset(),
+            conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset() );
+#endif
+        }
+
+        // update POC of display order
+        m_iPOCLastDisplay = pcPic->getPOC();
+#endif
+
+        // erase non-referenced picture in the reference picture list after display
+        if ( !pcPic->getSlice(0)->isReferenced() && pcPic->getReconMark() == true )
+        {
 #if !DYN_REF_FREE
-        pcPic->setReconMark(false);
-        
-        // mark it should be extended later
-        pcPic->getPicYuvRec()->setBorderExtension( false );
-        
-#else
-        pcPic->destroy();
-        pcListPic->erase( iterPic );
-        iterPic = pcListPic->begin(); // to the beginning, non-efficient way, have to be revised!
-        continue;
-#endif
-      }
-      pcPic->setOutputMark(false);
-    }
-    
-    iterPic++;
+          pcPic->setReconMark(false);
+
+          // mark it should be extended later
+          pcPic->getPicYuvRec()->setBorderExtension( false );
+
+#else
+          pcPic->destroy();
+          pcListPic->erase( iterPic );
+          iterPic = pcListPic->begin(); // to the beginning, non-efficient way, have to be revised!
+          continue;
+#endif
+        }
+        pcPic->setOutputMark(false);
+      }
+
+      iterPic++;
+    }
   }
 }
@@ -628,82 +727,194 @@
 
   iterPic   = pcListPic->begin();
-  
-  while (iterPic != pcListPic->end())
-  {
-    TComPic* pcPic = *(iterPic);
-
-    if ( pcPic->getOutputMark() )
-    {
-      // write to file
-#if SVC_EXTENSION
-      if ( m_pchReconFile[layerId] )
-      {
-        const Window &conf = pcPic->getConformanceWindow();
-        const Window &defDisp = m_respectDefDispWindow ? pcPic->getDefDisplayWindow() : Window();
+  TComPic* pcPic = *(iterPic);
+
+  if (pcPic->isField()) //Field Decoding
+  {
+    TComList<TComPic*>::iterator endPic   = pcListPic->end();
+    endPic--;
+    TComPic *pcPicTop, *pcPicBottom = NULL;
+    while (iterPic != endPic)
+    {
+      pcPicTop = *(iterPic);
+      iterPic++;
+      pcPicBottom = *(iterPic);
+
+      if ( pcPicTop->getOutputMark() && pcPicBottom->getOutputMark() && !(pcPicTop->getPOC()%2) && (pcPicBottom->getPOC() == pcPicTop->getPOC()+1) )
+      {
+        // write to file
+#if SVC_EXTENSION
+        if ( m_pchReconFile[layerId] )
+        {
+          const Window &conf = pcPicTop->getConformanceWindow();
+          const Window &defDisp = m_respectDefDispWindow ? pcPicTop->getDefDisplayWindow() : Window();
+          const Bool isTff = pcPicTop->isTopField();
 #if REPN_FORMAT_IN_VPS
-        UInt chromaFormatIdc = pcPic->getSlice(0)->getChromaFormatIdc();
-        Int xScal =  TComSPS::getWinUnitX( chromaFormatIdc ), yScal = TComSPS::getWinUnitY( chromaFormatIdc );
-        m_acTVideoIOYuvReconFile[layerId].write( pcPic->getPicYuvRec(),
-                                       conf.getWindowLeftOffset()  *xScal + defDisp.getWindowLeftOffset(),
-                                       conf.getWindowRightOffset() *xScal + defDisp.getWindowRightOffset(),
-                                       conf.getWindowTopOffset()   *yScal + defDisp.getWindowTopOffset(),
-                                       conf.getWindowBottomOffset()*yScal + defDisp.getWindowBottomOffset() );
-
-#else
-        m_acTVideoIOYuvReconFile[layerId].write( pcPic->getPicYuvRec(),
-                                       conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(),
-                                       conf.getWindowRightOffset() + defDisp.getWindowRightOffset(),
-                                       conf.getWindowTopOffset() + defDisp.getWindowTopOffset(),
-                                       conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset() );
-#endif
-      }
-      
-      // update POC of display order
-      m_aiPOCLastDisplay[layerId] = pcPic->getPOC();
-#else
-      if ( m_pchReconFile )
-      {
-        const Window &conf = pcPic->getConformanceWindow();
-        const Window &defDisp = m_respectDefDispWindow ? pcPic->getDefDisplayWindow() : Window();
-        m_cTVideoIOYuvReconFile.write( pcPic->getPicYuvRec(),
-                                       conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(),
-                                       conf.getWindowRightOffset() + defDisp.getWindowRightOffset(),
-                                       conf.getWindowTopOffset() + defDisp.getWindowTopOffset(),
-                                       conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset() );
-      }
-      
-      // update POC of display order
-      m_iPOCLastDisplay = pcPic->getPOC();
-#endif
-      
-      // erase non-referenced picture in the reference picture list after display
-      if ( !pcPic->getSlice(0)->isReferenced() && pcPic->getReconMark() == true )
-      {
+          UInt chromaFormatIdc = pcPic->getSlice(0)->getChromaFormatIdc();
+          Int xScal =  TComSPS::getWinUnitX( chromaFormatIdc ), yScal = TComSPS::getWinUnitY( chromaFormatIdc );
+          m_acTVideoIOYuvReconFile[layerId].write( pcPic->getPicYuvRec(),
+            conf.getWindowLeftOffset()  *xScal + defDisp.getWindowLeftOffset(),
+            conf.getWindowRightOffset() *xScal + defDisp.getWindowRightOffset(),
+            conf.getWindowTopOffset()   *yScal + defDisp.getWindowTopOffset(),
+            conf.getWindowBottomOffset()*yScal + defDisp.getWindowBottomOffset() );
+
+#else
+          m_cTVideoIOYuvReconFile[layerId].write( pcPicTop->getPicYuvRec(), pcPicBottom->getPicYuvRec(),
+            conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(),
+            conf.getWindowRightOffset() + defDisp.getWindowRightOffset(),
+            conf.getWindowTopOffset() + defDisp.getWindowTopOffset(),
+            conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset(), isTff );
+#endif
+        }
+
+        // update POC of display order
+        m_aiPOCLastDisplay[layerId] = pcPicBottom->getPOC();
+#else
+        if ( m_pchReconFile )
+        {
+          const Window &conf = pcPicTop->getConformanceWindow();
+          const Window &defDisp = m_respectDefDispWindow ? pcPicTop->getDefDisplayWindow() : Window();
+          const Bool isTff = pcPicTop->isTopField();
+          m_cTVideoIOYuvReconFile.write( pcPicTop->getPicYuvRec(), pcPicBottom->getPicYuvRec(),
+            conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(),
+            conf.getWindowRightOffset() + defDisp.getWindowRightOffset(),
+            conf.getWindowTopOffset() + defDisp.getWindowTopOffset(),
+            conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset(), isTff );
+        }
+
+        // update POC of display order
+        m_iPOCLastDisplay = pcPicBottom->getPOC();
+#endif
+
+        // erase non-referenced picture in the reference picture list after display
+        if ( !pcPicTop->getSlice(0)->isReferenced() && pcPicTop->getReconMark() == true )
+        {
 #if !DYN_REF_FREE
-        pcPic->setReconMark(false);
-        
-        // mark it should be extended later
-        pcPic->getPicYuvRec()->setBorderExtension( false );
-        
-#else
-        pcPic->destroy();
-        pcListPic->erase( iterPic );
-        iterPic = pcListPic->begin(); // to the beginning, non-efficient way, have to be revised!
-        continue;
-#endif
-      }
-      pcPic->setOutputMark(false);
-    }
+          pcPicTop->setReconMark(false);
+
+          // mark it should be extended later
+          pcPicTop->getPicYuvRec()->setBorderExtension( false );
+
+#else
+          pcPicTop->destroy();
+          pcListPic->erase( iterPic );
+          iterPic = pcListPic->begin(); // to the beginning, non-efficient way, have to be revised!
+          continue;
+#endif
+        }
+        if ( !pcPicBottom->getSlice(0)->isReferenced() && pcPicBottom->getReconMark() == true )
+        {
+#if !DYN_REF_FREE
+          pcPicBottom->setReconMark(false);
+
+          // mark it should be extended later
+          pcPicBottom->getPicYuvRec()->setBorderExtension( false );
+
+#else
+          pcPicBottom->destroy();
+          pcListPic->erase( iterPic );
+          iterPic = pcListPic->begin(); // to the beginning, non-efficient way, have to be revised!
+          continue;
+#endif
+        }
+        pcPicTop->setOutputMark(false);
+        pcPicBottom->setOutputMark(false);
+
+#if !DYN_REF_FREE
+        if(pcPicTop)
+        {
+          pcPicTop->destroy();
+          delete pcPicTop;
+          pcPicTop = NULL;
+        }
+#endif
+      }
+    }
+    if(pcPicBottom)
+    {
+      pcPicBottom->destroy();
+      delete pcPicBottom;
+      pcPicBottom = NULL;
+    }
+  }
+  else //Frame decoding
+  {
+    while (iterPic != pcListPic->end())
+    {
+      pcPic = *(iterPic);
+
+      if ( pcPic->getOutputMark() )
+      {
+        // write to file
+#if SVC_EXTENSION
+        if ( m_pchReconFile[layerId] )
+        {
+          const Window &conf = pcPic->getConformanceWindow();
+          const Window &defDisp = m_respectDefDispWindow ? pcPic->getDefDisplayWindow() : Window();
+#if REPN_FORMAT_IN_VPS
+          UInt chromaFormatIdc = pcPic->getSlice(0)->getChromaFormatIdc();
+          Int xScal =  TComSPS::getWinUnitX( chromaFormatIdc ), yScal = TComSPS::getWinUnitY( chromaFormatIdc );
+          m_acTVideoIOYuvReconFile[layerId].write( pcPic->getPicYuvRec(),
+            conf.getWindowLeftOffset()  *xScal + defDisp.getWindowLeftOffset(),
+            conf.getWindowRightOffset() *xScal + defDisp.getWindowRightOffset(),
+            conf.getWindowTopOffset()   *yScal + defDisp.getWindowTopOffset(),
+            conf.getWindowBottomOffset()*yScal + defDisp.getWindowBottomOffset() );
+
+#else
+          m_acTVideoIOYuvReconFile[layerId].write( pcPic->getPicYuvRec(),
+            conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(),
+            conf.getWindowRightOffset() + defDisp.getWindowRightOffset(),
+            conf.getWindowTopOffset() + defDisp.getWindowTopOffset(),
+            conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset() );
+#endif
+        }
+
+        // update POC of display order
+        m_aiPOCLastDisplay[layerId] = pcPic->getPOC();
+#else
+        if ( m_pchReconFile )
+        {
+          const Window &conf = pcPic->getConformanceWindow();
+          const Window &defDisp = m_respectDefDispWindow ? pcPic->getDefDisplayWindow() : Window();
+          m_cTVideoIOYuvReconFile.write( pcPic->getPicYuvRec(),
+            conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(),
+            conf.getWindowRightOffset() + defDisp.getWindowRightOffset(),
+            conf.getWindowTopOffset() + defDisp.getWindowTopOffset(),
+            conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset() );
+        }
+
+        // update POC of display order
+        m_iPOCLastDisplay = pcPic->getPOC();
+#endif
+
+        // erase non-referenced picture in the reference picture list after display
+        if ( !pcPic->getSlice(0)->isReferenced() && pcPic->getReconMark() == true )
+        {
+#if !DYN_REF_FREE
+          pcPic->setReconMark(false);
+
+          // mark it should be extended later
+          pcPic->getPicYuvRec()->setBorderExtension( false );
+
+#else
+          pcPic->destroy();
+          pcListPic->erase( iterPic );
+          iterPic = pcListPic->begin(); // to the beginning, non-efficient way, have to be revised!
+          continue;
+#endif
+        }
+        pcPic->setOutputMark(false);
+      }
 #if !SVC_EXTENSION
 #if !DYN_REF_FREE
-    if(pcPic)
-    {
-      pcPic->destroy();
-      delete pcPic;
-      pcPic = NULL;
-    }
+      if(pcPic)
+      {
+        pcPic->destroy();
+        delete pcPic;
+        pcPic = NULL;
+      }
 #endif    
 #endif
-    iterPic++;
+      iterPic++;
+    }
   }
 #if SVC_EXTENSION
Index: branches/SHM-3.1-dev/source/App/TAppDecoder/TAppDecTop.h
===================================================================
--- branches/SHM-3.1-dev/source/App/TAppDecoder/TAppDecTop.h	(revision 430)
+++ branches/SHM-3.1-dev/source/App/TAppDecoder/TAppDecTop.h	(revision 431)
@@ -70,6 +70,5 @@
 #endif
   
-  // for output control
-  Bool                            m_abDecFlag[ MAX_GOP ];         ///< decoded flag in one GOP
+  // for output control  
 #if SVC_EXTENSION
   Int                             m_aiPOCLastDisplay [MAX_LAYERS]; ///< last POC in display order
Index: branches/SHM-3.1-dev/source/App/TAppEncoder/TAppEncCfg.cpp
===================================================================
--- branches/SHM-3.1-dev/source/App/TAppEncoder/TAppEncCfg.cpp	(revision 430)
+++ branches/SHM-3.1-dev/source/App/TAppEncoder/TAppEncCfg.cpp	(revision 431)
@@ -348,9 +348,9 @@
   
 #if SVC_EXTENSION
-  string  cfg_LayerCfgFile  [MAX_LAYERS];
+  string  cfg_LayerCfgFile   [MAX_LAYERS];
   string  cfg_BitstreamFile;
-  string* cfg_InputFile     [MAX_LAYERS];
-  string* cfg_ReconFile     [MAX_LAYERS];
-  Double* cfg_fQP           [MAX_LAYERS];
+  string* cfg_InputFile      [MAX_LAYERS];
+  string* cfg_ReconFile      [MAX_LAYERS];
+  Double* cfg_fQP            [MAX_LAYERS];
 
 #if REPN_FORMAT_IN_VPS
@@ -565,4 +565,8 @@
   ("FrameRate,-fr",         m_iFrameRate,          0, "Frame rate")
 #endif
+
+  //Field coding parameters
+  ("FieldCoding", m_isField, false, "Signals if it's a field based coding")
+  ("TopFieldFirst, Tff", m_isTopFieldFirst, false, "In case of field based coding, signals whether if it's a top field first or not")
   ("FrameSkip,-fs",         m_FrameSkip,          0u, "Number of frames to skip at start of input YUV")
   ("FramesToBeEncoded,f",   m_framesToBeEncoded,   0, "Number of frames to be encoded (default=all)")
@@ -862,4 +866,24 @@
   const list<const Char*>& argv_unhandled = po::scanArgv(opts, argc, (const Char**) argv);
 
+  if(m_isField)
+  {
+#if SVC_EXTENSION
+    for(Int layer = 0; layer < MAX_LAYERS; layer++)
+    {
+      //Frame height
+      m_acLayerCfg[layer].m_iSourceHeightOrg = m_acLayerCfg[layer].m_iSourceHeight;
+      //Field height
+      m_acLayerCfg[layer].m_iSourceHeight = m_acLayerCfg[layer].m_iSourceHeight >> 1;
+    }
+#else
+    //Frame height
+    m_iSourceHeightOrg = m_iSourceHeight;
+    //Field height
+    m_iSourceHeight = m_iSourceHeight >> 1;
+#endif
+    //number of fields to encode
+    m_framesToBeEncoded *= 2;
+  }
+  
   for (list<const Char*>::const_iterator it = argv_unhandled.begin(); it != argv_unhandled.end(); it++)
   {
@@ -1193,4 +1217,9 @@
         m_aiPad[1] = m_confBottom = ((m_iSourceHeight / minCuSize) + 1) * minCuSize - m_iSourceHeight;
         m_iSourceHeight += m_confBottom;
+        if ( m_isField )
+        {
+          m_iSourceHeightOrg += m_confBottom << 1;
+          m_aiPad[1] = m_confBottom << 1;
+        }
       }
       if (m_aiPad[0] % TComSPS::getWinUnitX(CHROMA_420) != 0)
@@ -1515,8 +1544,12 @@
 #if  EXTERNAL_USEDBYCURR_N0082|| !FINAL_RPL_CHANGE_N0082
   Int checkGOP=1;
-  Int numRefs = 1;
+  Int numRefs = m_isField ? 2 : 1;
 #endif
   Int refList[MAX_NUM_REF_PICS+1];
   refList[0]=0;
+  if(m_isField)
+  {
+    refList[1] = 1;
+  }
   Bool isOK[MAX_GOP];
   for(Int i=0; i<MAX_GOP; i++) 
@@ -1546,5 +1579,5 @@
   for(UInt layer=0; layer<m_numLayers; layer++)
   {
-    if(m_acLayerCfg[layer].xCheckParameter())
+    if(m_acLayerCfg[layer].xCheckParameter(m_isField))
     {
       printf("\nError: invalid configuration parameter found in layer %d \n", layer);
@@ -2181,5 +2214,22 @@
   printf("Internal Format              : %dx%d %dHz\n", m_iSourceWidth, m_iSourceHeight, m_iFrameRate );
 #endif
-  printf("Frame index                  : %u - %d (%d frames)\n", m_FrameSkip, m_FrameSkip+m_framesToBeEncoded-1, m_framesToBeEncoded );
+  if (m_isField)
+  {
+    printf("Frame/Field          : Field based coding\n");
+    printf("Field index          : %u - %d (%d fields)\n", m_FrameSkip, m_FrameSkip+m_framesToBeEncoded-1, m_framesToBeEncoded );
+    if (m_isTopFieldFirst)
+    {
+      printf("Field Order            : Top field first\n");
+    }
+    else
+    {
+      printf("Field Order            : Bottom field first\n");
+    }
+  }
+  else
+  {
+    printf("Frame/Field                  : Frame based coding\n");
+    printf("Frame index                  : %u - %d (%d frames)\n", m_FrameSkip, m_FrameSkip+m_framesToBeEncoded-1, m_framesToBeEncoded );
+  }
   printf("CU size / depth              : %d / %d\n", m_uiMaxCUWidth, m_uiMaxCUDepth );
   printf("RQT trans. size (min / max)  : %d / %d\n", 1 << m_uiQuadtreeTULog2MinSize, 1 << m_uiQuadtreeTULog2MaxSize );
Index: branches/SHM-3.1-dev/source/App/TAppEncoder/TAppEncCfg.h
===================================================================
--- branches/SHM-3.1-dev/source/App/TAppEncoder/TAppEncCfg.h	(revision 430)
+++ branches/SHM-3.1-dev/source/App/TAppEncoder/TAppEncCfg.h	(revision 431)
@@ -88,5 +88,9 @@
   UInt      m_FrameSkip;                                      ///< number of skipped frames from the beginning
   Int       m_iSourceWidth;                                   ///< source width in pixel
-  Int       m_iSourceHeight;                                  ///< source height in pixel
+  Int       m_iSourceHeight;                                  ///< source height in pixel (when interlaced = field height)
+  
+  Int       m_iSourceHeightOrg;                               ///< original source height in pixel (when interlaced = frame height)
+  
+  
   Int       m_conformanceMode;
   Int       m_confLeft;
@@ -97,4 +101,7 @@
   Int       m_aiPad[2];                                       ///< number of padded pixels for width and height
 #endif  
+
+  Bool      m_isField;                                        ///< enable field coding
+  Bool      m_isTopFieldFirst;
 
   // profile/level
Index: branches/SHM-3.1-dev/source/App/TAppEncoder/TAppEncLayerCfg.cpp
===================================================================
--- branches/SHM-3.1-dev/source/App/TAppEncoder/TAppEncLayerCfg.cpp	(revision 430)
+++ branches/SHM-3.1-dev/source/App/TAppEncoder/TAppEncLayerCfg.cpp	(revision 431)
@@ -161,5 +161,5 @@
 Bool confirmPara(Bool bflag, const char* message);
 
-Bool TAppEncLayerCfg::xCheckParameter()
+Bool TAppEncLayerCfg::xCheckParameter( Bool isField )
 {
   switch (m_conformanceMode)
@@ -185,4 +185,9 @@
         m_aiPad[1] = m_confBottom = ((m_iSourceHeight / minCuSize) + 1) * minCuSize - m_iSourceHeight;
         m_iSourceHeight += m_confBottom;
+        if ( isField )
+        {
+          m_iSourceHeightOrg += m_confBottom << 1;
+          m_aiPad[1] = m_confBottom << 1;
+        }
       }
       break;
Index: branches/SHM-3.1-dev/source/App/TAppEncoder/TAppEncLayerCfg.h
===================================================================
--- branches/SHM-3.1-dev/source/App/TAppEncoder/TAppEncLayerCfg.h	(revision 430)
+++ branches/SHM-3.1-dev/source/App/TAppEncoder/TAppEncLayerCfg.h	(revision 431)
@@ -33,5 +33,6 @@
   Int       m_iFrameRate;                                     ///< source frame-rates (Hz)
   Int       m_iSourceWidth;                                   ///< source width in pixel
-  Int       m_iSourceHeight;                                  ///< source height in pixel
+  Int       m_iSourceHeight;                                  ///< source height in pixel (when interlaced = field height)
+  Int       m_iSourceHeightOrg;                               ///< original source height in pixel (when interlaced = frame height)
   Int       m_conformanceMode;
   Int       m_confLeft;
@@ -104,5 +105,5 @@
   Void  xPrintParameter();
 #endif
-  Bool  xCheckParameter();
+  Bool  xCheckParameter( Bool isField );
 
   Void    setAppEncCfg(TAppEncCfg* p) {m_cAppEncCfg = p;          }
@@ -113,4 +114,5 @@
   Int     getSourceWidth()            {return m_iSourceWidth;     }
   Int     getSourceHeight()           {return m_iSourceHeight;    }
+  Int     getSourceHeightOrg()        {return m_iSourceHeightOrg; }
   Int     getConformanceMode()        { return m_conformanceMode; }
   Int*    getPad()                    {return m_aiPad;            }
Index: branches/SHM-3.1-dev/source/App/TAppEncoder/TAppEncTop.cpp
===================================================================
--- branches/SHM-3.1-dev/source/App/TAppEncoder/TAppEncTop.cpp	(revision 430)
+++ branches/SHM-3.1-dev/source/App/TAppEncoder/TAppEncTop.cpp	(revision 431)
@@ -888,10 +888,10 @@
 }
 
-Void TAppEncTop::xInitLib()
+Void TAppEncTop::xInitLib(Bool isFieldCoding)
 {
 #if SVC_EXTENSION
   for(UInt layer=0; layer<m_numLayers; layer++)
   {
-    m_acTEncTop[layer].init();
+    m_acTEncTop[layer].init(isFieldCoding);
   }
 #if VPS_RENAME
@@ -1091,7 +1091,7 @@
   vps->setExtensionOffset( 0xffff );
 #endif
-#else
-  m_cTEncTop.init();
-#endif
+#else //SVC_EXTENSION
+  m_cTEncTop.init(isFieldCoding);
+#endif //SVC_EXTENSION
 }
 
@@ -1124,5 +1124,5 @@
   xInitLibCfg();
   xCreateLib();
-  xInitLib();
+  xInitLib(m_isField);
 
   // main encoder loop
@@ -1136,9 +1136,20 @@
     // allocate original YUV buffer
     pcPicYuvOrg[layer] = new TComPicYuv;
+    if( m_isField )
+    {
 #if SVC_UPSAMPLING
-    pcPicYuvOrg[layer]->create( m_acLayerCfg[layer].getSourceWidth(), m_acLayerCfg[layer].getSourceHeight(), m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth, NULL );
-#else
-    pcPicYuvOrg->create( m_acLayerCfg[layer].getSourceWidth(), m_acLayerCfg[layer].getSourceHeight(), m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth );
-#endif
+      pcPicYuvOrg[layer]->create( m_acLayerCfg[layer].getSourceWidth(), m_acLayerCfg[layer].getSourceHeightOrg(), m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth, NULL );
+#else
+      pcPicYuvOrg->create( m_acLayerCfg[layer].getSourceWidth(), m_acLayerCfg[layer].getSourceHeightOrg(), m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth );
+#endif
+    }
+    else
+    {
+#if SVC_UPSAMPLING
+      pcPicYuvOrg[layer]->create( m_acLayerCfg[layer].getSourceWidth(), m_acLayerCfg[layer].getSourceHeight(), m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth, NULL );
+#else
+      pcPicYuvOrg->create( m_acLayerCfg[layer].getSourceWidth(), m_acLayerCfg[layer].getSourceHeight(), m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth );
+#endif
+    }
   }
 
@@ -1182,8 +1193,15 @@
           m_iFrameRcvd++;
           // check end of file
-          bEos = (m_iFrameRcvd == m_framesToBeEncoded);
+          bEos = (m_isField && (m_iFrameRcvd == (m_framesToBeEncoded >> 1) )) || ( !m_isField && (m_iFrameRcvd == m_framesToBeEncoded) );
         }
 
-        m_acTEncTop[layer].encodePrep( pcPicYuvOrg[layer] );
+        if ( m_isField )
+        {
+          m_acTEncTop[layer].encodePrep( pcPicYuvOrg[layer], m_isTopFieldFirst );
+        }
+        else
+        {
+          m_acTEncTop[layer].encodePrep( pcPicYuvOrg[layer] );
+        }
       }
 
@@ -1232,5 +1250,12 @@
       {
         // call encoding function for one frame
-        m_acTEncTop[layer].encode( flush ? 0 : pcPicYuvOrg[layer], m_acListPicYuvRec[layer], outputAccessUnits, iPicIdInGOP );
+        if ( m_isField )
+        {
+          m_acTEncTop[layer].encode( flush ? 0 : pcPicYuvOrg[layer], m_acListPicYuvRec[layer], outputAccessUnits, iPicIdInGOP, m_isTopFieldFirst );
+        }
+        else
+        {
+          m_acTEncTop[layer].encode( flush ? 0 : pcPicYuvOrg[layer], m_acListPicYuvRec[layer], outputAccessUnits, iPicIdInGOP );
+        }
       }
     }
@@ -1269,5 +1294,5 @@
     if (bEos)
     {
-      printOutSummary();
+      printOutSummary(m_isTopFieldFirst);
     }
 
@@ -1301,5 +1326,5 @@
 }
 
-Void TAppEncTop::printOutSummary()
+Void TAppEncTop::printOutSummary(Bool isField)
 {
   UInt layer;
@@ -1308,8 +1333,18 @@
   for(layer = 0; layer < m_numLayers; layer++)
   {
-    m_gcAnalyzeAll[layer].setFrmRate( m_acLayerCfg[layer].getFrameRate());
-    m_gcAnalyzeI[layer].setFrmRate( m_acLayerCfg[layer].getFrameRate() );
-    m_gcAnalyzeP[layer].setFrmRate( m_acLayerCfg[layer].getFrameRate() );
-    m_gcAnalyzeB[layer].setFrmRate( m_acLayerCfg[layer].getFrameRate() );
+    if(isField)
+    {
+      m_gcAnalyzeAll[layer].setFrmRate( m_acLayerCfg[layer].getFrameRate());
+      m_gcAnalyzeI[layer].setFrmRate( m_acLayerCfg[layer].getFrameRate() );
+      m_gcAnalyzeP[layer].setFrmRate( m_acLayerCfg[layer].getFrameRate() );
+      m_gcAnalyzeB[layer].setFrmRate( m_acLayerCfg[layer].getFrameRate() );
+    }
+    else
+    {
+      m_gcAnalyzeAll[layer].setFrmRate( m_acLayerCfg[layer].getFrameRate() * 2);
+      m_gcAnalyzeI[layer].setFrmRate( m_acLayerCfg[layer].getFrameRate() * 2 );
+      m_gcAnalyzeP[layer].setFrmRate( m_acLayerCfg[layer].getFrameRate() * 2 );
+      m_gcAnalyzeB[layer].setFrmRate( m_acLayerCfg[layer].getFrameRate() * 2 );
+    }
   }
 
@@ -1342,4 +1377,19 @@
     m_gcAnalyzeB[layer].printOut('b', layer);
   }
+
+  if(isField)
+  {
+    for(layer = 0; layer < m_numLayers; layer++)
+    {
+      //-- interlaced summary
+      m_gcAnalyzeAll_in.setFrmRate( m_acLayerCfg[layer].getFrameRate());
+      printf( "\n\nSUMMARY INTERLACED ---------------------------------------------\n" );
+      m_gcAnalyzeAll_in.printOutInterlaced('a',  m_gcAnalyzeAll[layer].getBits());
+
+#if _SUMMARY_OUT_
+      m_gcAnalyzeAll_in.printSummaryOutInterlaced();
+#endif
+    }
+  }
 }
 
@@ -1360,5 +1410,5 @@
   xInitLibCfg();
   xCreateLib();
-  xInitLib();
+  xInitLib(m_isField);
 
   // main encoder loop
@@ -1369,5 +1419,12 @@
 
   // allocate original YUV buffer
-  pcPicYuvOrg->create( m_iSourceWidth, m_iSourceHeight, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth );
+  if( m_isField )
+  {
+    pcPicYuvOrg->create( m_iSourceWidth, m_iSourceHeightOrg, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth );
+  }
+  else
+  {
+    pcPicYuvOrg->create( m_iSourceWidth, m_iSourceHeight, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth );
+  }
 
   while ( !bEos )
@@ -1382,6 +1439,5 @@
     m_iFrameRcvd++;
 
-    bEos = (m_iFrameRcvd == m_framesToBeEncoded);
-
+    bEos = (m_isField && (m_iFrameRcvd == (m_framesToBeEncoded >> 1) )) || ( !m_isField && (m_iFrameRcvd == m_framesToBeEncoded) );
     Bool flush = 0;
     // if end of file (which is only detected on a read failure) flush the encoder of any queued pictures
@@ -1395,5 +1451,12 @@
 
     // call encoding function for one frame
+    if ( m_isField )
+    {
+      m_cTEncTop.encode( bEos, flush ? 0 : pcPicYuvOrg, m_cListPicYuvRec, outputAccessUnits, iNumEncoded, m_isTopFieldFirst);
+    }
+    else
+    {
     m_cTEncTop.encode( bEos, flush ? 0 : pcPicYuvOrg, m_cListPicYuvRec, outputAccessUnits, iNumEncoded );
+    }
 
     // write bistream to file if necessary
@@ -1405,5 +1468,5 @@
   }
 
-  m_cTEncTop.printSummary();
+  m_cTEncTop.printSummary(m_isField);
 
   // delete original YUV buffer
@@ -1479,24 +1542,53 @@
 Void TAppEncTop::xWriteRecon(UInt layer, Int iNumEncoded)
 {
-  Int i;
-
-  TComList<TComPicYuv*>::iterator iterPicYuvRec = m_acListPicYuvRec[layer].end();
-
-  for ( i = 0; i < iNumEncoded; i++ )
-  {
-    --iterPicYuvRec;
-  }
-
-  for ( i = 0; i < iNumEncoded; i++ )
-  {
-    TComPicYuv*  pcPicYuvRec  = *(iterPicYuvRec++);
+  if (m_isField)
+  {
+    //Reinterlace fields
+    Int i;
+    TComList<TComPicYuv*>::iterator iterPicYuvRec = m_acListPicYuvRec[layer].end();
+
+    for ( i = 0; i < iNumEncoded; i++ )
+    {
+      --iterPicYuvRec;
+    }
+
+    for ( i = 0; i < iNumEncoded/2; i++ )
+    {
+      TComPicYuv*  pcPicYuvRecTop  = *(iterPicYuvRec++);
+      TComPicYuv*  pcPicYuvRecBottom  = *(iterPicYuvRec++);
+
 #if M0040_ADAPTIVE_RESOLUTION_CHANGE
-    if (!m_acLayerCfg[layer].getReconFile().empty() && pcPicYuvRec->isReconstructed())
-#else
-    if (!m_acLayerCfg[layer].getReconFile().empty())
-#endif
-    {
-      m_acTVideoIOYuvReconFile[layer].write( pcPicYuvRec, m_acLayerCfg[layer].getConfLeft(), m_acLayerCfg[layer].getConfRight(), 
-        m_acLayerCfg[layer].getConfTop(), m_acLayerCfg[layer].getConfBottom() );
+      if (!m_acLayerCfg[layer].getReconFile().empty() && pcPicYuvRecTop->isReconstructed() && pcPicYuvRecBottom->isReconstructed())
+#else
+      if (!m_acLayerCfg[layer].getReconFile().empty())
+#endif
+      {
+        m_acTVideoIOYuvReconFile[layer].write( pcPicYuvRecTop, pcPicYuvRecBottom, m_acLayerCfg[layer].getConfLeft(), m_acLayerCfg[layer].getConfRight(), m_acLayerCfg[layer].getConfTop(), m_acLayerCfg[layer].getConfBottom(), m_isTopFieldFirst );
+      }
+    }
+  }
+  else
+  {
+    Int i;
+
+    TComList<TComPicYuv*>::iterator iterPicYuvRec = m_acListPicYuvRec[layer].end();
+
+    for ( i = 0; i < iNumEncoded; i++ )
+    {
+      --iterPicYuvRec;
+    }
+
+    for ( i = 0; i < iNumEncoded; i++ )
+    {
+      TComPicYuv*  pcPicYuvRec  = *(iterPicYuvRec++);
+#if M0040_ADAPTIVE_RESOLUTION_CHANGE
+      if (!m_acLayerCfg[layer].getReconFile().empty() && pcPicYuvRec->isReconstructed())
+#else
+      if (!m_acLayerCfg[layer].getReconFile().empty())
+#endif
+      {
+        m_acTVideoIOYuvReconFile[layer].write( pcPicYuvRec, m_acLayerCfg[layer].getConfLeft(), m_acLayerCfg[layer].getConfRight(), 
+          m_acLayerCfg[layer].getConfTop(), m_acLayerCfg[layer].getConfBottom() );
+      }
     }
   }
@@ -1505,17 +1597,41 @@
 Void TAppEncTop::xWriteStream(std::ostream& bitstreamFile, Int iNumEncoded, const std::list<AccessUnit>& accessUnits)
 {
-  Int i;
-
-  list<AccessUnit>::const_iterator iterBitstream = accessUnits.begin();
+  if (m_isField)
+  {
+    //Reinterlace fields
+    Int i;
+    list<AccessUnit>::const_iterator iterBitstream = accessUnits.begin();
 
 #if M0040_ADAPTIVE_RESOLUTION_CHANGE
-  for ( i = 0; i < iNumEncoded && iterBitstream != accessUnits.end(); i++ )
-#else
-  for ( i = 0; i < iNumEncoded; i++ )
-#endif
-  {
-    const AccessUnit& au = *(iterBitstream++);
-    const vector<UInt>& stats = writeAnnexB(bitstreamFile, au);
-    rateStatsAccum(au, stats);
+    for ( i = 0; i < iNumEncoded/2 && iterBitstream != accessUnits.end(); i++ )
+#else
+    for ( i = 0; i < iNumEncoded/2; i++ )
+#endif
+    {      
+      const AccessUnit& auTop = *(iterBitstream++);
+      const vector<UInt>& statsTop = writeAnnexB(bitstreamFile, auTop);
+      rateStatsAccum(auTop, statsTop);
+
+      const AccessUnit& auBottom = *(iterBitstream++);
+      const vector<UInt>& statsBottom = writeAnnexB(bitstreamFile, auBottom);
+      rateStatsAccum(auBottom, statsBottom);
+    }
+  }
+  else
+  {
+    Int i;
+
+    list<AccessUnit>::const_iterator iterBitstream = accessUnits.begin();
+
+#if M0040_ADAPTIVE_RESOLUTION_CHANGE
+    for ( i = 0; i < iNumEncoded && iterBitstream != accessUnits.end(); i++ )
+#else
+    for ( i = 0; i < iNumEncoded; i++ )
+#endif
+    {
+      const AccessUnit& au = *(iterBitstream++);
+      const vector<UInt>& stats = writeAnnexB(bitstreamFile, au);
+      rateStatsAccum(au, stats);
+    }
   }
 }
@@ -1561,27 +1677,61 @@
 Void TAppEncTop::xWriteOutput(std::ostream& bitstreamFile, Int iNumEncoded, const std::list<AccessUnit>& accessUnits)
 {
-  Int i;
-
-  TComList<TComPicYuv*>::iterator iterPicYuvRec = m_cListPicYuvRec.end();
-  list<AccessUnit>::const_iterator iterBitstream = accessUnits.begin();
-
-  for ( i = 0; i < iNumEncoded; i++ )
-  {
-    --iterPicYuvRec;
-  }
-
-  for ( i = 0; i < iNumEncoded; i++ )
-  {
-    TComPicYuv*  pcPicYuvRec  = *(iterPicYuvRec++);
-    if (m_pchReconFile)
-    {
+  if (m_isField)
+  {
+    //Reinterlace fields
+    Int i;
+    TComList<TComPicYuv*>::iterator iterPicYuvRec = m_cListPicYuvRec.end();
+    list<AccessUnit>::const_iterator iterBitstream = accessUnits.begin();
+
+    for ( i = 0; i < iNumEncoded; i++ )
+    {
+      --iterPicYuvRec;
+    }
+
+    for ( i = 0; i < iNumEncoded/2; i++ )
+    {
+      TComPicYuv*  pcPicYuvRecTop  = *(iterPicYuvRec++);
+      TComPicYuv*  pcPicYuvRecBottom  = *(iterPicYuvRec++);
+
+      if (m_pchReconFile)
+      {
+        m_cTVideoIOYuvReconFile.write( pcPicYuvRecTop, pcPicYuvRecBottom, m_confLeft, m_confRight, m_confTop, m_confBottom, m_isTopFieldFirst );
+      }
+
+      const AccessUnit& auTop = *(iterBitstream++);
+      const vector<UInt>& statsTop = writeAnnexB(bitstreamFile, auTop);
+      rateStatsAccum(auTop, statsTop);
+
+      const AccessUnit& auBottom = *(iterBitstream++);
+      const vector<UInt>& statsBottom = writeAnnexB(bitstreamFile, auBottom);
+      rateStatsAccum(auBottom, statsBottom);
+    }
+  }
+  else
+  {
+    Int i;
+
+    TComList<TComPicYuv*>::iterator iterPicYuvRec = m_cListPicYuvRec.end();
+    list<AccessUnit>::const_iterator iterBitstream = accessUnits.begin();
+
+    for ( i = 0; i < iNumEncoded; i++ )
+    {
+      --iterPicYuvRec;
+    }
+
+    for ( i = 0; i < iNumEncoded; i++ )
+    {
+      TComPicYuv*  pcPicYuvRec  = *(iterPicYuvRec++);
+      if (m_pchReconFile)
+      {
 #if SYNTAX_OUTPUT
-      m_cTVideoIOYuvReconFile.write( pcPicYuvRec, m_confLeft, m_confRight, m_confTop, m_confBottom );
-#endif
-    }
-
-    const AccessUnit& au = *(iterBitstream++);
-    const vector<UInt>& stats = writeAnnexB(bitstreamFile, au);
-    rateStatsAccum(au, stats);
+        m_cTVideoIOYuvReconFile.write( pcPicYuvRec, m_confLeft, m_confRight, m_confTop, m_confBottom );
+#endif
+      }
+
+      const AccessUnit& au = *(iterBitstream++);
+      const vector<UInt>& stats = writeAnnexB(bitstreamFile, au);
+      rateStatsAccum(au, stats);
+    }
   }
 }
@@ -1602,5 +1752,5 @@
     case NAL_UNIT_CODED_SLICE_TRAIL_R:
     case NAL_UNIT_CODED_SLICE_TRAIL_N:
-    case NAL_UNIT_CODED_SLICE_TSA_R:
+    case NAL_UNIT_CODED_SLICE_TLA_R:
     case NAL_UNIT_CODED_SLICE_TSA_N:
     case NAL_UNIT_CODED_SLICE_STSA_R:
Index: branches/SHM-3.1-dev/source/App/TAppEncoder/TAppEncTop.h
===================================================================
--- branches/SHM-3.1-dev/source/App/TAppEncoder/TAppEncTop.h	(revision 430)
+++ branches/SHM-3.1-dev/source/App/TAppEncoder/TAppEncTop.h	(revision 431)
@@ -82,5 +82,5 @@
   Void  xCreateLib        ();                               ///< create files & encoder class
   Void  xInitLibCfg       ();                               ///< initialize internal variables
-  Void  xInitLib          ();                               ///< initialize encoder class
+  Void  xInitLib          (Bool isFieldCoding);             ///< initialize encoder class
   Void  xDestroyLib       ();                               ///< destroy encoder class
   
@@ -99,5 +99,5 @@
   Void xWriteRecon(UInt layer, Int iNumEncoded);
   Void xWriteStream(std::ostream& bitstreamFile, Int iNumEncoded, const std::list<AccessUnit>& accessUnits);
-  Void printOutSummary();
+  Void printOutSummary(Bool isField);
 #else
   Void xWriteOutput(std::ostream& bitstreamFile, Int iNumEncoded, const std::list<AccessUnit>& accessUnits); ///< write bitstream to file
Index: branches/SHM-3.1-dev/source/Lib/TLibCommon/CommonDef.h
===================================================================
--- branches/SHM-3.1-dev/source/Lib/TLibCommon/CommonDef.h	(revision 430)
+++ branches/SHM-3.1-dev/source/Lib/TLibCommon/CommonDef.h	(revision 431)
@@ -59,5 +59,5 @@
 #define NV_VERSION        "3.0.1"                 ///< Current software version
 #else
-#define NV_VERSION        "11.0"                ///< Current software version
+#define NV_VERSION        "12.0"                ///< Current software version
 #endif
 
@@ -200,5 +200,5 @@
   
   NAL_UNIT_CODED_SLICE_TSA_N,     // 2
-  NAL_UNIT_CODED_SLICE_TSA_R,       // 3
+  NAL_UNIT_CODED_SLICE_TLA_R,       // 3
   
   NAL_UNIT_CODED_SLICE_STSA_N,    // 4
Index: branches/SHM-3.1-dev/source/Lib/TLibCommon/NAL.h
===================================================================
--- branches/SHM-3.1-dev/source/Lib/TLibCommon/NAL.h	(revision 430)
+++ branches/SHM-3.1-dev/source/Lib/TLibCommon/NAL.h	(revision 431)
@@ -76,5 +76,5 @@
     return m_nalUnitType == NAL_UNIT_CODED_SLICE_TRAIL_R
         || m_nalUnitType == NAL_UNIT_CODED_SLICE_TRAIL_N
-        || m_nalUnitType == NAL_UNIT_CODED_SLICE_TSA_R
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_TLA_R
         || m_nalUnitType == NAL_UNIT_CODED_SLICE_TSA_N
         || m_nalUnitType == NAL_UNIT_CODED_SLICE_STSA_R
Index: branches/SHM-3.1-dev/source/Lib/TLibCommon/TComMv.h
===================================================================
--- branches/SHM-3.1-dev/source/Lib/TLibCommon/TComMv.h	(revision 430)
+++ branches/SHM-3.1-dev/source/Lib/TLibCommon/TComMv.h	(revision 431)
@@ -40,4 +40,5 @@
 
 #include "CommonDef.h"
+#include <cstdlib>
 
 //! \ingroup TLibCommon
Index: branches/SHM-3.1-dev/source/Lib/TLibCommon/TComPic.cpp
===================================================================
--- branches/SHM-3.1-dev/source/Lib/TLibCommon/TComPic.cpp	(revision 430)
+++ branches/SHM-3.1-dev/source/Lib/TLibCommon/TComPic.cpp	(revision 431)
@@ -53,5 +53,4 @@
 , m_bUsedByCurr                           (false)
 , m_bIsLongTerm                           (false)
-, m_bIsUsedAsLongTerm                     (false)
 , m_apcPicSym                             (NULL)
 , m_pcPicYuvPred                          (NULL)
Index: branches/SHM-3.1-dev/source/Lib/TLibCommon/TComPic.h
===================================================================
--- branches/SHM-3.1-dev/source/Lib/TLibCommon/TComPic.h	(revision 430)
+++ branches/SHM-3.1-dev/source/Lib/TLibCommon/TComPic.h	(revision 431)
@@ -66,5 +66,4 @@
   Bool                  m_bUsedByCurr;            //  Used by current picture
   Bool                  m_bIsLongTerm;            //  IS long term picture
-  Bool                  m_bIsUsedAsLongTerm;      //  long term picture is used as reference before
   TComPicSym*           m_apcPicSym;              //  Symbol
   
@@ -88,4 +87,7 @@
   Window                m_defaultDisplayWindow;
 
+  Bool                  m_isTop;
+  Bool                  m_isField;
+  
   std::vector<std::vector<TComDataCU*> > m_vSliceCUDataLink;
 
@@ -194,4 +196,11 @@
   std::vector<TComDataCU*>& getOneSliceCUDataForNDBFilter      (Int sliceID) { return m_vSliceCUDataLink[sliceID];}
 
+  /* field coding parameters*/
+
+  Void              setTopField(bool b)                  {m_isTop = b;}
+  Bool              isTopField()                         {return m_isTop;}
+  Void              setField(bool b)                     {m_isField = b;}
+  Bool              isField()                            {return m_isField;}
+
   /** transfer ownership of seis to this picture */
   void setSEIs(SEIMessages& seis) { m_SEIs = seis; }
Index: branches/SHM-3.1-dev/source/Lib/TLibCommon/TComPicSym.cpp
===================================================================
--- branches/SHM-3.1-dev/source/Lib/TLibCommon/TComPicSym.cpp	(revision 430)
+++ branches/SHM-3.1-dev/source/Lib/TLibCommon/TComPicSym.cpp	(revision 431)
@@ -61,5 +61,4 @@
 ,m_uiNumAllocatedSlice (0)
 ,m_apcTComDataCU (NULL)
-,m_iTileBoundaryIndependenceIdr (0)
 ,m_iNumColumnsMinus1 (0)
 ,m_iNumRowsMinus1(0)
Index: branches/SHM-3.1-dev/source/Lib/TLibCommon/TComPicSym.h
===================================================================
--- branches/SHM-3.1-dev/source/Lib/TLibCommon/TComPicSym.h	(revision 430)
+++ branches/SHM-3.1-dev/source/Lib/TLibCommon/TComPicSym.h	(revision 431)
@@ -100,5 +100,4 @@
   TComDataCU**  m_apcTComDataCU;        ///< array of CU data
   
-  Int           m_iTileBoundaryIndependenceIdr;
   Int           m_iNumColumnsMinus1; 
   Int           m_iNumRowsMinus1;
Index: branches/SHM-3.1-dev/source/Lib/TLibCommon/TComPrediction.cpp
===================================================================
--- branches/SHM-3.1-dev/source/Lib/TLibCommon/TComPrediction.cpp	(revision 430)
+++ branches/SHM-3.1-dev/source/Lib/TLibCommon/TComPrediction.cpp	(revision 431)
@@ -696,5 +696,5 @@
   Int k, l, bottomLeft, topRight;
   Int horPred;
-  Int leftColumn[MAX_CU_SIZE], topRow[MAX_CU_SIZE], bottomRow[MAX_CU_SIZE], rightColumn[MAX_CU_SIZE];
+  Int leftColumn[MAX_CU_SIZE+1], topRow[MAX_CU_SIZE+1], bottomRow[MAX_CU_SIZE], rightColumn[MAX_CU_SIZE];
   UInt blkSize = width;
   UInt offset2D = width;
Index: branches/SHM-3.1-dev/source/Lib/TLibCommon/TComRdCost.h
===================================================================
--- branches/SHM-3.1-dev/source/Lib/TLibCommon/TComRdCost.h	(revision 430)
+++ branches/SHM-3.1-dev/source/Lib/TLibCommon/TComRdCost.h	(revision 431)
@@ -116,6 +116,4 @@
 private:
   // for distortion
-  Int                     m_iBlkWidth;
-  Int                     m_iBlkHeight;
   
 #if AMP_SAD
Index: branches/SHM-3.1-dev/source/Lib/TLibCommon/TComRom.cpp
===================================================================
--- branches/SHM-3.1-dev/source/Lib/TLibCommon/TComRom.cpp	(revision 430)
+++ branches/SHM-3.1-dev/source/Lib/TLibCommon/TComRom.cpp	(revision 431)
@@ -55,10 +55,9 @@
   ::memset( g_aucConvertToBit,   -1, sizeof( g_aucConvertToBit ) );
   c=0;
-  for ( i=4; i<MAX_CU_SIZE; i*=2 )
+  for ( i=4; i<=MAX_CU_SIZE; i*=2 )
   {
     g_aucConvertToBit[ i ] = c;
     c++;
   }
-  g_aucConvertToBit[ i ] = c;
   
   c=2;
@@ -278,5 +277,5 @@
 
 #if FAST_UDI_USE_MPM
-const UChar g_aucIntraModeNumFast[7] =
+const UChar g_aucIntraModeNumFast[MAX_CU_DEPTH] =
 {
   3,  //   2x2
@@ -285,9 +284,8 @@
   3,  //  16x16   
   3,  //  32x32   
-  3,  //  64x64   
-  3   // 128x128  
+  3   //  64x64   
 };
 #else // FAST_UDI_USE_MPM
-const UChar g_aucIntraModeNumFast[7] =
+const UChar g_aucIntraModeNumFast[MAX_CU_DEPTH] =
 {
   3,  //   2x2
@@ -296,6 +294,5 @@
   4,  //  16x16   33
   4,  //  32x32   33
-  5,  //  64x64   33
-  4   // 128x128  33
+  5   //  64x64   33
 };
 #endif // FAST_UDI_USE_MPM
Index: branches/SHM-3.1-dev/source/Lib/TLibCommon/TComRom.h
===================================================================
--- branches/SHM-3.1-dev/source/Lib/TLibCommon/TComRom.h	(revision 430)
+++ branches/SHM-3.1-dev/source/Lib/TLibCommon/TComRom.h	(revision 431)
@@ -51,5 +51,5 @@
 // ====================================================================================================================
 
-#define     MAX_CU_DEPTH            7                           // log2(LCUSize)
+#define     MAX_CU_DEPTH            6                           // log2(LCUSize)
 #define     MAX_CU_SIZE             (1<<(MAX_CU_DEPTH))         // maximum allowable size of CU
 #define     MIN_PU_SIZE             4
@@ -131,5 +131,5 @@
 // ====================================================================================================================
 
-extern const UChar  g_aucIntraModeNumFast[7];
+extern const UChar  g_aucIntraModeNumFast[ MAX_CU_DEPTH ];
 
 #if FAST_INTRA_SHVC
Index: branches/SHM-3.1-dev/source/Lib/TLibCommon/TComSlice.cpp
===================================================================
--- branches/SHM-3.1-dev/source/Lib/TLibCommon/TComSlice.cpp	(revision 430)
+++ branches/SHM-3.1-dev/source/Lib/TLibCommon/TComSlice.cpp	(revision 431)
@@ -186,4 +186,5 @@
   m_aiNumRefIdx[0]      = 0;
   m_aiNumRefIdx[1]      = 0;
+  
   m_colFromL0Flag = 1;
   
@@ -292,5 +293,5 @@
   if (!pocHasMsb)
   {
-    poc = poc % pocCycle;
+    poc = poc & (pocCycle - 1);
   }
   
@@ -303,5 +304,5 @@
       if (!pocHasMsb)
       {
-        picPoc = picPoc % pocCycle;
+        picPoc = picPoc & (pocCycle - 1);
       }
       
@@ -966,5 +967,5 @@
 }
 
-Void TComSlice::checkCRA(TComReferencePictureSet *pReferencePictureSet, Int& pocCRA, Bool& prevRAPisBLA, TComList<TComPic *>& rcListPic)
+Void TComSlice::checkCRA(TComReferencePictureSet *pReferencePictureSet, Int& pocCRA, NalUnitType& associatedIRAPType, TComList<TComPic *>& rcListPic)
 {
   for(Int i = 0; i < pReferencePictureSet->getNumberOfNegativePictures()+pReferencePictureSet->getNumberOfPositivePictures(); i++)
@@ -992,10 +993,10 @@
   {
     pocCRA = getPOC();
-    prevRAPisBLA = false;
+    associatedIRAPType = getNalUnitType();
   }
   else if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA ) // CRA picture found
   {
     pocCRA = getPOC();
-    prevRAPisBLA = false;
+    associatedIRAPType = getNalUnitType();
   }
   else if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
@@ -1004,5 +1005,5 @@
   {
     pocCRA = getPOC();
-    prevRAPisBLA = true;
+    associatedIRAPType = getNalUnitType();
   }
 }
@@ -1029,4 +1030,5 @@
 {
   TComPic*                 rpcPic;
+  setAssociatedIRAPPOC(pocCRA);
   Int pocCurr = getPOC(); 
 
@@ -1195,5 +1197,5 @@
 }
 
-Int TComSlice::m_prevPOC = 0;
+Int TComSlice::m_prevTid0POC = 0;
 
 /** Function for setting the slice's temporal layer ID and corresponding temporal_layer_switching_point_flag.
@@ -1250,4 +1252,164 @@
 }
 
+
+Void TComSlice::checkLeadingPictureRestrictions(TComList<TComPic*>& rcListPic)
+{
+  TComPic* rpcPic;
+
+  Int nalUnitType = this->getNalUnitType();
+
+  // When a picture is a leading picture, it shall be a RADL or RASL picture.
+  if(this->getAssociatedIRAPPOC() > this->getPOC())
+  {
+    // Do not check IRAP pictures since they may get a POC lower than their associated IRAP
+    if(nalUnitType < NAL_UNIT_CODED_SLICE_BLA_W_LP ||
+       nalUnitType > NAL_UNIT_RESERVED_IRAP_VCL23)
+    {
+      assert(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
+             nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R ||
+             nalUnitType == NAL_UNIT_CODED_SLICE_RADL_N ||
+             nalUnitType == NAL_UNIT_CODED_SLICE_RADL_R);
+    }
+  }
+
+  // When a picture is a trailing picture, it shall not be a RADL or RASL picture.
+  if(this->getAssociatedIRAPPOC() < this->getPOC())
+  {
+    assert(nalUnitType != NAL_UNIT_CODED_SLICE_RASL_N &&
+           nalUnitType != NAL_UNIT_CODED_SLICE_RASL_R &&
+           nalUnitType != NAL_UNIT_CODED_SLICE_RADL_N &&
+           nalUnitType != NAL_UNIT_CODED_SLICE_RADL_R);
+  }
+
+  // No RASL pictures shall be present in the bitstream that are associated
+  // with a BLA picture having nal_unit_type equal to BLA_W_RADL or BLA_N_LP.
+  if(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
+     nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R)
+  {
+    assert(this->getAssociatedIRAPType() != NAL_UNIT_CODED_SLICE_BLA_W_RADL &&
+           this->getAssociatedIRAPType() != NAL_UNIT_CODED_SLICE_BLA_N_LP);
+  }
+
+  // No RASL pictures shall be present in the bitstream that are associated with
+  // an IDR picture.
+  if(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
+     nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R)
+  {
+    assert(this->getAssociatedIRAPType() != NAL_UNIT_CODED_SLICE_IDR_N_LP   &&
+           this->getAssociatedIRAPType() != NAL_UNIT_CODED_SLICE_IDR_W_RADL);
+  }
+
+  // No RADL pictures shall be present in the bitstream that are associated with
+  // a BLA picture having nal_unit_type equal to BLA_N_LP or that are associated
+  // with an IDR picture having nal_unit_type equal to IDR_N_LP.
+  if(nalUnitType == NAL_UNIT_CODED_SLICE_RADL_N ||
+     nalUnitType == NAL_UNIT_CODED_SLICE_RADL_R)
+  {
+    assert(this->getAssociatedIRAPType() != NAL_UNIT_CODED_SLICE_BLA_N_LP   &&
+           this->getAssociatedIRAPType() != NAL_UNIT_CODED_SLICE_IDR_N_LP);
+  }
+
+  // loop through all pictures in the reference picture buffer
+  TComList<TComPic*>::iterator iterPic = rcListPic.begin();
+  while ( iterPic != rcListPic.end())
+  {
+    rpcPic = *(iterPic++);
+    if (rpcPic->getPOC() == this->getPOC())
+    {
+      continue;
+    }
+
+    // Any picture that has PicOutputFlag equal to 1 that precedes an IRAP picture
+    // in decoding order shall precede the IRAP picture in output order.
+    // (Note that any picture following in output order would be present in the DPB)
+    if(rpcPic->getSlice(0)->getPicOutputFlag() == 1)
+    {
+      if(nalUnitType == NAL_UNIT_CODED_SLICE_BLA_N_LP    ||
+         nalUnitType == NAL_UNIT_CODED_SLICE_BLA_W_LP    ||
+         nalUnitType == NAL_UNIT_CODED_SLICE_BLA_W_RADL  ||
+         nalUnitType == NAL_UNIT_CODED_SLICE_CRA         ||
+         nalUnitType == NAL_UNIT_CODED_SLICE_IDR_N_LP    ||
+         nalUnitType == NAL_UNIT_CODED_SLICE_IDR_W_RADL)
+      {
+        assert(rpcPic->getPOC() < this->getPOC());
+      }
+    }
+
+    // Any picture that has PicOutputFlag equal to 1 that precedes an IRAP picture
+    // in decoding order shall precede any RADL picture associated with the IRAP
+    // picture in output order.
+    if(rpcPic->getSlice(0)->getPicOutputFlag() == 1)
+    {
+      if((nalUnitType == NAL_UNIT_CODED_SLICE_RADL_N ||
+          nalUnitType == NAL_UNIT_CODED_SLICE_RADL_R))
+      {
+        // rpcPic precedes the IRAP in decoding order
+        if(this->getAssociatedIRAPPOC() > rpcPic->getSlice(0)->getAssociatedIRAPPOC())
+        {
+          // rpcPic must not be the IRAP picture
+          if(this->getAssociatedIRAPPOC() != rpcPic->getPOC())
+          {
+            assert(rpcPic->getPOC() < this->getPOC());
+          }
+        }
+      }
+    }
+
+    // When a picture is a leading picture, it shall precede, in decoding order,
+    // all trailing pictures that are associated with the same IRAP picture.
+    if(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
+       nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R ||
+       nalUnitType == NAL_UNIT_CODED_SLICE_RADL_N ||
+       nalUnitType == NAL_UNIT_CODED_SLICE_RADL_R)
+    {
+      if(rpcPic->getSlice(0)->getAssociatedIRAPPOC() == this->getAssociatedIRAPPOC())
+      {
+        // rpcPic is a picture that preceded the leading in decoding order since it exist in the DPB
+        // rpcPic would violate the constraint if it was a trailing picture
+        assert(rpcPic->getPOC() <= this->getAssociatedIRAPPOC());
+      }
+    }
+
+    // Any RASL picture associated with a CRA or BLA picture shall precede any
+    // RADL picture associated with the CRA or BLA picture in output order
+    if(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
+       nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R)
+    { 
+      if((this->getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_BLA_N_LP   ||
+          this->getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_BLA_W_LP   ||
+          this->getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL ||
+          this->getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_CRA)       &&
+          this->getAssociatedIRAPPOC() == rpcPic->getSlice(0)->getAssociatedIRAPPOC())
+      {
+        if(rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_RADL_N ||
+           rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_RADL_R)
+        {
+          assert(rpcPic->getPOC() > this->getPOC());
+        }
+      }
+    }
+
+    // Any RASL picture associated with a CRA picture shall follow, in output
+    // order, any IRAP picture that precedes the CRA picture in decoding order.
+    if(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
+       nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R)
+    {
+      if(this->getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_CRA)
+      {
+        if(rpcPic->getSlice(0)->getPOC() < this->getAssociatedIRAPPOC() &&
+           (rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP   ||
+            rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP   ||
+            rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL ||
+            rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP   ||
+            rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL ||
+            rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA))
+        {
+          assert(this->getPOC() > rpcPic->getSlice(0)->getPOC());
+        }
+      }
+    }
+  }
+}
+
 /** Function for applying picture marking based on the Reference Picture Set in pReferencePictureSet.
 */
@@ -1256,4 +1418,6 @@
   TComPic* rpcPic;
   Int i, isReference;
+
+  checkLeadingPictureRestrictions(rcListPic);
 
   // loop through all pictures in the reference picture buffer
@@ -1292,5 +1456,8 @@
       else 
       {
-        if(rpcPic->getIsLongTerm() && (rpcPic->getPicSym()->getSlice(0)->getPOC()%(1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC())) == pReferencePictureSet->getPOC(i)%(1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC()))
+        Int pocCycle = 1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC();
+        Int curPoc = rpcPic->getPicSym()->getSlice(0)->getPOC() & (pocCycle-1);
+        Int refPoc = pReferencePictureSet->getPOC(i) & (pocCycle-1);
+        if(rpcPic->getIsLongTerm() && curPoc == refPoc)
         {
           isReference = 1;
@@ -1311,5 +1478,5 @@
     assert(rpcPic->getSlice( 0 )->isReferenced()==0||rpcPic->getUsedByCurr()==0||rpcPic->getTLayer()<=this->getTLayer());
     //check that pictures of higher or equal temporal layer are not in the RPS if the current picture is a TSA picture
-    if(this->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_R || this->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_N)
+    if(this->getNalUnitType() == NAL_UNIT_CODED_SLICE_TLA_R || this->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_N)
     {
       assert(rpcPic->getSlice( 0 )->isReferenced()==0||rpcPic->getTLayer()<this->getTLayer());
@@ -1352,5 +1519,8 @@
       else 
       {
-        if(rpcPic->getIsLongTerm() && (rpcPic->getPicSym()->getSlice(0)->getPOC()%(1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC())) == pReferencePictureSet->getPOC(i)%(1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC()) && rpcPic->getSlice(0)->isReferenced())
+        Int pocCycle = 1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC();
+        Int curPoc = rpcPic->getPicSym()->getSlice(0)->getPOC() & (pocCycle-1);
+        Int refPoc = pReferencePictureSet->getPOC(i) & (pocCycle-1);
+        if(rpcPic->getIsLongTerm() && curPoc == refPoc && rpcPic->getSlice(0)->isReferenced())
         {
           isAvailable = 1;
@@ -1371,6 +1541,6 @@
         if (!pReferencePictureSet->getCheckLTMSBPresent(i))
         {
-          curPoc = curPoc % pocCycle;
-          refPoc = refPoc % pocCycle;
+          curPoc = curPoc & (pocCycle - 1);
+          refPoc = refPoc & (pocCycle - 1);
         }
         
@@ -2114,7 +2284,7 @@
     }
 
-  /*
+/*
      Note: only the case of "vps_max_temporal_layers_minus1 = 0" is supported.
-  */
+*/
     Int i, j;
     UInt birateValue, cpbSizeValue;
@@ -2410,7 +2580,7 @@
 TComScalingList::TComScalingList()
 {
-  m_useTransformSkip = false;
   init();
 }
+
 TComScalingList::~TComScalingList()
 {
@@ -2495,4 +2665,5 @@
     {
       src = getScalingListAddress(sizeIdc, listIdc);
+
       fseek(fp,0,0);
       do 
Index: branches/SHM-3.1-dev/source/Lib/TLibCommon/TComSlice.h
===================================================================
--- branches/SHM-3.1-dev/source/Lib/TLibCommon/TComSlice.h	(revision 430)
+++ branches/SHM-3.1-dev/source/Lib/TLibCommon/TComSlice.h	(revision 431)
@@ -166,11 +166,6 @@
 #endif
 
-  Bool     getUseTransformSkip    ()                                     { return m_useTransformSkip; }      
-  Void     setUseTransformSkip    (Bool b)                               { m_useTransformSkip = b;    }
-
   Int*     getScalingListAddress          (UInt sizeId, UInt listId)           { return m_scalingListCoef[sizeId][listId]; } //!< get matrix coefficient
-
   Bool     checkPredMode                  (UInt sizeId, UInt listId);
-
   Void     setRefMatrixId                 (UInt sizeId, UInt listId, UInt u)   { m_refMatrixId[sizeId][listId] = u;    }     //!< set reference matrix ID
   UInt     getRefMatrixId                 (UInt sizeId, UInt listId)           { return m_refMatrixId[sizeId][listId]; }     //!< get reference matrix ID
@@ -201,5 +196,4 @@
   Void     init                    ();
   Void     destroy                 ();
-
   Int      m_scalingListDC               [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM]; //!< the DC value of the matrix coefficient for 16x16
   Bool     m_useDefaultScalingMatrixFlag [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM]; //!< UseDefaultScalingMatrixFlag
@@ -213,8 +207,5 @@
 
   UInt     m_predMatrixId                [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM]; //!< reference list index
-
-  Int      *m_scalingListCoef            [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM]; //!< quantization matrix
-
-  Bool     m_useTransformSkip;                                                      //!< transform skipping flag for setting default scaling matrix for 4x4
+  Int      *m_scalingListCoef            [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM]; //!< quantization matrix                                            
 };
 
@@ -1627,5 +1618,7 @@
   Int         m_iPOC;
   Int         m_iLastIDR;
-  static Int  m_prevPOC;
+  Int         m_iAssociatedIRAP;
+  NalUnitType m_iAssociatedIRAPType;
+  static Int  m_prevTid0POC;
   TComReferencePictureSet *m_pcRPS;
   TComReferencePictureSet m_LocalRPS;
@@ -1788,8 +1781,12 @@
   Void      setRPSidx          ( Int iBDidx ) { m_iBDidx = iBDidx; }
   Int       getRPSidx          () { return m_iBDidx; }
-  Int       getPrevPOC      ()                          { return  m_prevPOC;       }
+  Int       getPrevTid0POC      ()                        { return  m_prevTid0POC;       }
   TComRefPicListModification* getRefPicListModification() { return &m_RefPicListModification; }
   Void      setLastIDR(Int iIDRPOC)                       { m_iLastIDR = iIDRPOC; }
   Int       getLastIDR()                                  { return m_iLastIDR; }
+  Void      setAssociatedIRAPPOC(Int iAssociatedIRAPPOC)             { m_iAssociatedIRAP = iAssociatedIRAPPOC; }
+  Int       getAssociatedIRAPPOC()                        { return m_iAssociatedIRAP; }
+  Void      setAssociatedIRAPType(NalUnitType associatedIRAPType)    { m_iAssociatedIRAPType = associatedIRAPType; }
+  NalUnitType getAssociatedIRAPType()                        { return m_iAssociatedIRAPType; }
   SliceType getSliceType    ()                          { return  m_eSliceType;         }
   Int       getPOC          ()                          { return  m_iPOC;           }
@@ -1817,4 +1814,5 @@
   Void      checkColRefIdx      (UInt curSliceIdx, TComPic* pic);
   Bool      getIsUsedAsLongTerm (Int i, Int j)                  { return m_bIsUsedAsLongTerm[i][j]; }
+  Void      setIsUsedAsLongTerm (Int i, Int j, Bool value)      { m_bIsUsedAsLongTerm[i][j] = value; }
   Bool      getCheckLDC     ()                                  { return m_bCheckLDC; }
   Bool      getMvdL1ZeroFlag ()                                  { return m_bLMvdL1Zero;    }
@@ -1826,5 +1824,6 @@
   Void      setReferenced(Bool b)                               { m_bRefenced = b; }
   Bool      isReferenced()                                      { return m_bRefenced; }
-  Void      setPOC              ( Int i )                       { m_iPOC              = i; if(getTLayer()==0) m_prevPOC=i; }
+  Bool      isReferenceNalu()                                   { return ((getNalUnitType() <= NAL_UNIT_RESERVED_VCL_R15) && (getNalUnitType()%2 != 0)) || ((getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP) && (getNalUnitType() <= NAL_UNIT_RESERVED_IRAP_VCL23) ); }
+  Void      setPOC              ( Int i )                       { m_iPOC              = i; if ((getTLayer()==0) && (isReferenceNalu() && (getNalUnitType()!=NAL_UNIT_CODED_SLICE_RASL_R)&& (getNalUnitType()!=NAL_UNIT_CODED_SLICE_RADL_R))) {m_prevTid0POC=i;} }
   Void      setNalUnitType      ( NalUnitType e )               { m_eNalUnitType      = e;      }
   NalUnitType getNalUnitType    () const                        { return m_eNalUnitType;        }
@@ -1848,5 +1847,5 @@
 #endif
 
-  Void      checkCRA(TComReferencePictureSet *pReferencePictureSet, Int& pocCRA, Bool& prevRAPisBLA, TComList<TComPic *>& rcListPic);
+  Void      checkCRA(TComReferencePictureSet *pReferencePictureSet, Int& pocCRA, NalUnitType& associatedIRAPType, TComList<TComPic *>& rcListPic);
   Void      decodingRefreshMarking(Int& pocCRA, Bool& bRefreshPending, TComList<TComPic*>& rcListPic);
   Void      setSliceType        ( SliceType e )                 { m_eSliceType        = e;      }
@@ -1917,4 +1916,5 @@
   Void setTLayerInfo( UInt uiTLayer );
   Void decodingMarking( TComList<TComPic*>& rcListPic, Int iGOPSIze, Int& iMaxRefPicNum ); 
+  Void checkLeadingPictureRestrictions( TComList<TComPic*>& rcListPic );
   Void applyReferencePictureSet( TComList<TComPic*>& rcListPic, TComReferencePictureSet *RPSList);
   Bool isTemporalLayerSwitchingPoint( TComList<TComPic*>& rcListPic );
Index: branches/SHM-3.1-dev/source/Lib/TLibCommon/TComWeightPrediction.h
===================================================================
--- branches/SHM-3.1-dev/source/Lib/TLibCommon/TComWeightPrediction.h	(revision 430)
+++ branches/SHM-3.1-dev/source/Lib/TLibCommon/TComWeightPrediction.h	(revision 431)
@@ -53,6 +53,4 @@
 class TComWeightPrediction
 {
-  wpScalingParam  m_wp0[3], m_wp1[3];
-
 public:
   TComWeightPrediction();
Index: branches/SHM-3.1-dev/source/Lib/TLibCommon/TypeDef.h
===================================================================
--- branches/SHM-3.1-dev/source/Lib/TLibCommon/TypeDef.h	(revision 430)
+++ branches/SHM-3.1-dev/source/Lib/TLibCommon/TypeDef.h	(revision 431)
@@ -43,8 +43,7 @@
 #define SYNTAX_BYTES                     10      ///< number of bytes taken by syntaxes per 4x4 block [RefIdxL0(1byte), RefIdxL1(1byte), MVxL0(2bytes), MVyL0(2bytes), MVxL1(2bytes), MVyL1(2bytes)]
 
-#define HM12_RANDOM_ACCESS               1
 #define RANDOM_ACCESS_SEI_FIX            1
+#if SVC_EXTENSION
 #define VPS_NUH_LAYER_ID                 1      ///< JCTVC-N0085: Assert that the nuh_layer_id of VPS NAL unit should be 0
-#if SVC_EXTENSION
 #define MAX_LAYERS                       2      ///< max number of layers the codec is supposed to handle
 #define POC_RESET_FLAG                   1      ///< JCTVC-N0244: POC reset flag for  layer pictures.
@@ -156,4 +155,6 @@
 #define RC_SHVC_HARMONIZATION            1      ///< JCTVC-M0037: rate control for SHVC
 
+#define VIEW_ID_RELATED_SIGNALING        1      ///< Introduce syntax elements view_id_len_minus1 and view_id_val
+#define M0043_LAYERS_PRESENT_SEI         0      ///< JCTVC-M0043: add layers present SEI. Macro shall be equal to 0 according to the JCTVC-N0174 discussion. The code is to be removed.
 #else
 #define SYNTAX_OUTPUT                    0
@@ -165,6 +166,4 @@
 
 #define FIX1071 1 ///< fix for issue #1071
-#define VIEW_ID_RELATED_SIGNALING        1 ///< Introduce syntax elements view_id_len_minus1 and view_id_val
-#define M0043_LAYERS_PRESENT_SEI         0 ///< JCTVC-M0043: add layers present SEI. Macro shall be equal to 0 according to the JCTVC-N0174 discussion. The code is to be removed.
 
 #define MAX_NUM_PICS_IN_SOP           1024
Index: branches/SHM-3.1-dev/source/Lib/TLibDecoder/NALread.cpp
===================================================================
--- branches/SHM-3.1-dev/source/Lib/TLibDecoder/NALread.cpp	(revision 430)
+++ branches/SHM-3.1-dev/source/Lib/TLibDecoder/NALread.cpp	(revision 431)
@@ -126,5 +126,5 @@
   else
   {
-    assert( nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_TSA_R
+    assert( nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_TLA_R
          && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_TSA_N
          && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_STSA_R
Index: branches/SHM-3.1-dev/source/Lib/TLibDecoder/SEIread.cpp
===================================================================
--- branches/SHM-3.1-dev/source/Lib/TLibDecoder/SEIread.cpp	(revision 430)
+++ branches/SHM-3.1-dev/source/Lib/TLibDecoder/SEIread.cpp	(revision 431)
@@ -349,4 +349,5 @@
 
   /* restore primary bitstream for sei_message */
+  getBitstream()->deleteFifo();
   delete getBitstream();
   setBitstream(bs);
Index: branches/SHM-3.1-dev/source/Lib/TLibDecoder/SyntaxElementParser.cpp
===================================================================
--- branches/SHM-3.1-dev/source/Lib/TLibDecoder/SyntaxElementParser.cpp	(revision 430)
+++ branches/SHM-3.1-dev/source/Lib/TLibDecoder/SyntaxElementParser.cpp	(revision 431)
@@ -52,9 +52,9 @@
   if (length < 10)
   {
-    fprintf( g_hTrace, "%-50s u(%d)  : %d\n", pSymbolName, length, rValue ); 
+    fprintf( g_hTrace, "%-50s u(%d)  : %u\n", pSymbolName, length, rValue ); 
   }
   else
   {
-    fprintf( g_hTrace, "%-50s u(%d) : %d\n", pSymbolName, length, rValue ); 
+    fprintf( g_hTrace, "%-50s u(%d) : %u\n", pSymbolName, length, rValue ); 
   }
   fflush ( g_hTrace );
@@ -65,5 +65,5 @@
   xReadUvlc (rValue);
   fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
-  fprintf( g_hTrace, "%-50s ue(v) : %d\n", pSymbolName, rValue ); 
+  fprintf( g_hTrace, "%-50s ue(v) : %u\n", pSymbolName, rValue ); 
   fflush ( g_hTrace );
 }
Index: branches/SHM-3.1-dev/source/Lib/TLibDecoder/TDecCAVLC.cpp
===================================================================
--- branches/SHM-3.1-dev/source/Lib/TLibDecoder/TDecCAVLC.cpp	(revision 430)
+++ branches/SHM-3.1-dev/source/Lib/TLibDecoder/TDecCAVLC.cpp	(revision 431)
@@ -1614,7 +1614,7 @@
       READ_CODE(sps->getBitsForPOC(), uiCode, "pic_order_cnt_lsb");
       Int iPOClsb = uiCode;
-      Int iPrevPOC = rpcSlice->getPrevPOC();
+      Int iPrevPOC = rpcSlice->getPrevTid0POC();
       Int iMaxPOClsb = 1<< sps->getBitsForPOC();
-      Int iPrevPOClsb = iPrevPOC%iMaxPOClsb;
+      Int iPrevPOClsb = iPrevPOC & (iMaxPOClsb - 1);
       Int iPrevPOCmsb = iPrevPOC-iPrevPOClsb;
       Int iPOCmsb;
@@ -1738,4 +1738,10 @@
             rps->setDeltaPOC(j, - rpcSlice->getPOC() + pocLsbLt);
             rps->setCheckLTMSBPresent(j,false);
+            
+            // reset deltaPocMSBCycleLT for first LTRP from slice header if MSB not present
+            if( j == offset+(numOfLtrp-numLtrpInSPS)-1 )
+            {
+              deltaPocMSBCycleLT = 0;
+            }
           }
           prevDeltaMSB = deltaPocMSBCycleLT;
Index: branches/SHM-3.1-dev/source/Lib/TLibDecoder/TDecSlice.h
===================================================================
--- branches/SHM-3.1-dev/source/Lib/TLibDecoder/TDecSlice.h	(revision 430)
+++ branches/SHM-3.1-dev/source/Lib/TLibDecoder/TDecSlice.h	(revision 431)
@@ -65,5 +65,4 @@
   TDecEntropy*    m_pcEntropyDecoder;
   TDecCu*         m_pcCuDecoder;
-  UInt            m_uiCurrSliceIdx;
 
   TDecSbac*       m_pcBufferSbacDecoders;   ///< line to store temporary contexts, one per column of tiles.
Index: branches/SHM-3.1-dev/source/Lib/TLibDecoder/TDecTop.cpp
===================================================================
--- branches/SHM-3.1-dev/source/Lib/TLibDecoder/TDecTop.cpp	(revision 430)
+++ branches/SHM-3.1-dev/source/Lib/TLibDecoder/TDecTop.cpp	(revision 431)
@@ -57,6 +57,6 @@
   g_nSymbolCounter = 0;
 #endif
+  m_associatedIRAPType = NAL_UNIT_INVALID;
   m_pocCRA = 0;
-  m_prevRAPisBLA = false;
   m_pocRandomAccess = MAX_INT;          
 #if !SVC_EXTENSION
@@ -77,8 +77,6 @@
   m_pBLSyntaxFile = NULL;
 #endif
-#if HM12_RANDOM_ACCESS
   m_prevSliceSkipped = false;
   m_skippedPOC = 0;
-#endif
 }
 
@@ -700,5 +698,4 @@
 #endif
 
-#if HM12_RANDOM_ACCESS
   // set POC for dependent slices in skipped pictures
   if(m_apcSlicePilot->getDependentSliceSegmentFlag() && m_prevSliceSkipped) 
@@ -706,13 +703,13 @@
     m_apcSlicePilot->setPOC(m_skippedPOC);
   }
-#endif
+
+  m_apcSlicePilot->setAssociatedIRAPPOC(m_pocCRA);
+  m_apcSlicePilot->setAssociatedIRAPType(m_associatedIRAPType);
 
   // Skip pictures due to random access
   if (isRandomAccessSkipPicture(iSkipFrame, iPOCLastDisplay))
   {
-#if HM12_RANDOM_ACCESS
     m_prevSliceSkipped = true;
     m_skippedPOC = m_apcSlicePilot->getPOC();
-#endif
     return false;
   }
@@ -720,15 +717,11 @@
   if (isSkipPictureForBLA(iPOCLastDisplay))
   {
-#if HM12_RANDOM_ACCESS
     m_prevSliceSkipped = true;
     m_skippedPOC = m_apcSlicePilot->getPOC();
-#endif
     return false;
   }
 
-#if HM12_RANDOM_ACCESS
   // clear previous slice skipped flag
   m_prevSliceSkipped = false;
-#endif
 
   // exit when a new picture is found
@@ -913,4 +906,23 @@
     xGetNewPicBuffer (m_apcSlicePilot, pcPic);
 
+    Bool isField = false;
+    Bool isTff = false;
+    
+    if(!m_SEIs.empty())
+    {
+      // Check if any new Picture Timing SEI has arrived
+      SEIMessages pictureTimingSEIs = extractSeisByType (m_SEIs, SEI::PICTURE_TIMING);
+      if (pictureTimingSEIs.size()>0)
+      {
+        SEIPictureTiming* pictureTiming = (SEIPictureTiming*) *(pictureTimingSEIs.begin());
+        isField = (pictureTiming->m_picStruct == 1) || (pictureTiming->m_picStruct == 2);
+        isTff =  (pictureTiming->m_picStruct == 1);
+      }
+    }
+    
+    //Set Field/Frame coding mode
+    m_pcPic->setField(isField);
+    m_pcPic->setTopField(isTff);
+
     // transfer any SEI messages that have been received to the picture
     pcPic->setSEIs(m_SEIs);
@@ -1052,5 +1064,5 @@
   if (bNextSlice)
   {
-    pcSlice->checkCRA(pcSlice->getRPS(), m_pocCRA, m_prevRAPisBLA, m_cListPic );
+    pcSlice->checkCRA(pcSlice->getRPS(), m_pocCRA, m_associatedIRAPType, m_cListPic );
     // Set reference list
 #if SVC_EXTENSION
@@ -1251,5 +1263,4 @@
       pcSlice->setScalingList ( pcSlice->getPPS()->getScalingList()  );
     }
-    pcSlice->getScalingList()->setUseTransformSkip(pcSlice->getPPS()->getUseTransformSkip());
     if(!pcSlice->getPPS()->getScalingListPresentFlag() && !pcSlice->getSPS()->getScalingListPresentFlag())
     {
@@ -1497,5 +1508,5 @@
     case NAL_UNIT_CODED_SLICE_TRAIL_R:
     case NAL_UNIT_CODED_SLICE_TRAIL_N:
-    case NAL_UNIT_CODED_SLICE_TSA_R:
+    case NAL_UNIT_CODED_SLICE_TLA_R:
     case NAL_UNIT_CODED_SLICE_TSA_N:
     case NAL_UNIT_CODED_SLICE_STSA_R:
@@ -1532,5 +1543,6 @@
 Bool TDecTop::isSkipPictureForBLA(Int& iPOCLastDisplay)
 {
-  if (m_prevRAPisBLA && m_apcSlicePilot->getPOC() < m_pocCRA && (m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_R || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_N))
+  if ((m_associatedIRAPType == NAL_UNIT_CODED_SLICE_BLA_N_LP || m_associatedIRAPType == NAL_UNIT_CODED_SLICE_BLA_W_LP || m_associatedIRAPType == NAL_UNIT_CODED_SLICE_BLA_W_RADL) && 
+       m_apcSlicePilot->getPOC() < m_pocCRA && (m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_R || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_N))
   {
     iPOCLastDisplay++;
Index: branches/SHM-3.1-dev/source/Lib/TLibDecoder/TDecTop.h
===================================================================
--- branches/SHM-3.1-dev/source/Lib/TLibDecoder/TDecTop.h	(revision 430)
+++ branches/SHM-3.1-dev/source/Lib/TLibDecoder/TDecTop.h	(revision 431)
@@ -67,6 +67,6 @@
   Int                     m_iMaxRefPicNum;
   
+  NalUnitType             m_associatedIRAPType; ///< NAL unit type of the associated IRAP picture
   Int                     m_pocCRA;            ///< POC number of the latest CRA picture
-  Bool                    m_prevRAPisBLA;      ///< true if the previous RAP (CRA/CRANT/BLA/BLANT/IDR) picture is a BLA/BLANT picture
   Int                     m_pocRandomAccess;   ///< POC number of the random access point (the first IDR or CRA picture)
 
@@ -107,8 +107,6 @@
   Bool                    m_bFirstSliceInSequence;
 #endif
-#if HM12_RANDOM_ACCESS
   Bool                    m_prevSliceSkipped;
   Int                     m_skippedPOC;
-#endif
 
 #if SVC_EXTENSION
@@ -122,5 +120,5 @@
   fstream*                m_pBLReconFile;
   Int                     m_iBLSourceWidth;
-  Int                     m_iBLSourceHeight;
+  Int                     m_iBLSourceHeight;  
 #endif
 #if VPS_EXTN_DIRECT_REF_LAYERS && M0457_PREDICTION_INDICATIONS
@@ -159,9 +157,8 @@
 
   Void executeLoopFilters(Int& poc, TComList<TComPic*>*& rpcListPic);
+#if SVC_EXTENSION
 #if EARLY_REF_PIC_MARKING
   Void earlyPicMarking(Int maxTemporalLayer, std::vector<Int>& targetDecLayerIdList);
 #endif
-
-#if SVC_EXTENSION
   UInt      getLayerId            () { return m_layerId;              }
   Void      setLayerId            (UInt layer) { m_layerId = layer; }
Index: branches/SHM-3.1-dev/source/Lib/TLibEncoder/TEncAnalyze.cpp
===================================================================
--- branches/SHM-3.1-dev/source/Lib/TLibEncoder/TEncAnalyze.cpp	(revision 430)
+++ branches/SHM-3.1-dev/source/Lib/TLibEncoder/TEncAnalyze.cpp	(revision 431)
@@ -57,3 +57,4 @@
 #endif
 
+TEncAnalyze             m_gcAnalyzeAll_in;
 //! \}
Index: branches/SHM-3.1-dev/source/Lib/TLibEncoder/TEncAnalyze.h
===================================================================
--- branches/SHM-3.1-dev/source/Lib/TLibEncoder/TEncAnalyze.h	(revision 430)
+++ branches/SHM-3.1-dev/source/Lib/TLibEncoder/TEncAnalyze.h	(revision 431)
@@ -131,4 +131,32 @@
     fclose(pFile);
   }
+
+  Void    printOutInterlaced ( Char cDelim, Double bits )
+  {
+    Double dFps     =   m_dFrmRate; //--CFG_KDY
+    Double dScale   = dFps / 1000 / (Double)m_uiNumPic;
+    
+    printf( "\tTotal Frames |  "   "Bitrate    "  "Y-PSNR    "  "U-PSNR    "  "V-PSNR \n" );
+    //printf( "\t------------ "  " ----------"   " -------- "  " -------- "  " --------\n" );
+    printf( "\t %8d    %c"          "%12.4lf  "    "%8.4lf  "   "%8.4lf  "    "%8.4lf\n",
+           getNumPic(), cDelim,
+           bits * dScale,
+           getPsnrY() / (Double)getNumPic(),
+           getPsnrU() / (Double)getNumPic(),
+           getPsnrV() / (Double)getNumPic() );
+  }
+  
+  Void    printSummaryOutInterlaced (Int bits)
+  {
+    FILE* pFile = fopen ("summaryTotal.txt", "at");
+    Double dFps     =   m_dFrmRate; //--CFG_KDY
+    Double dScale   = dFps / 1000 / (Double)m_uiNumPic;
+    
+    fprintf(pFile, "%f\t %f\t %f\t %f\n", bits * dScale,
+            getPsnrY() / (Double)getNumPic(),
+            getPsnrU() / (Double)getNumPic(),
+            getPsnrV() / (Double)getNumPic() );
+    fclose(pFile);
+  }
   
   Void    printSummary(Char ch)
@@ -178,4 +206,5 @@
 #endif
 
+extern TEncAnalyze             m_gcAnalyzeAll_in;
 //! \}
 
Index: branches/SHM-3.1-dev/source/Lib/TLibEncoder/TEncCavlc.cpp
===================================================================
--- branches/SHM-3.1-dev/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 430)
+++ branches/SHM-3.1-dev/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 431)
@@ -1281,12 +1281,12 @@
       if( !pcSlice->getPocResetFlag() )
       {
-        picOrderCntLSB = (pcSlice->getPOC()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC()))%(1<<pcSlice->getSPS()->getBitsForPOC());
+        picOrderCntLSB = (pcSlice->getPOC()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC())) & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
       }
       else
       {
-        picOrderCntLSB = (pcSlice->getPocValueBeforeReset()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC()))%(1<<pcSlice->getSPS()->getBitsForPOC());
-      }
-#else
-      Int picOrderCntLSB = (pcSlice->getPOC()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC()))%(1<<pcSlice->getSPS()->getBitsForPOC());
+        picOrderCntLSB = (pcSlice->getPocValueBeforeReset()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC())) & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
+      }
+#else
+      Int picOrderCntLSB = (pcSlice->getPOC()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC())) & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
 #endif
       WRITE_CODE( picOrderCntLSB, pcSlice->getSPS()->getBitsForPOC(), "pic_order_cnt_lsb");
@@ -2142,5 +2142,5 @@
 {
   // Bool state = true, state2 = false;
-  Int lsb = ltrpPOC % (1<<pcSlice->getSPS()->getBitsForPOC());
+  Int lsb = ltrpPOC & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
   for (Int k = 0; k < pcSlice->getSPS()->getNumLongTermRefPicSPS(); k++)
   {
Index: branches/SHM-3.1-dev/source/Lib/TLibEncoder/TEncCu.cpp
===================================================================
--- branches/SHM-3.1-dev/source/Lib/TLibEncoder/TEncCu.cpp	(revision 430)
+++ branches/SHM-3.1-dev/source/Lib/TLibEncoder/TEncCu.cpp	(revision 431)
@@ -379,9 +379,4 @@
   m_ppcOrigYuv[uiDepth]->copyFromPicYuv( pcPic->getPicYuvOrg(), rpcBestCU->getAddr(), rpcBestCU->getZorderIdxInCU() );
 
-  // variables for fast encoder decision
-  Bool    bEarlySkip  = false;
-  Bool    bTrySplit    = true;
-  Double  fRD_Skip    = MAX_DOUBLE;
-
   // variable for Early CU determination
   Bool    bSubBranch = true;
@@ -390,15 +385,4 @@
   Bool    doNotBlockPu = true;
   Bool earlyDetectionSkipMode = false;
-
-  Bool    bTrySplitDQP  = true;
-
-  static  Double  afCost[ MAX_CU_DEPTH ];
-  static  Int      aiNum [ MAX_CU_DEPTH ];
-
-  if ( rpcBestCU->getAddr() == 0 )
-  {
-    ::memset( afCost, 0, sizeof( afCost ) );
-    ::memset( aiNum,  0, sizeof( aiNum  ) );
-  }
 
   Bool bBoundary = false;
@@ -471,11 +455,17 @@
     if (rpcBestCU->getLayerId() > 0)
     {
-        if(pcSlice->getSliceType() == P_SLICE && pcSlice->getNumRefIdx(REF_PIC_LIST_0) == pcSlice->getActiveNumILRRefIdx()) 
-            testInter = false; 
-        if(pcSlice->getSliceType() == B_SLICE && pcSlice->getNumRefIdx(REF_PIC_LIST_0) == pcSlice->getActiveNumILRRefIdx() && pcSlice->getNumRefIdx(REF_PIC_LIST_1) == pcSlice->getActiveNumILRRefIdx()) 
-            testInter = false;
+      if(pcSlice->getSliceType() == P_SLICE && pcSlice->getNumRefIdx(REF_PIC_LIST_0) == pcSlice->getActiveNumILRRefIdx())
+      {
+        testInter = false;
+      }
+      if(pcSlice->getSliceType() == B_SLICE && pcSlice->getNumRefIdx(REF_PIC_LIST_0) == pcSlice->getActiveNumILRRefIdx() && pcSlice->getNumRefIdx(REF_PIC_LIST_1) == pcSlice->getActiveNumILRRefIdx()) 
+      {
+        testInter = false;
+      }
 #if M0457_IL_SAMPLE_PRED_ONLY_FLAG
-        if( pcSlice->getInterLayerSamplePredOnlyFlag() ) 
-            testInter = false; 
+      if( pcSlice->getInterLayerSamplePredOnlyFlag() )
+      {
+        testInter = false;
+      }
 #endif
     }
@@ -487,8 +477,4 @@
         iQP = lowestQP;
       }
-      // variables for fast encoder decision
-      bEarlySkip  = false;
-      bTrySplit    = true;
-      fRD_Skip    = MAX_DOUBLE;
 
       rpcTempCU->initEstData( uiDepth, iQP );
@@ -509,49 +495,23 @@
         xCheckRDCostMerge2Nx2N( rpcBestCU, rpcTempCU, &earlyDetectionSkipMode );//by Merge for inter_2Nx2N
         rpcTempCU->initEstData( uiDepth, iQP );
-
-        // fast encoder decision for early skip
-        if ( m_pcEncCfg->getUseFastEnc() )
-        {
-          Int iIdx = g_aucConvertToBit[ rpcBestCU->getWidth(0) ];
-          if ( aiNum [ iIdx ] > 5 && fRD_Skip < EARLY_SKIP_THRES*afCost[ iIdx ]/aiNum[ iIdx ] )
-          {
-            bEarlySkip = true;
-            bTrySplit  = false;
-          }
-        }
+        
 #if (ENCODER_FAST_MODE == 2)
         if (testInter)
         {
 #endif
-
         if(!m_pcEncCfg->getUseEarlySkipDetection())
         {
           // 2Nx2N, NxN
-          if ( !bEarlySkip )
+          xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N );  rpcTempCU->initEstData( uiDepth, iQP );
+          if(m_pcEncCfg->getUseCbfFastMode())
           {
-            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N );  rpcTempCU->initEstData( uiDepth, iQP );
-            if(m_pcEncCfg->getUseCbfFastMode())
-            {
-              doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
-            }
+            doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
           }
         }
 #if (ENCODER_FAST_MODE == 2)
-    }
-#endif
-
-      }
-
-      if( (g_uiMaxCUWidth>>uiDepth) >= rpcTempCU->getSlice()->getPPS()->getMinCuDQPSize() )
-      {
-        if(iQP == iBaseQP)
-        {
-          bTrySplitDQP = bTrySplit;
-        }
-      }
-      else
-      {
-        bTrySplitDQP = bTrySplit;
-      }
+        }
+#endif
+      }
+
       if (isAddLowestQP && (iQP == lowestQP))
       {
@@ -580,5 +540,5 @@
         // do inter modes, NxN, 2NxN, and Nx2N
 #if (ENCODER_FAST_MODE)
-      if( rpcBestCU->getSlice()->getSliceType() != I_SLICE && testInter )
+        if( rpcBestCU->getSlice()->getSliceType() != I_SLICE && testInter )
 #else
         if( rpcBestCU->getSlice()->getSliceType() != I_SLICE )
@@ -586,13 +546,10 @@
         {
           // 2Nx2N, NxN
-          if ( !bEarlySkip )
+          if(!( (rpcBestCU->getWidth(0)==8) && (rpcBestCU->getHeight(0)==8) ))
           {
-            if(!( (rpcBestCU->getWidth(0)==8) && (rpcBestCU->getHeight(0)==8) ))
+            if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth && doNotBlockPu)
             {
-              if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth && doNotBlockPu)
-              {
-                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_NxN   );
-                rpcTempCU->initEstData( uiDepth, iQP );
-              }
+              xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_NxN   );
+              rpcTempCU->initEstData( uiDepth, iQP );
             }
           }
@@ -734,6 +691,4 @@
 
         // do normal intra modes
-        if ( !bEarlySkip )
-        {
           // speedup for inter frames
 #if (ENCODER_FAST_MODE)
@@ -761,5 +716,4 @@
             }
           }
-        }
 
         // test PCM
@@ -803,15 +757,4 @@
     rpcBestCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcBestCU->getTotalBits(), rpcBestCU->getTotalDistortion() );
 
-    // accumulate statistics for early skip
-    if ( m_pcEncCfg->getUseFastEnc() )
-    {
-      if ( rpcBestCU->isSkipped(0) )
-      {
-        Int iIdx = g_aucConvertToBit[ rpcBestCU->getWidth(0) ];
-        afCost[ iIdx ] += rpcBestCU->getTotalCost();
-        aiNum [ iIdx ] ++;
-      }
-    }
-
     // Early CU determination
     if( m_pcEncCfg->getUseEarlyCU() && rpcBestCU->isSkipped(0) )
@@ -896,5 +839,5 @@
 
     // further split
-    if( bSubBranch && bTrySplitDQP && uiDepth < g_uiMaxCUDepth - g_uiAddCUDepth )
+    if( bSubBranch && uiDepth < g_uiMaxCUDepth - g_uiAddCUDepth )
     {
       UChar       uhNextDepth         = uiDepth+1;
Index: branches/SHM-3.1-dev/source/Lib/TLibEncoder/TEncGOP.cpp
===================================================================
--- branches/SHM-3.1-dev/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 430)
+++ branches/SHM-3.1-dev/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 431)
@@ -375,7 +375,7 @@
 // ====================================================================================================================
 #if SVC_EXTENSION
-Void TEncGOP::compressGOP( Int iPicIdInGOP, Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP)
-#else
-Void TEncGOP::compressGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP)
+Void TEncGOP::compressGOP( Int iPicIdInGOP, Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP, Bool isField, Bool isTff)
+#else
+Void TEncGOP::compressGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP, Bool isField, Bool isTff)
 #endif
 {
@@ -390,5 +390,5 @@
   TComOutputBitstream* pcSubstreamsOut = NULL;
 
-  xInitGOP( iPOCLast, iNumPicRcvd, rcListPic, rcListPicYuvRecOut );
+  xInitGOP( iPOCLast, iNumPicRcvd, rcListPic, rcListPicYuvRecOut, isField );
 
   m_iNumPicCoded = 0;
@@ -463,11 +463,23 @@
 
     /////////////////////////////////////////////////////////////////////////////////////////////////// Initial to start encoding
-    Int pocCurr = iPOCLast -iNumPicRcvd+ m_pcCfg->getGOPEntry(iGOPid).m_POC;
-    Int iTimeOffset = m_pcCfg->getGOPEntry(iGOPid).m_POC;
-    if(iPOCLast == 0)
+    Int iTimeOffset;
+    Int pocCurr;
+    
+    if(iPOCLast == 0) //case first frame or first top field
     {
       pocCurr=0;
       iTimeOffset = 1;
     }
+    else if(iPOCLast == 1 && isField) //case first bottom field, just like the first frame, the poc computation is not right anymore, we set the right value
+    {
+      pocCurr = 1;
+      iTimeOffset = 1;
+    }
+    else
+    {
+      pocCurr = iPOCLast - iNumPicRcvd + m_pcCfg->getGOPEntry(iGOPid).m_POC - isField;
+      iTimeOffset = m_pcCfg->getGOPEntry(iGOPid).m_POC;
+    }
+
     if(pocCurr>=m_pcCfg->getFramesToBeEncoded())
     {
@@ -490,5 +502,5 @@
     accessUnitsInGOP.push_back(AccessUnit());
     AccessUnit& accessUnit = accessUnitsInGOP.back();
-    xGetBuffer( rcListPic, rcListPicYuvRecOut, iNumPicRcvd, iTimeOffset, pcPic, pcPicYuvRecOut, pocCurr );
+    xGetBuffer( rcListPic, rcListPicYuvRecOut, iNumPicRcvd, iTimeOffset, pcPic, pcPicYuvRecOut, pocCurr, isField );
 
     //  Slice data initialization
@@ -499,8 +511,12 @@
 #if SVC_EXTENSION
     pcPic->setLayerId( m_layerId );
-    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, pocCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getSPS(), m_pcEncTop->getPPS(), m_pcEncTop->getVPS() );
-#else
-    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, pocCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getSPS(), m_pcEncTop->getPPS() );
-#endif
+    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, pocCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getSPS(), m_pcEncTop->getPPS(), m_pcEncTop->getVPS(), isField );
+#else
+    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, pocCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getSPS(), m_pcEncTop->getPPS(), isField );
+#endif
+
+    //Set Frame/Field coding
+    pcSlice->getPic()->setField(isField);
+
 #if POC_RESET_FLAG
     if( !pcSlice->getPocResetFlag() ) // For picture that are not reset, we should adjust the value of POC calculated from the configuration files.
@@ -602,5 +618,4 @@
     pcSlice->setLFCrossSliceBoundaryFlag(  pcSlice->getPPS()->getLoopFilterAcrossSlicesEnabledFlag()  );
     pcSlice->setScalingList ( m_pcEncTop->getScalingList()  );
-    pcSlice->getScalingList()->setUseTransformSkip(m_pcEncTop->getPPS()->getUseTransformSkip());
     if(m_pcEncTop->getUseScalingListId() == SCALING_LIST_OFF)
     {
@@ -818,8 +833,10 @@
       }
     }
-#endif //SVC_EXTENSION
+#endif //#if SVC_EXTENSION
     if(pcSlice->getTemporalLayerNonReferenceFlag())
     {
-      if(pcSlice->getNalUnitType()==NAL_UNIT_CODED_SLICE_TRAIL_R)
+      if (pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_TRAIL_R &&
+          !(m_iGopSize == 1 && pcSlice->getSliceType() == I_SLICE))
+        // Add this condition to avoid POC issues with encoder_intra_main.cfg configuration (see #1127 in bug tracker)
       {
         pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TRAIL_N);
@@ -863,5 +880,5 @@
         else
         {
-          pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TSA_R);
+          pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TLA_R);
         }
 #if ALIGN_TSA_STSA_PICS
@@ -875,5 +892,5 @@
             {
               assert( ( lowerLayerPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_N ) ||
-                      ( lowerLayerPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_R ) );
+                      ( lowerLayerPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_TLA_R ) );
               // TSA pictures are aligned within an access unit.
             }
@@ -1019,15 +1036,15 @@
       if( pcSlice->getMFMEnabledFlag() )
 #else
-        if( pcSlice->getSPS()->getMFMEnabledFlag() )
-#endif
-        {
-          pcSlice->setRefPOCListILP(m_pcEncTop->getIlpList(), pcSlice->getBaseColPic());
+      if( pcSlice->getSPS()->getMFMEnabledFlag() )
+#endif
+      {
+        pcSlice->setRefPOCListILP(m_pcEncTop->getIlpList(), pcSlice->getBaseColPic());
 #if M0457_COL_PICTURE_SIGNALING && !REMOVE_COL_PICTURE_SIGNALING
-          pcSlice->setMotionPredIlp(getMotionPredIlp(pcSlice));
-#endif
-        }
-#else
-    //  Set reference list
-    pcSlice->setRefPicList ( rcListPic );
+        pcSlice->setMotionPredIlp(getMotionPredIlp(pcSlice));
+#endif
+      }
+#else
+      //  Set reference list
+      pcSlice->setRefPicList ( rcListPic );
 #endif //SVC_EXTENSION
       pcSlice->setRefPicListModificationSvc();
@@ -1080,5 +1097,8 @@
 #endif
     }
-#endif
+#else //SVC_EXTENSION
+    //  Set reference list
+    pcSlice->setRefPicList ( rcListPic );
+#endif //#if SVC_EXTENSION
 
     //  Slice info. refinement
@@ -1662,5 +1682,5 @@
         }
       }
-      pictureTimingSEI.m_auCpbRemovalDelay = std::max<Int>(1, m_totalCoded - m_lastBPSEI); // Syntax element signalled as minus, hence the .
+      pictureTimingSEI.m_auCpbRemovalDelay = std::min<Int>(std::max<Int>(1, m_totalCoded - m_lastBPSEI), static_cast<Int>(pow(2, static_cast<double>(pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getCpbRemovalDelayLengthMinus1()+1)))); // Syntax element signalled as minus, hence the .
 #if POC_RESET_FLAG
       pictureTimingSEI.m_picDpbOutputDelay = pcSlice->getSPS()->getNumReorderPics(0) + pocCurr - m_totalCoded;
@@ -2201,4 +2221,18 @@
       xCalculateAddPSNR( pcPic, pcPic->getPicYuvRec(), accessUnit, dEncTime );
 
+      //In case of field coding, compute the interlaced PSNR for both fields
+      if (isField && ((!pcPic->isTopField() && isTff) || (pcPic->isTopField() && !isTff)))
+      {
+        //get complementary top field
+        TComPic* pcPicTop;
+        TComList<TComPic*>::iterator   iterPic = rcListPic.begin();
+        while ((*iterPic)->getPOC() != pcPic->getPOC()-1)
+        {
+          iterPic ++;
+        }
+        pcPicTop = *(iterPic);
+        xCalculateInterlacedAddPSNR(pcPicTop, pcPic, pcPicTop->getPicYuvRec(), pcPic->getPicYuvRec(), accessUnit, dEncTime );
+      }
+
       if (digestStr)
       {
@@ -2333,4 +2367,5 @@
             OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI, pcSlice->getTLayer());
           m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
+          pictureTimingSEI.m_picStruct = (isField && pcSlice->getPic()->isTopField())? 1 : isField? 2 : 0;
           m_seiWriter.writeSEImessage(nalu.m_Bitstream, pictureTimingSEI, pcSlice->getSPS());
           writeRBSPTrailingBits(nalu.m_Bitstream);
@@ -2451,12 +2486,12 @@
 
 #if SVC_EXTENSION
-  assert ( m_iNumPicCoded <= 1 );
-#else
-  assert ( m_iNumPicCoded == iNumPicRcvd );
+  assert ( m_iNumPicCoded <= 1 || (isField && iPOCLast == 1) );
+#else
+  assert ( (m_iNumPicCoded == iNumPicRcvd) || (isField && iPOCLast == 1) );
 #endif
 }
 
 #if !SVC_EXTENSION
-Void TEncGOP::printOutSummary(UInt uiNumAllPicCoded)
+Void TEncGOP::printOutSummary(UInt uiNumAllPicCoded, Bool isField)
 {
   assert (uiNumAllPicCoded == m_gcAnalyzeAll.getNumPic());
@@ -2464,8 +2499,18 @@
     
   //--CFG_KDY
-  m_gcAnalyzeAll.setFrmRate( m_pcCfg->getFrameRate() );
-  m_gcAnalyzeI.setFrmRate( m_pcCfg->getFrameRate() );
-  m_gcAnalyzeP.setFrmRate( m_pcCfg->getFrameRate() );
-  m_gcAnalyzeB.setFrmRate( m_pcCfg->getFrameRate() );
+  if(isField)
+  {
+    m_gcAnalyzeAll.setFrmRate( m_pcCfg->getFrameRate() * 2);
+    m_gcAnalyzeI.setFrmRate( m_pcCfg->getFrameRate() * 2);
+    m_gcAnalyzeP.setFrmRate( m_pcCfg->getFrameRate() * 2);
+    m_gcAnalyzeB.setFrmRate( m_pcCfg->getFrameRate() * 2);
+  }
+   else
+  {
+    m_gcAnalyzeAll.setFrmRate( m_pcCfg->getFrameRate() );
+    m_gcAnalyzeI.setFrmRate( m_pcCfg->getFrameRate() );
+    m_gcAnalyzeP.setFrmRate( m_pcCfg->getFrameRate() );
+    m_gcAnalyzeB.setFrmRate( m_pcCfg->getFrameRate() );
+  }
   
   //-- all
@@ -2490,4 +2535,16 @@
   m_gcAnalyzeB.printSummary('B');
 #endif
+
+  if(isField)
+  {
+    //-- interlaced summary
+    m_gcAnalyzeAll_in.setFrmRate( m_pcCfg->getFrameRate());
+    printf( "\n\nSUMMARY INTERLACED ---------------------------------------------\n" );
+    m_gcAnalyzeAll_in.printOutInterlaced('a',  m_gcAnalyzeAll.getBits());
+    
+#if _SUMMARY_OUT_
+    m_gcAnalyzeAll_in.printSummaryOutInterlaced();
+#endif
+  }
 
   printf("\nRVM: %.3lf\n" , xCalculateRVM());
@@ -2531,4 +2588,22 @@
 // ====================================================================================================================
 
+
+Void TEncGOP::xInitGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, Bool isField )
+{
+  assert( iNumPicRcvd > 0 );
+  //  Exception for the first frames
+  if ( ( isField && (iPOCLast == 0 || iPOCLast == 1) ) || (!isField  && (iPOCLast == 0))  )
+  {
+    m_iGopSize    = 1;
+  }
+  else
+  {
+    m_iGopSize    = m_pcCfg->getGOPSize();
+  }
+  assert (m_iGopSize > 0);
+  
+  return;
+}
+
 Void TEncGOP::xInitGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut )
 {
@@ -2553,14 +2628,33 @@
                          TComPic*&                 rpcPic,
                          TComPicYuv*&              rpcPicYuvRecOut,
-                         Int                       pocCurr )
+                         Int                       pocCurr,
+                         Bool                      isField)
 {
   Int i;
   //  Rec. output
   TComList<TComPicYuv*>::iterator     iterPicYuvRec = rcListPicYuvRecOut.end();
-  for ( i = 0; i < iNumPicRcvd - iTimeOffset + 1; i++ )
-  {
-    iterPicYuvRec--;
-  }
-  
+
+  if (isField)
+  {
+    for ( i = 0; i < ( (pocCurr == 0 ) || (pocCurr == 1 ) ? (iNumPicRcvd - iTimeOffset + 1) : (iNumPicRcvd - iTimeOffset + 2) ); i++ )
+    {
+      iterPicYuvRec--;
+    }
+  }
+  else
+  {
+    for ( i = 0; i < (iNumPicRcvd - iTimeOffset + 1); i++ )
+    {
+      iterPicYuvRec--;
+    }
+  }
+  
+  if (isField)
+  {
+    if(pocCurr == 1)
+    {
+      iterPicYuvRec++;
+    }
+  }
   rpcPicYuvRecOut = *(iterPicYuvRec);
   
@@ -2647,28 +2741,28 @@
   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_TRAIL_R:    return "TRAIL_R";
+    case NAL_UNIT_CODED_SLICE_TRAIL_N:    return "TRAIL_N";
+    case NAL_UNIT_CODED_SLICE_TLA_R:      return "TLA_R";
+    case NAL_UNIT_CODED_SLICE_TSA_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_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_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_RASL_R:     return "RASL_R";
-    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_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";
+    default:                              return "UNK";
   }
 }
@@ -2874,4 +2968,163 @@
     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 ? (UChar) top[x] : (UChar) bottom[x];
+      dst[stride+x] = isTff ? (UChar) bottom[x] : (UChar) top[x];
+    }
+    top += stride;
+    bottom += stride;
+    dst += stride*2;
+  }
+}
+
+Void TEncGOP::xCalculateInterlacedAddPSNR( TComPic* pcPicOrgTop, TComPic* pcPicOrgBottom, TComPicYuv* pcPicRecTop, TComPicYuv* pcPicRecBottom, const AccessUnit& accessUnit, Double dEncTime )
+{
+  Int     x, y;
+  
+  UInt64 uiSSDY_in  = 0;
+  UInt64 uiSSDU_in  = 0;
+  UInt64 uiSSDV_in  = 0;
+  
+  Double  dYPSNR_in  = 0.0;
+  Double  dUPSNR_in  = 0.0;
+  Double  dVPSNR_in  = 0.0;
+  
+  /*------ INTERLACED PSNR -----------*/
+  
+  /* Luma */
+  
+  Pel*  pOrgTop = pcPicOrgTop->getPicYuvOrg()->getLumaAddr();
+  Pel*  pOrgBottom = pcPicOrgBottom->getPicYuvOrg()->getLumaAddr();
+  Pel*  pRecTop = pcPicRecTop->getLumaAddr();
+  Pel*  pRecBottom = pcPicRecBottom->getLumaAddr();
+  
+  Int   iWidth;
+  Int   iHeight;
+  Int iStride;
+  
+  iWidth  = pcPicOrgTop->getPicYuvOrg()->getWidth () - m_pcEncTop->getPad(0);
+  iHeight = pcPicOrgTop->getPicYuvOrg()->getHeight() - m_pcEncTop->getPad(1);
+  iStride = pcPicOrgTop->getPicYuvOrg()->getStride();
+  Int   iSize   = iWidth*iHeight;
+  bool isTff = pcPicOrgTop->isTopField();
+  
+  TComPicYuv* pcOrgInterlaced = new TComPicYuv;
+  pcOrgInterlaced->create( iWidth, iHeight << 1, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+  
+  TComPicYuv* pcRecInterlaced = new TComPicYuv;
+  pcRecInterlaced->create( iWidth, iHeight << 1, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+  
+  Pel* pOrgInterlaced = pcOrgInterlaced->getLumaAddr();
+  Pel* pRecInterlaced = pcRecInterlaced->getLumaAddr();
+  
+  //=== Interlace fields ====
+  reinterlace(pOrgTop, pOrgBottom, pOrgInterlaced, iStride, iWidth, iHeight, isTff);
+  reinterlace(pRecTop, pRecBottom, pRecInterlaced, iStride, iWidth, iHeight, isTff);
+  
+  //===== calculate PSNR =====
+  for( y = 0; y < iHeight << 1; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+      Int iDiff = (Int)( pOrgInterlaced[x] - pRecInterlaced[x] );
+      uiSSDY_in   += iDiff * iDiff;
+    }
+    pOrgInterlaced += iStride;
+    pRecInterlaced += iStride;
+  }
+  
+  /*Chroma*/
+  
+  iHeight >>= 1;
+  iWidth  >>= 1;
+  iStride >>= 1;
+  
+  pOrgTop = pcPicOrgTop->getPicYuvOrg()->getCbAddr();
+  pOrgBottom = pcPicOrgBottom->getPicYuvOrg()->getCbAddr();
+  pRecTop = pcPicRecTop->getCbAddr();
+  pRecBottom = pcPicRecBottom->getCbAddr();
+  pOrgInterlaced = pcOrgInterlaced->getCbAddr();
+  pRecInterlaced = pcRecInterlaced->getCbAddr();
+  
+  //=== Interlace fields ====
+  reinterlace(pOrgTop, pOrgBottom, pOrgInterlaced, iStride, iWidth, iHeight, isTff);
+  reinterlace(pRecTop, pRecBottom, pRecInterlaced, iStride, iWidth, iHeight, isTff);
+  
+  //===== calculate PSNR =====
+  for( y = 0; y < iHeight << 1; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+      Int iDiff = (Int)( pOrgInterlaced[x] - pRecInterlaced[x] );
+      uiSSDU_in   += iDiff * iDiff;
+    }
+    pOrgInterlaced += iStride;
+    pRecInterlaced += iStride;
+  }
+  
+  pOrgTop = pcPicOrgTop->getPicYuvOrg()->getCrAddr();
+  pOrgBottom = pcPicOrgBottom->getPicYuvOrg()->getCrAddr();
+  pRecTop = pcPicRecTop->getCrAddr();
+  pRecBottom = pcPicRecBottom->getCrAddr();
+  pOrgInterlaced = pcOrgInterlaced->getCrAddr();
+  pRecInterlaced = pcRecInterlaced->getCrAddr();
+  
+  //=== Interlace fields ====
+  reinterlace(pOrgTop, pOrgBottom, pOrgInterlaced, iStride, iWidth, iHeight, isTff);
+  reinterlace(pRecTop, pRecBottom, pRecInterlaced, iStride, iWidth, iHeight, isTff);
+  
+  //===== calculate PSNR =====
+  for( y = 0; y < iHeight << 1; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+      Int iDiff = (Int)( pOrgInterlaced[x] - pRecInterlaced[x] );
+      uiSSDV_in   += iDiff * iDiff;
+    }
+    pOrgInterlaced += iStride;
+    pRecInterlaced += iStride;
+  }
+  
+  Int maxvalY = 255 << (g_bitDepthY-8);
+  Int maxvalC = 255 << (g_bitDepthC-8);
+  Double fRefValueY = (Double) maxvalY * maxvalY * iSize*2;
+  Double fRefValueC = (Double) maxvalC * maxvalC * iSize*2 / 4.0;
+  dYPSNR_in            = ( uiSSDY_in ? 10.0 * log10( fRefValueY / (Double)uiSSDY_in ) : 99.99 );
+  dUPSNR_in            = ( uiSSDU_in ? 10.0 * log10( fRefValueC / (Double)uiSSDU_in ) : 99.99 );
+  dVPSNR_in            = ( uiSSDV_in ? 10.0 * log10( fRefValueC / (Double)uiSSDV_in ) : 99.99 );
+  
+  /* calculate the size of the access unit, excluding:
+   *  - any AnnexB contributions (start_code_prefix, zero_byte, etc.,)
+   *  - SEI NAL units
+   */
+  UInt numRBSPBytes = 0;
+  for (AccessUnit::const_iterator it = accessUnit.begin(); it != accessUnit.end(); it++)
+  {
+    UInt numRBSPBytes_nal = UInt((*it)->m_nalUnitData.str().size());
+    
+    if ((*it)->m_nalUnitType != NAL_UNIT_PREFIX_SEI && (*it)->m_nalUnitType != NAL_UNIT_SUFFIX_SEI)
+      numRBSPBytes += numRBSPBytes_nal;
+  }
+  
+  UInt uibits = numRBSPBytes * 8 ;
+  
+  //===== add PSNR =====
+  m_gcAnalyzeAll_in.addResult (dYPSNR_in, dUPSNR_in, dVPSNR_in, (Double)uibits);
+  
+  printf("\n                                      Interlaced frame %d: [Y %6.4lf dB    U %6.4lf dB    V %6.4lf dB]", pcPicOrgBottom->getPOC()/2 , dYPSNR_in, dUPSNR_in, dVPSNR_in );
+  
+  pcOrgInterlaced->destroy();
+  delete pcOrgInterlaced;
+  pcRecInterlaced->destroy();
+  delete pcRecInterlaced;
 }
 
Index: branches/SHM-3.1-dev/source/Lib/TLibEncoder/TEncGOP.h
===================================================================
--- branches/SHM-3.1-dev/source/Lib/TLibEncoder/TEncGOP.h	(revision 430)
+++ branches/SHM-3.1-dev/source/Lib/TLibEncoder/TEncGOP.h	(revision 431)
@@ -145,7 +145,7 @@
   Void  init        ( TEncTop* pcTEncTop );
 #if SVC_EXTENSION
-  Void  compressGOP ( Int iPicIdInGOP, Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRec, std::list<AccessUnit>& accessUnitsInGOP );
+  Void  compressGOP ( Int iPicIdInGOP, Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRec, std::list<AccessUnit>& accessUnitsInGOP, Bool isField, Bool isTff );
 #else
-  Void  compressGOP ( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRec, std::list<AccessUnit>& accessUnitsInGOP );
+  Void  compressGOP ( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRec, std::list<AccessUnit>& accessUnitsInGOP, Bool isField, Bool isTff );
 #endif
   Void  xAttachSliceDataToNalUnit (OutputNALUnit& rNalu, TComOutputBitstream*& rpcBitstreamRedirect);
@@ -156,5 +156,7 @@
   TComList<TComPic*>*   getListPic()      { return m_pcListPic; }
   
-  Void  printOutSummary      ( UInt uiNumAllPicCoded );
+#if !SVC_EXTENSION
+  Void  printOutSummary      ( UInt uiNumAllPicCoded, Bool isField);
+#endif
   Void  preLoopFilterPicAll  ( TComPic* pcPic, UInt64& ruiDist, UInt64& ruiBits );
   
@@ -166,8 +168,11 @@
 
 protected:
+  
+  Void xInitGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, Bool isField );
   Void  xInitGOP          ( Int iPOC, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut );
-  Void  xGetBuffer        ( TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, Int iNumPicRcvd, Int iTimeOffset, TComPic*& rpcPic, TComPicYuv*& rpcPicYuvRecOut, Int pocCurr );
+  Void  xGetBuffer        ( TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, Int iNumPicRcvd, Int iTimeOffset, TComPic*& rpcPic, TComPicYuv*& rpcPicYuvRecOut, Int pocCurr, Bool isField );
   
   Void  xCalculateAddPSNR ( TComPic* pcPic, TComPicYuv* pcPicD, const AccessUnit&, Double dEncTime );
+  Void  xCalculateInterlacedAddPSNR( TComPic* pcPicOrgTop, TComPic* pcPicOrgBottom, TComPicYuv* pcPicRecTop, TComPicYuv* pcPicRecBottom, const AccessUnit& accessUnit, Double dEncTime );
   
   UInt64 xFindDistortionFrame (TComPicYuv* pcPic0, TComPicYuv* pcPic1);
Index: branches/SHM-3.1-dev/source/Lib/TLibEncoder/TEncSlice.cpp
===================================================================
--- branches/SHM-3.1-dev/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 430)
+++ branches/SHM-3.1-dev/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 431)
@@ -180,7 +180,7 @@
 #if SVC_EXTENSION
 //\param vps          VPS associated with the slice
-Void TEncSlice::initEncSlice( TComPic* pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd, Int iGOPid, TComSlice*& rpcSlice, TComSPS* pSPS, TComPPS *pPPS, TComVPS *vps )
-#else
-Void TEncSlice::initEncSlice( TComPic* pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd, Int iGOPid, TComSlice*& rpcSlice, TComSPS* pSPS, TComPPS *pPPS )
+Void TEncSlice::initEncSlice( TComPic* pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd, Int iGOPid, TComSlice*& rpcSlice, TComSPS* pSPS, TComPPS *pPPS, TComVPS *vps, Bool isField )
+#else
+Void TEncSlice::initEncSlice( TComPic* pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd, Int iGOPid, TComSlice*& rpcSlice, TComSPS* pSPS, TComPPS *pPPS, Bool isField )
 #endif
 {
@@ -298,5 +298,7 @@
     Int    NumberBFrames = ( m_pcCfg->getGOPSize() - 1 );
     Int    SHIFT_QP = 12;
-    Double dLambda_scale = 1.0 - Clip3( 0.0, 0.5, 0.05*(Double)NumberBFrames );
+
+    Double dLambda_scale = 1.0 - Clip3( 0.0, 0.5, 0.05*(Double)(isField ? NumberBFrames/2 : NumberBFrames) );
+
 #if FULL_NBIT
     Int    bitdepth_luma_qp_scale = 6 * (g_bitDepth - 8);
Index: branches/SHM-3.1-dev/source/Lib/TLibEncoder/TEncSlice.h
===================================================================
--- branches/SHM-3.1-dev/source/Lib/TLibEncoder/TEncSlice.h	(revision 430)
+++ branches/SHM-3.1-dev/source/Lib/TLibEncoder/TEncSlice.h	(revision 431)
@@ -118,8 +118,8 @@
 #if SVC_EXTENSION
   Void    initEncSlice        ( TComPic*  pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd,
-                                Int iGOPid,   TComSlice*& rpcSlice, TComSPS* pSPS, TComPPS *pPPS, TComVPS *vps );
+                                Int iGOPid,   TComSlice*& rpcSlice, TComSPS* pSPS, TComPPS *pPPS, TComVPS *vps, Bool isField );
 #else
   Void    initEncSlice        ( TComPic*  pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd,
-                                Int iGOPid,   TComSlice*& rpcSlice, TComSPS* pSPS, TComPPS *pPPS );
+                                Int iGOPid,   TComSlice*& rpcSlice, TComSPS* pSPS, TComPPS *pPPS, Bool isField );
 #endif
 
Index: branches/SHM-3.1-dev/source/Lib/TLibEncoder/TEncTop.cpp
===================================================================
--- branches/SHM-3.1-dev/source/Lib/TLibEncoder/TEncTop.cpp	(revision 430)
+++ branches/SHM-3.1-dev/source/Lib/TLibEncoder/TEncTop.cpp	(revision 431)
@@ -308,5 +308,5 @@
 }
 
-Void TEncTop::init()
+Void TEncTop::init(Bool isFieldCoding)
 {
   // initialize SPS
@@ -319,5 +319,5 @@
   m_cPPS.setSPS(&m_cSPS);
   xInitPPS();
-  xInitRPS();
+  xInitRPS(isFieldCoding);
 
   xInitPPSforTiles();
@@ -396,5 +396,5 @@
 
   // compress GOP
-  m_cGOPEncoder.compressGOP(iPicIdInGOP, m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut);
+  m_cGOPEncoder.compressGOP(iPicIdInGOP, m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, false, false);
 
 #if RATE_CONTROL_LAMBDA_DOMAIN
@@ -456,5 +456,6 @@
 
   // compress GOP
-  m_cGOPEncoder.compressGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut);
+
+  m_cGOPEncoder.compressGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, false, false);
 
 #if RATE_CONTROL_LAMBDA_DOMAIN
@@ -467,4 +468,271 @@
   iNumEncoded         = m_iNumPicRcvd;
   m_iNumPicRcvd       = 0;
+  m_uiNumAllPicCoded += iNumEncoded;
+}
+#endif
+
+/**------------------------------------------------
+ Separate interlaced frame into two fields
+ -------------------------------------------------**/
+void separateFields(Pel* org, Pel* dstField, UInt stride, UInt width, UInt height, Bool isTop)
+{
+  if (!isTop)
+  {
+    org += stride;
+  }
+  for (Int y = 0; y < height>>1; y++)
+  {
+    for (Int x = 0; x < width; x++)
+    {
+      dstField[x] = org[x];
+    }
+    
+    dstField += stride;
+    org += stride*2;
+  }
+  
+}
+
+#if SVC_EXTENSION
+Void TEncTop::encodePrep( TComPicYuv* pcPicYuvOrg, Bool isTff )
+{
+  if (pcPicYuvOrg)
+  {
+    /* -- TOP FIELD -- */
+    /* -- Top field initialization -- */
+    
+    TComPic *pcTopField;
+    xGetNewPicBuffer( pcTopField );
+    pcTopField->getPicSym()->allocSaoParam(&m_cEncSAO);
+    pcTopField->setReconMark (false);
+    
+    pcTopField->getSlice(0)->setPOC( m_iPOCLast );
+    pcTopField->getPicYuvRec()->setBorderExtension(false);
+    pcTopField->setTopField(isTff);
+    
+    Int nHeight = pcPicYuvOrg->getHeight();
+    Int nWidth = pcPicYuvOrg->getWidth();
+    Int nStride = pcPicYuvOrg->getStride();
+    Int nPadLuma = pcPicYuvOrg->getLumaMargin();
+    Int nPadChroma = pcPicYuvOrg->getChromaMargin();
+    
+    // Get pointers
+    Pel * PicBufY = pcPicYuvOrg->getBufY();
+    Pel * PicBufU = pcPicYuvOrg->getBufU();
+    Pel * PicBufV = pcPicYuvOrg->getBufV();
+    
+    Pel * pcTopFieldY =  pcTopField->getPicYuvOrg()->getLumaAddr();
+    Pel * pcTopFieldU =  pcTopField->getPicYuvOrg()->getCbAddr();
+    Pel * pcTopFieldV =  pcTopField->getPicYuvOrg()->getCrAddr();
+    
+    // compute image characteristics
+    if ( getUseAdaptiveQP() )
+    {
+      m_cPreanalyzer.xPreanalyze( dynamic_cast<TEncPic*>( pcTopField ) );
+    }
+    
+    /* -- Defield -- */
+    
+    Bool isTop = isTff;
+    
+    separateFields(PicBufY + nPadLuma + nStride*nPadLuma, pcTopFieldY, nStride, nWidth, nHeight, isTop);
+    separateFields(PicBufU + nPadChroma + (nStride >> 1)*nPadChroma, pcTopFieldU, nStride >> 1, nWidth >> 1, nHeight >> 1, isTop);
+    separateFields(PicBufV + nPadChroma + (nStride >> 1)*nPadChroma, pcTopFieldV, nStride >> 1, nWidth >> 1, nHeight >> 1, isTop);
+
+    /* -- BOTTOM FIELD -- */
+    /* -- Bottom field initialization -- */
+    
+    TComPic* pcBottomField;
+    xGetNewPicBuffer( pcBottomField );
+    pcBottomField->getPicSym()->allocSaoParam(&m_cEncSAO);
+    pcBottomField->setReconMark (false);
+   
+    pcBottomField->getSlice(0)->setPOC( m_iPOCLast);
+    pcBottomField->getPicYuvRec()->setBorderExtension(false);
+    pcBottomField->setTopField(!isTff);
+    
+    nHeight = pcPicYuvOrg->getHeight();
+    nWidth = pcPicYuvOrg->getWidth();
+    nStride = pcPicYuvOrg->getStride();
+    nPadLuma = pcPicYuvOrg->getLumaMargin();
+    nPadChroma = pcPicYuvOrg->getChromaMargin();
+    
+    // Get pointers
+    PicBufY = pcPicYuvOrg->getBufY();
+    PicBufU = pcPicYuvOrg->getBufU();
+    PicBufV = pcPicYuvOrg->getBufV();
+    
+    Pel * pcBottomFieldY =  pcBottomField->getPicYuvOrg()->getLumaAddr();
+    Pel * pcBottomFieldU =  pcBottomField->getPicYuvOrg()->getCbAddr();
+    Pel * pcBottomFieldV =  pcBottomField->getPicYuvOrg()->getCrAddr();
+    
+    // Compute image characteristics
+    if ( getUseAdaptiveQP() )
+    {
+      m_cPreanalyzer.xPreanalyze( dynamic_cast<TEncPic*>( pcBottomField ) );
+    }
+    
+    /* -- Defield -- */
+    
+    isTop = !isTff;
+    
+    separateFields(PicBufY + nPadLuma + nStride*nPadLuma, pcBottomFieldY, nStride, nWidth, nHeight, isTop);
+    separateFields(PicBufU + nPadChroma + (nStride >> 1)*nPadChroma, pcBottomFieldU, nStride >> 1, nWidth >> 1, nHeight >> 1, isTop);
+    separateFields(PicBufV + nPadChroma + (nStride >> 1)*nPadChroma, pcBottomFieldV, nStride >> 1, nWidth >> 1, nHeight >> 1, isTop);
+    
+  }
+}
+
+Void TEncTop::encode( TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int iPicIdInGOP, Bool isTff )
+{
+  // compress GOP
+  if (m_iPOCLast == 0) // compress field 0
+  {
+    m_cGOPEncoder.compressGOP(iPicIdInGOP, m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, true, isTff);
+  }
+
+  if (pcPicYuvOrg)
+  {
+    TComPicYuv* rpcPicYuvRec = new TComPicYuv;
+    if ( rcListPicYuvRecOut.size() == (UInt)m_iGOPSize )
+    {
+      rpcPicYuvRec = rcListPicYuvRecOut.popFront();
+    }
+    else
+    {
+      rpcPicYuvRec->create( m_iSourceWidth, m_iSourceHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+    }
+    rcListPicYuvRecOut.pushBack( rpcPicYuvRec );
+  }
+  
+  // compress GOP
+  m_cGOPEncoder.compressGOP(iPicIdInGOP, m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, true, isTff);
+
+  m_uiNumAllPicCoded ++;
+}
+#else
+Void TEncTop::encode(Bool flush, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded, Bool isTff)
+{
+  /* -- TOP FIELD -- */
+  
+  if (pcPicYuvOrg)
+  {
+    
+    /* -- Top field initialization -- */
+    
+    TComPic *pcTopField;
+    xGetNewPicBuffer( pcTopField );
+    pcTopField->getPicSym()->allocSaoParam(&m_cEncSAO);
+    pcTopField->setReconMark (false);
+    
+    pcTopField->getSlice(0)->setPOC( m_iPOCLast );
+    pcTopField->getPicYuvRec()->setBorderExtension(false);
+    pcTopField->setTopField(isTff);
+    
+    Int nHeight = pcPicYuvOrg->getHeight();
+    Int nWidth = pcPicYuvOrg->getWidth();
+    Int nStride = pcPicYuvOrg->getStride();
+    Int nPadLuma = pcPicYuvOrg->getLumaMargin();
+    Int nPadChroma = pcPicYuvOrg->getChromaMargin();
+    
+    // Get pointers
+    Pel * PicBufY = pcPicYuvOrg->getBufY();
+    Pel * PicBufU = pcPicYuvOrg->getBufU();
+    Pel * PicBufV = pcPicYuvOrg->getBufV();
+    
+    Pel * pcTopFieldY =  pcTopField->getPicYuvOrg()->getLumaAddr();
+    Pel * pcTopFieldU =  pcTopField->getPicYuvOrg()->getCbAddr();
+    Pel * pcTopFieldV =  pcTopField->getPicYuvOrg()->getCrAddr();
+    
+    // compute image characteristics
+    if ( getUseAdaptiveQP() )
+    {
+      m_cPreanalyzer.xPreanalyze( dynamic_cast<TEncPic*>( pcTopField ) );
+    }
+    
+    /* -- Defield -- */
+    
+    Bool isTop = isTff;
+    
+    separateFields(PicBufY + nPadLuma + nStride*nPadLuma, pcTopFieldY, nStride, nWidth, nHeight, isTop);
+    separateFields(PicBufU + nPadChroma + (nStride >> 1)*nPadChroma, pcTopFieldU, nStride >> 1, nWidth >> 1, nHeight >> 1, isTop);
+    separateFields(PicBufV + nPadChroma + (nStride >> 1)*nPadChroma, pcTopFieldV, nStride >> 1, nWidth >> 1, nHeight >> 1, isTop);
+    
+  }
+  
+  if (m_iPOCLast == 0) // compress field 0
+  {
+    m_cGOPEncoder.compressGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, true, isTff);
+  }
+  
+  /* -- BOTTOM FIELD -- */
+  
+  if (pcPicYuvOrg)
+  {
+    
+    /* -- Bottom field initialization -- */
+    
+    TComPic* pcBottomField;
+    xGetNewPicBuffer( pcBottomField );
+    pcBottomField->getPicSym()->allocSaoParam(&m_cEncSAO);
+    pcBottomField->setReconMark (false);
+    
+    TComPicYuv* rpcPicYuvRec = new TComPicYuv;
+    if ( rcListPicYuvRecOut.size() == (UInt)m_iGOPSize )
+    {
+      rpcPicYuvRec = rcListPicYuvRecOut.popFront();
+    }
+    else
+    {
+      rpcPicYuvRec->create( m_iSourceWidth, m_iSourceHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+    }
+    rcListPicYuvRecOut.pushBack( rpcPicYuvRec );
+    
+    pcBottomField->getSlice(0)->setPOC( m_iPOCLast);
+    pcBottomField->getPicYuvRec()->setBorderExtension(false);
+    pcBottomField->setTopField(!isTff);
+    
+    int nHeight = pcPicYuvOrg->getHeight();
+    int nWidth = pcPicYuvOrg->getWidth();
+    int nStride = pcPicYuvOrg->getStride();
+    int nPadLuma = pcPicYuvOrg->getLumaMargin();
+    int nPadChroma = pcPicYuvOrg->getChromaMargin();
+    
+    // Get pointers
+    Pel * PicBufY = pcPicYuvOrg->getBufY();
+    Pel * PicBufU = pcPicYuvOrg->getBufU();
+    Pel * PicBufV = pcPicYuvOrg->getBufV();
+    
+    Pel * pcBottomFieldY =  pcBottomField->getPicYuvOrg()->getLumaAddr();
+    Pel * pcBottomFieldU =  pcBottomField->getPicYuvOrg()->getCbAddr();
+    Pel * pcBottomFieldV =  pcBottomField->getPicYuvOrg()->getCrAddr();
+    
+    // Compute image characteristics
+    if ( getUseAdaptiveQP() )
+    {
+      m_cPreanalyzer.xPreanalyze( dynamic_cast<TEncPic*>( pcBottomField ) );
+    }
+    
+    /* -- Defield -- */
+    
+    Bool isTop = !isTff;
+    
+    separateFields(PicBufY + nPadLuma + nStride*nPadLuma, pcBottomFieldY, nStride, nWidth, nHeight, isTop);
+    separateFields(PicBufU + nPadChroma + (nStride >> 1)*nPadChroma, pcBottomFieldU, nStride >> 1, nWidth >> 1, nHeight >> 1, isTop);
+    separateFields(PicBufV + nPadChroma + (nStride >> 1)*nPadChroma, pcBottomFieldV, nStride >> 1, nWidth >> 1, nHeight >> 1, isTop);
+    
+  }
+  
+  if ( ( !(m_iNumPicRcvd) || (!flush && m_iPOCLast != 1 && m_iNumPicRcvd != m_iGOPSize && m_iGOPSize)) )
+  {
+    iNumEncoded = 0;
+    return;
+  }
+  
+  // compress GOP
+  m_cGOPEncoder.compressGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, true, isTff);
+  
+  iNumEncoded = m_iNumPicRcvd;
+  m_iNumPicRcvd = 0;
   m_uiNumAllPicCoded += iNumEncoded;
 }
@@ -911,9 +1179,9 @@
 
 //Function for initializing m_RPSList, a list of TComReferencePictureSet, based on the GOPEntry objects read from the config file.
-Void TEncTop::xInitRPS()
+Void TEncTop::xInitRPS(Bool isFieldCoding)
 {
   TComReferencePictureSet*      rps;
   
-  m_cSPS.createRPSList(getGOPSize()+m_extraRPSs);
+  m_cSPS.createRPSList(getGOPSize()+m_extraRPSs+1);
   TComRPSList* rpsList = m_cSPS.getRPSList();
 
@@ -1016,5 +1284,5 @@
         printf("Warning: number of negative pictures in RPS is different between intra and inter RPS specified in the config file.\n");
         rps->setNumberOfNegativePictures(numNeg);
-        rps->setNumberOfPositivePictures(numNeg+numPos);
+        rps->setNumberOfPictures(numNeg+numPos);
       }
       if (numPos != rps->getNumberOfPositivePictures())
@@ -1022,5 +1290,5 @@
         printf("Warning: number of positive pictures in RPS is different between intra and inter RPS specified in the config file.\n");
         rps->setNumberOfPositivePictures(numPos);
-        rps->setNumberOfPositivePictures(numNeg+numPos);
+        rps->setNumberOfPictures(numNeg+numPos);
       }
       RPSTemp.setNumberOfPictures(numNeg+numPos);
@@ -1086,5 +1354,21 @@
 #endif //INTER_RPS_AUTO
   }
-  
+  //In case of field coding, we need to set special parameters for the first bottom field of the sequence, since it is not specified in the cfg file. 
+  //The position = GOPSize + extraRPSs which is (a priori) unused is reserved for this field in the RPS. 
+  if (isFieldCoding) 
+  {
+    rps = rpsList->getReferencePictureSet(getGOPSize()+m_extraRPSs);
+    rps->setNumberOfPictures(1);
+    rps->setNumberOfNegativePictures(1);
+    rps->setNumberOfPositivePictures(0);
+    rps->setNumberOfLongtermPictures(0);
+    rps->setDeltaPOC(0,-1);
+    rps->setPOC(0,0);
+    rps->setUsed(0,true);
+    rps->setInterRPSPrediction(false);
+    rps->setDeltaRIdxMinus1(0);
+    rps->setDeltaRPS(0);
+    rps->setNumRefIdc(0);
+}
 }
 
@@ -1095,5 +1379,4 @@
 {
   slice->setRPSidx(GOPid);
-
   for(Int extraNum=m_iGOPSize; extraNum<m_extraRPSs+m_iGOPSize; extraNum++)
   {    
@@ -1119,7 +1402,11 @@
   }
 
+  if(POCCurr == 1 && slice->getPic()->isField())
+  {
+    slice->setRPSidx(m_iGOPSize+m_extraRPSs);
+  }
+
   slice->setRPS(getSPS()->getRPSList()->getReferencePictureSet(slice->getRPSidx()));
   slice->getRPS()->setNumberOfPictures(slice->getRPS()->getNumberOfNegativePictures()+slice->getRPS()->getNumberOfPositivePictures());
-
 }
 
Index: branches/SHM-3.1-dev/source/Lib/TLibEncoder/TEncTop.h
===================================================================
--- branches/SHM-3.1-dev/source/Lib/TLibEncoder/TEncTop.h	(revision 430)
+++ branches/SHM-3.1-dev/source/Lib/TLibEncoder/TEncTop.h	(revision 431)
@@ -144,7 +144,7 @@
   Window                  m_scaledRefLayerWindow[MAX_LAYERS];
 #endif
-#endif
 #if POC_RESET_FLAG
   Int                     m_pocAdjustmentValue;
+#endif
 #endif
 protected:
@@ -154,5 +154,5 @@
   
   Void  xInitPPSforTiles  ();
-  Void  xInitRPS          ();                             ///< initialize PPS from encoder options
+  Void  xInitRPS          (Bool isFieldCoding);           ///< initialize PPS from encoder options
 #if SVC_EXTENSION
   Void xInitILRP();
@@ -164,5 +164,5 @@
   Void      create          ();
   Void      destroy         ();
-  Void      init            ();
+  Void      init            (Bool isFieldCoding);
   Void      deletePicBuffer ();
 
@@ -209,9 +209,9 @@
   Int                     getNumPicRcvd         () { return m_iNumPicRcvd;            }
   Void                    setNumPicRcvd         ( Int num ) { m_iNumPicRcvd = num;      }
-#endif
 #if SCALED_REF_LAYER_OFFSETS
   Void                    setNumScaledRefLayerOffsets(Int x) { m_numScaledRefLayerOffsets = x; }
   UInt                    getNumScaledRefLayerOffsets() { return m_numScaledRefLayerOffsets; }
   Window&  getScaledRefLayerWindow(Int x)            { return m_scaledRefLayerWindow[x]; }
+#endif
 #endif
 
@@ -236,19 +236,25 @@
   fstream*  getBLSyntaxFile() { return m_pBLSyntaxFile; }
 #endif
-  Void      encode( TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int iPicIdInGOP  );
+  Void      encode( TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int iPicIdInGOP );
   Void      encodePrep( TComPicYuv* pcPicYuvOrg );
+  Void      encode( TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int iPicIdInGOP, Bool isTff );
+  Void      encodePrep( TComPicYuv* pcPicYuvOrg, Bool isTff );
 #if VPS_EXTN_DIRECT_REF_LAYERS
   TEncTop*  getRefLayerEnc(UInt refLayerIdc);
 #endif
-#else
-  Void encode( Bool bEos, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut,
-              std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded );  
-#endif
-
-  void printSummary() { m_cGOPEncoder.printOutSummary (m_uiNumAllPicCoded); }
 #if POC_RESET_FLAG
   Int  getPocAdjustmentValue()      { return m_pocAdjustmentValue;}
   Void setPocAdjustmentValue(Int x) { m_pocAdjustmentValue = x;   }
 #endif
+#else //SVC_EXTENSION
+  Void encode( Bool bEos, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut,
+              std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded );
+
+  /// encode several number of pictures until end-of-sequence
+  Void encode( bool bEos, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut,
+              std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded, Bool isTff);
+
+  Void printSummary(Bool isField) { m_cGOPEncoder.printOutSummary (m_uiNumAllPicCoded, isField); }
+#endif //#if SVC_EXTENSION
 };
 
Index: branches/SHM-3.1-dev/source/Lib/TLibVideoIO/TVideoIOYuv.cpp
===================================================================
--- branches/SHM-3.1-dev/source/Lib/TLibVideoIO/TVideoIOYuv.cpp	(revision 430)
+++ branches/SHM-3.1-dev/source/Lib/TLibVideoIO/TVideoIOYuv.cpp	(revision 431)
@@ -339,4 +339,44 @@
 }
 
+static Bool writeField(ostream& fd, Pel* top, Pel* bottom, Bool is16bit,
+                       UInt stride,
+                       UInt width, UInt height, bool isTff)
+{
+  Int write_len = width * (is16bit ? 2 : 1)*2;
+  UChar *buf = new UChar[write_len];
+  for (Int y = 0; y < height; y++)
+  {
+    if (!is16bit)
+    {
+      for (Int x = 0; x < width; x++)
+      {
+        buf[x] = isTff ? (UChar) top[x] : (UChar) bottom[x];
+        buf[width+x] = isTff ? (UChar) bottom[x] : (UChar) top[x];
+      }
+    }
+    else
+    {
+      for (Int x = 0; x < width; x++)
+      {
+        buf[2*x] = isTff ? top[x] & 0xff : bottom[x] & 0xff;
+        buf[2*x+1] = isTff ? (top[x] >> 8) & 0xff : (bottom[x] >> 8) & 0xff;
+        
+        buf[width+2*x] = isTff ? bottom[x] & 0xff : top[x] & 0xff;
+        buf[width+2*x+1] = isTff ? (bottom[x] >> 8) & 0xff : (top[x] >> 8) & 0xff;
+      }
+    }
+    
+    fd.write(reinterpret_cast<Char*>(buf), write_len);
+    if (fd.eof() || fd.fail() )
+    {
+      delete[] buf;
+      return false;
+    }
+    top += stride;
+    bottom += stride;
+  }
+  delete[] buf;
+  return true;
+}
 /**
  * Read one Y'CbCr frame, performing any required input scaling to change
@@ -501,2 +541,108 @@
 }
 
+
+/**
+ * Write one Y'CbCr frame. No bit-depth conversion is performed, pcPicYuv is
+ * assumed to be at TVideoIO::m_fileBitdepth depth.
+ *
+ * @param pPicTop     input top field YUV buffer class pointer
+ * @param pPicBottom  input bottom field YUV buffer class pointer
+ * @param aiPad       source padding size, aiPad[0] = horizontal, aiPad[1] = vertical
+ * @return true for success, false in case of error
+ */
+Bool TVideoIOYuv::write( TComPicYuv* pPicTop, TComPicYuv* pPicBottom, Int cropLeft, Int cropRight, Int cropTop, Int cropBottom , bool isTff)
+{
+  // compute actual YUV frame size excluding padding size
+  Int   iStride = pPicTop->getStride();
+  UInt  width  = pPicTop->getWidth()  - cropLeft - cropRight;
+  UInt  height = pPicTop->getHeight() - cropTop  - cropBottom;
+  Bool is16bit = m_fileBitDepthY > 8 || m_fileBitDepthC > 8;
+  
+  TComPicYuv *dstPicTop = NULL;
+  TComPicYuv *dstPicBottom = NULL;
+  
+  Bool retval = true;
+  
+  if (m_bitDepthShiftY != 0 || m_bitDepthShiftC != 0)
+  {
+    dstPicTop = new TComPicYuv;
+    dstPicTop->create( pPicTop->getWidth(), pPicTop->getHeight(), 1, 1, 0 );
+    pPicTop->copyToPic(dstPicTop);
+    
+    dstPicBottom = new TComPicYuv;
+    dstPicBottom->create( pPicBottom->getWidth(), pPicBottom->getHeight(), 1, 1, 0 );
+    pPicBottom->copyToPic(dstPicBottom);
+    
+    Pel minvalY = 0;
+    Pel minvalC = 0;
+    Pel maxvalY = (1 << m_fileBitDepthY) - 1;
+    Pel maxvalC = (1 << m_fileBitDepthC) - 1;
+#if CLIP_TO_709_RANGE
+    if (-m_bitDepthShiftY < 0 && m_fileBitDepthY >= 8)
+    {
+      /* ITU-R BT.709 compliant clipping for converting say 10b to 8b */
+      minvalY = 1 << (m_fileBitDepthY - 8);
+      maxvalY = (0xff << (m_fileBitDepthY - 8)) -1;
+    }
+    if (-m_bitDepthShiftC < 0 && m_fileBitDepthC >= 8)
+    {
+      /* ITU-R BT.709 compliant clipping for converting say 10b to 8b */
+      minvalC = 1 << (m_fileBitDepthC - 8);
+      maxvalC = (0xff << (m_fileBitDepthC - 8)) -1;
+    }
+#endif
+    scalePlane(dstPicTop->getLumaAddr(), dstPicTop->getStride(), dstPicTop->getWidth(), dstPicTop->getHeight(), -m_bitDepthShiftY, minvalY, maxvalY);
+    scalePlane(dstPicTop->getCbAddr(), dstPicTop->getCStride(), dstPicTop->getWidth()>>1, dstPicTop->getHeight()>>1, -m_bitDepthShiftC, minvalC, maxvalC);
+    scalePlane(dstPicTop->getCrAddr(), dstPicTop->getCStride(), dstPicTop->getWidth()>>1, dstPicTop->getHeight()>>1, -m_bitDepthShiftC, minvalC, maxvalC);
+    
+    scalePlane(dstPicBottom->getLumaAddr(), dstPicBottom->getStride(), dstPicBottom->getWidth(), dstPicBottom->getHeight(), -m_bitDepthShiftY, minvalY, maxvalY);
+    scalePlane(dstPicBottom->getCbAddr(), dstPicBottom->getCStride(), dstPicBottom->getWidth()>>1, dstPicBottom->getHeight()>>1, -m_bitDepthShiftC, minvalC, maxvalC);
+    scalePlane(dstPicBottom->getCrAddr(), dstPicBottom->getCStride(), dstPicBottom->getWidth()>>1, dstPicBottom->getHeight()>>1, -m_bitDepthShiftC, minvalC, maxvalC);
+  }
+  else
+  {
+    dstPicTop = pPicTop;
+    dstPicBottom = pPicBottom;
+  }
+  // location of upper left pel in a plane
+  Int planeOffset = 0; //cropLeft + cropTop * iStride;
+  //Write luma
+  if (! writeField(m_cHandle, dstPicTop->getLumaAddr() + planeOffset,  dstPicBottom->getLumaAddr() + planeOffset, is16bit, iStride, width, height, isTff))
+  {
+    retval=false;
+    goto exit;
+  }
+  
+  width >>= 1;
+  height >>= 1;
+  iStride >>= 1;
+  cropLeft >>= 1;
+  cropRight >>= 1;
+  
+  planeOffset = 0; // cropLeft + cropTop * iStride;
+  
+  //Write chroma U
+  if (! writeField(m_cHandle, dstPicTop->getCbAddr() + planeOffset, dstPicBottom->getCbAddr() + planeOffset, is16bit, iStride, width, height, isTff))
+  {
+    retval=false;
+    goto exit;
+  }
+  
+  //Write chroma V
+  if (! writeField(m_cHandle, dstPicTop->getCrAddr() + planeOffset, dstPicBottom->getCrAddr() + planeOffset, is16bit, iStride, width, height, isTff))
+    
+  {
+    retval=false;
+    goto exit;
+  }
+  
+exit:
+  if (m_bitDepthShiftY != 0 || m_bitDepthShiftC != 0)
+  {
+    dstPicTop->destroy();
+    delete dstPicTop;
+    dstPicBottom->destroy();
+    delete dstPicBottom;
+  }  
+  return retval;
+}
Index: branches/SHM-3.1-dev/source/Lib/TLibVideoIO/TVideoIOYuv.h
===================================================================
--- branches/SHM-3.1-dev/source/Lib/TLibVideoIO/TVideoIOYuv.h	(revision 430)
+++ branches/SHM-3.1-dev/source/Lib/TLibVideoIO/TVideoIOYuv.h	(revision 431)
@@ -72,4 +72,5 @@
   Bool  read  ( TComPicYuv*   pPicYuv, Int aiPad[2] );     ///< read  one YUV frame with padding parameter
   Bool  write( TComPicYuv*    pPicYuv, Int confLeft=0, Int confRight=0, Int confTop=0, Int confBottom=0 );
+  Bool  write( TComPicYuv*    pPicYuv, TComPicYuv*    pPicYuv2, Int confLeft=0, Int confRight=0, Int confTop=0, Int confBottom=0  , bool isTff=false); 
   
   Bool  isEof ();                                           ///< check for end-of-file
