Index: /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/encoder_intra_main.cfg
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/encoder_intra_main.cfg	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/encoder_intra_main.cfg	(revision 651)
@@ -3,7 +3,6 @@
 ReconFile                     : rec.yuv
 
-#======== Profile/Level ================
+#======== Profile ================
 Profile                       : main
-Level                         : 6.2
 
 #======== Unit definition ================
Index: /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/encoder_intra_main10.cfg
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/encoder_intra_main10.cfg	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/encoder_intra_main10.cfg	(revision 651)
@@ -3,7 +3,6 @@
 ReconFile                     : rec.yuv
 
-#======== Profile/Level ================
+#======== Profile ================
 Profile                       : main10
-Level                         : 6.2
 
 #======== Unit definition ================
Index: /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/encoder_lowdelay_P_main.cfg
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/encoder_lowdelay_P_main.cfg	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/encoder_lowdelay_P_main.cfg	(revision 651)
@@ -3,7 +3,6 @@
 ReconFile                     : rec.yuv
 
-#======== Profile/Level ================
+#======== Profile ================
 Profile                       : main
-Level                         : 6.2
 
 #======== Unit definition ================
Index: /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/encoder_lowdelay_P_main10.cfg
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/encoder_lowdelay_P_main10.cfg	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/encoder_lowdelay_P_main10.cfg	(revision 651)
@@ -3,7 +3,6 @@
 ReconFile                     : rec.yuv
 
-#======== Profile/Level ================
+#======== Profile ================
 Profile                       : main10
-Level                         : 6.2
 
 #======== Unit definition ================
Index: /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/encoder_lowdelay_main.cfg
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/encoder_lowdelay_main.cfg	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/encoder_lowdelay_main.cfg	(revision 651)
@@ -3,7 +3,6 @@
 ReconFile                     : rec.yuv
 
-#======== Profile/Level ================
+#======== Profile ================
 Profile                       : main
-Level                         : 6.2
 
 #======== Unit definition ================
Index: /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/encoder_lowdelay_main10.cfg
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/encoder_lowdelay_main10.cfg	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/encoder_lowdelay_main10.cfg	(revision 651)
@@ -3,7 +3,6 @@
 ReconFile                     : rec.yuv
 
-#======== Profile/Level ================
+#======== Profile ================
 Profile                       : main10
-Level                         : 6.2
 
 #======== Unit definition ================
Index: /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/encoder_randomaccess_main.cfg
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/encoder_randomaccess_main.cfg	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/encoder_randomaccess_main.cfg	(revision 651)
@@ -3,7 +3,6 @@
 ReconFile                     : rec.yuv
 
-#======== Profile/Level ================
+#======== Profile ================
 Profile                       : main
-Level                         : 6.2
 
 #======== Unit definition ================
Index: /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/encoder_randomaccess_main10.cfg
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/encoder_randomaccess_main10.cfg	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/encoder_randomaccess_main10.cfg	(revision 651)
@@ -3,7 +3,6 @@
 ReconFile                     : rec.yuv
 
-#======== Profile/Level ================
+#======== Profile ================
 Profile                       : main10
-Level                         : 6.2
 
 #======== Unit definition ================
Index: /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/BQMall.cfg
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/BQMall.cfg	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/BQMall.cfg	(revision 651)
@@ -7,2 +7,4 @@
 SourceHeight                  : 480         # Input  frame height
 FramesToBeEncoded              : 600         # Number of frames to be coded
+
+Level                         : 3.1
Index: /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/BQSquare.cfg
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/BQSquare.cfg	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/BQSquare.cfg	(revision 651)
@@ -7,2 +7,4 @@
 SourceHeight                  : 240         # Input  frame height
 FramesToBeEncoded              : 600         # Number of frames to be coded
+
+Level                         : 2.1
Index: /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/BQTerrace.cfg
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/BQTerrace.cfg	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/BQTerrace.cfg	(revision 651)
@@ -7,2 +7,4 @@
 SourceHeight                  : 1080        # Input  frame height
 FramesToBeEncoded              : 600         # Number of frames to be coded
+
+Level                         : 4.1
Index: /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/BasketballDrill.cfg
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/BasketballDrill.cfg	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/BasketballDrill.cfg	(revision 651)
@@ -7,2 +7,4 @@
 SourceHeight                  : 480         # Input  frame height
 FramesToBeEncoded              : 500         # Number of frames to be coded
+
+Level                         : 3.1
Index: /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/BasketballDrillText.cfg
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/BasketballDrillText.cfg	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/BasketballDrillText.cfg	(revision 651)
@@ -7,2 +7,4 @@
 SourceHeight                  : 480         # Input  frame height
 FramesToBeEncoded              : 500         # Number of frames to be coded
+
+Level                         : 3.1
Index: /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/BasketballDrive.cfg
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/BasketballDrive.cfg	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/BasketballDrive.cfg	(revision 651)
@@ -7,2 +7,4 @@
 SourceHeight                  : 1080        # Input  frame height
 FramesToBeEncoded              : 500         # Number of frames to be coded
+
+Level                         : 4.1
Index: /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/BasketballPass.cfg
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/BasketballPass.cfg	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/BasketballPass.cfg	(revision 651)
@@ -7,2 +7,4 @@
 SourceHeight                  : 240         # Input  frame height
 FramesToBeEncoded              : 500         # Number of frames to be coded
+
+Level                         : 2.1
Index: /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/BlowingBubbles.cfg
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/BlowingBubbles.cfg	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/BlowingBubbles.cfg	(revision 651)
@@ -7,2 +7,4 @@
 SourceHeight                  : 240         # Input  frame height
 FramesToBeEncoded              : 500         # Number of frames to be coded
+
+Level                         : 2.1
Index: /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/Cactus.cfg
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/Cactus.cfg	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/Cactus.cfg	(revision 651)
@@ -7,2 +7,4 @@
 SourceHeight                  : 1080        # Input  frame height
 FramesToBeEncoded              : 500         # Number of frames to be coded
+
+Level                         : 4.1
Index: /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/ChinaSpeed.cfg
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/ChinaSpeed.cfg	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/ChinaSpeed.cfg	(revision 651)
@@ -7,2 +7,4 @@
 SourceHeight                  : 768         # Input  frame height
 FramesToBeEncoded              : 500         # Number of frames to be coded
+
+Level                         : 3.1
Index: /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/FourPeople.cfg
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/FourPeople.cfg	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/FourPeople.cfg	(revision 651)
@@ -7,2 +7,4 @@
 SourceHeight                  : 720         # Input  frame height
 FramesToBeEncoded              : 600         # Number of frames to be coded
+
+Level                         : 4
Index: /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/Johnny.cfg
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/Johnny.cfg	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/Johnny.cfg	(revision 651)
@@ -7,2 +7,4 @@
 SourceHeight                  : 720         # Input  frame height
 FramesToBeEncoded              : 600         # Number of frames to be coded
+
+Level                         : 4
Index: /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/Kimono.cfg
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/Kimono.cfg	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/Kimono.cfg	(revision 651)
@@ -7,2 +7,4 @@
 SourceHeight                  : 1080        # Input  frame height
 FramesToBeEncoded              : 240         # Number of frames to be coded
+
+Level                         : 4.0
Index: /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/KristenAndSara.cfg
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/KristenAndSara.cfg	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/KristenAndSara.cfg	(revision 651)
@@ -7,2 +7,4 @@
 SourceHeight                  : 720         # Input  frame height
 FramesToBeEncoded              : 600         # Number of frames to be coded
+
+Level                         : 4
Index: /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/NebutaFestival_10bit.cfg
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/NebutaFestival_10bit.cfg	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/NebutaFestival_10bit.cfg	(revision 651)
@@ -7,2 +7,4 @@
 SourceHeight                  : 1600        # Input  frame height
 FramesToBeEncoded              : 300         # Number of frames to be coded
+
+Level                         : 5
Index: /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/ParkScene.cfg
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/ParkScene.cfg	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/ParkScene.cfg	(revision 651)
@@ -7,2 +7,4 @@
 SourceHeight                  : 1080        # Input  frame height
 FramesToBeEncoded              : 240         # Number of frames to be coded
+
+Level                         : 4.0
Index: /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/PartyScene.cfg
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/PartyScene.cfg	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/PartyScene.cfg	(revision 651)
@@ -7,2 +7,4 @@
 SourceHeight                  : 480         # Input  frame height
 FramesToBeEncoded              : 500         # Number of frames to be coded
+
+Level                         : 3.1
Index: /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/PeopleOnStreet.cfg
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/PeopleOnStreet.cfg	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/PeopleOnStreet.cfg	(revision 651)
@@ -7,2 +7,4 @@
 SourceHeight                  : 1600        # Input  frame height
 FramesToBeEncoded              : 150         # Number of frames to be coded
+
+Level                         : 5
Index: /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/RaceHorses.cfg
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/RaceHorses.cfg	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/RaceHorses.cfg	(revision 651)
@@ -7,2 +7,4 @@
 SourceHeight                  : 240         # Input  frame height
 FramesToBeEncoded              : 300         # Number of frames to be coded
+
+Level                         : 2
Index: /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/RaceHorsesC.cfg
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/RaceHorsesC.cfg	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/RaceHorsesC.cfg	(revision 651)
@@ -7,2 +7,4 @@
 SourceHeight                  : 480         # Input  frame height
 FramesToBeEncoded              : 300         # Number of frames to be coded
+
+Level                         : 3
Index: /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/SlideEditing.cfg
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/SlideEditing.cfg	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/SlideEditing.cfg	(revision 651)
@@ -7,2 +7,4 @@
 SourceHeight                  : 720         # Input  frame height
 FramesToBeEncoded              : 300         # Number of frames to be coded
+
+Level                         : 3.1
Index: /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/SlideShow.cfg
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/SlideShow.cfg	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/SlideShow.cfg	(revision 651)
@@ -7,2 +7,4 @@
 SourceHeight                  : 720         # Input  frame height
 FramesToBeEncoded              : 500         # Number of frames to be coded
+
+Level                         : 3.1
Index: /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/SteamLocomotiveTrain_10bit.cfg
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/SteamLocomotiveTrain_10bit.cfg	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/SteamLocomotiveTrain_10bit.cfg	(revision 651)
@@ -7,2 +7,4 @@
 SourceHeight                  : 1600        # Input  frame height
 FramesToBeEncoded              : 300         # Number of frames to be coded
+
+Level                         : 5
Index: /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/Traffic.cfg
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/Traffic.cfg	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/Traffic.cfg	(revision 651)
@@ -7,2 +7,4 @@
 SourceHeight                  : 1600        # Input  frame height
 FramesToBeEncoded              : 150         # Number of frames to be coded
+
+Level                         : 5
Index: /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/Vidyo1.cfg
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/Vidyo1.cfg	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/Vidyo1.cfg	(revision 651)
@@ -7,2 +7,4 @@
 SourceHeight                  : 720         # Input  frame height
 FramesToBeEncoded              : 600         # Number of frames to be coded
+
+Level                         : 4
Index: /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/Vidyo3.cfg
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/Vidyo3.cfg	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/Vidyo3.cfg	(revision 651)
@@ -7,2 +7,4 @@
 SourceHeight                  : 720         # Input  frame height
 FramesToBeEncoded              : 600         # Number of frames to be coded
+
+Level                         : 4
Index: /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/Vidyo4.cfg
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/Vidyo4.cfg	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/cfg/HEVC/HM/per-sequence/Vidyo4.cfg	(revision 651)
@@ -7,2 +7,4 @@
 SourceHeight                  : 720         # Input  frame height
 FramesToBeEncoded              : 600         # Number of frames to be coded
+
+Level                         : 4
Index: /branches/HTM-8.2-dev0-Cleanup/source/App/TAppDecoder/TAppDecTop.cpp
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/source/App/TAppDecoder/TAppDecTop.cpp	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/source/App/TAppDecoder/TAppDecTop.cpp	(revision 651)
@@ -60,5 +60,4 @@
 #endif
 {
-  ::memset (m_abDecFlag, 0, sizeof (m_abDecFlag));
 #if H_MV
   for (Int i = 0; i < MAX_NUM_LAYER_IDS; i++) m_layerIdToDecIdx[i] = -1; 
@@ -148,5 +147,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)
 #else
 #if H_3D
@@ -176,8 +175,4 @@
 #endif
     AnnexBStats stats = AnnexBStats();
-#if !H_MV
-    Bool bPreviousPictureDecoded = false;
-#endif
-
     vector<uint8_t> nalUnit;
     InputNALUnit nalu;
@@ -246,18 +241,8 @@
 #endif
         }
-
-        
 #else
       if( (m_iMaxTemporalLayer >= 0 && nalu.m_temporalId > m_iMaxTemporalLayer) || !isNaluWithinTargetDecLayerIdSet(&nalu)  )
       {
-        if(bPreviousPictureDecoded)
-        {
-          bNewPicture = true;
-          bPreviousPictureDecoded = false;
-        }
-        else
-        {
-          bNewPicture = false;
-        }
+        bNewPicture = false;
       }
       else
@@ -290,7 +275,4 @@
 #endif
         }
-#if !H_MV
-        bPreviousPictureDecoded = true; 
-#endif
       }
     }
@@ -321,5 +303,5 @@
       if ( m_pchReconFiles[decIdxLastPic] && !m_reconOpen[decIdxLastPic] )
 #else
-      if ( m_pchReconFile && !recon_opened )
+      if ( m_pchReconFile && !openedReconFile  )
 #endif
       {
@@ -334,5 +316,5 @@
 #else
         m_cTVideoIOYuvReconFile.open( m_pchReconFile, true, m_outputBitDepthY, m_outputBitDepthC, g_bitDepthY, g_bitDepthC ); // write mode
-        recon_opened = true;
+        openedReconFile  = true;
       }
       if ( bNewPicture && 
@@ -462,41 +444,136 @@
 {
   TComList<TComPic*>::iterator iterPic   = pcListPic->begin();
-  Int not_displayed = 0;
-
-  while (iterPic != pcListPic->end())
-  {
-    TComPic* pcPic = *(iterPic);
-#if H_MV
-    if(pcPic->getOutputMark() && pcPic->getPOC() > m_pocLastDisplay[decIdx])
-#else
-    if(pcPic->getOutputMark() && pcPic->getPOC() > m_iPOCLastDisplay)
-#endif
-    {
-       not_displayed++;
-    }
-    iterPic++;
-  }
-  iterPic   = pcListPic->begin();
+  Int numPicsNotYetDisplayed = 0;
   
   while (iterPic != pcListPic->end())
   {
     TComPic* pcPic = *(iterPic);
-    
-#if H_MV
-    if ( pcPic->getOutputMark() && (not_displayed >  pcPic->getNumReorderPics(tId) && pcPic->getPOC() > m_pocLastDisplay[decIdx]))
-#else
-    if ( pcPic->getOutputMark() && (not_displayed >  pcPic->getNumReorderPics(tId) && pcPic->getPOC() > m_iPOCLastDisplay))
-#endif
-    {
-      // write to file
-       not_displayed--;
+#if H_MV
+    if(pcPic->getOutputMark() && pcPic->getPOC() > m_pocLastDisplay[decIdx])
+#else
+    if(pcPic->getOutputMark() && pcPic->getPOC() > m_iPOCLastDisplay)
+#endif
+    {
+      numPicsNotYetDisplayed++;
+    }
+    iterPic++;
+  }
+  iterPic   = pcListPic->begin();
+  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 H_MV
+      if ( pcPicTop->getOutputMark() && (numPicsNotYetDisplayed >  pcPicTop->getNumReorderPics(tId) && !(pcPicTop->getPOC()%2) && pcPicBottom->getPOC() == pcPicTop->getPOC()+1)
+          && pcPicBottom->getOutputMark() && (numPicsNotYetDisplayed >  pcPicBottom->getNumReorderPics(tId) && (pcPicTop->getPOC() == m_pocLastDisplay[decIdx]+1 || m_pocLastDisplay[decIdx]<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 H_MV
       if ( m_pchReconFiles[decIdx] )
 #else
-      if ( m_pchReconFile )
-#endif
-      {
-        const Window &conf = pcPic->getConformanceWindow();
-        const Window &defDisp = m_respectDefDispWindow ? pcPic->getDefDisplayWindow() : Window();
+        if ( m_pchReconFile )
+#endif
+        {
+          const Window &conf = pcPicTop->getConformanceWindow();
+          const Window &defDisp = m_respectDefDispWindow ? pcPicTop->getDefDisplayWindow() : Window();
+
+          const Bool isTff = pcPicTop->isTopField();
+#if H_MV
+        assert( conf   .getScaledFlag() );
+        assert( defDisp.getScaledFlag() );
+        m_tVideoIOYuvReconFile[decIdx]->write( pcPicTop->getPicYuvRec(), pcPicBottom->getPicYuvRec(),
+#else
+          m_cTVideoIOYuvReconFile.write( pcPicTop->getPicYuvRec(), pcPicBottom->getPicYuvRec(),
+#endif
+                                        conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(),
+                                        conf.getWindowRightOffset() + defDisp.getWindowRightOffset(),
+                                        conf.getWindowTopOffset() + defDisp.getWindowTopOffset(),
+                                        conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset(), isTff );
+        }
+        
+        // update POC of display order
+#if H_MV
+        m_pocLastDisplay[decIdx] = pcPic->getPOC();
+#else
+        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 H_MV
+      if ( pcPic->getOutputMark() && (numPicsNotYetDisplayed >  pcPic->getNumReorderPics(tId) && pcPic->getPOC() > m_pocLastDisplay[decIdx]))
+#else      
+      if ( pcPic->getOutputMark() && (numPicsNotYetDisplayed >  pcPic->getNumReorderPics(tId) && pcPic->getPOC() > m_iPOCLastDisplay))
+#endif
+      {
+        // write to file
+        numPicsNotYetDisplayed--;
+#if H_MV
+      if ( m_pchReconFiles[decIdx] )
+#else
+        if ( m_pchReconFile )
+#endif
+        {
+          const Window &conf = pcPic->getConformanceWindow();
+          const Window &defDisp = m_respectDefDispWindow ? pcPic->getDefDisplayWindow() : Window();
 #if H_MV
         assert( conf   .getScaledFlag() );
@@ -504,42 +581,42 @@
         m_tVideoIOYuvReconFile[decIdx]->write( pcPic->getPicYuvRec(),
 #else
-        m_cTVideoIOYuvReconFile.write( pcPic->getPicYuvRec(),
-#endif
-                                       conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(),
-                                       conf.getWindowRightOffset() + defDisp.getWindowRightOffset(),
-                                       conf.getWindowTopOffset() + defDisp.getWindowTopOffset(),
-                                       conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset() );
+          m_cTVideoIOYuvReconFile.write( pcPic->getPicYuvRec(),
+#endif
+                                        conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(),
+                                        conf.getWindowRightOffset() + defDisp.getWindowRightOffset(),
+                                        conf.getWindowTopOffset() + defDisp.getWindowTopOffset(),
+                                        conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset() );
+        }
+        
+        // update POC of display order
+#if H_MV
+        m_pocLastDisplay[decIdx] = pcPic->getPOC();
+#else
+        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);
       }
       
-      // update POC of display order
-#if H_MV
-      m_pocLastDisplay[decIdx] = pcPic->getPOC();
-#else
-      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++;
-  }
-}
-
+      iterPic++;
+    }
+  }
+}
 /** \param pcListPic list of pictures to be written to file
     \todo            DYN_REF_FREE should be revised
@@ -554,24 +631,116 @@
   {
     return;
-  } 
+  }
   TComList<TComPic*>::iterator iterPic   = pcListPic->begin();
-
+  
   iterPic   = pcListPic->begin();
+  TComPic* pcPic = *(iterPic);
   
-  while (iterPic != pcListPic->end())
-  {
-    TComPic* pcPic = *(iterPic);
-
-    if ( pcPic->getOutputMark() )
-    {
-      // write to file
+  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 H_MV
       if ( m_pchReconFiles[decIdx] )
 #else
-      if ( m_pchReconFile )
-#endif
-      {
-        const Window &conf = pcPic->getConformanceWindow();
-        const Window &defDisp = m_respectDefDispWindow ? pcPic->getDefDisplayWindow() : Window();
+        if ( m_pchReconFile )
+#endif
+        {
+          const Window &conf = pcPicTop->getConformanceWindow();
+          const Window &defDisp = m_respectDefDispWindow ? pcPicTop->getDefDisplayWindow() : Window();
+          const Bool isTff = pcPicTop->isTopField();
+#if H_MV
+        assert( conf   .getScaledFlag() );
+        assert( defDisp.getScaledFlag() );
+        m_tVideoIOYuvReconFile[decIdx]->write( pcPicTop->getPicYuvRec(), pcPicBottom->getPicYuvRec(),
+#else
+          m_cTVideoIOYuvReconFile.write( pcPicTop->getPicYuvRec(), pcPicBottom->getPicYuvRec(),
+#endif
+                                        conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(),
+                                        conf.getWindowRightOffset() + defDisp.getWindowRightOffset(),
+                                        conf.getWindowTopOffset() + defDisp.getWindowTopOffset(),
+                                        conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset(), isTff );
+        }
+        
+        // update POC of display order
+#if H_MV
+      m_pocLastDisplay[decIdx] = pcPic->getPOC();
+#else
+      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);
+        
+#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 ( m_pchReconFile )
+        {
+          const Window &conf = pcPic->getConformanceWindow();
+          const Window &defDisp = m_respectDefDispWindow ? pcPic->getDefDisplayWindow() : Window();
 #if H_MV
         assert( conf   .getScaledFlag() );
@@ -579,48 +748,49 @@
         m_tVideoIOYuvReconFile[decIdx]->write( pcPic->getPicYuvRec(),
 #else
-        m_cTVideoIOYuvReconFile.write( pcPic->getPicYuvRec(),
-#endif
-                                       conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(),
-                                       conf.getWindowRightOffset() + defDisp.getWindowRightOffset(),
-                                       conf.getWindowTopOffset() + defDisp.getWindowTopOffset(),
-                                       conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset() );
-      }
-      
-      // update POC of display order
+          m_cTVideoIOYuvReconFile.write( pcPic->getPicYuvRec(),
+#endif
+                                        conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(),
+                                        conf.getWindowRightOffset() + defDisp.getWindowRightOffset(),
+                                        conf.getWindowTopOffset() + defDisp.getWindowTopOffset(),
+                                        conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset() );
+        }
+        
+        // update POC of display order
 #if H_MV
       m_pocLastDisplay[decIdx] = pcPic->getPOC();
 #else
-      m_iPOCLastDisplay = pcPic->getPOC();
-#endif
-      
-      // erase non-referenced picture in the reference picture list after display
-      if ( !pcPic->getSlice(0)->isReferenced() && pcPic->getReconMark() == true )
-      {
+        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);
-    }
+          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 !H_MV
 #if !DYN_REF_FREE
-    if(pcPic)
-    {
-      pcPic->destroy();
-      delete pcPic;
-      pcPic = NULL;
-    }
-#endif 
-#endif
-    iterPic++;
+      if(pcPic)
+      {
+        pcPic->destroy();
+        delete pcPic;
+        pcPic = NULL;
+      }
+#endif    
+#endif
+      iterPic++;
+    }
   }
 #if H_MV
Index: /branches/HTM-8.2-dev0-Cleanup/source/App/TAppDecoder/TAppDecTop.h
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/source/App/TAppDecoder/TAppDecTop.h	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/source/App/TAppDecoder/TAppDecTop.h	(revision 651)
@@ -72,5 +72,4 @@
 #endif
     // for output control
-  Bool                            m_abDecFlag[ MAX_GOP ];         ///< decoded flag in one GOP
 #if H_MV
   Int                             m_pocLastDisplay      [ MAX_NUM_LAYERS ]; ///< last POC in display order
Index: /branches/HTM-8.2-dev0-Cleanup/source/App/TAppEncoder/TAppEncCfg.cpp
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/source/App/TAppEncoder/TAppEncCfg.cpp	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/source/App/TAppEncoder/TAppEncCfg.cpp	(revision 651)
@@ -418,4 +418,8 @@
   ("FramesToBeEncoded,f",   m_framesToBeEncoded,   0, "Number of frames to be encoded (default=all)")
 
+  //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")
+  
   // Profile and level
   ("Profile", m_profile,   Profile::NONE, "Profile to be used when encoding (Incomplete)")
@@ -812,4 +816,14 @@
   const list<const Char*>& argv_unhandled = po::scanArgv(opts, argc, (const Char**) argv);
 
+  if(m_isField)
+  {
+    //Frame height
+    m_iSourceHeightOrg = m_iSourceHeight;
+    //Field height
+    m_iSourceHeight = m_iSourceHeight >> 1;
+    //number of fields to encode
+    m_framesToBeEncoded *= 2;
+  }
+  
   for (list<const Char*>::const_iterator it = argv_unhandled.begin(); it != argv_unhandled.end(); it++)
   {
@@ -930,4 +944,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)
@@ -1692,7 +1711,11 @@
   Bool errorGOP=false;
   Int checkGOP=1;
-  Int numRefs = 1;
+  Int numRefs = m_isField ? 2 : 1;
   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++) 
@@ -2213,5 +2236,22 @@
   printf("Real     Format              : %dx%d %dHz\n", m_iSourceWidth - m_confLeft - m_confRight, m_iSourceHeight - m_confTop - m_confBottom, m_iFrameRate );
   printf("Internal Format              : %dx%d %dHz\n", m_iSourceWidth, m_iSourceHeight, m_iFrameRate );
+  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/HTM-8.2-dev0-Cleanup/source/App/TAppEncoder/TAppEncCfg.h
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/source/App/TAppEncoder/TAppEncCfg.h	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/source/App/TAppEncoder/TAppEncCfg.h	(revision 651)
@@ -139,5 +139,11 @@
   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)
+  
+  bool      m_isField;                                        ///< enable field coding
+  bool      m_isTopFieldFirst;
+  
   Int       m_conformanceMode;
   Int       m_confLeft;
Index: /branches/HTM-8.2-dev0-Cleanup/source/App/TAppEncoder/TAppEncTop.cpp
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/source/App/TAppEncoder/TAppEncTop.cpp	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/source/App/TAppEncoder/TAppEncTop.cpp	(revision 651)
@@ -756,5 +756,5 @@
 }
 
-Void TAppEncTop::xInitLib()
+Void TAppEncTop::xInitLib(Bool isFieldCoding)
 {
 #if H_MV
@@ -762,11 +762,11 @@
   {
 #if KWU_RC_MADPRED_E0227
-    m_acTEncTopList[layer]->init( this );
-#else
-    m_acTEncTopList[layer]->init( );
-#endif
-  }
-#else
-  m_cTEncTop.init();
+    m_acTEncTopList[layer]->init( isFieldCoding, this );
+#else
+    m_acTEncTopList[layer]->init( isFieldCoding );
+#endif
+  }
+#else
+  m_cTEncTop.init( isFieldCoding );
 #endif
 }
@@ -799,5 +799,5 @@
   xInitLibCfg();
   xCreateLib();
-  xInitLib();
+  xInitLib(m_isField);
   
   // main encoder loop
@@ -824,5 +824,12 @@
 
   // allocate original YUV buffer
+  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 );
+  }
   
 #if H_MV
@@ -900,5 +907,5 @@
   for(Int layer=0; layer < m_numberOfLayers; layer++ )
   {
-    m_acTEncTopList[layer]->printSummary( m_acTEncTopList[layer]->getNumAllPicCoded() );
+    m_acTEncTopList[layer]->printSummary( m_acTEncTopList[layer]->getNumAllPicCoded(), m_isField );
   }
 #else
@@ -914,5 +921,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;
@@ -927,5 +934,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
@@ -937,5 +951,5 @@
   }
 
-  m_cTEncTop.printSummary();
+  m_cTEncTop.printSummary(m_isField);
 #endif
 
@@ -1048,6 +1062,8 @@
 #endif
 {
-  Int i;
-  
+  if (m_isField)
+  {
+    //Reinterlace fields
+    Int i;
 #if H_MV
   if( iNumEncoded > 0 )
@@ -1055,23 +1071,24 @@
     TComList<TComPicYuv*>::iterator iterPicYuvRec = m_picYuvRec[layerId]->end();
 #else
-  TComList<TComPicYuv*>::iterator iterPicYuvRec = m_cListPicYuvRec.end();
-  list<AccessUnit>::const_iterator iterBitstream = accessUnits.begin();
-#endif
-
-  for ( i = 0; i < iNumEncoded; i++ )
-  {
-    --iterPicYuvRec;
-  }
-  
-  for ( i = 0; i < iNumEncoded; i++ )
-  {
-    TComPicYuv*  pcPicYuvRec  = *(iterPicYuvRec++);
+    TComList<TComPicYuv*>::iterator iterPicYuvRec = m_cListPicYuvRec.end();
+    list<AccessUnit>::const_iterator iterBitstream = accessUnits.begin();
+#endif
+    
+    for ( i = 0; i < iNumEncoded; i++ )
+    {
+      --iterPicYuvRec;
+    }
+    
+    for ( i = 0; i < iNumEncoded/2; i++ )
+    {
+      TComPicYuv*  pcPicYuvRecTop  = *(iterPicYuvRec++);
+      TComPicYuv*  pcPicYuvRecBottom  = *(iterPicYuvRec++);
+      
 #if H_MV
       if (m_pchReconFileList[layerId])
       {
-        m_acTVideoIOYuvReconFileList[layerId]->write( pcPicYuvRec, m_confLeft, m_confRight, m_confTop, m_confBottom );
-      }
-    }
-  }
+        m_acTVideoIOYuvReconFileList[layerId]->write( pcPicYuvRecTop, pcPicYuvRecBottom, m_confLeft, m_confRight, m_confTop, m_confBottom, m_isTopFieldFirst );
+      }
+    }
   if( ! accessUnits.empty() )
   {
@@ -1079,4 +1096,56 @@
     for( aUIter = accessUnits.begin(); aUIter != accessUnits.end(); aUIter++ )
     {
+      const vector<UInt>& stats = writeAnnexB(bitstreamFile, *aUIter);
+      rateStatsAccum(*aUIter, stats);
+    }
+  }
+#else
+      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);
+    }
+#endif
+  }
+  else
+  {
+    Int i;
+#if H_MV
+  if( iNumEncoded > 0 )
+  {
+    TComList<TComPicYuv*>::iterator iterPicYuvRec = m_picYuvRec[layerId]->end();
+#else
+    TComList<TComPicYuv*>::iterator iterPicYuvRec = m_cListPicYuvRec.end();
+    list<AccessUnit>::const_iterator iterBitstream = accessUnits.begin();
+#endif
+    
+    for ( i = 0; i < iNumEncoded; i++ )
+    {
+      --iterPicYuvRec;
+    }
+    
+    for ( i = 0; i < iNumEncoded; i++ )
+    {
+      TComPicYuv*  pcPicYuvRec  = *(iterPicYuvRec++);
+#if H_MV
+      if (m_pchReconFileList[layerId])
+      {
+        m_acTVideoIOYuvReconFileList[layerId]->write( pcPicYuvRec, m_confLeft, m_confRight, m_confTop, m_confBottom );
+      }
+    }
+  }
+  if( ! accessUnits.empty() )
+  {
+    list<AccessUnit>::iterator aUIter;
+    for( aUIter = accessUnits.begin(); aUIter != accessUnits.end(); aUIter++ )
+    {
       const vector<unsigned>& stats = writeAnnexB(bitstreamFile, *aUIter);
       rateStatsAccum(*aUIter, stats);
@@ -1084,16 +1153,16 @@
   }
 #else
-    if (m_pchReconFile)
-    {
-      m_cTVideoIOYuvReconFile.write( pcPicYuvRec, m_confLeft, m_confRight, m_confTop, m_confBottom );
-    }
-
-    const AccessUnit& au = *(iterBitstream++);
-    const vector<UInt>& stats = writeAnnexB(bitstreamFile, au);
-    rateStatsAccum(au, stats);
-  }
-#endif
-}
-
+      if (m_pchReconFile)
+      {
+        m_cTVideoIOYuvReconFile.write( pcPicYuvRec, m_confLeft, m_confRight, m_confTop, m_confBottom );
+      }
+      
+      const AccessUnit& au = *(iterBitstream++);
+      const vector<UInt>& stats = writeAnnexB(bitstreamFile, au);
+      rateStatsAccum(au, stats);
+#endif
+    }
+  }
+}
 /**
  *
Index: /branches/HTM-8.2-dev0-Cleanup/source/App/TAppEncoder/TAppEncTop.h
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/source/App/TAppEncoder/TAppEncTop.h	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/source/App/TAppEncoder/TAppEncTop.h	(revision 651)
@@ -96,5 +96,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
   
Index: /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/CommonDef.h
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/CommonDef.h	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/CommonDef.h	(revision 651)
@@ -61,7 +61,7 @@
 #if H_MV
 #define NV_VERSION        "8.1"                 ///< Current software version
-#define HM_VERSION        "11.0"                ///< 
+#define HM_VERSION        "12.0"                ///< 
 #else
-#define NV_VERSION        "11.0"                 ///< Current software version
+#define NV_VERSION        "12.0"                 ///< Current software version
 #endif
 
Index: /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/TComMv.h
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/TComMv.h	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/TComMv.h	(revision 651)
@@ -40,4 +40,5 @@
 
 #include "CommonDef.h"
+#include <cstdlib>
 
 //! \ingroup TLibCommon
Index: /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/TComPic.cpp
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/TComPic.cpp	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/TComPic.cpp	(revision 651)
@@ -50,5 +50,4 @@
 , m_bUsedByCurr                           (false)
 , m_bIsLongTerm                           (false)
-, m_bIsUsedAsLongTerm                     (false)
 , m_apcPicSym                             (NULL)
 , m_pcPicYuvPred                          (NULL)
Index: /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/TComPic.h
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/TComPic.h	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/TComPic.h	(revision 651)
@@ -61,5 +61,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
   
@@ -83,4 +82,7 @@
   Window                m_defaultDisplayWindow;
 
+  bool                  m_isTop;
+  bool                  m_isField;
+  
   std::vector<std::vector<TComDataCU*> > m_vSliceCUDataLink;
 
@@ -208,4 +210,12 @@
   TComPicYuv*   getYuvPicBufferForIndependentBoundaryProcessing()             {return m_pNDBFilterYuvTmp;}
   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;}
 
 #if H_MV
Index: /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/TComPicSym.cpp
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/TComPicSym.cpp	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/TComPicSym.cpp	(revision 651)
@@ -61,5 +61,4 @@
 ,m_uiNumAllocatedSlice (0)
 ,m_apcTComDataCU (NULL)
-,m_iTileBoundaryIndependenceIdr (0)
 ,m_iNumColumnsMinus1 (0)
 ,m_iNumRowsMinus1(0)
Index: /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/TComPicSym.h
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/TComPicSym.h	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/TComPicSym.h	(revision 651)
@@ -99,6 +99,5 @@
   UInt          m_uiNumAllocatedSlice;
   TComDataCU**  m_apcTComDataCU;        ///< array of CU data
-  
-  Int           m_iTileBoundaryIndependenceIdr;
+    
   Int           m_iNumColumnsMinus1; 
   Int           m_iNumRowsMinus1;
Index: /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/TComPrediction.cpp
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/TComPrediction.cpp	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/TComPrediction.cpp	(revision 651)
@@ -1261,5 +1261,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/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/TComRdCost.h
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/TComRdCost.h	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/TComRdCost.h	(revision 651)
@@ -148,6 +148,4 @@
 private:
   // for distortion
-  Int                     m_iBlkWidth;
-  Int                     m_iBlkHeight;
   
 #if AMP_SAD
Index: /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/TComRom.cpp
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/TComRom.cpp	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/TComRom.cpp	(revision 651)
@@ -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;
@@ -292,5 +291,5 @@
 
 #if FAST_UDI_USE_MPM
-const UChar g_aucIntraModeNumFast[7] =
+const UChar g_aucIntraModeNumFast[MAX_CU_DEPTH] =
 {
   3,  //   2x2
@@ -299,9 +298,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
@@ -310,6 +308,5 @@
   4,  //  16x16   33
   4,  //  32x32   33
-  5,  //  64x64   33
-  4   // 128x128  33
+  5   //  64x64   33
 };
 #endif // FAST_UDI_USE_MPM
Index: /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/TComRom.h
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/TComRom.h	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/TComRom.h	(revision 651)
@@ -56,5 +56,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
@@ -136,5 +136,5 @@
 // ====================================================================================================================
 
-extern const UChar  g_aucIntraModeNumFast[7];
+extern const UChar  g_aucIntraModeNumFast[ MAX_CU_DEPTH ];
 
 // ====================================================================================================================
Index: /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/TComSlice.cpp
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/TComSlice.cpp	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/TComSlice.cpp	(revision 651)
@@ -302,5 +302,5 @@
   if (!pocHasMsb)
   {
-    poc = poc % pocCycle;
+    poc = poc & (pocCycle - 1);
   }
   
@@ -313,5 +313,5 @@
       if (!pocHasMsb)
       {
-        picPoc = picPoc % pocCycle;
+        picPoc = picPoc & (pocCycle - 1);
       }
       
@@ -806,5 +806,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++)
@@ -832,10 +832,9 @@
   {
     pocCRA = getPOC();
-    prevRAPisBLA = false;
   }
   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
@@ -844,5 +843,5 @@
   {
     pocCRA = getPOC();
-    prevRAPisBLA = true;
+    associatedIRAPType = getNalUnitType();
   }
 }
@@ -869,4 +868,5 @@
 {
   TComPic*                 rpcPic;
+  setAssociatedIRAPPOC(pocCRA);
   Int pocCurr = getPOC(); 
 
@@ -1054,5 +1054,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.
@@ -1109,4 +1109,166 @@
 }
 
+
+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.
 */
@@ -1115,4 +1277,6 @@
   TComPic* rpcPic;
   Int i, isReference;
+
+  checkLeadingPictureRestrictions(rcListPic);
 
   // loop through all pictures in the reference picture buffer
@@ -1151,5 +1315,4 @@
       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()))
         {
           isReference = 1;
@@ -1211,5 +1374,4 @@
       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())
         {
           isAvailable = 1;
@@ -1230,6 +1392,6 @@
         if (!pReferencePictureSet->getCheckLTMSBPresent(i))
         {
-          curPoc = curPoc % pocCycle;
-          refPoc = refPoc % pocCycle;
+          curPoc = curPoc & (pocCycle - 1);
+          refPoc = refPoc & (pocCycle - 1);
         }
         
@@ -2437,5 +2599,4 @@
 TComScalingList::TComScalingList()
 {
-  m_useTransformSkip = false;
   init();
 }
Index: /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/TComSlice.h
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/TComSlice.h	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/TComSlice.h	(revision 651)
@@ -155,6 +155,4 @@
   Void     setScalingListPresentFlag    (Bool b)                               { m_scalingListPresentFlag = b;    }
   Bool     getScalingListPresentFlag    ()                                     { return m_scalingListPresentFlag; }
-  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);
@@ -182,5 +180,4 @@
   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
 };
 
@@ -1617,5 +1614,7 @@
 #endif
   Int         m_iLastIDR;
-  static Int  m_prevPOC;
+  Int         m_iAssociatedIRAP;
+  NalUnitType m_iAssociatedIRAPType;
+  static Int  m_prevTid0POC;
   TComReferencePictureSet *m_pcRPS;
   TComReferencePictureSet m_LocalRPS;
@@ -1776,8 +1775,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;           }
@@ -1824,4 +1827,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;    }
@@ -1830,5 +1834,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;        }
@@ -1836,5 +1841,5 @@
   Bool      getIdrPicFlag       ()                              { return getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP; }
   Bool      isIRAP              () const                        { return (getNalUnitType() >= 16) && (getNalUnitType() <= 23); }  
-  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;      }
@@ -1912,4 +1917,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);
 #if H_MV
Index: /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/TComWeightPrediction.h
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/TComWeightPrediction.h	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibCommon/TComWeightPrediction.h	(revision 651)
@@ -53,6 +53,4 @@
 class TComWeightPrediction
 {
-  wpScalingParam  m_wp0[3], m_wp1[3];
-
 public:
   TComWeightPrediction();
Index: /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibDecoder/SEIread.cpp
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibDecoder/SEIread.cpp	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibDecoder/SEIread.cpp	(revision 651)
@@ -315,4 +315,5 @@
 
   /* restore primary bitstream for sei_message */
+  getBitstream()->deleteFifo();
   delete getBitstream();
   setBitstream(bs);
Index: /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibDecoder/SyntaxElementParser.cpp
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibDecoder/SyntaxElementParser.cpp	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibDecoder/SyntaxElementParser.cpp	(revision 651)
@@ -58,9 +58,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 );
@@ -77,5 +77,5 @@
 #endif
   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/HTM-8.2-dev0-Cleanup/source/Lib/TLibDecoder/TDecCAVLC.cpp
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibDecoder/TDecCAVLC.cpp	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibDecoder/TDecCAVLC.cpp	(revision 651)
@@ -1441,7 +1441,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;
@@ -1572,4 +1572,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/HTM-8.2-dev0-Cleanup/source/Lib/TLibDecoder/TDecSlice.h
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibDecoder/TDecSlice.h	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibDecoder/TDecSlice.h	(revision 651)
@@ -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/HTM-8.2-dev0-Cleanup/source/Lib/TLibDecoder/TDecTop.cpp
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibDecoder/TDecTop.cpp	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibDecoder/TDecTop.cpp	(revision 651)
@@ -347,10 +347,12 @@
 #endif
 #endif
+  m_associatedIRAPType = NAL_UNIT_INVALID;
   m_pocCRA = 0;
-  m_prevRAPisBLA = false;
   m_pocRandomAccess = MAX_INT;  
   m_prevPOC                = MAX_INT;
   m_bFirstSliceInPicture    = true;
   m_bFirstSliceInSequence   = true;
+  m_prevSliceSkipped = false;
+  m_skippedPOC = 0;
 #if H_MV
   m_layerId = 0;
@@ -686,4 +688,13 @@
   m_cEntropyDecoder.decodeSliceHeader (m_apcSlicePilot, &m_parameterSetManagerDecoder);
 
+  // set POC for dependent slices in skipped pictures
+  if(m_apcSlicePilot->getDependentSliceSegmentFlag() && m_prevSliceSkipped) 
+  {
+    m_apcSlicePilot->setPOC(m_skippedPOC);
+  }
+
+  m_apcSlicePilot->setAssociatedIRAPPOC(m_pocCRA);
+  m_apcSlicePilot->setAssociatedIRAPType(m_associatedIRAPType);
+
 #if H_MV  
   TComVPS* vps     = m_apcSlicePilot->getVPS();
@@ -699,4 +710,6 @@
     if (isRandomAccessSkipPicture(iSkipFrame, iPOCLastDisplay))
     {
+    m_prevSliceSkipped = true;
+    m_skippedPOC = m_apcSlicePilot->getPOC();
       return false;
     }
@@ -704,6 +717,11 @@
     if (isSkipPictureForBLA(iPOCLastDisplay))
     {
+    m_prevSliceSkipped = true;
+    m_skippedPOC = m_apcSlicePilot->getPOC();
       return false;
     }
+
+  // clear previous slice skipped flag
+  m_prevSliceSkipped = false;
 
   //we should only get a different poc for a new picture (with CTU address==0)
@@ -766,4 +784,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);
@@ -904,5 +941,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 H_MV    
@@ -1003,5 +1040,4 @@
       pcSlice->setScalingList ( pcSlice->getPPS()->getScalingList()  );
     }
-    pcSlice->getScalingList()->setUseTransformSkip(pcSlice->getPPS()->getUseTransformSkip());
     if(!pcSlice->getPPS()->getScalingListPresentFlag() && !pcSlice->getSPS()->getScalingListPresentFlag())
     {
@@ -1168,5 +1204,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/HTM-8.2-dev0-Cleanup/source/Lib/TLibDecoder/TDecTop.h
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibDecoder/TDecTop.h	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibDecoder/TDecTop.h	(revision 651)
@@ -176,6 +176,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)
 
@@ -211,4 +211,7 @@
   Bool                    m_bFirstSliceInPicture;
   Bool                    m_bFirstSliceInSequence;
+  Bool                    m_prevSliceSkipped;
+  Int                     m_skippedPOC;
+
 #if H_MV
   // For H_MV m_bFirstSliceInSequence indicates first slice in sequence of the particular layer  
Index: /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibEncoder/TEncAnalyze.cpp
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibEncoder/TEncAnalyze.cpp	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibEncoder/TEncAnalyze.cpp	(revision 651)
@@ -52,4 +52,6 @@
 TEncAnalyze             m_gcAnalyzeP;
 TEncAnalyze             m_gcAnalyzeB;
+
+TEncAnalyze             m_gcAnalyzeAll_in;
 #endif
 
Index: /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibEncoder/TEncAnalyze.h
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibEncoder/TEncAnalyze.h	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibEncoder/TEncAnalyze.h	(revision 651)
@@ -116,4 +116,33 @@
   }
   
+  Void    printOutInterlaced ( Char cDelim, Double bits )
+  {
+    Double dFps     =   m_dFrmRate; //--CFG_KDY
+    Double dScale   = dFps / 1000 / (Double)m_uiNumPic;
+    
+    printf( "\tTotal Frames |  "   "Bitrate    "  "Y-PSNR    "  "U-PSNR    "  "V-PSNR \n" );
+    //printf( "\t------------ "  " ----------"   " -------- "  " -------- "  " --------\n" );
+    printf( "\t %8d    %c"          "%12.4lf  "    "%8.4lf  "   "%8.4lf  "    "%8.4lf\n",
+           getNumPic(), cDelim,
+           bits * dScale,
+           getPsnrY() / (Double)getNumPic(),
+           getPsnrU() / (Double)getNumPic(),
+           getPsnrV() / (Double)getNumPic() );
+  }
+  
+  Void    printSummaryOutInterlaced (Int bits)
+  {
+    FILE* pFile = fopen ("summaryTotal.txt", "at");
+    Double dFps     =   m_dFrmRate; //--CFG_KDY
+    Double dScale   = dFps / 1000 / (Double)m_uiNumPic;
+    
+    fprintf(pFile, "%f\t %f\t %f\t %f\n", bits * dScale,
+            getPsnrY() / (Double)getNumPic(),
+            getPsnrU() / (Double)getNumPic(),
+            getPsnrV() / (Double)getNumPic() );
+    fclose(pFile);
+  }
+  
+  
   Void    printSummary(Char ch)
   {
@@ -155,4 +184,6 @@
 extern TEncAnalyze             m_gcAnalyzeP;
 extern TEncAnalyze             m_gcAnalyzeB;
+
+extern TEncAnalyze             m_gcAnalyzeAll_in;
 #endif
 
Index: /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibEncoder/TEncCavlc.cpp
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 651)
@@ -1130,5 +1130,5 @@
     if( !pcSlice->getIdrPicFlag() )
     {
-      Int picOrderCntLSB = (pcSlice->getPOC()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC()))%(1<<pcSlice->getSPS()->getBitsForPOC());
+      Int picOrderCntLSB = (pcSlice->getPOC()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC())) & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
       WRITE_CODE( picOrderCntLSB, pcSlice->getSPS()->getBitsForPOC(), "pic_order_cnt_lsb");
       TComReferencePictureSet* rps = pcSlice->getRPS();
@@ -1927,5 +1927,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/HTM-8.2-dev0-Cleanup/source/Lib/TLibEncoder/TEncCu.cpp
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibEncoder/TEncCu.cpp	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibEncoder/TEncCu.cpp	(revision 651)
@@ -432,7 +432,8 @@
 
   // variables for fast encoder decision
-  Bool    bEarlySkip  = false;
-  Bool    bTrySplit    = true;
-  Double  fRD_Skip    = MAX_DOUBLE;
+#if H_3D_QTLPC  
+  Bool    bTrySplit     = true;
+  Bool    bTrySplitDQP  = true;
+#endif
 
   // variable for Early CU determination
@@ -443,5 +444,4 @@
   Bool earlyDetectionSkipMode = false;
 
-  Bool    bTrySplitDQP  = true;
 #if H_3D_VSP
   DisInfo DvInfo; 
@@ -453,13 +453,4 @@
 #endif
 #endif
-  static  Double  afCost[ MAX_CU_DEPTH ];
-  static  Int      aiNum [ MAX_CU_DEPTH ];
-
-  if ( rpcBestCU->getAddr() == 0 )
-  {
-    ::memset( afCost, 0, sizeof( afCost ) );
-    ::memset( aiNum,  0, sizeof( aiNum  ) );
-  }
-
   Bool bBoundary = false;
   UInt uiLPelX   = rpcBestCU->getCUPelX();
@@ -529,7 +520,7 @@
       }
       // variables for fast encoder decision
-      bEarlySkip  = false;
+#if H_3D_QTLPC
       bTrySplit    = true;
-      fRD_Skip    = MAX_DOUBLE;
+#endif
 
       rpcTempCU->initEstData( uiDepth, iQP );
@@ -633,20 +624,8 @@
         rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
 #endif
-        // fast encoder decision for early skip
-        if ( m_pcEncCfg->getUseFastEnc() )
-        {
-          Int iIdx = g_aucConvertToBit[ rpcBestCU->getWidth(0) ];
-          if ( aiNum [ iIdx ] > 5 && fRD_Skip < EARLY_SKIP_THRES*afCost[ iIdx ]/aiNum[ iIdx ] )
-          {
-            bEarlySkip = true;
-            bTrySplit  = false;
-          }
-        }
 
         if(!m_pcEncCfg->getUseEarlySkipDetection())
         {
           // 2Nx2N, NxN
-          if ( !bEarlySkip )
-          {
 #if H_3D_IC
             rpcTempCU->setICFlagSubParts(bICFlag, 0, 0, uiDepth);
@@ -664,5 +643,4 @@
               doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
             }
-          }
         }
 #if H_3D_IC
@@ -671,24 +649,8 @@
       }
 
-#if H_3D_QTLPC
+#if H_3D_QTLPC      
       if(depthMapDetect && !bIntraSliceDetect && !rapPic && sps->getUseQTL())
       {
         bTrySplitDQP = bTrySplit;
-      }
-      else
-      {
-#endif
-        if( (g_uiMaxCUWidth>>uiDepth) >= rpcTempCU->getSlice()->getPPS()->getMinCuDQPSize() )
-        {
-          if(iQP == iBaseQP)
-          {
-            bTrySplitDQP = bTrySplit;
-          }
-        }
-        else
-        {
-          bTrySplitDQP = bTrySplit;
-        }
-#if H_3D_QTLPC
       }
 #endif
@@ -750,6 +712,4 @@
         {
           // 2Nx2N, NxN
-          if ( !bEarlySkip )
-          {
             if(!( (rpcBestCU->getWidth(0)==8) && (rpcBestCU->getHeight(0)==8) ))
             {
@@ -771,5 +731,4 @@
               }
             }
-          }
 
           // 2NxN, Nx2N
@@ -1046,7 +1005,5 @@
         // do normal intra modes
 #if H_3D_DIM_ENC
-        if ( !bEarlySkip || ( rpcBestCU->getSlice()->getIsDepth() && rpcBestCU->getSlice()->isIRAP() ) )
-#else
-        if ( !bEarlySkip )
+        if (( rpcBestCU->getSlice()->getIsDepth() && rpcBestCU->getSlice()->isIRAP() ) )
 #endif
         {
@@ -1146,15 +1103,4 @@
 #endif
     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
Index: /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibEncoder/TEncGOP.cpp
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 651)
@@ -355,7 +355,7 @@
 #endif
 #if H_MV
-Void TEncGOP::compressPicInGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP, Int iGOPid)
-#else
-Void TEncGOP::compressGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP)
+Void TEncGOP::compressPicInGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP, Int iGOPid, bool isField, bool isTff)
+#else
+Void TEncGOP::compressGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP, bool isField, bool isTff)
 #endif
 {
@@ -371,5 +371,6 @@
 
 #if !H_MV
-  xInitGOP( iPOCLast, iNumPicRcvd, rcListPic, rcListPicYuvRecOut );
+  xInitGOP( iPOCLast, iNumPicRcvd, rcListPic, rcListPicYuvRecOut, isField );
+
   
   m_iNumPicCoded = 0;
@@ -443,10 +444,21 @@
 
     /////////////////////////////////////////////////////////////////////////////////////////////////// Initial to start encoding
-    Int pocCurr = iPOCLast -iNumPicRcvd+ m_pcCfg->getGOPEntry(iGOPid).m_POC;
-    Int iTimeOffset = m_pcCfg->getGOPEntry(iGOPid).m_POC;
-    if(iPOCLast == 0)
+    Int iTimeOffset;
+    Int pocCurr;
+    
+    if(iPOCLast == 0) //case first frame or first top field
     {
       pocCurr=0;
       iTimeOffset = 1;
+    }
+    else if(iPOCLast == 1 && isField) //case first bottom field, just like the first frame, the poc computation is not right anymore, we set the right value
+    {
+      pocCurr = 1;
+      iTimeOffset = 1;
+    }
+    else
+    {
+      pocCurr = iPOCLast - iNumPicRcvd + m_pcCfg->getGOPEntry(iGOPid).m_POC - isField;
+      iTimeOffset = m_pcCfg->getGOPEntry(iGOPid).m_POC;
     }
     if(pocCurr>=m_pcCfg->getFramesToBeEncoded())
@@ -467,5 +479,5 @@
     accessUnitsInGOP.push_back(AccessUnit());
     AccessUnit& accessUnit = accessUnitsInGOP.back();
-    xGetBuffer( rcListPic, rcListPicYuvRecOut, iNumPicRcvd, iTimeOffset, pcPic, pcPicYuvRecOut, pocCurr );
+    xGetBuffer( rcListPic, rcListPicYuvRecOut, iNumPicRcvd, iTimeOffset, pcPic, pcPicYuvRecOut, pocCurr, isField);
 
     //  Slice data initialization
@@ -477,8 +489,12 @@
 
 #if H_MV
-    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, pocCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getVPS(), m_pcEncTop->getSPS(), m_pcEncTop->getPPS(), getLayerId() );     
-#else
-    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, pocCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getSPS(), m_pcEncTop->getPPS() );
-#endif
+    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, pocCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getVPS(), m_pcEncTop->getSPS(), m_pcEncTop->getPPS(), getLayerId(), isField  );     
+#else
+    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, pocCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getSPS(), m_pcEncTop->getPPS(), isField  );
+#endif
+    
+    //Set Frame/Field coding
+    pcSlice->getPic()->setField(isField);
+
     pcSlice->setLastIDR(m_iLastIDR);
     pcSlice->setSliceIdx(0);
@@ -500,5 +516,4 @@
     pcSlice->setLFCrossSliceBoundaryFlag(  pcSlice->getPPS()->getLoopFilterAcrossSlicesEnabledFlag()  );
     pcSlice->setScalingList ( m_pcEncTop->getScalingList()  );
-    pcSlice->getScalingList()->setUseTransformSkip(m_pcEncTop->getPPS()->getUseTransformSkip());
     if(m_pcEncTop->getUseScalingListId() == SCALING_LIST_OFF)
     {
@@ -554,5 +569,7 @@
     if(pcSlice->getTemporalLayerNonReferenceFlag())
     {
-      if(pcSlice->getNalUnitType()==NAL_UNIT_CODED_SLICE_TRAIL_R)
+      if (pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_TRAIL_R &&
+          !(m_iGopSize == 1 && pcSlice->getSliceType() == I_SLICE))
+        // Add this condition to avoid POC issues with encoder_intra_main.cfg configuration (see #1127 in bug tracker)
       {
         pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TRAIL_N);
@@ -1356,5 +1373,5 @@
         }
       }
-      pictureTimingSEI.m_auCpbRemovalDelay = std::max<Int>(1, m_totalCoded - m_lastBPSEI); // Syntax element signalled as minus, hence the .
+      pictureTimingSEI.m_auCpbRemovalDelay = std::min<Int>(std::max<Int>(1, m_totalCoded - m_lastBPSEI), static_cast<Int>(pow(2, static_cast<double>(pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getCpbRemovalDelayLengthMinus1()+1)))); // Syntax element signalled as minus, hence the .
       pictureTimingSEI.m_picDpbOutputDelay = pcSlice->getSPS()->getNumReorderPics(0) + pcSlice->getPOC() - m_totalCoded;
       Int factor = pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getTickDivisorMinus2() + 2;
@@ -1884,4 +1901,18 @@
       xCalculateAddPSNR( pcPic, pcPic->getPicYuvRec(), accessUnit, dEncTime );
 
+    //In case of field coding, compute the interlaced PSNR for both fields
+    if (isField && ((!pcPic->isTopField() && isTff) || (pcPic->isTopField() && !isTff)))
+    {
+      //get complementary top field
+      TComPic* pcPicTop;
+      TComList<TComPic*>::iterator   iterPic = rcListPic.begin();
+      while ((*iterPic)->getPOC() != pcPic->getPOC()-1)
+      {
+        iterPic ++;
+      }
+      pcPicTop = *(iterPic);
+      xCalculateInterlacedAddPSNR(pcPicTop, pcPic, pcPicTop->getPicYuvRec(), pcPic->getPicYuvRec(), accessUnit, dEncTime );
+    }
+    
       if (digestStr)
       {
@@ -2016,4 +2047,5 @@
             OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI, pcSlice->getTLayer());
           m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
+          pictureTimingSEI.m_picStruct = (isField && pcSlice->getPic()->isTopField())? 1 : isField? 2 : 0;
           m_seiWriter.writeSEImessage(nalu.m_Bitstream, pictureTimingSEI, pcSlice->getSPS());
           writeRBSPTrailingBits(nalu.m_Bitstream);
@@ -2136,10 +2168,10 @@
 
 #if !H_MV
-  assert ( m_iNumPicCoded == iNumPicRcvd );
+  assert ( (m_iNumPicCoded == iNumPicRcvd) || (isField && iPOCLast == 1) );
 #endif
 }
 
 #if !H_MV
-Void TEncGOP::printOutSummary(UInt uiNumAllPicCoded)
+Void TEncGOP::printOutSummary(UInt uiNumAllPicCoded, bool isField)
 {
   assert (uiNumAllPicCoded == m_gcAnalyzeAll.getNumPic());
@@ -2147,8 +2179,18 @@
     
   //--CFG_KDY
+  if(isField)
+  {
+    m_gcAnalyzeAll.setFrmRate( m_pcCfg->getFrameRate() * 2);
+    m_gcAnalyzeI.setFrmRate( m_pcCfg->getFrameRate() * 2);
+    m_gcAnalyzeP.setFrmRate( m_pcCfg->getFrameRate() * 2);
+    m_gcAnalyzeB.setFrmRate( m_pcCfg->getFrameRate() * 2);
+  }
+  else
+  {
   m_gcAnalyzeAll.setFrmRate( m_pcCfg->getFrameRate() );
   m_gcAnalyzeI.setFrmRate( m_pcCfg->getFrameRate() );
   m_gcAnalyzeP.setFrmRate( m_pcCfg->getFrameRate() );
   m_gcAnalyzeB.setFrmRate( m_pcCfg->getFrameRate() );
+  }
   
   //-- all
@@ -2173,4 +2215,16 @@
   m_gcAnalyzeB.printSummary('B');
 #endif
+
+  if(isField)
+  {
+    //-- interlaced summary
+    m_gcAnalyzeAll_in.setFrmRate( m_pcCfg->getFrameRate());
+    printf( "\n\nSUMMARY INTERLACED ---------------------------------------------\n" );
+    m_gcAnalyzeAll_in.printOutInterlaced('a',  m_gcAnalyzeAll.getBits());
+    
+#if _SUMMARY_OUT_
+    m_gcAnalyzeAll_in.printSummaryOutInterlaced();
+#endif
+  }
 
   printf("\nRVM: %.3lf\n" , xCalculateRVM());
@@ -2216,4 +2270,22 @@
 // Protected member functions
 // ====================================================================================================================
+
+
+Void TEncGOP::xInitGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, bool isField )
+{
+  assert( iNumPicRcvd > 0 );
+  //  Exception for the first frames
+  if ( ( isField && (iPOCLast == 0 || iPOCLast == 1) ) || (!isField  && (iPOCLast == 0))  )
+  {
+    m_iGopSize    = 1;
+  }
+  else
+  {
+    m_iGopSize    = m_pcCfg->getGOPSize();
+  }
+  assert (m_iGopSize > 0);
+  
+  return;
+}
 
 Void TEncGOP::xInitGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut )
@@ -2239,14 +2311,34 @@
                          TComPic*&                 rpcPic,
                          TComPicYuv*&              rpcPicYuvRecOut,
-                         Int                       pocCurr )
+                         Int                       pocCurr,
+                         bool                      isField)
 {
   Int i;
   //  Rec. output
   TComList<TComPicYuv*>::iterator     iterPicYuvRec = rcListPicYuvRecOut.end();
-  for ( i = 0; i < iNumPicRcvd - iTimeOffset + 1; i++ )
+  
+  if (isField)
+  {
+    for ( i = 0; i < ( (pocCurr == 0 ) || (pocCurr == 1 ) ? (iNumPicRcvd - iTimeOffset + 1) : (iNumPicRcvd - iTimeOffset + 2) ); i++ )
+    {
+      iterPicYuvRec--;
+    }
+  }
+  else
+  {
+    for ( i = 0; i < (iNumPicRcvd - iTimeOffset + 1); i++ )
   {
     iterPicYuvRec--;
   }
   
+  }
+  
+  if (isField)
+  {
+    if(pocCurr == 1)
+    {
+      iterPicYuvRec++;
+    }
+  }
   rpcPicYuvRecOut = *(iterPicYuvRec);
   
@@ -2582,4 +2674,167 @@
 }
 
+
+Void reinterlace(Pel* top, Pel* bottom, Pel* dst, UInt stride, UInt width, UInt height, bool isTff)
+{
+  
+  for (Int y = 0; y < height; y++)
+  {
+    for (Int x = 0; x < width; x++)
+    {
+      dst[x] = isTff ? (UChar) top[x] : (UChar) bottom[x];
+      dst[stride+x] = isTff ? (UChar) bottom[x] : (UChar) top[x];
+    }
+    top += stride;
+    bottom += stride;
+    dst += stride*2;
+  }
+}
+
+
+Void TEncGOP::xCalculateInterlacedAddPSNR( TComPic* pcPicOrgTop, TComPic* pcPicOrgBottom, TComPicYuv* pcPicRecTop, TComPicYuv* pcPicRecBottom, const AccessUnit& accessUnit, Double dEncTime )
+{
+#if  H_MV
+  assert( 0 ); // Field coding and MV need to be aligned. 
+#else
+  Int     x, y;
+  
+  UInt64 uiSSDY_in  = 0;
+  UInt64 uiSSDU_in  = 0;
+  UInt64 uiSSDV_in  = 0;
+  
+  Double  dYPSNR_in  = 0.0;
+  Double  dUPSNR_in  = 0.0;
+  Double  dVPSNR_in  = 0.0;
+  
+  /*------ INTERLACED PSNR -----------*/
+  
+  /* Luma */
+  
+  Pel*  pOrgTop = pcPicOrgTop->getPicYuvOrg()->getLumaAddr();
+  Pel*  pOrgBottom = pcPicOrgBottom->getPicYuvOrg()->getLumaAddr();
+  Pel*  pRecTop = pcPicRecTop->getLumaAddr();
+  Pel*  pRecBottom = pcPicRecBottom->getLumaAddr();
+  
+  Int   iWidth;
+  Int   iHeight;
+  Int iStride;
+  
+  iWidth  = pcPicOrgTop->getPicYuvOrg()->getWidth () - m_pcEncTop->getPad(0);
+  iHeight = pcPicOrgTop->getPicYuvOrg()->getHeight() - m_pcEncTop->getPad(1);
+  iStride = pcPicOrgTop->getPicYuvOrg()->getStride();
+  Int   iSize   = iWidth*iHeight;
+  bool isTff = pcPicOrgTop->isTopField();
+  
+  TComPicYuv* pcOrgInterlaced = new TComPicYuv;
+  pcOrgInterlaced->create( iWidth, iHeight << 1, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+  
+  TComPicYuv* pcRecInterlaced = new TComPicYuv;
+  pcRecInterlaced->create( iWidth, iHeight << 1, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+  
+  Pel* pOrgInterlaced = pcOrgInterlaced->getLumaAddr();
+  Pel* pRecInterlaced = pcRecInterlaced->getLumaAddr();
+  
+  //=== Interlace fields ====
+  reinterlace(pOrgTop, pOrgBottom, pOrgInterlaced, iStride, iWidth, iHeight, isTff);
+  reinterlace(pRecTop, pRecBottom, pRecInterlaced, iStride, iWidth, iHeight, isTff);
+  
+  //===== calculate PSNR =====
+  for( y = 0; y < iHeight << 1; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+      Int iDiff = (Int)( pOrgInterlaced[x] - pRecInterlaced[x] );
+      uiSSDY_in   += iDiff * iDiff;
+    }
+    pOrgInterlaced += iStride;
+    pRecInterlaced += iStride;
+  }
+  
+  /*Chroma*/
+  
+  iHeight >>= 1;
+  iWidth  >>= 1;
+  iStride >>= 1;
+  
+  pOrgTop = pcPicOrgTop->getPicYuvOrg()->getCbAddr();
+  pOrgBottom = pcPicOrgBottom->getPicYuvOrg()->getCbAddr();
+  pRecTop = pcPicRecTop->getCbAddr();
+  pRecBottom = pcPicRecBottom->getCbAddr();
+  pOrgInterlaced = pcOrgInterlaced->getCbAddr();
+  pRecInterlaced = pcRecInterlaced->getCbAddr();
+  
+  //=== Interlace fields ====
+  reinterlace(pOrgTop, pOrgBottom, pOrgInterlaced, iStride, iWidth, iHeight, isTff);
+  reinterlace(pRecTop, pRecBottom, pRecInterlaced, iStride, iWidth, iHeight, isTff);
+  
+  //===== calculate PSNR =====
+  for( y = 0; y < iHeight << 1; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+      Int iDiff = (Int)( pOrgInterlaced[x] - pRecInterlaced[x] );
+      uiSSDU_in   += iDiff * iDiff;
+    }
+    pOrgInterlaced += iStride;
+    pRecInterlaced += iStride;
+  }
+  
+  pOrgTop = pcPicOrgTop->getPicYuvOrg()->getCrAddr();
+  pOrgBottom = pcPicOrgBottom->getPicYuvOrg()->getCrAddr();
+  pRecTop = pcPicRecTop->getCrAddr();
+  pRecBottom = pcPicRecBottom->getCrAddr();
+  pOrgInterlaced = pcOrgInterlaced->getCrAddr();
+  pRecInterlaced = pcRecInterlaced->getCrAddr();
+  
+  //=== Interlace fields ====
+  reinterlace(pOrgTop, pOrgBottom, pOrgInterlaced, iStride, iWidth, iHeight, isTff);
+  reinterlace(pRecTop, pRecBottom, pRecInterlaced, iStride, iWidth, iHeight, isTff);
+  
+  //===== calculate PSNR =====
+  for( y = 0; y < iHeight << 1; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+      Int iDiff = (Int)( pOrgInterlaced[x] - pRecInterlaced[x] );
+      uiSSDV_in   += iDiff * iDiff;
+    }
+    pOrgInterlaced += iStride;
+    pRecInterlaced += iStride;
+  }
+  
+  Int maxvalY = 255 << (g_bitDepthY-8);
+  Int maxvalC = 255 << (g_bitDepthC-8);
+  Double fRefValueY = (Double) maxvalY * maxvalY * iSize*2;
+  Double fRefValueC = (Double) maxvalC * maxvalC * iSize*2 / 4.0;
+  dYPSNR_in            = ( uiSSDY_in ? 10.0 * log10( fRefValueY / (Double)uiSSDY_in ) : 99.99 );
+  dUPSNR_in            = ( uiSSDU_in ? 10.0 * log10( fRefValueC / (Double)uiSSDU_in ) : 99.99 );
+  dVPSNR_in            = ( uiSSDV_in ? 10.0 * log10( fRefValueC / (Double)uiSSDV_in ) : 99.99 );
+  
+  /* calculate the size of the access unit, excluding:
+   *  - any AnnexB contributions (start_code_prefix, zero_byte, etc.,)
+   *  - SEI NAL units
+   */
+  UInt numRBSPBytes = 0;
+  for (AccessUnit::const_iterator it = accessUnit.begin(); it != accessUnit.end(); it++)
+  {
+    UInt numRBSPBytes_nal = UInt((*it)->m_nalUnitData.str().size());
+    
+    if ((*it)->m_nalUnitType != NAL_UNIT_PREFIX_SEI && (*it)->m_nalUnitType != NAL_UNIT_SUFFIX_SEI)
+      numRBSPBytes += numRBSPBytes_nal;
+  }
+  
+  UInt uibits = numRBSPBytes * 8 ;
+  
+  //===== add PSNR =====
+  m_gcAnalyzeAll_in.addResult (dYPSNR_in, dUPSNR_in, dVPSNR_in, (Double)uibits);
+  
+  printf("\n                                      Interlaced frame %d: [Y %6.4lf dB    U %6.4lf dB    V %6.4lf dB]", pcPicOrgBottom->getPOC()/2 , dYPSNR_in, dUPSNR_in, dVPSNR_in );
+  
+  pcOrgInterlaced->destroy();
+  delete pcOrgInterlaced;
+  pcRecInterlaced->destroy();
+  delete pcRecInterlaced;
+#endif
+}
 /** Function for deciding the nal_unit_type.
  * \param pocCurr POC of the current picture
Index: /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibEncoder/TEncGOP.h
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibEncoder/TEncGOP.h	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibEncoder/TEncGOP.h	(revision 651)
@@ -147,7 +147,7 @@
 #if H_MV
   Void  initGOP     ( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP);
-  Void  compressPicInGOP ( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP, Int iGOPid );
+  Void  compressPicInGOP ( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP, Int iGOPid, Bool isField, Bool isTff  );
 #else
-  Void  compressGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRec, std::list<AccessUnit>& accessUnitsInGOP );
+  Void  compressGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRec, std::list<AccessUnit>& accessUnitsInGOP, Bool isField, Bool isTff  );
 #endif
   Void  xAttachSliceDataToNalUnit (OutputNALUnit& rNalu, TComOutputBitstream*& rpcBitstreamRedirect);
@@ -168,5 +168,5 @@
 
 #if !H_MV
-  Void  printOutSummary      ( UInt uiNumAllPicCoded );
+  Void  printOutSummary      ( UInt uiNumAllPicCoded , bool isField);
 #endif
 #if H_3D_VSO
@@ -187,8 +187,12 @@
 
 protected:
+  Void xInitGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, bool isField );
+
   Void  xInitGOP          ( Int iPOC, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut );
-  Void  xGetBuffer        ( TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, Int iNumPicRcvd, Int iTimeOffset, TComPic*& rpcPic, TComPicYuv*& rpcPicYuvRecOut, Int pocCurr );
+  Void  xGetBuffer        ( TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, Int iNumPicRcvd, Int iTimeOffset, TComPic*& rpcPic, TComPicYuv*& rpcPicYuvRecOut, Int pocCurr, bool isField );
   
   Void  xCalculateAddPSNR ( TComPic* pcPic, TComPicYuv* pcPicD, const AccessUnit&, Double dEncTime );
+  Void  xCalculateInterlacedAddPSNR( TComPic* pcPicOrgTop, TComPic* pcPicOrgBottom, TComPicYuv* pcPicRecTop, TComPicYuv* pcPicRecBottom, const AccessUnit& accessUnit, Double dEncTime );
+
 #if H_3D_VSO
   Dist64 xFindDistortionFrame (TComPicYuv* pcPic0, TComPicYuv* pcPic1);
Index: /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibEncoder/TEncSlice.cpp
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 651)
@@ -188,7 +188,7 @@
  */
 #if H_MV
-Void TEncSlice::initEncSlice( TComPic* pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd, Int iGOPid, TComSlice*& rpcSlice, TComVPS* pVPS, TComSPS* pSPS, TComPPS *pPPS, Int layerId )
-#else
-Void TEncSlice::initEncSlice( TComPic* pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd, Int iGOPid, TComSlice*& rpcSlice, TComSPS* pSPS, TComPPS *pPPS )
+Void TEncSlice::initEncSlice( TComPic* pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd, Int iGOPid, TComSlice*& rpcSlice, TComVPS* pVPS, TComSPS* pSPS, TComPPS *pPPS, Int layerId, bool isField )
+#else
+Void TEncSlice::initEncSlice( TComPic* pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd, Int iGOPid, TComSlice*& rpcSlice, TComSPS* pSPS, TComPPS *pPPS, bool isField )
 #endif
 {
@@ -334,5 +334,5 @@
     Int    NumberBFrames = ( m_pcCfg->getGOPSize() - 1 );
     Int    SHIFT_QP = 12;
-    Double dLambda_scale = 1.0 - Clip3( 0.0, 0.5, 0.05*(Double)NumberBFrames );
+    Double dLambda_scale = 1.0 - Clip3( 0.0, 0.5, 0.05*(Double)(isField ? NumberBFrames/2 : NumberBFrames) );
 #if FULL_NBIT
     Int    bitdepth_luma_qp_scale = 6 * (g_bitDepth - 8);
Index: /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibEncoder/TEncSlice.h
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibEncoder/TEncSlice.h	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibEncoder/TEncSlice.h	(revision 651)
@@ -118,8 +118,8 @@
 #if H_MV
   Void    initEncSlice        ( TComPic* pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd, 
-                                Int iGOPid, TComSlice*& rpcSlice, TComVPS* pVPS, TComSPS* pSPS, TComPPS *pPPS, Int layerId ); 
+                                Int iGOPid, TComSlice*& rpcSlice, TComVPS* pVPS, TComSPS* pSPS, TComPPS *pPPS, Int layerId, bool isField  ); 
 #else
   Void    initEncSlice        ( TComPic*  pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd,
-                                Int iGOPid,   TComSlice*& rpcSlice, TComSPS* pSPS, TComPPS *pPPS );
+                                Int iGOPid,   TComSlice*& rpcSlice, TComSPS* pSPS, TComPPS *pPPS, bool isField  );
 #endif
 #if RATE_CONTROL_LAMBDA_DOMAIN
Index: /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibEncoder/TEncTop.cpp
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibEncoder/TEncTop.cpp	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibEncoder/TEncTop.cpp	(revision 651)
@@ -293,7 +293,7 @@
 
 #if KWU_RC_MADPRED_E0227
-Void TEncTop::init(TAppEncTop* pcTAppEncTop)
+Void TEncTop::init(TAppEncTop* pcTAppEncTop, Bool isFieldCoding)
 #else
-Void TEncTop::init()
+Void TEncTop::init(Bool isFieldCoding)
 #endif
 {
@@ -313,5 +313,5 @@
   m_cPPS.setSPS(&m_cSPS);
   xInitPPS();
-  xInitRPS();
+  xInitRPS(isFieldCoding);
 
   xInitPPSforTiles();
@@ -444,5 +444,5 @@
 #if H_MV
   }
-  m_cGOPEncoder.compressPicInGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, gopId );
+  m_cGOPEncoder.compressPicInGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, gopId, false, false );
 
   if( gopId + 1 == m_cGOPEncoder.getGOPSize() )
@@ -450,5 +450,5 @@
 #else
   // compress GOP
-  m_cGOPEncoder.compressGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut);
+  m_cGOPEncoder.compressGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, false, false);
 #endif
 
@@ -467,4 +467,160 @@
 #endif
 }
+/**------------------------------------------------
+ Separate interlaced frame into two fields
+ -------------------------------------------------**/
+void separateFields(Pel* org, Pel* dstField, UInt stride, UInt width, UInt height, bool isTop)
+{
+  if (!isTop)
+  {
+    org += stride;
+  }
+  for (Int y = 0; y < height>>1; y++)
+  {
+    for (Int x = 0; x < width; x++)
+    {
+      dstField[x] = org[x];
+    }
+    
+    dstField += stride;
+    org += stride*2;
+  }
+  
+}
+
+#if H_MV
+Void TEncTop::encode(Bool flush, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded, bool isTff, Int gopId )
+{
+  assert( 0 ); // Field coding and multiview need to be furhter harmonized. 
+}
+#else
+Void TEncTop::encode(Bool flush, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded, bool isTff)
+{
+  /* -- TOP FIELD -- */
+  
+  if (pcPicYuvOrg)
+  {
+    
+    /* -- Top field initialization -- */
+    
+    TComPic *pcTopField;
+    xGetNewPicBuffer( pcTopField );
+    pcTopField->getPicSym()->allocSaoParam(&m_cEncSAO);
+    pcTopField->setReconMark (false);
+    
+    pcTopField->getSlice(0)->setPOC( m_iPOCLast );
+    pcTopField->getPicYuvRec()->setBorderExtension(false);
+    pcTopField->setTopField(isTff);
+    
+    int nHeight = pcPicYuvOrg->getHeight();
+    int nWidth = pcPicYuvOrg->getWidth();
+    int nStride = pcPicYuvOrg->getStride();
+    int nPadLuma = pcPicYuvOrg->getLumaMargin();
+    int nPadChroma = pcPicYuvOrg->getChromaMargin();
+    
+    // Get pointers
+    Pel * PicBufY = pcPicYuvOrg->getBufY();
+    Pel * PicBufU = pcPicYuvOrg->getBufU();
+    Pel * PicBufV = pcPicYuvOrg->getBufV();
+    
+    Pel * pcTopFieldY =  pcTopField->getPicYuvOrg()->getLumaAddr();
+    Pel * pcTopFieldU =  pcTopField->getPicYuvOrg()->getCbAddr();
+    Pel * pcTopFieldV =  pcTopField->getPicYuvOrg()->getCrAddr();
+    
+    // compute image characteristics
+    if ( getUseAdaptiveQP() )
+    {
+      m_cPreanalyzer.xPreanalyze( dynamic_cast<TEncPic*>( pcTopField ) );
+    }
+    
+    /* -- Defield -- */
+    
+    bool isTop = isTff;
+    
+    separateFields(PicBufY + nPadLuma + nStride*nPadLuma, pcTopFieldY, nStride, nWidth, nHeight, isTop);
+    separateFields(PicBufU + nPadChroma + (nStride >> 1)*nPadChroma, pcTopFieldU, nStride >> 1, nWidth >> 1, nHeight >> 1, isTop);
+    separateFields(PicBufV + nPadChroma + (nStride >> 1)*nPadChroma, pcTopFieldV, nStride >> 1, nWidth >> 1, nHeight >> 1, isTop);
+    
+  }
+  
+  if (m_iPOCLast == 0) // compress field 0
+  {
+    m_cGOPEncoder.compressGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, true, isTff);
+  }
+  
+  /* -- BOTTOM FIELD -- */
+  
+  if (pcPicYuvOrg)
+  {
+    
+    /* -- Bottom field initialization -- */
+    
+    TComPic* pcBottomField;
+    xGetNewPicBuffer( pcBottomField );
+    pcBottomField->getPicSym()->allocSaoParam(&m_cEncSAO);
+    pcBottomField->setReconMark (false);
+    
+    TComPicYuv* rpcPicYuvRec = new TComPicYuv;
+    if ( rcListPicYuvRecOut.size() == (UInt)m_iGOPSize )
+    {
+      rpcPicYuvRec = rcListPicYuvRecOut.popFront();
+    }
+    else
+    {
+      rpcPicYuvRec->create( m_iSourceWidth, m_iSourceHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+    }
+    rcListPicYuvRecOut.pushBack( rpcPicYuvRec );
+    
+    pcBottomField->getSlice(0)->setPOC( m_iPOCLast);
+    pcBottomField->getPicYuvRec()->setBorderExtension(false);
+    pcBottomField->setTopField(!isTff);
+    
+    int nHeight = pcPicYuvOrg->getHeight();
+    int nWidth = pcPicYuvOrg->getWidth();
+    int nStride = pcPicYuvOrg->getStride();
+    int nPadLuma = pcPicYuvOrg->getLumaMargin();
+    int nPadChroma = pcPicYuvOrg->getChromaMargin();
+    
+    // Get pointers
+    Pel * PicBufY = pcPicYuvOrg->getBufY();
+    Pel * PicBufU = pcPicYuvOrg->getBufU();
+    Pel * PicBufV = pcPicYuvOrg->getBufV();
+    
+    Pel * pcBottomFieldY =  pcBottomField->getPicYuvOrg()->getLumaAddr();
+    Pel * pcBottomFieldU =  pcBottomField->getPicYuvOrg()->getCbAddr();
+    Pel * pcBottomFieldV =  pcBottomField->getPicYuvOrg()->getCrAddr();
+    
+    // Compute image characteristics
+    if ( getUseAdaptiveQP() )
+    {
+      m_cPreanalyzer.xPreanalyze( dynamic_cast<TEncPic*>( pcBottomField ) );
+    }
+    
+    /* -- Defield -- */
+    
+    bool isTop = !isTff;
+    
+    separateFields(PicBufY + nPadLuma + nStride*nPadLuma, pcBottomFieldY, nStride, nWidth, nHeight, isTop);
+    separateFields(PicBufU + nPadChroma + (nStride >> 1)*nPadChroma, pcBottomFieldU, nStride >> 1, nWidth >> 1, nHeight >> 1, isTop);
+    separateFields(PicBufV + nPadChroma + (nStride >> 1)*nPadChroma, pcBottomFieldV, nStride >> 1, nWidth >> 1, nHeight >> 1, isTop);
+    
+  }
+  
+  if ( ( !(m_iNumPicRcvd) || (!flush && m_iPOCLast != 1 && m_iNumPicRcvd != m_iGOPSize && m_iGOPSize)) )
+  {
+    iNumEncoded = 0;
+    return;
+  }
+  
+  // compress GOP
+  m_cGOPEncoder.compressGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, true, isTff);
+  
+  iNumEncoded = m_iNumPicRcvd;
+  m_iNumPicRcvd = 0;
+  m_uiNumAllPicCoded += iNumEncoded;
+}
+#endif
+
+
 
 // ====================================================================================================================
@@ -821,9 +977,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();
 
@@ -922,5 +1078,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())
@@ -928,5 +1084,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);
@@ -992,5 +1148,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);
+}
 }
 
@@ -1037,11 +1209,14 @@
     }
   }
+#if H_MV
+  }
+#endif
+  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());
-#if H_MV
-  }
-#endif
-
 }
 
@@ -1156,6 +1331,7 @@
 }
 #if H_MV
-Void TEncTop::printSummary( Int numAllPicCoded )
-{
+Void TEncTop::printSummary( Int numAllPicCoded, Bool isField )
+{
+  assert ( !isField ); // Multiview and field coding need to be further unified
   assert (numAllPicCoded == m_cAnalyzeAll.getNumPic());
 
Index: /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibEncoder/TEncTop.h
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibEncoder/TEncTop.h	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibEncoder/TEncTop.h	(revision 651)
@@ -145,5 +145,5 @@
   
   Void  xInitPPSforTiles  ();
-  Void  xInitRPS          ();                             ///< initialize PPS from encoder options
+  Void  xInitRPS          (Bool isFieldCoding);           ///< initialize PPS from encoder options
 
 public:
@@ -154,7 +154,7 @@
   Void      destroy         ();
 #if KWU_RC_MADPRED_E0227
-  Void      init            ( TAppEncTop* pcTAppEncTop );
-#else
-  Void      init            ();
+  Void      init            ( TAppEncTop* pcTAppEncTop, Bool isFieldCoding );
+#else
+  Void      init            (Bool isFieldCoding);
 #endif
 
@@ -228,13 +228,22 @@
 #if H_MV
   Void encode( Bool bEos, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded  , Int gopId  );  
+
+   /// encode several number of pictures until end-of-sequence
+  Void encode( bool bEos, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut,
+              std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded, bool isTff  , Int gopId );
+
 #else
   Void encode( Bool bEos, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut,
-              std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded );  
-#endif
-
-#if H_MV
-  Void printSummary      ( Int numAllPicCoded ); 
-#else
-  void printSummary() { m_cGOPEncoder.printOutSummary (m_uiNumAllPicCoded); } 
+              std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded ); 
+   /// encode several number of pictures until end-of-sequence
+  Void encode( bool bEos, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut,
+              std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded, bool isTff);
+
+#endif
+
+#if H_MV
+  Void printSummary      ( Int numAllPicCoded, bool isField ); 
+#else
+  Void printSummary(bool isField) { m_cGOPEncoder.printOutSummary (m_uiNumAllPicCoded, isField); }
 #endif
 
Index: /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibVideoIO/TVideoIOYuv.cpp
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibVideoIO/TVideoIOYuv.cpp	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibVideoIO/TVideoIOYuv.cpp	(revision 651)
@@ -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/HTM-8.2-dev0-Cleanup/source/Lib/TLibVideoIO/TVideoIOYuv.h
===================================================================
--- /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibVideoIO/TVideoIOYuv.h	(revision 650)
+++ /branches/HTM-8.2-dev0-Cleanup/source/Lib/TLibVideoIO/TVideoIOYuv.h	(revision 651)
@@ -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
