Index: trunk/source/App/TAppDecoder/TAppDecCfg.cpp
===================================================================
--- trunk/source/App/TAppDecoder/TAppDecCfg.cpp	(revision 1357)
+++ trunk/source/App/TAppDecoder/TAppDecCfg.cpp	(revision 1386)
@@ -62,9 +62,7 @@
     \param argv array of arguments
  */
-Bool TAppDecCfg::parseCfg( Int argc, Char* argv[] )
+Bool TAppDecCfg::parseCfg( Int argc, TChar* argv[] )
 {
   Bool do_help = false;
-  string cfg_BitstreamFile;
-  string cfg_ReconFile;
   string cfg_TargetDecLayerIdSetFile;
 #if NH_3D
@@ -79,6 +77,6 @@
 
   ("help",                      do_help,                               false,      "this help text")
-  ("BitstreamFile,b",           cfg_BitstreamFile,                     string(""), "bitstream input file name")
-  ("ReconFile,o",               cfg_ReconFile,                         string(""), "reconstructed YUV output file name\n"
+  ("BitstreamFile,b",           m_bitstreamFileName,                   string(""), "bitstream input file name")
+  ("ReconFile,o",               m_reconFileName,                       string(""), "reconstructed YUV output file name\n"
                                                                                    "YUV writing is skipped if omitted")
 #if NH_3D
@@ -92,5 +90,5 @@
   ("OutputColourSpaceConvert",  outputColourSpaceConvert,              string(""), "Colour space conversion to apply to input 444 video. Permitted values are (empty string=UNCHANGED) " + getListOfColourSpaceConverts(false))
 #if NH_MV
-  ("TargetOptLayerSetIdx,x",    m_targetOptLayerSetIdx,                -1,         "Target output layer set index. (default: -1, determine automatically to be equal to highest layer set index") // Should actually equal to 0 as default. However, this would cause only the base layer to be decoded.  
+  ("TargetOptLayerSetIdx,x", m_targetOptLayerSetInd, std::vector<Int>(1,-1), "Target output layer set index. (default: -1, determine automatically to be equal to highest layer set index") // Should actually equal to 0 as default. However, this would cause only the base layer to be decoded.  
 #endif
   ("MaxTemporalLayer,t",        m_iMaxTemporalLayer,                   -1,         "Maximum Temporal Layer to be decoded. -1 to decode all layers")
@@ -106,8 +104,10 @@
   ("PrintNalus,n",              m_printReceivedNalus,                 false,        "Print information on received NAL units")
 #endif
+  ("SEIColourRemappingInfoFilename",  m_colourRemapSEIFileName,        string(""), "Colour Remapping YUV output file name. If empty, no remapping is applied (ignore SEI message)\n")
+
 #if O0043_BEST_EFFORT_DECODING
   ("ForceDecodeBitDepth",       m_forceDecodeBitDepth,                 0U,         "Force the decoder to operate at a particular bit-depth (best effort decoding)")
 #endif
-#if NH_MV_SEI
+#if NH_MV
   ("OutputDecodedSEIMessagesFilename,m",  m_outputDecodedSEIMessagesFilename,    string(""), "When non empty, output decoded SEI messages to the indicated file. If file is '-', then output to stdout\n")
 #else
@@ -119,7 +119,7 @@
   po::setDefaults(opts);
   po::ErrorReporter err;
-  const list<const Char*>& argv_unhandled = po::scanArgv(opts, argc, (const Char**) argv, err);
-
-  for (list<const Char*>::const_iterator it = argv_unhandled.begin(); it != argv_unhandled.end(); it++)
+  const list<const TChar*>& argv_unhandled = po::scanArgv(opts, argc, (const TChar**) argv, err);
+
+  for (list<const TChar*>::const_iterator it = argv_unhandled.begin(); it != argv_unhandled.end(); it++)
   {
     fprintf(stderr, "Unhandled argument ignored: `%s'\n", *it);
@@ -148,13 +148,9 @@
   }
 
-  /* convert std::string to c string for compatability */
-  m_pchBitstreamFile = cfg_BitstreamFile.empty() ? NULL : strdup(cfg_BitstreamFile.c_str());
-  m_pchReconFile = cfg_ReconFile.empty() ? NULL : strdup(cfg_ReconFile.c_str());
-
 #if NH_3D
   m_pchScaleOffsetFile = cfg_ScaleOffsetFile.empty() ? NULL : strdup(cfg_ScaleOffsetFile.c_str());
 #endif
 
-  if (!m_pchBitstreamFile)
+  if (m_bitstreamFileName.empty())
   {
     fprintf(stderr, "No input file specified, aborting\n");
@@ -217,11 +213,11 @@
 
 #if NH_MV
-Void TAppDecCfg::xAppendToFileNameEnd( Char* pchInputFileName, const Char* pchStringToAppend, Char*& rpchOutputFileName)
+Void TAppDecCfg::xAppendToFileNameEnd( const TChar* pchInputFileName, const TChar* pchStringToAppend, TChar*& rpchOutputFileName)
 {
   size_t iInLength     = strlen(pchInputFileName);
   size_t iAppendLength = strlen(pchStringToAppend); 
 
-  rpchOutputFileName = (Char*) malloc(iInLength+iAppendLength+1);                        
-  Char* pCDot = strrchr(pchInputFileName,'.');         
+  rpchOutputFileName = (TChar*) malloc(iInLength+iAppendLength+1);                        
+  const TChar* pCDot = strrchr(pchInputFileName,'.');         
   pCDot = pCDot ? pCDot : pchInputFileName + iInLength;        
   size_t iCharsToDot = pCDot - pchInputFileName ; 
Index: trunk/source/App/TAppDecoder/TAppDecCfg.h
===================================================================
--- trunk/source/App/TAppDecoder/TAppDecCfg.h	(revision 1357)
+++ trunk/source/App/TAppDecoder/TAppDecCfg.h	(revision 1386)
@@ -60,6 +60,6 @@
 {
 protected:
-  Char*         m_pchBitstreamFile;                     ///< input bitstream file name
-  Char*         m_pchReconFile;                         ///< output reconstruction file name
+  std::string   m_bitstreamFileName;                    ///< input bitstream file name
+  std::string   m_reconFileName;                        ///< output reconstruction file name
   Int           m_iSkipFrame;                           ///< counter for frames prior to the random access point to skip
   Int           m_outputBitDepth[MAX_NUM_CHANNEL_TYPE]; ///< bit depth used for writing output
@@ -69,4 +69,5 @@
   Int           m_decodedPictureHashSEIEnabled;       ///< Checksum(3)/CRC(2)/MD5(1)/disable(0) acting on decoded picture hash SEI message
   Bool          m_decodedNoDisplaySEIEnabled;         ///< Enable(true)/disable(false) writing only pictures that get displayed based on the no display SEI message
+  std::string   m_colourRemapSEIFileName;             ///< output Colour Remapping file name
   std::vector<Int> m_targetDecLayerIdSet;             ///< set of LayerIds to be included in the sub-bitstream extraction process.
 
@@ -78,40 +79,47 @@
   Bool          m_bClipOutputVideoToRec709Range;      ///< If true, clip the output video to the Rec 709 range on saving.
 #if NH_MV
-  std::vector<Char*> m_pchReconFiles;                   ///< array of output reconstruction file name create from output reconstruction file name
+  std::vector<TChar*> m_pchReconFiles;                ///< array of output reconstruction file name create from output reconstruction file name
 
-  Int           m_targetOptLayerSetIdx;                 ///< target output layer set index
+  std::vector<Int> m_targetOptLayerSetInd;            ///< target output layer set indices (multiple decoding when more than one element, e.g. for additional layer sets)
+  Int           m_targetOptLayerSetIdx;               ///< current target output layer set index
+
   Int           m_targetDecLayerSetIdx;
   Int           m_baseLayerOutputFlag;
   Int           m_baseLayerPicOutputFlag;
   Int           m_auOutputFlag;
-  Int           m_maxLayerId;                           ///< maximum nuh_layer_id decoded
+  Int           m_maxLayerId;                         ///< maximum nuh_layer_id decoded
   std::ifstream m_bitstreamFile;
   Int           m_highestTid;
   Bool          m_targetDecLayerIdSetFileEmpty;       ///< indication if target layers are given by file
 
-  Bool          m_printVpsInfo;                      ///< Output VPS information
+  Bool          m_printVpsInfo;                       ///< Output VPS information
   Bool          m_printPicOutput;                     ///< Print information on picture output
   Bool          m_printReceivedNalus;                 ///< Print information on received NAL units
 #if NH_3D
-  Char*         m_pchScaleOffsetFile;                   ///< output coded scale and offset parameters
+  TChar*        m_pchScaleOffsetFile;                   ///< output coded scale and offset parameters
   Bool          m_depth420OutputFlag;                   ///< output depth layers in 4:2:0
 #endif
 
-  Void xAppendToFileNameEnd( Char* pchInputFileName, const Char* pchStringToAppend, Char*& rpchOutputFileName); ///< create filenames
+  Void xAppendToFileNameEnd( const TChar* pchInputFileName, const TChar* pchStringToAppend, TChar*& rpchOutputFileName); ///< create filenames
 #endif
 
 public:
   TAppDecCfg()
-  : m_pchBitstreamFile(NULL)
-  , m_pchReconFile(NULL)
+  : m_bitstreamFileName()
+  , m_reconFileName()
   , m_iSkipFrame(0)
+  // m_outputBitDepth array initialised below
   , m_outputColourSpaceConvert(IPCOLOURSPACE_UNCHANGED)
   , m_iMaxTemporalLayer(-1)
   , m_decodedPictureHashSEIEnabled(0)
   , m_decodedNoDisplaySEIEnabled(false)
+  , m_colourRemapSEIFileName()
+  , m_targetDecLayerIdSet()
   , m_respectDefDispWindow(0)
 #if O0043_BEST_EFFORT_DECODING
   , m_forceDecodeBitDepth(0)
 #endif
+  , m_outputDecodedSEIMessagesFilename()
+  , m_bClipOutputVideoToRec709Range(false)
 #if NH_MV
   , m_highestTid(-1)
@@ -131,5 +139,8 @@
   virtual ~TAppDecCfg() {}
 
-  Bool  parseCfg        ( Int argc, Char* argv[] );   ///< initialize option class from configuration
+  Bool  parseCfg        ( Int argc, TChar* argv[] );   ///< initialize option class from configuration
+#if NH_MV
+  Int   getNumDecodings ( ) { return (Int) m_targetOptLayerSetInd.size();  }; 
+#endif
 };
 
Index: trunk/source/App/TAppDecoder/TAppDecTop.cpp
===================================================================
--- trunk/source/App/TAppDecoder/TAppDecTop.cpp	(revision 1357)
+++ trunk/source/App/TAppDecoder/TAppDecTop.cpp	(revision 1386)
@@ -62,4 +62,5 @@
 : m_numDecoders( 0 )
 #endif
+ ,m_pcSeiColourRemappingInfoPrevious(NULL)
 {
 #if NH_MV
@@ -118,10 +119,5 @@
   xDestroyDecLib();
 #endif
-
-  if (m_pchBitstreamFile)
-  {
-    free (m_pchBitstreamFile);
-    m_pchBitstreamFile = NULL;
-  }
+  m_bitstreamFileName.clear();
 #if NH_MV
   for (Int decIdx = 0; decIdx < m_numDecoders; decIdx++)
@@ -134,9 +130,5 @@
   }
 #endif
-  if (m_pchReconFile)
-  {
-    free (m_pchReconFile);
-    m_pchReconFile = NULL;
-  }
+  m_reconFileName.clear();
 #if NH_3D
   if (m_pchScaleOffsetFile)
@@ -160,8 +152,8 @@
  .
  */
-
 #if NH_MV
-Void TAppDecTop::decode()
-{
+Void TAppDecTop::decode( Int num )
+{
+  m_targetOptLayerSetIdx = m_targetOptLayerSetInd[ num ]; 
   // create & initialize internal classes
   xInitFileIO  ();
@@ -221,13 +213,13 @@
 
 #if !NH_MV
-Void TAppDecTop::decode()
+Void TAppDecTop::decode( )
 {
   Int                 poc;
   TComList<TComPic*>* pcListPic = NULL;
 
-  ifstream bitstreamFile(m_pchBitstreamFile, ifstream::in | ifstream::binary);
+  ifstream bitstreamFile(m_bitstreamFileName.c_str(), ifstream::in | ifstream::binary);
   if (!bitstreamFile)
   {
-    fprintf(stderr, "\nfailed to open bitstream file `%s' for reading\n", m_pchBitstreamFile);
+    fprintf(stderr, "\nfailed to open bitstream file `%s' for reading\n", m_bitstreamFileName.c_str());
     exit(EXIT_FAILURE);
   }
@@ -250,4 +242,15 @@
 
   m_iPOCLastDisplay += m_iSkipFrame;      // set the last displayed POC correctly for skip forward.
+
+  // clear contents of colour-remap-information-SEI output file
+  if (!m_colourRemapSEIFileName.empty())
+  {
+    std::ofstream ofile(m_colourRemapSEIFileName.c_str());
+    if (!ofile.good() || !ofile.is_open())
+    {
+      fprintf(stderr, "\nUnable to open file '%s' for writing colour-remap-information-SEI video\n", m_colourRemapSEIFileName.c_str());
+      exit(EXIT_FAILURE);
+    }
+  }
 
   // main decoder loop
@@ -336,5 +339,5 @@
     if( pcListPic )
     {
-      if ( m_pchReconFile && !openedReconFile )
+      if ( (!m_reconFileName.empty()) && (!openedReconFile) )
       {
         const BitDepths &bitDepths=pcListPic->front()->getPicSym()->getSPS().getBitDepths(); // use bit depths of first reconstructed picture.
@@ -346,5 +349,6 @@
           }
         }
-        m_cTVideoIOYuvReconFile.open( m_pchReconFile, true, m_outputBitDepth, m_outputBitDepth, bitDepths.recon ); // write mode
+
+        m_cTVideoIOYuvReconFile.open( m_reconFileName, true, m_outputBitDepth, m_outputBitDepth, bitDepths.recon ); // write mode
         openedReconFile = true;
       }
@@ -436,5 +440,5 @@
   }
 #else
-  if ( m_pchReconFile )
+  if ( !m_reconFileName.empty() )
   {
     m_cTVideoIOYuvReconFile. close();
@@ -444,4 +448,9 @@
   m_cTDecTop.destroy();
 #endif
+  if (m_pcSeiColourRemappingInfoPrevious != NULL)
+  {
+    delete m_pcSeiColourRemappingInfoPrevious;
+    m_pcSeiColourRemappingInfoPrevious = NULL;
+  }
 #if NH_3D
   m_cCamParsCollector.uninit();
@@ -474,4 +483,9 @@
   }
 #endif
+  if (m_pcSeiColourRemappingInfoPrevious != NULL)
+  {
+    delete m_pcSeiColourRemappingInfoPrevious;
+    m_pcSeiColourRemappingInfoPrevious = NULL;
+  }
 }
 
@@ -549,5 +563,5 @@
         // write to file
         numPicsNotYetDisplayed = numPicsNotYetDisplayed-2;
-        if ( m_pchReconFile )
+        if ( !m_reconFileName.empty() )
         {
           const Window &conf = pcPicTop->getConformanceWindow();
@@ -617,5 +631,5 @@
           dpbFullness--;
         }
-        if ( m_pchReconFile )
+        if ( !m_reconFileName.empty() )
         {
           const Window &conf    = pcPic->getConformanceWindow();
@@ -631,4 +645,9 @@
         }
 
+        if (!m_colourRemapSEIFileName.empty())
+        {
+          xOutputColourRemapPic(pcPic);
+        }
+
         // update POC of display order
         m_iPOCLastDisplay = pcPic->getPOC();
@@ -678,5 +697,5 @@
         // write to file
 
-        if ( m_pchReconFile )
+        if ( !m_reconFileName.empty() )
         {
           const Window &conf = pcPicTop->getConformanceWindow();
@@ -736,5 +755,5 @@
       {
         // write to file
-        if ( m_pchReconFile )
+        if ( !m_reconFileName.empty() )
         {
           const Window &conf    = pcPic->getConformanceWindow();
@@ -749,4 +768,9 @@
         }
 
+        if (!m_colourRemapSEIFileName.empty())
+        {
+          xOutputColourRemapPic(pcPic);
+        }
+
         // update POC of display order
         m_iPOCLastDisplay = pcPic->getPOC();
@@ -1068,5 +1092,5 @@
     m_newVpsActivatedbyCurAu  = true; //TBD
     m_newVpsActivatedbyCurPic = true;
-#if NH_3D
+#if NH_3D_VSO
     m_dpb.setVPS( m_vps ); 
 #endif
@@ -1232,5 +1256,5 @@
   }
 
-  if ( m_printVpsInfo  && ( m_decProcCvsg == ANNEX_F ) )
+  if ( m_printVpsInfo  && ( m_decProcCvsg == ANNEX_F ) && ( m_targetOptLayerSetIdx == m_targetOptLayerSetInd[ 0 ] ) )
   {
     m_vps->printScalabilityId();
@@ -1979,5 +2003,5 @@
       // - After all slices of the current picture have been decoded, the decoding process for ending the decoding of a
       //   coded picture with nuh_layer_id greater than 0 specified in clause F.8.1.6 is invoked.
-      xF816decProcEndDecOfCodPicLIdGrtZero( );
+      xF816decProcEndDecOfCodPicLIdGrtZero( );      
     }
 
@@ -2671,11 +2695,11 @@
 
     // create recon file related stuff
-    Char* pchTempFilename = NULL;
-    if ( m_pchReconFile )
-    {
-      Char buffer[4];
+    TChar* pchTempFilename = NULL;
+    if ( !m_reconFileName.empty() )
+    {
+      TChar buffer[4];
       sprintf(buffer,"_%i", layerId );
-      assert ( m_pchReconFile );
-      xAppendToFileNameEnd( m_pchReconFile , buffer, pchTempFilename );
+      assert ( !m_reconFileName.empty() );
+      xAppendToFileNameEnd( m_reconFileName.c_str() , buffer, pchTempFilename );
       assert( m_pchReconFiles.size() == m_numDecoders );
     }
@@ -2870,9 +2894,9 @@
 Void TAppDecTop::xInitFileIO()
 {
-  m_bitstreamFile.open(m_pchBitstreamFile, ifstream::in | ifstream::binary);
+  m_bitstreamFile.open(m_bitstreamFileName.c_str(), ifstream::in | ifstream::binary);
 
   if ( !m_bitstreamFile)
   {
-    fprintf(stderr, "\nUnable to open bitstream file `%s' for reading\n", m_pchBitstreamFile);
+    fprintf(stderr, "\nUnable to open bitstream file `%s' for reading\n", m_bitstreamFileName.c_str());
     exit(EXIT_FAILURE);
   }
@@ -2905,5 +2929,5 @@
   Int decIdx = xGetDecoderIdx( curPic->getLayerId() );
 
-  if ( m_pchReconFile && !m_reconOpen[decIdx] )
+  if ( !m_reconFileName.empty() && !m_reconOpen[decIdx] )
   {
     const BitDepths &bitDepths= curPic->getPicSym()->getSPS().getBitDepths(); // use bit depths of first reconstructed picture.
@@ -3007,3 +3031,324 @@
 
 #endif
+
+Void TAppDecTop::xOutputColourRemapPic(TComPic* pcPic)
+{
+  const TComSPS &sps=pcPic->getPicSym()->getSPS();
+  SEIMessages colourRemappingInfo = getSeisByType(pcPic->getSEIs(), SEI::COLOUR_REMAPPING_INFO );
+  SEIColourRemappingInfo *seiColourRemappingInfo = ( colourRemappingInfo.size() > 0 ) ? (SEIColourRemappingInfo*) *(colourRemappingInfo.begin()) : NULL;
+
+  if (colourRemappingInfo.size() > 1)
+  {
+    printf ("Warning: Got multiple Colour Remapping Information SEI messages. Using first.");
+  }
+  if (seiColourRemappingInfo)
+  {
+    applyColourRemapping(*pcPic->getPicYuvRec(), *seiColourRemappingInfo, sps);
+
+    // save the last CRI SEI received
+    if (m_pcSeiColourRemappingInfoPrevious == NULL)
+    {
+      m_pcSeiColourRemappingInfoPrevious = new SEIColourRemappingInfo();
+    }
+    m_pcSeiColourRemappingInfoPrevious->copyFrom(*seiColourRemappingInfo);
+  }
+  else  // using the last CRI SEI received
+  {
+    // TODO: prevent persistence of CRI SEI across C(L)VS.
+    if (m_pcSeiColourRemappingInfoPrevious != NULL)
+    {
+      if (m_pcSeiColourRemappingInfoPrevious->m_colourRemapPersistenceFlag == false)
+      {
+        printf("Warning No SEI-CRI message is present for the current picture, persistence of the CRI is not managed\n");
+      }
+      applyColourRemapping(*pcPic->getPicYuvRec(), *m_pcSeiColourRemappingInfoPrevious, sps);
+    }
+  }
+}
+
+// compute lut from SEI
+// use at lutPoints points aligned on a power of 2 value
+// SEI Lut must be in ascending values of coded Values
+static std::vector<Int>
+initColourRemappingInfoLut(const Int                                          bitDepth_in,     // bit-depth of the input values of the LUT
+                           const Int                                          nbDecimalValues, // Position of the fixed point
+                           const std::vector<SEIColourRemappingInfo::CRIlut> &lut,
+                           const Int                                          maxValue, // maximum output value
+                           const Int                                          lutOffset)
+{
+  const Int lutPoints = (1 << bitDepth_in) + 1 ;
+  std::vector<Int> retLut(lutPoints);
+
+  // missing values: need to define default values before first definition (check codedValue[0] == 0)
+  Int iTargetPrev = (lut.size() && lut[0].codedValue == 0) ? lut[0].targetValue: 0;
+  Int startPivot = (lut.size())? ((lut[0].codedValue == 0)? 1: 0): 1;
+  Int iCodedPrev  = 0;
+  // set max value with the coded bit-depth
+  // + ((1 << nbDecimalValues) - 1) is for the added bits
+  const Int maxValueFixedPoint = (maxValue << nbDecimalValues) + ((1 << nbDecimalValues) - 1);
+
+  Int iValue = 0;
+
+  for ( Int iPivot=startPivot ; iPivot < (Int)lut.size(); iPivot++ )
+  {
+    Int iCodedNext  = lut[iPivot].codedValue;
+    Int iTargetNext = lut[iPivot].targetValue;
+
+    // ensure correct bit depth and avoid overflow in lut address
+    Int iCodedNext_bitDepth = std::min(iCodedNext, (1 << bitDepth_in));
+
+    const Int divValue =  (iCodedNext - iCodedPrev > 0)? (iCodedNext - iCodedPrev): 1;
+    const Int lutValInit = (lutOffset + iTargetPrev) << nbDecimalValues;
+    const Int roundValue = divValue / 2;
+    for ( ; iValue<iCodedNext_bitDepth; iValue++ )
+    {
+      Int value = iValue;
+      Int interpol = ((((value-iCodedPrev) * (iTargetNext - iTargetPrev)) << nbDecimalValues) + roundValue) / divValue;               
+      retLut[iValue]  = std::min(lutValInit + interpol , maxValueFixedPoint);
+    }
+    iCodedPrev  = iCodedNext;
+    iTargetPrev = iTargetNext;
+  }
+  // fill missing values if necessary
+  if(iCodedPrev < (1 << bitDepth_in)+1)
+  {
+    Int iCodedNext  = (1 << bitDepth_in);
+    Int iTargetNext = (1 << bitDepth_in) - 1;
+
+    const Int divValue =  (iCodedNext - iCodedPrev > 0)? (iCodedNext - iCodedPrev): 1;
+    const Int lutValInit = (lutOffset + iTargetPrev) << nbDecimalValues;
+    const Int roundValue = divValue / 2;
+
+    for ( ; iValue<=iCodedNext; iValue++ )
+    {
+      Int value = iValue;
+      Int interpol = ((((value-iCodedPrev) * (iTargetNext - iTargetPrev)) << nbDecimalValues) + roundValue) / divValue; 
+      retLut[iValue]  = std::min(lutValInit + interpol , maxValueFixedPoint);
+    }
+  }
+  return retLut;
+}
+
+static Void
+initColourRemappingInfoLuts(std::vector<Int>      (&preLut)[3],
+                            std::vector<Int>      (&postLut)[3],
+                            SEIColourRemappingInfo &pCriSEI,
+                            const Int               maxBitDepth)
+{
+  Int internalBitDepth = pCriSEI.m_colourRemapBitDepth;
+  for ( Int c=0 ; c<3 ; c++ )
+  {
+    std::sort(pCriSEI.m_preLut[c].begin(), pCriSEI.m_preLut[c].end()); // ensure preLut is ordered in ascending values of codedValues   
+    preLut[c] = initColourRemappingInfoLut(pCriSEI.m_colourRemapInputBitDepth, maxBitDepth - pCriSEI.m_colourRemapInputBitDepth, pCriSEI.m_preLut[c], ((1 << internalBitDepth) - 1), 0); //Fill preLut
+
+    std::sort(pCriSEI.m_postLut[c].begin(), pCriSEI.m_postLut[c].end()); // ensure postLut is ordered in ascending values of codedValues       
+    postLut[c] = initColourRemappingInfoLut(pCriSEI.m_colourRemapBitDepth, maxBitDepth - pCriSEI.m_colourRemapBitDepth, pCriSEI.m_postLut[c], (1 << internalBitDepth) - 1, 0); //Fill postLut
+  }
+}
+
+// apply lut.
+// Input lut values are aligned on power of 2 boundaries
+static Int
+applyColourRemappingInfoLut1D(Int inVal, const std::vector<Int> &lut, const Int inValPrecisionBits)
+{
+  const Int roundValue = (inValPrecisionBits)? 1 << (inValPrecisionBits - 1): 0;
+  inVal = std::min(std::max(0, inVal), (Int)(((lut.size()-1) << inValPrecisionBits)));
+  Int index  = (Int) std::min((inVal >> inValPrecisionBits), (Int)(lut.size()-2));
+  Int outVal = (( inVal - (index<<inValPrecisionBits) ) * (lut[index+1] - lut[index]) + roundValue) >> inValPrecisionBits;
+  outVal +=  lut[index] ;
+
+  return outVal;
+}  
+
+static Int
+applyColourRemappingInfoMatrix(const Int (&colourRemapCoeffs)[3], const Int postOffsetShift, const Int p0, const Int p1, const Int p2, const Int offset)
+{
+  Int YUVMat = (colourRemapCoeffs[0]* p0 + colourRemapCoeffs[1]* p1 + colourRemapCoeffs[2]* p2  + offset) >> postOffsetShift;
+  return YUVMat;
+}
+
+static Void
+setColourRemappingInfoMatrixOffset(Int (&matrixOffset)[3], Int offset0, Int offset1, Int offset2)
+{
+  matrixOffset[0] = offset0;
+  matrixOffset[1] = offset1;
+  matrixOffset[2] = offset2;
+}
+
+static Void
+setColourRemappingInfoMatrixOffsets(      Int  (&matrixInputOffset)[3],
+                                          Int  (&matrixOutputOffset)[3],
+                                    const Int  bitDepth,
+                                    const Bool crInputFullRangeFlag,
+                                    const Int  crInputMatrixCoefficients,
+                                    const Bool crFullRangeFlag,
+                                    const Int  crMatrixCoefficients)
+{
+  // set static matrix offsets
+  Int crInputOffsetLuma = (crInputFullRangeFlag)? 0:-(16 << (bitDepth-8));
+  Int crOffsetLuma = (crFullRangeFlag)? 0:(16 << (bitDepth-8));
+  Int crInputOffsetChroma = 0;
+  Int crOffsetChroma = 0;
+
+  switch(crInputMatrixCoefficients)
+  {
+    case MATRIX_COEFFICIENTS_RGB:
+      crInputOffsetChroma = 0;
+      if(!crInputFullRangeFlag)
+      {
+        fprintf(stderr, "WARNING: crInputMatrixCoefficients set to MATRIX_COEFFICIENTS_RGB and crInputFullRangeFlag not set\n");
+        crInputOffsetLuma = 0;
+      }
+      break;
+    case MATRIX_COEFFICIENTS_UNSPECIFIED:
+    case MATRIX_COEFFICIENTS_BT709:
+    case MATRIX_COEFFICIENTS_BT2020_NON_CONSTANT_LUMINANCE:
+      crInputOffsetChroma = -(1 << (bitDepth-1));
+      break;
+    default:
+      fprintf(stderr, "WARNING: crInputMatrixCoefficients set to undefined value: %d\n", crInputMatrixCoefficients);
+  }
+
+  switch(crMatrixCoefficients)
+  {
+    case MATRIX_COEFFICIENTS_RGB:
+      crOffsetChroma = 0;
+      if(!crFullRangeFlag)
+      {
+        fprintf(stderr, "WARNING: crMatrixCoefficients set to MATRIX_COEFFICIENTS_RGB and crInputFullRangeFlag not set\n");
+        crOffsetLuma = 0;
+      }
+      break;
+    case MATRIX_COEFFICIENTS_UNSPECIFIED:
+    case MATRIX_COEFFICIENTS_BT709:
+    case MATRIX_COEFFICIENTS_BT2020_NON_CONSTANT_LUMINANCE:
+      crOffsetChroma = (1 << (bitDepth-1));
+      break;
+    default:
+      fprintf(stderr, "WARNING: crMatrixCoefficients set to undefined value: %d\n", crMatrixCoefficients);
+  }
+
+  setColourRemappingInfoMatrixOffset(matrixInputOffset, crInputOffsetLuma, crInputOffsetChroma, crInputOffsetChroma);
+  setColourRemappingInfoMatrixOffset(matrixOutputOffset, crOffsetLuma, crOffsetChroma, crOffsetChroma);
+}
+
+Void TAppDecTop::applyColourRemapping(const TComPicYuv& pic, SEIColourRemappingInfo& criSEI, const TComSPS &activeSPS)
+{  
+  const Int maxBitDepth = 16;
+
+  // create colour remapped picture
+  if( !criSEI.m_colourRemapCancelFlag && pic.getChromaFormat()!=CHROMA_400) // 4:0:0 not supported.
+  {
+    const Int          iHeight         = pic.getHeight(COMPONENT_Y);
+    const Int          iWidth          = pic.getWidth(COMPONENT_Y);
+    const ChromaFormat chromaFormatIDC = pic.getChromaFormat();
+
+    TComPicYuv picYuvColourRemapped;
+    picYuvColourRemapped.createWithoutCUInfo( iWidth, iHeight, chromaFormatIDC );
+
+    const Int  iStrideIn   = pic.getStride(COMPONENT_Y);
+    const Int  iCStrideIn  = pic.getStride(COMPONENT_Cb);
+    const Int  iStrideOut  = picYuvColourRemapped.getStride(COMPONENT_Y);
+    const Int  iCStrideOut = picYuvColourRemapped.getStride(COMPONENT_Cb);
+    const Bool b444        = ( pic.getChromaFormat() == CHROMA_444 );
+    const Bool b422        = ( pic.getChromaFormat() == CHROMA_422 );
+    const Bool b420        = ( pic.getChromaFormat() == CHROMA_420 );
+
+    std::vector<Int> preLut[3];
+    std::vector<Int> postLut[3];
+    Int matrixInputOffset[3];
+    Int matrixOutputOffset[3];
+    const Pel *YUVIn[MAX_NUM_COMPONENT];
+    Pel *YUVOut[MAX_NUM_COMPONENT];
+    YUVIn[COMPONENT_Y]  = pic.getAddr(COMPONENT_Y);
+    YUVIn[COMPONENT_Cb] = pic.getAddr(COMPONENT_Cb);
+    YUVIn[COMPONENT_Cr] = pic.getAddr(COMPONENT_Cr);
+    YUVOut[COMPONENT_Y]  = picYuvColourRemapped.getAddr(COMPONENT_Y);
+    YUVOut[COMPONENT_Cb] = picYuvColourRemapped.getAddr(COMPONENT_Cb);
+    YUVOut[COMPONENT_Cr] = picYuvColourRemapped.getAddr(COMPONENT_Cr);
+
+    const Int bitDepth = criSEI.m_colourRemapBitDepth;
+    BitDepths        bitDepthsCriFile;
+    bitDepthsCriFile.recon[CHANNEL_TYPE_LUMA]   = bitDepth;
+    bitDepthsCriFile.recon[CHANNEL_TYPE_CHROMA] = bitDepth; // Different bitdepth is not implemented
+
+    const Int postOffsetShift = criSEI.m_log2MatrixDenom;
+    const Int matrixRound = 1 << (postOffsetShift - 1);
+    const Int postLutInputPrecision = (maxBitDepth - criSEI.m_colourRemapBitDepth);
+
+    if ( ! criSEI.m_colourRemapVideoSignalInfoPresentFlag ) // setting default
+    {
+      setColourRemappingInfoMatrixOffsets(matrixInputOffset, matrixOutputOffset, maxBitDepth,
+          activeSPS.getVuiParameters()->getVideoFullRangeFlag(), activeSPS.getVuiParameters()->getMatrixCoefficients(),
+          activeSPS.getVuiParameters()->getVideoFullRangeFlag(), activeSPS.getVuiParameters()->getMatrixCoefficients());
+    }
+    else
+    {
+      setColourRemappingInfoMatrixOffsets(matrixInputOffset, matrixOutputOffset, maxBitDepth,
+          activeSPS.getVuiParameters()->getVideoFullRangeFlag(), activeSPS.getVuiParameters()->getMatrixCoefficients(),
+          criSEI.m_colourRemapFullRangeFlag, criSEI.m_colourRemapMatrixCoefficients);
+    }
+
+    // add matrix rounding to output matrix offsets
+    matrixOutputOffset[0] = (matrixOutputOffset[0] << postOffsetShift) + matrixRound;
+    matrixOutputOffset[1] = (matrixOutputOffset[1] << postOffsetShift) + matrixRound;
+    matrixOutputOffset[2] = (matrixOutputOffset[2] << postOffsetShift) + matrixRound;
+
+    // Merge   matrixInputOffset and matrixOutputOffset to matrixOutputOffset
+    matrixOutputOffset[0] += applyColourRemappingInfoMatrix(criSEI.m_colourRemapCoeffs[0], 0, matrixInputOffset[0], matrixInputOffset[1], matrixInputOffset[2], 0);
+    matrixOutputOffset[1] += applyColourRemappingInfoMatrix(criSEI.m_colourRemapCoeffs[1], 0, matrixInputOffset[0], matrixInputOffset[1], matrixInputOffset[2], 0);
+    matrixOutputOffset[2] += applyColourRemappingInfoMatrix(criSEI.m_colourRemapCoeffs[2], 0, matrixInputOffset[0], matrixInputOffset[1], matrixInputOffset[2], 0);
+
+    // rescaling output: include CRI/output frame difference
+    const Int scaleShiftOut_neg = abs(bitDepth - maxBitDepth);
+    const Int scaleOut_round = 1 << (scaleShiftOut_neg-1);
+
+    initColourRemappingInfoLuts(preLut, postLut, criSEI, maxBitDepth);
+
+    assert(pic.getChromaFormat() != CHROMA_400);
+    const Int hs = pic.getComponentScaleX(ComponentID(COMPONENT_Cb));
+    const Int maxOutputValue = (1 << bitDepth) - 1;
+
+    for( Int y = 0; y < iHeight; y++ )
+    {
+      for( Int x = 0; x < iWidth; x++ )
+      {
+        const Int xc = (x>>hs);
+        Bool computeChroma = b444 || ((b422 || !(y&1)) && !(x&1));
+
+        Int YUVPre_0 = applyColourRemappingInfoLut1D(YUVIn[COMPONENT_Y][x], preLut[0], 0);
+        Int YUVPre_1 = applyColourRemappingInfoLut1D(YUVIn[COMPONENT_Cb][xc], preLut[1], 0);
+        Int YUVPre_2 = applyColourRemappingInfoLut1D(YUVIn[COMPONENT_Cr][xc], preLut[2], 0);
+
+        Int YUVMat_0 = applyColourRemappingInfoMatrix(criSEI.m_colourRemapCoeffs[0], postOffsetShift, YUVPre_0, YUVPre_1, YUVPre_2, matrixOutputOffset[0]);
+        Int YUVLutB_0 = applyColourRemappingInfoLut1D(YUVMat_0, postLut[0], postLutInputPrecision);
+        YUVOut[COMPONENT_Y][x] = std::min(maxOutputValue, (YUVLutB_0 + scaleOut_round) >> scaleShiftOut_neg);
+
+        if( computeChroma )
+        {
+          Int YUVMat_1 = applyColourRemappingInfoMatrix(criSEI.m_colourRemapCoeffs[1], postOffsetShift, YUVPre_0, YUVPre_1, YUVPre_2, matrixOutputOffset[1]);
+          Int YUVLutB_1 = applyColourRemappingInfoLut1D(YUVMat_1, postLut[1], postLutInputPrecision);
+          YUVOut[COMPONENT_Cb][xc] = std::min(maxOutputValue, (YUVLutB_1 + scaleOut_round) >> scaleShiftOut_neg);
+
+          Int YUVMat_2 = applyColourRemappingInfoMatrix(criSEI.m_colourRemapCoeffs[2], postOffsetShift, YUVPre_0, YUVPre_1, YUVPre_2, matrixOutputOffset[2]);
+          Int YUVLutB_2 = applyColourRemappingInfoLut1D(YUVMat_2, postLut[2], postLutInputPrecision);
+          YUVOut[COMPONENT_Cr][xc] = std::min(maxOutputValue, (YUVLutB_2 + scaleOut_round) >> scaleShiftOut_neg);
+        }
+      }
+
+      YUVIn[COMPONENT_Y]  += iStrideIn;
+      YUVOut[COMPONENT_Y] += iStrideOut;
+      if( !(b420 && !(y&1)) )
+      {
+         YUVIn[COMPONENT_Cb]  += iCStrideIn;
+         YUVIn[COMPONENT_Cr]  += iCStrideIn;
+         YUVOut[COMPONENT_Cb] += iCStrideOut;
+         YUVOut[COMPONENT_Cr] += iCStrideOut;
+      }
+    }
+    //Write remapped picture in display order
+    picYuvColourRemapped.dump( m_colourRemapSEIFileName, bitDepthsCriFile, true );
+    picYuvColourRemapped.destroy();
+  }
+}
 //! \}
Index: trunk/source/App/TAppDecoder/TAppDecTop.h
===================================================================
--- trunk/source/App/TAppDecoder/TAppDecTop.h	(revision 1357)
+++ trunk/source/App/TAppDecoder/TAppDecTop.h	(revision 1386)
@@ -128,4 +128,7 @@
 #endif
   std::ofstream                   m_seiMessageFileStream;         ///< Used for outputing SEI messages.  
+
+  SEIColourRemappingInfo*         m_pcSeiColourRemappingInfoPrevious;
+
 public:
   TAppDecTop();
@@ -134,9 +137,11 @@
   Void  create            (); ///< create internal members
   Void  destroy           (); ///< destroy internal members
-  Void  decode            (); ///< main decoding function
+  
 #if NH_MV
+  Void  decode            ( Int i ); ///< main decoding function
   UInt  getNumberOfChecksumErrorsDetected( ) const;
   UInt  getNumberOfChecksumErrorsDetected( Int decIdx ) const { return m_tDecTop[decIdx]->getNumberOfChecksumErrorsDetected(); }
 #else
+  Void  decode            ( ); ///< main decoding function
   UInt  getNumberOfChecksumErrorsDetected() const { return m_cTDecTop.getNumberOfChecksumErrorsDetected(); }
 #endif
@@ -206,4 +211,8 @@
   Void  xCropAndOutput                     ( TComPic* curPic );  
 #endif
+
+private:
+  Void applyColourRemapping(const TComPicYuv& pic, SEIColourRemappingInfo& pCriSEI, const TComSPS &activeSPS);
+  Void xOutputColourRemapPic(TComPic* pcPic);
 };
 
Index: trunk/source/App/TAppDecoder/decmain.cpp
===================================================================
--- trunk/source/App/TAppDecoder/decmain.cpp	(revision 1357)
+++ trunk/source/App/TAppDecoder/decmain.cpp	(revision 1386)
@@ -51,6 +51,7 @@
 {
   Int returnCode = EXIT_SUCCESS;
+#if !NH_MV
   TAppDecTop  cTAppDecTop;
-
+#endif
   // print information
   fprintf( stdout, "\n" );
@@ -65,35 +66,61 @@
   fprintf( stdout, "\n" );
 
-  // create application decoder class
-  cTAppDecTop.create();
+#if NH_MV
+  Int numDecodings = 1; 
+  Int curDecoding  = 0; 
+  Double dResult = 0; 
+  do {
+    TAppDecTop  cTAppDecTop;
+#endif
+    // create application decoder class
+    cTAppDecTop.create();
 
-  // parse configuration
-  if(!cTAppDecTop.parseCfg( argc, argv ))
-  {
-    cTAppDecTop.destroy();
-    returnCode = EXIT_FAILURE;
-    return returnCode;
-  }
+    // parse configuration
+    if(!cTAppDecTop.parseCfg( argc, argv ))
+    {
+      cTAppDecTop.destroy();
+      returnCode = EXIT_FAILURE;
+      return returnCode;
+    }
+#if NH_MV
+    numDecodings = cTAppDecTop.getNumDecodings(); 
+#endif
 
-  // starting time
+    // starting time    
+#if !NH_MV
   Double dResult;
-  clock_t lBefore = clock();
+#endif
+    clock_t lBefore = clock();
 
-  // call decoding function
-  cTAppDecTop.decode();
+    // call decoding function
+#if NH_MV
+    cTAppDecTop.decode( curDecoding );
+#else
+    cTAppDecTop.decode();
+#endif
 
-  if (cTAppDecTop.getNumberOfChecksumErrorsDetected() != 0)
-  {
-    printf("\n\n***ERROR*** A decoding mismatch occured: signalled md5sum does not match\n");
-    returnCode = EXIT_FAILURE;
-  }
+    if (cTAppDecTop.getNumberOfChecksumErrorsDetected() != 0)
+    {
+      printf("\n\n***ERROR*** A decoding mismatch occured: signalled md5sum does not match\n");
+      returnCode = EXIT_FAILURE;
+    }
 
-  // ending time
+    // ending time
+#if NH_MV
+    dResult += (double)(clock()-lBefore) / CLOCKS_PER_SEC;
+#else
   dResult = (Double)(clock()-lBefore) / CLOCKS_PER_SEC;
   printf("\n Total Time: %12.3f sec.\n", dResult);
+#endif
 
-  // destroy application decoder class
-  cTAppDecTop.destroy();
+    // destroy application decoder class
+    cTAppDecTop.destroy();
+#if NH_MV
+    curDecoding++; 
+  } 
+  while ( curDecoding < numDecodings );
 
+  printf("\n Total Time: %12.3f sec.\n", dResult);
+#endif
   return returnCode;
 }
Index: trunk/source/App/TAppEncoder/TAppEncCfg.cpp
===================================================================
--- trunk/source/App/TAppEncoder/TAppEncCfg.cpp	(revision 1357)
+++ trunk/source/App/TAppEncoder/TAppEncCfg.cpp	(revision 1386)
@@ -109,16 +109,7 @@
 
 TAppEncCfg::TAppEncCfg()
-#if NH_MV
-: m_pchBitstreamFile()
-#else
-: m_pchInputFile()
-, m_pchBitstreamFile()
-, m_pchReconFile()
-#endif
-, m_inputColourSpaceConvert(IPCOLOURSPACE_UNCHANGED)
+: m_inputColourSpaceConvert(IPCOLOURSPACE_UNCHANGED)
 , m_snrInternalColourSpace(false)
 , m_outputInternalColourSpace(false)
-, m_pchdQPFile()
-, m_scalingListFile()
 {
 #if !NH_MV
@@ -171,8 +162,4 @@
     m_targetPivotValue = NULL;
   }
-#if !NH_MV
-  free(m_pchInputFile);
-#endif
-  free(m_pchBitstreamFile);
 #if NH_MV
   for(Int i = 0; i< m_pchReconFileList.size(); i++ )
@@ -181,10 +168,5 @@
       free (m_pchReconFileList[i]);
   }
-#else
-  free(m_pchReconFile);
-#endif
-  free(m_pchdQPFile);
-  free(m_scalingListFile);
-#if NH_MV
+
   for( Int i = 0; i < m_GOPListMvc.size(); i++ )
   {
@@ -195,6 +177,10 @@
     }
   }
-#endif
-#if NH_3D
+
+  if ( m_pchBaseViewCameraNumbers != NULL )
+  {
+    free ( m_pchBaseViewCameraNumbers ); 
+  }
+#endif
 #if NH_3D_VSO
   if (  m_pchVSOConfig != NULL)
@@ -202,13 +188,8 @@
     free (  m_pchVSOConfig );
   }
-#endif
+  
   if ( m_pchCameraParameterFile != NULL )
   {
     free ( m_pchCameraParameterFile ); 
-  }
-
-  if ( m_pchBaseViewCameraNumbers != NULL )
-  {
-    free ( m_pchBaseViewCameraNumbers ); 
   }
 #endif
@@ -224,5 +205,5 @@
 
 
-#if NH_MV_SEI
+#if NH_MV
 Void TAppEncCfg::xParseSeiCfg()
 {
@@ -302,5 +283,5 @@
 }
 
-Bool confirmPara(Bool bflag, const Char* message);
+Bool confirmPara(Bool bflag, const TChar* message);
 
 static inline ChromaFormat numberToChromaFormat(const Int val)
@@ -318,5 +299,5 @@
 static const struct MapStrToProfile
 {
-  const Char* str;
+  const TChar* str;
   Profile::Name value;
 }
@@ -340,5 +321,5 @@
 static const struct MapStrToExtendedProfile
 {
-  const Char* str;
+  const TChar* str;
   ExtendedProfileName value;
 }
@@ -405,5 +386,5 @@
 static const struct MapStrToTier
 {
-  const Char* str;
+  const TChar* str;
   Level::Tier value;
 }
@@ -416,5 +397,5 @@
 static const struct MapStrToLevel
 {
-  const Char* str;
+  const TChar* str;
   Level::Name value;
 }
@@ -438,7 +419,16 @@
 };
 
+#if U0132_TARGET_BITS_SATURATION
+UInt g_uiMaxCpbSize[2][21] =
+{
+  //         LEVEL1,        LEVEL2,LEVEL2_1,     LEVEL3, LEVEL3_1,      LEVEL4, LEVEL4_1,       LEVEL5,  LEVEL5_1,  LEVEL5_2,    LEVEL6,  LEVEL6_1,  LEVEL6_2 
+  { 0, 0, 0, 350000, 0, 0, 1500000, 3000000, 0, 6000000, 10000000, 0, 12000000, 20000000, 0,  25000000,  40000000,  60000000,  60000000, 120000000, 240000000 },
+  { 0, 0, 0,      0, 0, 0,       0,       0, 0,       0,        0, 0, 30000000, 50000000, 0, 100000000, 160000000, 240000000, 240000000, 480000000, 800000000 }
+};
+#endif
+
 static const struct MapStrToCostMode
 {
-  const Char* str;
+  const TChar* str;
   CostMode    value;
 }
@@ -453,5 +443,5 @@
 static const struct MapStrToScalingListMode
 {
-  const Char* str;
+  const TChar* str;
   ScalingListMode value;
 }
@@ -533,5 +523,5 @@
 {
   const T              minValIncl;
-  const T              maxValIncl; // Use 0 for unlimited
+  const T              maxValIncl;
   const std::size_t    minNumValuesIncl;
   const std::size_t    maxNumValuesIncl; // Use 0 for unlimited
@@ -545,9 +535,60 @@
   SMultiValueInput<T> &operator=(const std::vector<T> &userValues) { values=userValues; return *this; }
   SMultiValueInput<T> &operator=(const SMultiValueInput<T> &userValues) { values=userValues.values; return *this; }
+
+  T readValue(const TChar *&pStr, Bool &bSuccess);
+
+  istream& readValues(std::istream &in);
 };
 
-static inline istream& operator >> (istream &in, SMultiValueInput<UInt> &values)
+template <class T>
+static inline istream& operator >> (std::istream &in, SMultiValueInput<T> &values)
 {
-  values.values.clear();
+  return values.readValues(in);
+  }
+
+template<>
+UInt SMultiValueInput<UInt>::readValue(const TChar *&pStr, Bool &bSuccess)
+    {
+  TChar *eptr;
+      UInt val=strtoul(pStr, &eptr, 0);
+  pStr=eptr;
+  bSuccess=!(*eptr!=0 && !isspace(*eptr) && *eptr!=',') && !(val<minValIncl || val>maxValIncl);
+  return val;
+      }
+
+template<>
+Int SMultiValueInput<Int>::readValue(const TChar *&pStr, Bool &bSuccess)
+      {
+  TChar *eptr;
+  Int val=strtol(pStr, &eptr, 0);
+      pStr=eptr;
+  bSuccess=!(*eptr!=0 && !isspace(*eptr) && *eptr!=',') && !(val<minValIncl || val>maxValIncl);
+  return val;
+}
+
+template<>
+Double SMultiValueInput<Double>::readValue(const TChar *&pStr, Bool &bSuccess)
+  {
+  TChar *eptr;
+  Double val=strtod(pStr, &eptr);
+  pStr=eptr;
+  bSuccess=!(*eptr!=0 && !isspace(*eptr) && *eptr!=',') && !(val<minValIncl || val>maxValIncl);
+  return val;
+  }
+
+template<>
+Bool SMultiValueInput<Bool>::readValue(const TChar *&pStr, Bool &bSuccess)
+    {
+  TChar *eptr;
+      Int val=strtol(pStr, &eptr, 0);
+      pStr=eptr;
+  bSuccess=!(*eptr!=0 && !isspace(*eptr) && *eptr!=',') && !(val<Int(minValIncl) || val>Int(maxValIncl));
+  return val!=0;
+}
+
+template <class T>
+istream& SMultiValueInput<T>::readValues(std::istream &in)
+{
+  values.clear();
   string str;
   while (!in.eof())
@@ -557,5 +598,5 @@
   if (!str.empty())
   {
-    const Char *pStr=str.c_str();
+    const TChar *pStr=str.c_str();
     // soak up any whitespace
     for(;isspace(*pStr);pStr++);
@@ -563,25 +604,19 @@
     while (*pStr != 0)
     {
-      Char *eptr;
-      UInt val=strtoul(pStr, &eptr, 0);
-      if (*eptr!=0 && !isspace(*eptr) && *eptr!=',')
+      Bool bSuccess=true;
+      T val=readValue(pStr, bSuccess);
+      if (!bSuccess)
       {
         in.setstate(ios::failbit);
         break;
       }
-      if (val<values.minValIncl || val>values.maxValIncl)
+
+      if (maxNumValuesIncl != 0 && values.size() >= maxNumValuesIncl)
       {
         in.setstate(ios::failbit);
         break;
       }
-
-      if (values.maxNumValuesIncl != 0 && values.values.size() >= values.maxNumValuesIncl)
-      {
-        in.setstate(ios::failbit);
-        break;
-      }
-      values.values.push_back(val);
+      values.push_back(val);
       // soak up any whitespace and up to 1 comma.
-      pStr=eptr;
       for(;isspace(*pStr);pStr++);
       if (*pStr == ',')
@@ -592,109 +627,5 @@
     }
   }
-  if (values.values.size() < values.minNumValuesIncl)
-  {
-    in.setstate(ios::failbit);
-  }
-  return in;
-}
-
-static inline istream& operator >> (istream &in, SMultiValueInput<Int> &values)
-{
-  values.values.clear();
-  string str;
-  while (!in.eof())
-  {
-    string tmp; in >> tmp; str+=" " + tmp;
-  }
-  if (!str.empty())
-  {
-    const Char *pStr=str.c_str();
-    // soak up any whitespace
-    for(;isspace(*pStr);pStr++);
-
-    while (*pStr != 0)
-    {
-      Char *eptr;
-      Int val=strtol(pStr, &eptr, 0);
-      if (*eptr!=0 && !isspace(*eptr) && *eptr!=',')
-      {
-        in.setstate(ios::failbit);
-        break;
-      }
-      if (val<values.minValIncl || val>values.maxValIncl)
-      {
-        in.setstate(ios::failbit);
-        break;
-      }
-
-      if (values.maxNumValuesIncl != 0 && values.values.size() >= values.maxNumValuesIncl)
-      {
-        in.setstate(ios::failbit);
-        break;
-      }
-      values.values.push_back(val);
-      // soak up any whitespace and up to 1 comma.
-      pStr=eptr;
-      for(;isspace(*pStr);pStr++);
-      if (*pStr == ',')
-      {
-        pStr++;
-      }
-      for(;isspace(*pStr);pStr++);
-    }
-  }
-  if (values.values.size() < values.minNumValuesIncl)
-  {
-    in.setstate(ios::failbit);
-  }
-  return in;
-}
-
-static inline istream& operator >> (istream &in, SMultiValueInput<Bool> &values)
-{
-  values.values.clear();
-  string str;
-  while (!in.eof())
-  {
-    string tmp; in >> tmp; str+=" " + tmp;
-  }
-  if (!str.empty())
-  {
-    const Char *pStr=str.c_str();
-    // soak up any whitespace
-    for(;isspace(*pStr);pStr++);
-
-    while (*pStr != 0)
-    {
-      Char *eptr;
-      Int val=strtol(pStr, &eptr, 0);
-      if (*eptr!=0 && !isspace(*eptr) && *eptr!=',')
-      {
-        in.setstate(ios::failbit);
-        break;
-      }
-      if (val<Int(values.minValIncl) || val>Int(values.maxValIncl))
-      {
-        in.setstate(ios::failbit);
-        break;
-      }
-
-      if (values.maxNumValuesIncl != 0 && values.values.size() >= values.maxNumValuesIncl)
-      {
-        in.setstate(ios::failbit);
-        break;
-      }
-      values.values.push_back(val!=0);
-      // soak up any whitespace and up to 1 comma.
-      pStr=eptr;
-      for(;isspace(*pStr);pStr++);
-      if (*pStr == ',')
-      {
-        pStr++;
-      }
-      for(;isspace(*pStr);pStr++);
-    }
-  }
-  if (values.values.size() < values.minNumValuesIncl)
+  if (values.size() < minNumValuesIncl)
   {
     in.setstate(ios::failbit);
@@ -786,15 +717,8 @@
     \retval             true when success
  */
-Bool TAppEncCfg::parseCfg( Int argc, Char* argv[] )
+Bool TAppEncCfg::parseCfg( Int argc, TChar* argv[] )
 {
   Bool do_help = false;
 
-#if !NH_MV
-  string cfg_InputFile;
-#endif
-  string cfg_BitstreamFile;
-#if !NH_MV
-  string cfg_ReconFile;
-#endif
 #if NH_MV
   vector<Int>   cfg_dimensionLength; 
@@ -809,10 +733,14 @@
 #endif 
 #endif
-  string cfg_dQPFile;
-  string cfg_ScalingListFile;
 
   Int tmpChromaFormat;
   Int tmpInputChromaFormat;
   Int tmpConstraintChromaFormat;
+  Int tmpWeightedPredictionMethod;
+  Int tmpFastInterSearchMode;
+  Int tmpMotionEstimationSearchMethod;
+  Int tmpSliceMode;
+  Int tmpSliceSegmentMode;
+  Int tmpDecodedPictureHashSEIMappedType;
   string inputColourSpaceConvert;
 #if NH_MV
@@ -829,4 +757,7 @@
   SMultiValueInput<Int>  cfg_codedPivotValue                 (std::numeric_limits<Int>::min(), std::numeric_limits<Int>::max(), 0, 1<<16);
   SMultiValueInput<Int>  cfg_targetPivotValue                (std::numeric_limits<Int>::min(), std::numeric_limits<Int>::max(), 0, 1<<16);
+
+  SMultiValueInput<Double> cfg_adIntraLambdaModifier         (0, std::numeric_limits<Double>::max(), 0, MAX_TLAYER); ///< Lambda modifier for Intra pictures, one for each temporal layer. If size>temporalLayer, then use [temporalLayer], else if size>0, use [size()-1], else use m_adLambdaModifier.
+
 
   const UInt defaultInputKneeCodes[3]  = { 600, 800, 900 };
@@ -866,36 +797,36 @@
   ("InputFile_%d,i_%d",       m_pchInputFileList,       (char *) 0 , MAX_NUM_LAYER_IDS , "original Yuv input file name %d")
 #else
-  ("InputFile,i",                                     cfg_InputFile,                               string(""), "Original YUV input file name")
-#endif
-  ("BitstreamFile,b",                                 cfg_BitstreamFile,                           string(""), "Bitstream output file name")
+  ("InputFile,i",                                     m_inputFileName,                             string(""), "Original YUV input file name")
+#endif
+  ("BitstreamFile,b",                                 m_bitstreamFileName,                         string(""), "Bitstream output file name")
 #if NH_MV
   ("ReconFile_%d,o_%d",       m_pchReconFileList,       (char *) 0 , MAX_NUM_LAYER_IDS , "reconstructed Yuv output file name %d")
 #else
-  ("ReconFile,o",                                     cfg_ReconFile,                               string(""), "Reconstructed YUV output file name")
-#endif
-#if NH_MV
-  ("NumberOfLayers",        m_numberOfLayers     , 1,                     "Number of layers")
-#if !NH_3D
-  ("ScalabilityMask",       m_scalabilityMask    , 2                    , "Scalability Mask: 2: Multiview, 8: Auxiliary, 10: Multiview + Auxiliary")    
-#else
-  ("ScalabilityMask",       m_scalabilityMask    , 3                    , "Scalability Mask, 1: Texture 3: Texture + Depth ")    
+  ("ReconFile,o",                                     m_reconFileName,                             string(""), "Reconstructed YUV output file name")
+#endif
+#if NH_MV
+  ("NumberOfLayers",                 m_numberOfLayers     , 1,                     "Number of layers")
+#if !NH_3D                           
+  ("ScalabilityMask",                m_scalabilityMask    , 2                    , "Scalability Mask: 2: Multiview, 8: Auxiliary, 10: Multiview + Auxiliary")    
+#else                                
+  ("ScalabilityMask",                m_scalabilityMask    , 3                    , "Scalability Mask, 1: Texture 3: Texture + Depth ")    
 #endif  
-  ("DimensionIdLen",        m_dimensionIdLen     , cfg_dimensionLength  , "Number of bits used to store dimensions Id")
+  ("DimensionIdLen",                 m_dimensionIdLen     , cfg_dimensionLength  , "Number of bits used to store dimensions Id")
   ("ViewOrderIndex",                 m_viewOrderIndex              , IntAry1d(1,0),                                 "View Order Index per layer")
   ("ViewId",                         m_viewId                      , IntAry1d(1,0),                                 "View Id per View Order Index")
   ("AuxId",                          m_auxId                       , IntAry1d(1,0),                                 "AuxId per layer")
-#if NH_3D
+#if NH_3D_VSO
   ("DepthFlag",                      m_depthFlag                   , IntAry1d(1,0),                                 "Depth Flag")
 #endif
   ("TargetEncLayerIdList",           m_targetEncLayerIdList        , IntAry1d(0,0),                                 "LayerIds in Nuh to be encoded")  
   ("LayerIdInNuh",                   m_layerIdInNuh                , IntAry1d(1,0),                                 "LayerId in Nuh")  
-  ("SplittingFlag",         m_splittingFlag       , false                , "Splitting Flag")    
+  ("SplittingFlag",                  m_splittingFlag               , false,                                         "Splitting Flag")    
 
   // Layer Sets + Output Layer Sets + Profile Tier Level
-  ("VpsNumLayerSets",       m_vpsNumLayerSets    , 1                    , "Number of layer sets")    
-  ("LayerIdsInSet_%d"              , m_layerIdsInSets              , IntAry1d(1,0) , MAX_VPS_OP_SETS_PLUS1      ,   "LayerIds of Layer set")  
-  ("NumAddLayerSets"     , m_numAddLayerSets     , 0                                              , "NumAddLayerSets     ")
+  ("VpsNumLayerSets"               , m_vpsNumLayerSets             , 1                                          ,   "Number of layer sets")    
+  ("LayerIdsInSet_%d"              , m_layerIdxInVpsInSets         , IntAry1d(1,0) , MAX_VPS_OP_SETS_PLUS1      ,   "Layer indices in VPS of layers in layer set")  
+  ("NumAddLayerSets"               , m_numAddLayerSets             , 0 ,                                             "NumAddLayerSets     ")
   ("HighestLayerIdxPlus1_%d"       , m_highestLayerIdxPlus1        , IntAry1d(0,0) , MAX_VPS_NUM_ADD_LAYER_SETS ,   "HighestLayerIdxPlus1")
-  ("DefaultTargetOutputLayerIdc"     , m_defaultOutputLayerIdc     , 0, "Specifies output layers of layer sets, 0: output all layers, 1: output highest layer, 2: specified by LayerIdsInDefOutputLayerSet")
+  ("DefaultTargetOutputLayerIdc"   , m_defaultOutputLayerIdc       , 0 ,                                             "Specifies output layers of layer sets, 0: output all layers, 1: output highest layer, 2: specified by LayerIdsInDefOutputLayerSet")
   ("OutputLayerSetIdx"             , m_outputLayerSetIdx           , IntAry1d(0,0)                              ,   "Indices of layer sets used as additional output layer sets")
   ("LayerIdsInAddOutputLayerSet_%d", m_layerIdsInAddOutputLayerSet , IntAry1d(0,0) , MAX_VPS_ADD_OUTPUT_LAYER_SETS, "Indices in VPS of output layers in additional output layer set")  
@@ -941,4 +872,5 @@
   ("ConfWinTop",                                      m_confWinTop,                                         0, "Top offset for window conformance mode 3")
   ("ConfWinBottom",                                   m_confWinBottom,                                      0, "Bottom offset for window conformance mode 3")
+  ("AccessUnitDelimiter",                             m_AccessUnitDelimiter,                            false, "Enable Access Unit Delimiter NALUs")
   ("FrameRate,-fr",                                   m_iFrameRate,                                         0, "Frame rate")
   ("FrameSkip,-fs",                                   m_FrameSkip,                                         0u, "Number of frames to skip at start of input YUV")
@@ -1003,5 +935,5 @@
   // motion search options
   ("DisableIntraInInter",                             m_bDisableIntraPUsInInterSlices,                  false, "Flag to disable intra PUs in inter slices")
-  ("FastSearch",                                      m_iFastSearch,                                        1, "0:Full search  1:Diamond  2:PMVFAST")
+  ("FastSearch",                                      tmpMotionEstimationSearchMethod,  Int(MESEARCH_DIAMOND), "0:Full search 1:Diamond 2:Selective 3:Enhanced Diamond")
   ("SearchRange,-sr",                                 m_iSearchRange,                                      96, "Motion search range")
 #if NH_MV
@@ -1010,4 +942,6 @@
 #endif
   ("BipredSearchRange",                               m_bipredSearchRange,                                  4, "Motion search range for bipred refinement")
+  ("MinSearchWindow",                                 m_minSearchWindow,                                    8, "Minimum motion search window size for the adaptive window ME")
+  ("RestrictMESampling",                              m_bRestrictMESampling,                            false, "Restrict ME Sampling for selective inter motion search")
   ("ClipForBiPredMEEnabled",                          m_bClipForBiPredMeEnabled,                        false, "Enables clipping in the Bi-Pred ME. It is disabled to reduce encoder run-time")
   ("FastMEAssumingSmootherMVEnabled",                 m_bFastMEAssumingSmootherMVEnabled,                true, "Enables fast ME assuming a smoother MV.")
@@ -1017,11 +951,13 @@
 
   // Mode decision parameters
-  ("LambdaModifier0,-LM0",                            m_adLambdaModifier[ 0 ],                  ( Double )1.0, "Lambda modifier for temporal layer 0")
-  ("LambdaModifier1,-LM1",                            m_adLambdaModifier[ 1 ],                  ( Double )1.0, "Lambda modifier for temporal layer 1")
-  ("LambdaModifier2,-LM2",                            m_adLambdaModifier[ 2 ],                  ( Double )1.0, "Lambda modifier for temporal layer 2")
-  ("LambdaModifier3,-LM3",                            m_adLambdaModifier[ 3 ],                  ( Double )1.0, "Lambda modifier for temporal layer 3")
-  ("LambdaModifier4,-LM4",                            m_adLambdaModifier[ 4 ],                  ( Double )1.0, "Lambda modifier for temporal layer 4")
-  ("LambdaModifier5,-LM5",                            m_adLambdaModifier[ 5 ],                  ( Double )1.0, "Lambda modifier for temporal layer 5")
-  ("LambdaModifier6,-LM6",                            m_adLambdaModifier[ 6 ],                  ( Double )1.0, "Lambda modifier for temporal layer 6")
+  ("LambdaModifier0,-LM0",                            m_adLambdaModifier[ 0 ],                  ( Double )1.0, "Lambda modifier for temporal layer 0. If LambdaModifierI is used, this will not affect intra pictures")
+  ("LambdaModifier1,-LM1",                            m_adLambdaModifier[ 1 ],                  ( Double )1.0, "Lambda modifier for temporal layer 1. If LambdaModifierI is used, this will not affect intra pictures")
+  ("LambdaModifier2,-LM2",                            m_adLambdaModifier[ 2 ],                  ( Double )1.0, "Lambda modifier for temporal layer 2. If LambdaModifierI is used, this will not affect intra pictures")
+  ("LambdaModifier3,-LM3",                            m_adLambdaModifier[ 3 ],                  ( Double )1.0, "Lambda modifier for temporal layer 3. If LambdaModifierI is used, this will not affect intra pictures")
+  ("LambdaModifier4,-LM4",                            m_adLambdaModifier[ 4 ],                  ( Double )1.0, "Lambda modifier for temporal layer 4. If LambdaModifierI is used, this will not affect intra pictures")
+  ("LambdaModifier5,-LM5",                            m_adLambdaModifier[ 5 ],                  ( Double )1.0, "Lambda modifier for temporal layer 5. If LambdaModifierI is used, this will not affect intra pictures")
+  ("LambdaModifier6,-LM6",                            m_adLambdaModifier[ 6 ],                  ( Double )1.0, "Lambda modifier for temporal layer 6. If LambdaModifierI is used, this will not affect intra pictures")
+  ("LambdaModifierI,-LMI",                            cfg_adIntraLambdaModifier,    cfg_adIntraLambdaModifier, "Lambda modifiers for Intra pictures, comma separated, up to one the number of temporal layer. If entry for temporalLayer exists, then use it, else if some are specified, use the last, else use the standard LambdaModifiers.")
+  ("IQPFactor,-IQF",                                  m_dIntraQpFactor,                                  -1.0, "Intra QP Factor for Lambda Computation. If negative, use the default equation: 0.57*(1.0 - Clip3( 0.0, 0.5, 0.05*(Double)(isField ? (GopSize-1)/2 : GopSize-1) ))")
 
   /* Quantization parameters */
@@ -1046,5 +982,5 @@
   ("AdaptiveQP,-aq",                                  m_bUseAdaptiveQP,                                 false, "QP adaptation based on a psycho-visual model")
   ("MaxQPAdaptationRange,-aqr",                       m_iQPAdaptationRange,                                 6, "QP adaptation range")
-  ("dQPFile,m",                                       cfg_dQPFile,                                 string(""), "dQP file name")
+  ("dQPFile,m",                                       m_dQPFileName,                               string(""), "dQP file name")
   ("RDOQ",                                            m_useRDOQ,                                         true)
   ("RDOQTS",                                          m_useRDOQTS,                                       true)
@@ -1090,10 +1026,10 @@
   ("MaxNumOffsetsPerPic",                             m_maxNumOffsetsPerPic,                             2048, "Max number of SAO offset per picture (Default: 2048)")
   ("SAOLcuBoundary",                                  m_saoCtuBoundary,                                 false, "0: right/bottom CTU boundary areas skipped from SAO parameter estimation, 1: non-deblocked pixels are used for those areas")
-  ("SliceMode",                                       m_sliceMode,                                          0, "0: Disable all Recon slice limits, 1: Enforce max # of CTUs, 2: Enforce max # of bytes, 3:specify tiles per dependent slice")
+  ("SliceMode",                                       tmpSliceMode,                            Int(NO_SLICES), "0: Disable all Recon slice limits, 1: Enforce max # of CTUs, 2: Enforce max # of bytes, 3:specify tiles per dependent slice")
   ("SliceArgument",                                   m_sliceArgument,                                      0, "Depending on SliceMode being:"
                                                                                                                "\t1: max number of CTUs per slice"
                                                                                                                "\t2: max number of bytes per slice"
                                                                                                                "\t3: max number of tiles per slice")
-  ("SliceSegmentMode",                                m_sliceSegmentMode,                                   0, "0: Disable all slice segment limits, 1: Enforce max # of CTUs, 2: Enforce max # of bytes, 3:specify tiles per dependent slice")
+  ("SliceSegmentMode",                                tmpSliceSegmentMode,                     Int(NO_SLICES), "0: Disable all slice segment limits, 1: Enforce max # of CTUs, 2: Enforce max # of bytes, 3:specify tiles per dependent slice")
   ("SliceSegmentArgument",                            m_sliceSegmentArgument,                               0, "Depending on SliceSegmentMode being:"
                                                                                                                "\t1: max number of CTUs per slice segment"
@@ -1112,7 +1048,8 @@
   ("PCMInputBitDepthFlag",                            m_bPCMInputBitDepthFlag,                           true)
   ("PCMFilterDisableFlag",                            m_bPCMFilterDisableFlag,                          false)
-  ("IntraReferenceSmoothing",                         m_enableIntraReferenceSmoothing,                   true, "0: Disable use of intra reference smoothing. 1: Enable use of intra reference smoothing (not valid in V1 profiles)")
+  ("IntraReferenceSmoothing",                         m_enableIntraReferenceSmoothing,                   true, "0: Disable use of intra reference smoothing (not valid in V1 profiles). 1: Enable use of intra reference smoothing (same as V1)")
   ("WeightedPredP,-wpP",                              m_useWeightedPred,                                false, "Use weighted prediction in P slices")
   ("WeightedPredB,-wpB",                              m_useWeightedBiPred,                              false, "Use weighted (bidirectional) prediction in B slices")
+  ("WeightedPredMethod,-wpM",                         tmpWeightedPredictionMethod, Int(WP_PER_PICTURE_WITH_SIMPLE_DC_COMBINED_COMPONENT), "Weighted prediction method")
   ("Log2ParallelMergeLevel",                          m_log2ParallelMergeLevel,                            2u, "Parallel merge estimation region")
     //deprecated copies of renamed tile parameters
@@ -1127,11 +1064,11 @@
   ("TileRowHeightArray",                              cfg_RowHeight,                            cfg_RowHeight, "Array containing tile row height values in units of CTU")
   ("LFCrossTileBoundaryFlag",                         m_bLFCrossTileBoundaryFlag,                        true, "1: cross-tile-boundary loop filtering. 0:non-cross-tile-boundary loop filtering")
-  ("WaveFrontSynchro",                                m_iWaveFrontSynchro,                                  0, "0: no synchro; 1 synchro with top-right-right")
+  ("WaveFrontSynchro",                                m_entropyCodingSyncEnabledFlag,                   false, "0: entropy coding sync disabled; 1 entropy coding sync enabled")
   ("ScalingList",                                     m_useScalingListId,                    SCALING_LIST_OFF, "0/off: no scaling list, 1/default: default scaling lists, 2/file: scaling lists specified in ScalingListFile")
-  ("ScalingListFile",                                 cfg_ScalingListFile,                         string(""), "Scaling list file name. Use an empty string to produce help.")
+  ("ScalingListFile",                                 m_scalingListFileName,                       string(""), "Scaling list file name. Use an empty string to produce help.")
   ("SignHideFlag,-SBH",                               m_signHideFlag,                                    true)
   ("MaxNumMergeCand",                                 m_maxNumMergeCand,                                   5u, "Maximum number of merge candidates")
   /* Misc. */
-  ("SEIDecodedPictureHash",                           m_decodedPictureHashSEIEnabled,                       0, "Control generation of decode picture hash SEI messages\n"
+  ("SEIDecodedPictureHash",                           tmpDecodedPictureHashSEIMappedType,                   0, "Control generation of decode picture hash SEI messages\n"
                                                                                                                "\t3: checksum\n"
                                                                                                                "\t2: CRC\n"
@@ -1139,5 +1076,5 @@
                                                                                                                "\t0: disable")
   ("TMVPMode",                                        m_TMVPModeId,                                         1, "TMVP mode 0: TMVP disable for all slices. 1: TMVP enable for all slices (default) 2: TMVP enable for certain slices only")
-  ("FEN",                                             m_bUseFastEnc,                                    false, "fast encoder setting")
+  ("FEN",                                             tmpFastInterSearchMode,   Int(FASTINTERSEARCH_DISABLED), "fast encoder setting")
   ("ECU",                                             m_bUseEarlyCU,                                    false, "Early CU setting")
   ("FDM",                                             m_useFastDecisionForMerge,                         true, "Fast decision for Merge RD Cost")
@@ -1152,4 +1089,10 @@
   ( "RCForceIntraQP",                                 m_RCForceIntraQP,                                 false, "Rate control: force intra QP to be equal to initial QP" )
 
+#if U0132_TARGET_BITS_SATURATION
+  ( "RCCpbSaturation",                                m_RCCpbSaturationEnabled,                         false, "Rate control: enable target bits saturation to avoid CPB overflow and underflow" )
+  ( "RCCpbSize",                                      m_RCCpbSize,                                         0u, "Rate control: CPB size" )
+  ( "RCInitialCpbFullness",                           m_RCInitialCpbFullness,                             0.9, "Rate control: initial CPB fullness" )
+#endif
+
 #if KWU_RC_VIEWRC_E0227
   ("ViewWiseTargetBits, -vtbr" ,  m_viewTargetBits,  std::vector<Int>(1, 32), "View-wise target bit-rate setting")
@@ -1162,28 +1105,28 @@
 // A lot of this stuff could should actually be derived by the encoder.
   // VPS VUI
-  ("VpsVuiPresentFlag"           , m_vpsVuiPresentFlag           , false                                           , "VpsVuiPresentFlag           ")
-  ("CrossLayerPicTypeAlignedFlag", m_crossLayerPicTypeAlignedFlag, false                                           , "CrossLayerPicTypeAlignedFlag")  // Could actually be derived by the encoder
-  ("CrossLayerIrapAlignedFlag"   , m_crossLayerIrapAlignedFlag   , false                                           , "CrossLayerIrapAlignedFlag   ")  // Could actually be derived by the encoder
-  ("AllLayersIdrAlignedFlag"     , m_allLayersIdrAlignedFlag     , false                                           , "CrossLayerIrapAlignedFlag   ")  // Could actually be derived by the encoder
-  ("BitRatePresentVpsFlag"       , m_bitRatePresentVpsFlag       , false                                           , "BitRatePresentVpsFlag       ")
-  ("PicRatePresentVpsFlag"       , m_picRatePresentVpsFlag       , false                                           , "PicRatePresentVpsFlag       ")
-  ("BitRatePresentFlag"          , m_bitRatePresentFlag          , BoolAry1d(1,0)  ,MAX_VPS_OP_SETS_PLUS1, "BitRatePresentFlag per sub layer for the N-th layer set")
-  ("PicRatePresentFlag"          , m_picRatePresentFlag          , BoolAry1d(1,0)  ,MAX_VPS_OP_SETS_PLUS1, "PicRatePresentFlag per sub layer for the N-th layer set")
-  ("AvgBitRate"                  , m_avgBitRate                   , IntAry1d (1,0), MAX_VPS_OP_SETS_PLUS1, "AvgBitRate         per sub layer for the N-th layer set")
-  ("MaxBitRate"                  , m_maxBitRate                   , IntAry1d (1,0), MAX_VPS_OP_SETS_PLUS1, "MaxBitRate         per sub layer for the N-th layer set")
-  ("ConstantPicRateIdc"          , m_constantPicRateIdc           , IntAry1d (1,0), MAX_VPS_OP_SETS_PLUS1, "ConstantPicRateIdc per sub layer for the N-th layer set")
-  ("AvgPicRate"                  , m_avgPicRate                   , IntAry1d (1,0), MAX_VPS_OP_SETS_PLUS1, "AvgPicRate         per sub layer for the N-th layer set")
-  ("TilesNotInUseFlag"            , m_tilesNotInUseFlag            , true                                          , "TilesNotInUseFlag            ")
+  ("VpsVuiPresentFlag"            , m_vpsVuiPresentFlag            , false                                , "VpsVuiPresentFlag           ")
+  ("CrossLayerPicTypeAlignedFlag" , m_crossLayerPicTypeAlignedFlag , false                                , "CrossLayerPicTypeAlignedFlag")  // Could actually be derived by the encoder
+  ("CrossLayerIrapAlignedFlag"    , m_crossLayerIrapAlignedFlag    , false                                , "CrossLayerIrapAlignedFlag   ")  // Could actually be derived by the encoder
+  ("AllLayersIdrAlignedFlag"      , m_allLayersIdrAlignedFlag      , false                                , "CrossLayerIrapAlignedFlag   ")  // Could actually be derived by the encoder
+  ("BitRatePresentVpsFlag"        , m_bitRatePresentVpsFlag        , false                                , "BitRatePresentVpsFlag       ")
+  ("PicRatePresentVpsFlag"        , m_picRatePresentVpsFlag        , false                                , "PicRatePresentVpsFlag       ")
+  ("BitRatePresentFlag"           , m_bitRatePresentFlag           , BoolAry1d(1,0), MAX_VPS_OP_SETS_PLUS1, "BitRatePresentFlag per sub layer for the N-th layer set")
+  ("PicRatePresentFlag"           , m_picRatePresentFlag           , BoolAry1d(1,0), MAX_VPS_OP_SETS_PLUS1, "PicRatePresentFlag per sub layer for the N-th layer set")
+  ("AvgBitRate"                   , m_avgBitRate                   , IntAry1d (1,0), MAX_VPS_OP_SETS_PLUS1, "AvgBitRate         per sub layer for the N-th layer set")
+  ("MaxBitRate"                   , m_maxBitRate                   , IntAry1d (1,0), MAX_VPS_OP_SETS_PLUS1, "MaxBitRate         per sub layer for the N-th layer set")
+  ("ConstantPicRateIdc"           , m_constantPicRateIdc           , IntAry1d (1,0), MAX_VPS_OP_SETS_PLUS1, "ConstantPicRateIdc per sub layer for the N-th layer set")
+  ("AvgPicRate"                   , m_avgPicRate                   , IntAry1d (1,0), MAX_VPS_OP_SETS_PLUS1, "AvgPicRate         per sub layer for the N-th layer set")
+  ("TilesNotInUseFlag"            , m_tilesNotInUseFlag            , true                                 , "TilesNotInUseFlag            ")
   ("TilesInUseFlag"               , m_tilesInUseFlag               , BoolAry1d(1,false)                   , "TilesInUseFlag               ")
-  ("LoopFilterNotAcrossTilesFlag" , m_loopFilterNotAcrossTilesFlag , BoolAry1d(1,false)                  , "LoopFilterNotAcrossTilesFlag ")
-  ("WppNotInUseFlag"              , m_wppNotInUseFlag              , true                                          , "WppNotInUseFlag              ")
-  ("WppInUseFlag"                 , m_wppInUseFlag                 , BoolAry1d(1,0)                      , "WppInUseFlag                 ")
-  ("TileBoundariesAlignedFlag"   , m_tileBoundariesAlignedFlag   , BoolAry1d(1,0)  ,MAX_NUM_LAYERS       , "TileBoundariesAlignedFlag    per direct reference for the N-th layer")
-  ("IlpRestrictedRefLayersFlag"  , m_ilpRestrictedRefLayersFlag  , false                                           , "IlpRestrictedRefLayersFlag")
-  ("MinSpatialSegmentOffsetPlus1", m_minSpatialSegmentOffsetPlus1 , IntAry1d (1,0), MAX_NUM_LAYERS       , "MinSpatialSegmentOffsetPlus1 per direct reference for the N-th layer")
-  ("CtuBasedOffsetEnabledFlag"   , m_ctuBasedOffsetEnabledFlag   , BoolAry1d(1,0)  ,MAX_NUM_LAYERS       , "CtuBasedOffsetEnabledFlag    per direct reference for the N-th layer")
-  ("MinHorizontalCtuOffsetPlus1" , m_minHorizontalCtuOffsetPlus1  , IntAry1d (1,0), MAX_NUM_LAYERS       , "MinHorizontalCtuOffsetPlus1  per direct reference for the N-th layer")
-  ("SingleLayerForNonIrapFlag", m_singleLayerForNonIrapFlag, false                                          , "SingleLayerForNonIrapFlag")
-  ("HigherLayerIrapSkipFlag"  , m_higherLayerIrapSkipFlag  , false                                          , "HigherLayerIrapSkipFlag  ")
+  ("LoopFilterNotAcrossTilesFlag" , m_loopFilterNotAcrossTilesFlag , BoolAry1d(1,false)                   , "LoopFilterNotAcrossTilesFlag ")
+  ("WppNotInUseFlag"              , m_wppNotInUseFlag              , true                                 , "WppNotInUseFlag              ")
+  ("WppInUseFlag"                 , m_wppInUseFlag                 , BoolAry1d(1,0)                       , "WppInUseFlag                 ")
+  ("TileBoundariesAlignedFlag"    , m_tileBoundariesAlignedFlag    , BoolAry1d(1,0)  ,MAX_NUM_LAYERS      , "TileBoundariesAlignedFlag    per direct reference for the N-th layer")
+  ("IlpRestrictedRefLayersFlag"   , m_ilpRestrictedRefLayersFlag   , false                                , "IlpRestrictedRefLayersFlag")
+  ("MinSpatialSegmentOffsetPlus1" , m_minSpatialSegmentOffsetPlus1 , IntAry1d (1,0), MAX_NUM_LAYERS       , "MinSpatialSegmentOffsetPlus1 per direct reference for the N-th layer")
+  ("CtuBasedOffsetEnabledFlag"    , m_ctuBasedOffsetEnabledFlag    , BoolAry1d(1,0)  ,MAX_NUM_LAYERS      , "CtuBasedOffsetEnabledFlag    per direct reference for the N-th layer")
+  ("MinHorizontalCtuOffsetPlus1"  , m_minHorizontalCtuOffsetPlus1  , IntAry1d (1,0), MAX_NUM_LAYERS       , "MinHorizontalCtuOffsetPlus1  per direct reference for the N-th layer")
+  ("SingleLayerForNonIrapFlag"    , m_singleLayerForNonIrapFlag    , false                                , "SingleLayerForNonIrapFlag")
+  ("HigherLayerIrapSkipFlag"      , m_higherLayerIrapSkipFlag      , false                                , "HigherLayerIrapSkipFlag  ")
 #endif
 
@@ -1227,7 +1170,8 @@
   ("Log2MaxMvLengthHorizontal",                       m_log2MaxMvLengthHorizontal,                         15, "Indicate the maximum absolute value of a decoded horizontal MV component in quarter-pel luma units")
   ("Log2MaxMvLengthVertical",                         m_log2MaxMvLengthVertical,                           15, "Indicate the maximum absolute value of a decoded vertical MV component in quarter-pel luma units")
-  ("SEIRecoveryPoint",                                m_recoveryPointSEIEnabled,                            0, "Control generation of recovery point SEI messages")
-  ("SEIBufferingPeriod",                              m_bufferingPeriodSEIEnabled,                          0, "Control generation of buffering period SEI messages")
-  ("SEIPictureTiming",                                m_pictureTimingSEIEnabled,                            0, "Control generation of picture timing SEI messages")
+  ("SEIColourRemappingInfoFileRoot,-cri",             m_colourRemapSEIFileRoot,                    string(""), "Colour Remapping Information SEI parameters root file name (wo num ext)")
+  ("SEIRecoveryPoint",                                m_recoveryPointSEIEnabled,                        false, "Control generation of recovery point SEI messages")
+  ("SEIBufferingPeriod",                              m_bufferingPeriodSEIEnabled,                      false, "Control generation of buffering period SEI messages")
+  ("SEIPictureTiming",                                m_pictureTimingSEIEnabled,                        false, "Control generation of picture timing SEI messages")
   ("SEIToneMappingInfo",                              m_toneMappingInfoSEIEnabled,                      false, "Control generation of Tone Mapping SEI messages")
   ("SEIToneMapId",                                    m_toneMapId,                                          0, "Specifies Id of Tone Mapping SEI message for a given session")
@@ -1262,14 +1206,14 @@
   ("SEIToneMapNominalWhiteLevelLumaCodeValue",        m_nominalWhiteLevelLumaCodeValue,                   235, "Specifies luma sample value of the nominal white level assigned decoded pictures")
   ("SEIToneMapExtendedWhiteLevelLumaCodeValue",       m_extendedWhiteLevelLumaCodeValue,                  300, "Specifies luma sample value of the extended dynamic range assigned decoded pictures")
-  ("SEIChromaSamplingFilterHint",                     m_chromaSamplingFilterSEIenabled,                 false, "Control generation of the chroma sampling filter hint SEI message")
-  ("SEIChromaSamplingHorizontalFilterType",           m_chromaSamplingHorFilterIdc,                         2, "Defines the Index of the chroma sampling horizontal filter\n"
+  ("SEIChromaResamplingFilterHint",                   m_chromaResamplingFilterSEIenabled,               false, "Control generation of the chroma sampling filter hint SEI message")
+  ("SEIChromaResamplingHorizontalFilterType",         m_chromaResamplingHorFilterIdc,                       2, "Defines the Index of the chroma sampling horizontal filter\n"
                                                                                                                "\t0: unspecified  - Chroma filter is unknown or is determined by the application"
                                                                                                                "\t1: User-defined - Filter coefficients are specified in the chroma sampling filter hint SEI message"
                                                                                                                "\t2: Standards-defined - ITU-T Rec. T.800 | ISO/IEC15444-1, 5/3 filter")
-  ("SEIChromaSamplingVerticalFilterType",             m_chromaSamplingVerFilterIdc,                         2, "Defines the Index of the chroma sampling vertical filter\n"
+  ("SEIChromaResamplingVerticalFilterType",           m_chromaResamplingVerFilterIdc,                         2, "Defines the Index of the chroma sampling vertical filter\n"
                                                                                                                "\t0: unspecified  - Chroma filter is unknown or is determined by the application"
                                                                                                                "\t1: User-defined - Filter coefficients are specified in the chroma sampling filter hint SEI message"
                                                                                                                "\t2: Standards-defined - ITU-T Rec. T.800 | ISO/IEC15444-1, 5/3 filter")
-  ("SEIFramePacking",                                 m_framePackingSEIEnabled,                             0, "Control generation of frame packing SEI messages")
+  ("SEIFramePacking",                                 m_framePackingSEIEnabled,                         false, "Control generation of frame packing SEI messages")
   ("SEIFramePackingType",                             m_framePackingSEIType,                                0, "Define frame packing arrangement\n"
                                                                                                                "\t3: side by side - frames are displayed horizontally\n"
@@ -1282,5 +1226,5 @@
                                                                                                                "\t1: stereo pair, frame0 represents left view\n"
                                                                                                                "\t2: stereo pair, frame0 represents right view")
-  ("SEISegmentedRectFramePacking",                    m_segmentedRectFramePackingSEIEnabled,                0, "Controls generation of segmented rectangular frame packing SEI messages")
+  ("SEISegmentedRectFramePacking",                    m_segmentedRectFramePackingSEIEnabled,            false, "Controls generation of segmented rectangular frame packing SEI messages")
   ("SEISegmentedRectFramePackingCancel",              m_segmentedRectFramePackingSEICancel,             false, "If equal to 1, cancels the persistence of any previous SRFPA SEI message")
   ("SEISegmentedRectFramePackingType",                m_segmentedRectFramePackingSEIType,                   0, "Specifies the arrangement of the frames in the reconstructed picture")
@@ -1289,12 +1233,12 @@
                                                                                                                "\tN: 0 < N < (2^16 - 1) enable display orientation SEI message with anticlockwise_rotation = N and display_orientation_repetition_period = 1\n"
                                                                                                                "\t0: disable")
-  ("SEITemporalLevel0Index",                          m_temporalLevel0IndexSEIEnabled,                      0, "Control generation of temporal level 0 index SEI messages")
-  ("SEIGradualDecodingRefreshInfo",                   m_gradualDecodingRefreshInfoEnabled,                  0, "Control generation of gradual decoding refresh information SEI message")
+  ("SEITemporalLevel0Index",                          m_temporalLevel0IndexSEIEnabled,                  false, "Control generation of temporal level 0 index SEI messages")
+  ("SEIGradualDecodingRefreshInfo",                   m_gradualDecodingRefreshInfoEnabled,              false, "Control generation of gradual decoding refresh information SEI message")
   ("SEINoDisplay",                                    m_noDisplaySEITLayer,                                 0, "Control generation of no display SEI message\n"
                                                                                                                "\tN: 0 < N enable no display SEI message for temporal layer N or higher\n"
                                                                                                                "\t0: disable")
-  ("SEIDecodingUnitInfo",                             m_decodingUnitInfoSEIEnabled,                         0, "Control generation of decoding unit information SEI message.")
-  ("SEISOPDescription",                               m_SOPDescriptionSEIEnabled,                           0, "Control generation of SOP description SEI messages")
-  ("SEIScalableNesting",                              m_scalableNestingSEIEnabled,                          0, "Control generation of scalable nesting SEI messages")
+  ("SEIDecodingUnitInfo",                             m_decodingUnitInfoSEIEnabled,                     false, "Control generation of decoding unit information SEI message.")
+  ("SEISOPDescription",                               m_SOPDescriptionSEIEnabled,                       false, "Control generation of SOP description SEI messages")
+  ("SEIScalableNesting",                              m_scalableNestingSEIEnabled,                      false, "Control generation of scalable nesting SEI messages")
   ("SEITempMotionConstrainedTileSets",                m_tmctsSEIEnabled,                                false, "Control generation of temporal motion constrained tile sets SEI message")
   ("SEITimeCodeEnabled",                              m_timeCodeSEIEnabled,                             false, "Control generation of time code information SEI message")
@@ -1332,27 +1276,19 @@
   ("SEIMasteringDisplayWhitePoint",                   cfg_DisplayWhitePointCode,     cfg_DisplayWhitePointCode, "Mastering display white point CIE xy coordinates in normalised increments of 1/50000 (e.g. 0.333 = 16667)")
 #if NH_MV
-#if !NH_MV_SEI
-  ("SubBitstreamPropSEIEnabled",                      m_subBistreamPropSEIEnabled,    false                     ,"Enable signaling of sub-bitstream property SEI message")
-  ("SEISubBitstreamNumAdditionalSubStreams",          m_sbPropNumAdditionalSubStreams,0                         ,"Number of substreams for which additional information is signalled")
-  ("SEISubBitstreamSubBitstreamMode",                 m_sbPropSubBitstreamMode,       IntAry1d (1,0)            ,"Specifies mode of generation of the i-th sub-bitstream (0 or 1)")
-  ("SEISubBitstreamOutputLayerSetIdxToVps",           m_sbPropOutputLayerSetIdxToVps, IntAry1d (1,0)            ,"Specifies output layer set index of the i-th sub-bitstream ")
-  ("SEISubBitstreamHighestSublayerId",                m_sbPropHighestSublayerId,      IntAry1d (1,0)            ,"Specifies highest TemporalId of the i-th sub-bitstream")
-  ("SEISubBitstreamAvgBitRate",                       m_sbPropAvgBitRate,             IntAry1d (1,0)            ,"Specifies average bit rate of the i-th sub-bitstream")
-  ("SEISubBitstreamMaxBitRate",                       m_sbPropMaxBitRate,             IntAry1d (1,0)            ,"Specifies maximum bit rate of the i-th sub-bitstream")
-#else
-  ("SeiCfgFileName_%d",                               m_seiCfgFileNames,             (Char *) 0 , MAX_NUM_SEIS , "SEI cfg file name %d")
-#endif
+  ("SeiCfgFileName_%d",                               m_seiCfgFileNames,             (TChar *) 0 ,MAX_NUM_SEIS , "SEI cfg file name %d")
   ("OutputVpsInfo",                                   m_outputVpsInfo,                false                     ,"Output information about the layer dependencies and layer sets")
+
+/* Camera parameters */    
+  ("BaseViewCameraNumbers",                           m_pchBaseViewCameraNumbers,   (TChar *) 0                 , "Numbers of base views")
 #endif
 #if NH_3D
-/* Camera parameters */  
   ("Depth420OutputFlag",                              m_depth420OutputFlag,           true                     , "Output depth layers in 4:2:0 ") 
-  ("CameraParameterFile,cpf",                         m_pchCameraParameterFile,    (Char *) 0,                    "Camera Parameter File Name")
-  ("BaseViewCameraNumbers",                           m_pchBaseViewCameraNumbers,  (Char *) 0,                    "Numbers of base views")
+#endif
+#if NH_3D_VSO  
+  ("CameraParameterFile,cpf",                         m_pchCameraParameterFile,    (TChar *) 0                 , "Camera Parameter File Name")
   ("CodedCamParsPrecision",                           m_iCodedCamParPrecision,      STD_CAM_PARAMETERS_PRECISION, "precision for coding of camera parameters (in units of 2^(-x) luma samples)" )
 
-#if NH_3D_VSO
   /* View Synthesis Optimization */
-  ("VSOConfig",                                       m_pchVSOConfig            , (Char *) 0                    ,"VSO configuration")
+  ("VSOConfig",                                       m_pchVSOConfig            , (TChar *) 0                   ,"VSO configuration")
   ("VSO",                                             m_bUseVSO                 , false                         ,"Use VSO" )    
   ("VSOMode",                                         m_uiVSOMode               , (UInt)   4                    ,"VSO Mode")
@@ -1371,5 +1307,9 @@
 #endif //HHI_VSO
 /* 3D- HEVC Tools */                                                            
+#if NH_3D_QTL
   ("QTL"                   ,                          m_bUseQTL                 , true                          , "Use depth quad tree limitation (encoder only)" )
+#endif
+#if NH_3D
+
   ("IvMvPredFlag"          ,                          m_ivMvPredFlag            , BoolAry1d(2,true)             , "Inter-view motion prediction"              )
   ("IvMvScalingFlag"       ,                          m_ivMvScalingFlag         , BoolAry1d(2,true)             , "Inter-view motion vector scaling"          )
@@ -1447,7 +1387,7 @@
   po::setDefaults(opts);
   po::ErrorReporter err;
-  const list<const Char*>& argv_unhandled = po::scanArgv(opts, argc, (const Char**) argv, err);
-
-  for (list<const Char*>::const_iterator it = argv_unhandled.begin(); it != argv_unhandled.end(); it++)
+  const list<const TChar*>& argv_unhandled = po::scanArgv(opts, argc, (const TChar**) argv, err);
+
+  for (list<const TChar*>::const_iterator it = argv_unhandled.begin(); it != argv_unhandled.end(); it++)
   {
     fprintf(stderr, "Unhandled argument ignored: `%s'\n", *it);
@@ -1473,14 +1413,5 @@
    * Set any derived parameters
    */
-  /* convert std::string to c string for compatability */
-#if !NH_MV
-  m_pchInputFile = cfg_InputFile.empty() ? NULL : strdup(cfg_InputFile.c_str());
-#endif
-  m_pchBitstreamFile = cfg_BitstreamFile.empty() ? NULL : strdup(cfg_BitstreamFile.c_str());
-#if !NH_MV
-  m_pchReconFile = cfg_ReconFile.empty() ? NULL : strdup(cfg_ReconFile.c_str());
-#endif
-  m_pchdQPFile = cfg_dQPFile.empty() ? NULL : strdup(cfg_dQPFile.c_str());
-
+  m_adIntraLambdaModifier = cfg_adIntraLambdaModifier.values;
   if(m_isField)
   {
@@ -1545,6 +1476,4 @@
   }
 
-  m_scalingListFile = cfg_ScalingListFile.empty() ? NULL : strdup(cfg_ScalingListFile.c_str());
-
   /* rules for input, output and internal bitdepths as per help text */
   if (m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA  ] == 0)
@@ -1579,4 +1508,26 @@
   m_InputChromaFormatIDC = numberToChromaFormat(tmpInputChromaFormat);
   m_chromaFormatIDC      = ((tmpChromaFormat == 0) ? (m_InputChromaFormatIDC) : (numberToChromaFormat(tmpChromaFormat)));
+
+
+  assert(tmpWeightedPredictionMethod>=0 && tmpWeightedPredictionMethod<=WP_PER_PICTURE_WITH_HISTOGRAM_AND_PER_COMPONENT_AND_CLIPPING_AND_EXTENSION);
+  if (!(tmpWeightedPredictionMethod>=0 && tmpWeightedPredictionMethod<=WP_PER_PICTURE_WITH_HISTOGRAM_AND_PER_COMPONENT_AND_CLIPPING_AND_EXTENSION))
+  {
+    exit(EXIT_FAILURE);
+  }
+  m_weightedPredictionMethod = WeightedPredictionMethod(tmpWeightedPredictionMethod);
+
+  assert(tmpFastInterSearchMode>=0 && tmpFastInterSearchMode<=FASTINTERSEARCH_MODE3);
+  if (tmpFastInterSearchMode<0 || tmpFastInterSearchMode>FASTINTERSEARCH_MODE3)
+  {
+    exit(EXIT_FAILURE);
+  }
+  m_fastInterSearchMode = FastInterSearchMode(tmpFastInterSearchMode);
+
+  assert(tmpMotionEstimationSearchMethod>=0 && tmpMotionEstimationSearchMethod<MESEARCH_NUMBER_OF_METHODS);
+  if (tmpMotionEstimationSearchMethod<0 || tmpMotionEstimationSearchMethod>=MESEARCH_NUMBER_OF_METHODS)
+  {
+    exit(EXIT_FAILURE);
+  }
+  m_motionEstimationSearchMethod=MESearchMethod(tmpMotionEstimationSearchMethod);
 
 #if NH_MV
@@ -1802,4 +1753,32 @@
   }
 
+  if (tmpSliceMode<0 || tmpSliceMode>=Int(NUMBER_OF_SLICE_CONSTRAINT_MODES))
+  {
+    fprintf(stderr, "Error: bad slice mode\n");
+    exit(EXIT_FAILURE);
+  }
+  m_sliceMode = SliceConstraint(tmpSliceMode);
+  if (tmpSliceSegmentMode<0 || tmpSliceSegmentMode>=Int(NUMBER_OF_SLICE_CONSTRAINT_MODES))
+  {
+    fprintf(stderr, "Error: bad slice segment mode\n");
+    exit(EXIT_FAILURE);
+  }
+  m_sliceSegmentMode = SliceConstraint(tmpSliceSegmentMode);
+
+  if (tmpDecodedPictureHashSEIMappedType<0 || tmpDecodedPictureHashSEIMappedType>=Int(NUMBER_OF_HASHTYPES))
+  {
+    fprintf(stderr, "Error: bad checksum mode\n");
+    exit(EXIT_FAILURE);
+  }
+  // Need to map values to match those of the SEI message:
+  if (tmpDecodedPictureHashSEIMappedType==0)
+  {
+    m_decodedPictureHashSEIType=HASHTYPE_NONE;
+  }
+  else
+  {
+    m_decodedPictureHashSEIType=HashType(tmpDecodedPictureHashSEIMappedType-1);
+  }
+
   // allocate slice-based dQP values
 #if NH_MV
@@ -1828,5 +1807,5 @@
   xResizeVector( m_auxId );
 
-#if NH_3D
+#if NH_3D_VSO
   xResizeVector( m_depthFlag ); 
 #endif
@@ -1923,7 +1902,7 @@
 
   // reading external dQP description from file
-  if ( m_pchdQPFile )
-  {
-    FILE* fpt=fopen( m_pchdQPFile, "r" );
+  if ( !m_dQPFileName.empty() )
+  {
+    FILE* fpt=fopen( m_dQPFileName.c_str(), "r" );
     if ( fpt )
     {
@@ -1953,5 +1932,5 @@
   }
 
-#if NH_MV_SEI
+#if NH_MV
   xParseSeiCfg(); 
 #endif
@@ -2037,5 +2016,5 @@
   }
 
-#if NH_3D
+
 #if NH_3D_VSO
   // Table base optimization 
@@ -2054,5 +2033,5 @@
     for (Int layer = 0; layer < m_numberOfLayers; layer++ )
     {
-      if ( m_depthFlag[ layer ])
+      if ( m_depthFlag[ layer ]  || m_auxId[ layer ] == 2 )
       {
         firstDepthLayer = layer;
@@ -2091,4 +2070,5 @@
       LOG2_DISP_PREC_LUT );
   }
+#if NH_3D
   else
   {
@@ -2104,17 +2084,6 @@
       LOG2_DISP_PREC_LUT );
   }
-#else
-  m_cCameraData     .init     ( ((UInt) m_iNumberOfViews ), 
-    m_internalBitDepth[ CHANNEL_TYPE_LUMA],
-    (UInt) m_iCodedCamParPrecision,
-    m_FrameSkip,
-    (UInt) m_framesToBeEncoded,
-    m_pchCameraParameterFile,
-    m_pchBaseViewCameraNumbers,
-    NULL,
-    NULL,
-    LOG2_DISP_PREC_LUT );
-#endif
   m_cCameraData.check( false, true );
+#endif
 #endif
 
@@ -2145,5 +2114,5 @@
 Void TAppEncCfg::xCheckParameter()
 {
-  if (!m_decodedPictureHashSEIEnabled)
+  if (m_decodedPictureHashSEIType==HASHTYPE_NONE)
   {
     fprintf(stderr, "******************************************************************\n");
@@ -2173,5 +2142,5 @@
 #define xConfirmPara(a,b) check_failed |= confirmPara(a,b)
 
-  xConfirmPara(m_pchBitstreamFile==NULL, "A bitstream file name must be specified (BitstreamFile)");
+  xConfirmPara(m_bitstreamFileName.empty(), "A bitstream file name must be specified (BitstreamFile)");
   const UInt maxBitDepth=(m_chromaFormatIDC==CHROMA_400) ? m_internalBitDepth[CHANNEL_TYPE_LUMA] : std::max(m_internalBitDepth[CHANNEL_TYPE_LUMA], m_internalBitDepth[CHANNEL_TYPE_CHROMA]);
   xConfirmPara(m_bitDepthConstraint<maxBitDepth, "The internalBitDepth must not be greater than the bitDepthConstraint value");
@@ -2301,5 +2270,5 @@
 #endif
 
-#if NH_3D
+#if NH_3D_VSO
   if ( m_scalabilityMask & ( 1 << DEPTH_ID ) )
   {
@@ -2397,9 +2366,9 @@
     if (lsIdx == 0)
     {
-      xConfirmPara( m_layerIdsInSets[lsIdx].size() != 1 || m_layerIdsInSets[lsIdx][0] != 0 , "0-th layer shall only include layer 0. ");
-    }
-    for ( Int i = 0; i < m_layerIdsInSets[lsIdx].size(); i++ )
-    {
-      xConfirmPara( m_layerIdsInSets[lsIdx][i] < 0 || m_layerIdsInSets[lsIdx][i] >= MAX_NUM_LAYER_IDS, "LayerIdsInSet must be greater than 0 and less than MAX_NUM_LAYER_IDS" ); 
+      xConfirmPara( m_layerIdxInVpsInSets[lsIdx].size() != 1 || m_layerIdxInVpsInSets[lsIdx][0] != 0 , "0-th layer shall only include layer 0. ");
+    }
+    for ( Int i = 0; i < m_layerIdxInVpsInSets[lsIdx].size(); i++ )
+    {
+      xConfirmPara( m_layerIdxInVpsInSets[lsIdx][i] < 0 || m_layerIdxInVpsInSets[lsIdx][i] >= MAX_NUM_LAYER_IDS, "LayerIdsInSet must be greater than 0 and less than MAX_NUM_LAYER_IDS" ); 
     }
   }
@@ -2434,7 +2403,7 @@
       {
         Bool inLayerSetFlag = false; 
-        for (Int j = 0; j < m_layerIdsInSets[ lsIdx].size(); j++ )
+        for (Int j = 0; j < m_layerIdxInVpsInSets[ lsIdx].size(); j++ )
         {
-          if ( m_layerIdsInSets[ lsIdx ][ j ] == m_layerIdsInDefOutputLayerSet[ lsIdx ][ i ] )
+          if ( m_layerIdxInVpsInSets[ lsIdx ][ j ] == m_layerIdsInDefOutputLayerSet[ lsIdx ][ i ] )
           {
             inLayerSetFlag = true; 
@@ -2544,7 +2513,7 @@
   xConfirmPara( m_loopFilterBetaOffsetDiv2 < -6 || m_loopFilterBetaOffsetDiv2 > 6,        "Loop Filter Beta Offset div. 2 exceeds supported range (-6 to 6)");
   xConfirmPara( m_loopFilterTcOffsetDiv2 < -6 || m_loopFilterTcOffsetDiv2 > 6,            "Loop Filter Tc Offset div. 2 exceeds supported range (-6 to 6)");
-  xConfirmPara( m_iFastSearch < 0 || m_iFastSearch > 2,                                     "Fast Search Mode is not supported value (0:Full search  1:Diamond  2:PMVFAST)" );
   xConfirmPara( m_iSearchRange < 0 ,                                                        "Search Range must be more than 0" );
-  xConfirmPara( m_bipredSearchRange < 0 ,                                                   "Search Range must be more than 0" );
+  xConfirmPara( m_bipredSearchRange < 0 ,                                                   "Bi-prediction refinement search range must be more than 0" );
+  xConfirmPara( m_minSearchWindow < 0,                                                      "Minimum motion search window size for the adaptive window ME must be greater than or equal to 0" );
 #if NH_MV
   xConfirmPara( m_iVerticalDisparitySearchRange <= 0 ,                                      "Vertical Disparity Search Range must be more than 0" );
@@ -2624,11 +2593,9 @@
   }
 
-  xConfirmPara( m_sliceMode < 0 || m_sliceMode > 3, "SliceMode exceeds supported range (0 to 3)" );
-  if (m_sliceMode!=0)
+  if (m_sliceMode!=NO_SLICES)
   {
     xConfirmPara( m_sliceArgument < 1 ,         "SliceArgument should be larger than or equal to 1" );
   }
-  xConfirmPara( m_sliceSegmentMode < 0 || m_sliceSegmentMode > 3, "SliceSegmentMode exceeds supported range (0 to 3)" );
-  if (m_sliceSegmentMode!=0)
+  if (m_sliceSegmentMode!=NO_SLICES)
   {
     xConfirmPara( m_sliceSegmentArgument < 1 ,         "SliceSegmentArgument should be larger than or equal to 1" );
@@ -2638,5 +2605,5 @@
   if (m_profile!=Profile::HIGHTHROUGHPUTREXT)
   {
-    xConfirmPara( tileFlag && m_iWaveFrontSynchro,            "Tile and Wavefront can not be applied together, except in the High Throughput Intra 4:4:4 16 profile");
+    xConfirmPara( tileFlag && m_entropyCodingSyncEnabledFlag, "Tiles and entropy-coding-sync (Wavefronts) can not be applied together, except in the High Throughput Intra 4:4:4 16 profile");
   }
 
@@ -2662,10 +2629,9 @@
   }
 
-#if NH_3D
+#if NH_3D_VSO
   xConfirmPara( m_pchCameraParameterFile    == 0                ,   "CameraParameterFile must be given");
   xConfirmPara( m_pchBaseViewCameraNumbers  == 0                ,   "BaseViewCameraNumbers must be given" );
   xConfirmPara( m_iNumberOfViews != m_cCameraData.getBaseViewNumbers().size() ,   "Number of Views in BaseViewCameraNumbers must be equal to NumberOfViews" );
   xConfirmPara    ( m_iCodedCamParPrecision < 0 || m_iCodedCamParPrecision > 5,       "CodedCamParsPrecision must be in range of 0..5" );
-#if NH_3D_VSO
     if( m_bUseVSO )
     {
@@ -2673,5 +2639,4 @@
       xConfirmPara( m_uiVSOMode > 4 ,                                                "VSO Mode must be less than 5");
     }
-#endif
 #endif
   // max CU width and height should be power of 2
@@ -3237,5 +3202,5 @@
       m_minSpatialSegmentationIdc = 4*PicSizeInSamplesY/maxSizeInSamplesY-4;
     }
-    else if(m_iWaveFrontSynchro)
+    else if(m_entropyCodingSyncEnabledFlag)
     {
       m_minSpatialSegmentationIdc = 4*PicSizeInSamplesY/((2*m_iSourceHeight+m_iSourceWidth)*m_uiMaxCUHeight)-4;
@@ -3250,8 +3215,4 @@
     }
   }
-
-  xConfirmPara( m_iWaveFrontSynchro < 0, "WaveFrontSynchro cannot be negative" );
-
-  xConfirmPara( m_decodedPictureHashSEIEnabled<0 || m_decodedPictureHashSEIEnabled>3, "this hash type is not correct!\n");
 
   if (m_toneMappingInfoSEIEnabled)
@@ -3282,4 +3243,10 @@
   }
 
+  if (m_chromaResamplingFilterSEIenabled)
+  {
+    xConfirmPara( (m_chromaFormatIDC == CHROMA_400 ), "chromaResamplingFilterSEI is not allowed to be present when ChromaFormatIDC is equal to zero (4:0:0)" );
+    xConfirmPara(m_vuiParametersPresentFlag && m_chromaLocInfoPresentFlag && (m_chromaSampleLocTypeTopField != m_chromaSampleLocTypeBottomField ), "When chromaResamplingFilterSEI is enabled, ChromaSampleLocTypeTopField has to be equal to ChromaSampleLocTypeBottomField" );
+  }
+
   if ( m_RCEnableRateControl )
   {
@@ -3293,5 +3260,29 @@
     }
     xConfirmPara( m_uiDeltaQpRD > 0, "Rate control cannot be used together with slice level multiple-QP optimization!\n" );
-  }
+#if U0132_TARGET_BITS_SATURATION
+#if NH_MV
+    if ((m_RCCpbSaturationEnabled) && (m_level[0]!=Level::NONE) && (m_profile!=Profile::NONE))
+    {
+      UInt uiLevelIdx = (m_level[0] / 10) + (UInt)((m_level[0] % 10) / 3);    // (m_level / 30)*3 + ((m_level % 10) / 3);
+      xConfirmPara(m_RCCpbSize > g_uiMaxCpbSize[m_levelTier[0]][uiLevelIdx], "RCCpbSize should be smaller than or equal to Max CPB size according to tier and level");
+      xConfirmPara(m_RCInitialCpbFullness > 1, "RCInitialCpbFullness should be smaller than or equal to 1");
+    }
+#else
+    if ((m_RCCpbSaturationEnabled) && (m_level!=Level::NONE) && (m_profile!=Profile::NONE))
+    {
+      UInt uiLevelIdx = (m_level / 10) + (UInt)((m_level % 10) / 3);    // (m_level / 30)*3 + ((m_level % 10) / 3);
+      xConfirmPara(m_RCCpbSize > g_uiMaxCpbSize[m_levelTier][uiLevelIdx], "RCCpbSize should be smaller than or equal to Max CPB size according to tier and level");
+      xConfirmPara(m_RCInitialCpbFullness > 1, "RCInitialCpbFullness should be smaller than or equal to 1");
+    }
+#endif
+#endif
+  }
+#if U0132_TARGET_BITS_SATURATION
+  else
+  {
+    xConfirmPara( m_RCCpbSaturationEnabled != 0, "Target bits saturation cannot be processed without Rate control" );
+  }
+#endif
+
 #if NH_MV
   // VPS VUI
@@ -3328,28 +3319,9 @@
   }
   }
-#if !NH_MV_SEI
-  // Check input parameters for Sub-bitstream property SEI message
-  if( m_subBistreamPropSEIEnabled )
-  {
-    xConfirmPara( 
-      (this->m_sbPropNumAdditionalSubStreams != m_sbPropAvgBitRate.size() )
-      || (this->m_sbPropNumAdditionalSubStreams != m_sbPropHighestSublayerId.size() )
-      || (this->m_sbPropNumAdditionalSubStreams != m_sbPropMaxBitRate.size() )
-      || (this->m_sbPropNumAdditionalSubStreams != m_sbPropOutputLayerSetIdxToVps.size() )
-      || (this->m_sbPropNumAdditionalSubStreams != m_sbPropSubBitstreamMode.size()), "Some parameters of some sub-bitstream not defined");
-
-    for( Int i = 0; i < m_sbPropNumAdditionalSubStreams; i++ )
-    {
-      xConfirmPara( m_sbPropSubBitstreamMode[i] < 0 || m_sbPropSubBitstreamMode[i] > 1, "Mode value should be 0 or 1" );
-      xConfirmPara( m_sbPropHighestSublayerId[i] < 0 || m_sbPropHighestSublayerId[i] > MAX_TLAYER-1, "Maximum sub-layer ID out of range" );
-      xConfirmPara( m_sbPropOutputLayerSetIdxToVps[i] < 0 || m_sbPropOutputLayerSetIdxToVps[i] >= MAX_VPS_OUTPUTLAYER_SETS, "OutputLayerSetIdxToVps should be within allowed range" );
-    }
-  }
-#endif
 #endif
 
   if (m_segmentedRectFramePackingSEIEnabled)
   {
-    xConfirmPara(m_framePackingSEIEnabled > 0 , "SEISegmentedRectFramePacking must be 0 when SEIFramePacking is 1");
+    xConfirmPara(m_framePackingSEIEnabled , "SEISegmentedRectFramePacking must be 0 when SEIFramePacking is 1");
   }
 
@@ -3372,5 +3344,5 @@
 }
 
-const Char *profileToString(const Profile::Name profile)
+const TChar *profileToString(const Profile::Name profile)
 {
   static const UInt numberOfProfiles = sizeof(strToProfile)/sizeof(*strToProfile);
@@ -3400,7 +3372,7 @@
   }
 #else
-  printf("Input          File               : %s\n", m_pchInputFile          );
-#endif
-  printf("Bitstream      File               : %s\n", m_pchBitstreamFile      );
+  printf("Input          File                    : %s\n", m_inputFileName.c_str()          );
+#endif
+  printf("Bitstream      File                    : %s\n", m_bitstreamFileName.c_str()      );
 #if NH_MV
   for( Int layer = 0; layer < m_numberOfLayers; layer++)
@@ -3409,5 +3381,5 @@
   }
 #else
-  printf("Reconstruction File               : %s\n", m_pchReconFile          );
+  printf("Reconstruction File                    : %s\n", m_reconFileName.c_str()          );
 #endif
 #if NH_MV
@@ -3421,5 +3393,5 @@
   xPrintParaVector( "AuxId", m_auxId );
 #endif
-#if NH_3D
+#if NH_3D_VSO
   xPrintParaVector( "DepthLayerFlag", m_depthFlag ); 
   printf("Coded Camera Param. Precision     : %d\n", m_iCodedCamParPrecision);  
@@ -3581,4 +3553,5 @@
 
   printf("RateControl                       : %d\n", m_RCEnableRateControl );
+  printf("WPMethod                               : %d\n", Int(m_weightedPredictionMethod));
 
   if(m_RCEnableRateControl)
@@ -3591,4 +3564,13 @@
     printf("ForceIntraQP                      : %d\n", m_RCForceIntraQP );
 
+#if U0132_TARGET_BITS_SATURATION
+    printf("CpbSaturation                          : %d\n", m_RCCpbSaturationEnabled );
+    if (m_RCCpbSaturationEnabled)
+    {
+      printf("CpbSize                                : %d\n", m_RCCpbSize);
+      printf("InitalCpbFullness                      : %.2f\n", m_RCInitialCpbFullness);
+    }
+#endif
+
 #if KWU_RC_MADPRED_E0227
     printf("Depth based MAD prediction   : %d\n", m_depthMADPred);
@@ -3613,8 +3595,7 @@
 
   printf("Max Num Merge Candidates          : %d\n", m_maxNumMergeCand);
-#if NH_3D
+#if NH_3D_VSO
   printf("BaseViewCameraNumbers             : %s\n", m_pchBaseViewCameraNumbers ); 
   printf("Coded Camera Param. Precision     : %d\n", m_iCodedCamParPrecision);
-#if NH_3D_VSO
   printf("Force use of Lambda Scale         : %d\n", m_bForceLambdaScaleVSO );
 
@@ -3634,5 +3615,4 @@
   }
 #endif //HHI_VSO
-#endif //NH_3D
   printf("\n");
 #if NH_MV
@@ -3648,5 +3628,7 @@
   printf("SQP:%d ", m_uiDeltaQpRD         );
   printf("ASR:%d ", m_bUseASR             );
-  printf("FEN:%d ", m_bUseFastEnc         );
+  printf("MinSearchWindow:%d ", m_minSearchWindow        );
+  printf("RestrictMESampling:%d ", m_bRestrictMESampling );
+  printf("FEN:%d ", Int(m_fastInterSearchMode)           );
   printf("ECU:%d ", m_bUseEarlyCU         );
   printf("FDM:%d ", m_useFastDecisionForMerge );
@@ -3657,5 +3639,5 @@
   printf("TransformSkipFast:%d ", m_useTransformSkipFast       );
   printf("TransformSkipLog2MaxSize:%d ", m_log2MaxTransformSkipBlockSize);
-  printf("Slice: M=%d ", m_sliceMode);
+  printf("Slice: M=%d ", Int(m_sliceMode));
   if (m_sliceMode!=NO_SLICES)
   {
@@ -3685,7 +3667,6 @@
   printf("WPB:%d ", (Int)m_useWeightedBiPred);
   printf("PME:%d ", m_log2ParallelMergeLevel);
-  const Int iWaveFrontSubstreams = m_iWaveFrontSynchro ? (m_iSourceHeight + m_uiMaxCUHeight - 1) / m_uiMaxCUHeight : 1;
-  printf(" WaveFrontSynchro:%d WaveFrontSubstreams:%d",
-          m_iWaveFrontSynchro, iWaveFrontSubstreams);
+  const Int iWaveFrontSubstreams = m_entropyCodingSyncEnabledFlag ? (m_iSourceHeight + m_uiMaxCUHeight - 1) / m_uiMaxCUHeight : 1;
+  printf(" WaveFrontSynchro:%d WaveFrontSubstreams:%d", m_entropyCodingSyncEnabledFlag?1:0, iWaveFrontSubstreams);
   printf(" ScalingList:%d ", m_useScalingListId );
   printf("TMVPMode:%d ", m_TMVPModeId     );
@@ -3700,6 +3681,8 @@
   printf("WVSO:%d ", m_bUseWVSO );  
 #endif
+#if NH_3D_QTL
+  printf( "QTL:%d "                  , m_bUseQTL);
+#endif
 #if NH_3D
-  printf( "QTL:%d "                  , m_bUseQTL);
   printf( "IlluCompEnable:%d "       , m_abUseIC);
   printf( "IlluCompLowLatencyEnc:%d ",  m_bUseLowLatencyICEnc);
@@ -3730,5 +3713,5 @@
 }
 
-Bool confirmPara(Bool bflag, const Char* message)
+Bool confirmPara(Bool bflag, const TChar* message)
 {
   if (!bflag)
Index: trunk/source/App/TAppEncoder/TAppEncCfg.h
===================================================================
--- trunk/source/App/TAppEncoder/TAppEncCfg.h	(revision 1357)
+++ trunk/source/App/TAppEncoder/TAppEncCfg.h	(revision 1386)
@@ -62,9 +62,9 @@
   // file I/O
 #if NH_MV
-  std::vector<char*>     m_pchInputFileList;                  ///< source file names
-#else
-  Char*     m_pchInputFile;                                   ///< source file name
-#endif
-  Char*     m_pchBitstreamFile;                               ///< output bitstream file
+  std::vector<TChar*>     m_pchInputFileList;                  ///< source file names
+#else
+  std::string m_inputFileName;                                ///< source file name
+#endif
+  std::string m_bitstreamFileName;                            ///< output bitstream file
 #if NH_MV
   std::vector<char*>     m_pchReconFileList;                  ///< output reconstruction file names
@@ -72,5 +72,5 @@
   Int                    m_iNumberOfViews;                    ///< number of Layers that are views
 #else
-  Char*     m_pchReconFile;                                   ///< output reconstruction file
+  std::string m_reconFileName;                                ///< output reconstruction file
 #endif
   #if NH_MV
@@ -80,5 +80,5 @@
   IntAry1d               m_viewOrderIndex;                    ///< view order index  
   IntAry1d               m_auxId;                             ///< auxiliary id
-#if NH_3D
+#if NH_3D_VSO
   IntAry1d               m_depthFlag;                         ///< depth flag
 #endif
@@ -91,5 +91,5 @@
 // layer sets   
   Int                    m_vpsNumLayerSets;                   ///< Number of layer sets
-  IntAry2d m_layerIdsInSets;           ///< LayerIds in vps of layer set 
+  IntAry2d m_layerIdxInVpsInSets;           ///< LayerIds in vps of layer set 
   Int                    m_numAddLayerSets;                    ///< Number of additional layer sets
   IntAry2d m_highestLayerIdxPlus1;      ///< HighestLayerIdxPlus1 for each additional layer set and each independent layer (value with index 0 will be ignored)
@@ -112,32 +112,33 @@
   Bool m_bitRatePresentVpsFlag;
   Bool m_picRatePresentVpsFlag;
-  BoolAry2d              m_bitRatePresentFlag;
-  BoolAry2d              m_picRatePresentFlag;
-  IntAry2d               m_avgBitRate;
-  IntAry2d               m_maxBitRate;
-  IntAry2d               m_constantPicRateIdc;
-  IntAry2d               m_avgPicRate;
-  Bool                              m_tilesNotInUseFlag; 
-  BoolAry1d               m_tilesInUseFlag;
-  BoolAry1d               m_loopFilterNotAcrossTilesFlag; 
-  Bool                              m_wppNotInUseFlag;
-  BoolAry1d               m_wppInUseFlag;
-
-  BoolAry2d              m_tileBoundariesAlignedFlag;  
-  Bool m_ilpRestrictedRefLayersFlag;
-  IntAry2d               m_minSpatialSegmentOffsetPlus1;
-  BoolAry2d              m_ctuBasedOffsetEnabledFlag;
-  IntAry2d               m_minHorizontalCtuOffsetPlus1;
-  Bool m_singleLayerForNonIrapFlag;
-  Bool m_higherLayerIrapSkipFlag;
-
-
+  BoolAry2d m_bitRatePresentFlag;
+  BoolAry2d m_picRatePresentFlag;
+  IntAry2d  m_avgBitRate;
+  IntAry2d  m_maxBitRate;
+  IntAry2d  m_constantPicRateIdc;
+  IntAry2d  m_avgPicRate;
+  Bool      m_tilesNotInUseFlag; 
+  BoolAry1d m_tilesInUseFlag;
+  BoolAry1d m_loopFilterNotAcrossTilesFlag; 
+  Bool      m_wppNotInUseFlag;
+  BoolAry1d m_wppInUseFlag;
+
+  BoolAry2d m_tileBoundariesAlignedFlag;  
+  Bool      m_ilpRestrictedRefLayersFlag;
+  IntAry2d  m_minSpatialSegmentOffsetPlus1;
+  BoolAry2d m_ctuBasedOffsetEnabledFlag;
+  IntAry2d  m_minHorizontalCtuOffsetPlus1;
+  Bool      m_singleLayerForNonIrapFlag;
+  Bool      m_higherLayerIrapSkipFlag;
 #if NH_3D
   Bool      m_abUseIC;
   Bool      m_bUseLowLatencyICEnc;
 #endif
-
-#endif
+#endif
+  // Lambda modifiers
   Double    m_adLambdaModifier[ MAX_TLAYER ];                 ///< Lambda modifier array for each temporal layer
+  std::vector<Double> m_adIntraLambdaModifier;                ///< Lambda modifier for Intra pictures, one for each temporal layer. If size>temporalLayer, then use [temporalLayer], else if size>0, use [size()-1], else use m_adLambdaModifier.
+  Double    m_dIntraQpFactor;                                 ///< Intra Q Factor. If negative, use a default equation: 0.57*(1.0 - Clip3( 0.0, 0.5, 0.05*(Double)(isField ? (GopSize-1)/2 : GopSize-1) ))
+
   // source specification
   Int       m_iFrameRate;                                     ///< source frame-rates (Hz)
@@ -160,4 +161,5 @@
   Int       m_framesToBeEncoded;                              ///< number of encoded frames
   Int       m_aiPad[2];                                       ///< number of padded pixels for width and height
+  Bool      m_AccessUnitDelimiter;                            ///< add Access Unit Delimiter NAL units
   InputColourSpaceConversion m_inputColourSpaceConvert;       ///< colour space conversion to apply to input video
   Bool      m_snrInternalColourSpace;                       ///< if true, then no colour space conversion is applied for snr calculation, otherwise inverse of input is applied.
@@ -237,5 +239,5 @@
   Int       m_iQP;                                            ///< QP value of key-picture (integer)
 #endif
-  Char*     m_pchdQPFile;                                     ///< QP offset for each slice (initialized from external file)
+  std::string m_dQPFileName;                                  ///< QP offset for each slice (initialized from external file)
 #if NH_MV
   std::vector<Int*> m_aidQP;                                    ///< array of slice QP values for each layer
@@ -256,5 +258,5 @@
 #endif
   TComSEIMasteringDisplay m_masteringDisplay;
-#if NH_MV_SEI
+#if NH_MV
   std::vector<char*>     m_seiCfgFileNames;               ///< SEI message files.
   SEIMessages            m_seiMessages;                       ///< Buffer for SEI messages. 
@@ -338,7 +340,9 @@
   Int       m_rdPenalty;                                      ///< RD-penalty for 32x32 TU for intra in non-intra slices (0: no RD-penalty, 1: RD-penalty, 2: maximum RD-penalty)
   Bool      m_bDisableIntraPUsInInterSlices;                  ///< Flag for disabling intra predicted PUs in inter slices.
-  Int       m_iFastSearch;                                    ///< ME mode, 0 = full, 1 = diamond, 2 = PMVFAST
+  MESearchMethod m_motionEstimationSearchMethod;
+  Bool      m_bRestrictMESampling;                            ///< Restrict sampling for the Selective ME
   Int       m_iSearchRange;                                   ///< ME search range
   Int       m_bipredSearchRange;                              ///< ME search range for bipred refinement
+  Int       m_minSearchWindow;                                ///< ME minimum search window size for the Adaptive Window ME
   Bool      m_bClipForBiPredMeEnabled;                        ///< Enables clipping for Bi-Pred ME.
   Bool      m_bFastMEAssumingSmootherMVEnabled;               ///< Enables fast ME assuming a smoother MV.
@@ -347,14 +351,12 @@
   Int       m_iVerticalDisparitySearchRange;                  ///< ME vertical search range for inter-view prediction
 #endif
-  Bool      m_bUseFastEnc;                                    ///< flag for using fast encoder setting
+  FastInterSearchMode m_fastInterSearchMode;                  ///< Parameter that controls fast encoder settings
   Bool      m_bUseEarlyCU;                                    ///< flag for using Early CU setting
   Bool      m_useFastDecisionForMerge;                        ///< flag for using Fast Decision Merge RD-Cost
   Bool      m_bUseCbfFastMode;                              ///< flag for using Cbf Fast PU Mode Decision
   Bool      m_useEarlySkipDetection;                         ///< flag for using Early SKIP Detection
-  Int       m_sliceMode;                                     ///< 0: no slice limits, 1 : max number of CTBs per slice, 2: max number of bytes per slice,
-                                                             ///< 3: max number of tiles per slice
+  SliceConstraint m_sliceMode;
   Int       m_sliceArgument;                                 ///< argument according to selected slice mode
-  Int       m_sliceSegmentMode;                              ///< 0: no slice segment limits, 1 : max number of CTBs per slice segment, 2: max number of bytes per slice segment,
-                                                             ///< 3: max number of tiles per slice segment
+  SliceConstraint m_sliceSegmentMode;
   Int       m_sliceSegmentArgument;                          ///< argument according to selected slice segment mode
 
@@ -366,6 +368,5 @@
   std::vector<Int> m_tileColumnWidth;
   std::vector<Int> m_tileRowHeight;
-  Int       m_iWaveFrontSynchro; //< 0: no WPP. >= 1: WPP is enabled, the "Top right" from which inheritance occurs is this LCU offset in the line above the current.
-  Int       m_iWaveFrontFlush; //< enable(1)/disable(0) the CABAC flush at the end of each line of LCUs.
+  Bool      m_entropyCodingSyncEnabledFlag;
 
   Bool      m_bUseConstrainedIntraPred;                       ///< flag for using constrained intra prediction
@@ -374,12 +375,12 @@
   Bool      m_bUseBLambdaForNonKeyLowDelayPictures;
 
-  Int       m_decodedPictureHashSEIEnabled;                    ///< Checksum(3)/CRC(2)/MD5(1)/disable(0) acting on decoded picture hash SEI message
-  Int       m_recoveryPointSEIEnabled;
-  Int       m_bufferingPeriodSEIEnabled;
-  Int       m_pictureTimingSEIEnabled;
+  HashType  m_decodedPictureHashSEIType;                      ///< Checksum mode for decoded picture hash SEI message
+  Bool      m_recoveryPointSEIEnabled;
+  Bool      m_bufferingPeriodSEIEnabled;
+  Bool      m_pictureTimingSEIEnabled;
   Bool      m_toneMappingInfoSEIEnabled;
-  Bool      m_chromaSamplingFilterSEIenabled;
-  Int       m_chromaSamplingHorFilterIdc;
-  Int       m_chromaSamplingVerFilterIdc;
+  Bool      m_chromaResamplingFilterSEIenabled;
+  Int       m_chromaResamplingHorFilterIdc;
+  Int       m_chromaResamplingVerFilterIdc;
   Int       m_toneMapId;
   Bool      m_toneMapCancelFlag;
@@ -408,20 +409,20 @@
   Int*      m_codedPivotValue;
   Int*      m_targetPivotValue;
-  Int       m_framePackingSEIEnabled;
+  Bool      m_framePackingSEIEnabled;
   Int       m_framePackingSEIType;
   Int       m_framePackingSEIId;
   Int       m_framePackingSEIQuincunx;
   Int       m_framePackingSEIInterpretation;
-  Int       m_segmentedRectFramePackingSEIEnabled;
+  Bool      m_segmentedRectFramePackingSEIEnabled;
   Bool      m_segmentedRectFramePackingSEICancel;
   Int       m_segmentedRectFramePackingSEIType;
   Bool      m_segmentedRectFramePackingSEIPersistence;
   Int       m_displayOrientationSEIAngle;
-  Int       m_temporalLevel0IndexSEIEnabled;
-  Int       m_gradualDecodingRefreshInfoEnabled;
+  Bool      m_temporalLevel0IndexSEIEnabled;
+  Bool      m_gradualDecodingRefreshInfoEnabled;
   Int       m_noDisplaySEITLayer;
-  Int       m_decodingUnitInfoSEIEnabled;
-  Int       m_SOPDescriptionSEIEnabled;
-  Int       m_scalableNestingSEIEnabled;
+  Bool      m_decodingUnitInfoSEIEnabled;
+  Bool      m_SOPDescriptionSEIEnabled;
+  Bool      m_scalableNestingSEIEnabled;
   Bool      m_tmctsSEIEnabled;
   Bool      m_timeCodeSEIEnabled;
@@ -442,4 +443,5 @@
   Bool      m_useWeightedPred;                    ///< Use of weighted prediction in P slices
   Bool      m_useWeightedBiPred;                  ///< Use of bi-directional weighted prediction in B slices
+  WeightedPredictionMethod m_weightedPredictionMethod;
 
   UInt      m_log2ParallelMergeLevel;                         ///< Parallel merge estimation region
@@ -455,5 +457,11 @@
   Int       m_RCInitialQP;                        ///< inital QP for rate control
   Bool      m_RCForceIntraQP;                     ///< force all intra picture to use initial QP or not
-  
+
+#if U0132_TARGET_BITS_SATURATION
+  Bool      m_RCCpbSaturationEnabled;             ///< enable target bits saturation to avoid CPB overflow and underflow
+  UInt      m_RCCpbSize;                          ///< CPB size
+  Double    m_RCInitialCpbFullness;               ///< initial CPB fullness 
+#endif
+
 #if KWU_RC_VIEWRC_E0227
   vector<Int>     m_viewTargetBits;
@@ -464,6 +472,6 @@
 #endif
 
-ScalingListMode m_useScalingListId;                         ///< using quantization matrix
-  Char*     m_scalingListFile;                                ///< quantization matrix file name
+  ScalingListMode m_useScalingListId;                         ///< using quantization matrix
+  std::string m_scalingListFileName;                          ///< quantization matrix file name
 
   Bool      m_TransquantBypassEnableFlag;                     ///< transquant_bypass_enable_flag setting in PPS.
@@ -509,29 +517,24 @@
   Int       m_log2MaxMvLengthHorizontal;                      ///< Indicate the maximum absolute value of a decoded horizontal MV component in quarter-pel luma units
   Int       m_log2MaxMvLengthVertical;                        ///< Indicate the maximum absolute value of a decoded vertical MV component in quarter-pel luma units
+  std::string m_colourRemapSEIFileRoot;
+
   std::string m_summaryOutFilename;                           ///< filename to use for producing summary output file.
   std::string m_summaryPicFilenameBase;                       ///< Base filename to use for producing summary picture output files. The actual filenames used will have I.txt, P.txt and B.txt appended.
   UInt        m_summaryVerboseness;                           ///< Specifies the level of the verboseness of the text output.
 #if NH_MV
-#if !NH_MV_SEI
-  Bool              m_subBistreamPropSEIEnabled;
-  Int               m_sbPropNumAdditionalSubStreams;
-  IntAry1d          m_sbPropSubBitstreamMode;
-  IntAry1d          m_sbPropOutputLayerSetIdxToVps;
-  IntAry1d          m_sbPropHighestSublayerId;
-  IntAry1d          m_sbPropAvgBitRate;
-  IntAry1d          m_sbPropMaxBitRate;
-#endif
   Bool              m_outputVpsInfo;
-#endif
+  TChar*            m_pchBaseViewCameraNumbers;
+#endif
+
 #if NH_3D
   // Output Format
   Bool      m_depth420OutputFlag;                             ///< Output depth layers in 4:2:0 format
-  // Camera parameters
-  Char*     m_pchCameraParameterFile;                         ///< camera parameter file
-  Char*     m_pchBaseViewCameraNumbers;
+#endif
+    // Camera parameters
+#if NH_3D_VSO
+  TChar*    m_pchCameraParameterFile;                         ///< camera parameter file
   TAppComCamPara m_cCameraData;
   Int       m_iCodedCamParPrecision;                          ///< precision for coding of camera parameters
-#if NH_3D_VSO
-  Char*     m_pchVSOConfig;
+  TChar*    m_pchVSOConfig;
   Bool      m_bUseVSO;                                        ///< flag for using View Synthesis Optimization
   Bool      m_bVSOLSTable;                                    ///< Depth QP dependent Lagrange parameter optimization (m23714)
@@ -556,7 +559,11 @@
   TRenModSetupStrParser       m_cRenModStrParser;
 #endif
-
+#if NH_3D
   Bool       m_useDLT;                                        ///< flag for using DLT
+#endif
+#if NH_3D_QTL
   Bool       m_bUseQTL;                                        ///< flag for using depth QuadTree Limitation
+#endif
+#if NH_3D
   BoolAry1d  m_ivMvPredFlag;
   BoolAry1d  m_ivMvScalingFlag;
@@ -660,9 +667,6 @@
   Void xPrintVectorElem( Double elem ) { printf(" %5.2f", elem            );};  
   Void xPrintVectorElem( Bool   elem ) { printf(" %d"   , ( elem ? 1 : 0 ));};
-#if NH_MV_SEI
   Void xParseSeiCfg();
-#endif
-#endif
-#if NH_MV
+
   Int   getGOPSize() { return m_iGOPSize; }
 #endif
@@ -674,5 +678,5 @@
   Void  create    ();                                         ///< create option handling class
   Void  destroy   ();                                         ///< destroy option handling class
-  Bool  parseCfg  ( Int argc, Char* argv[] );                 ///< parse configuration file to fill member variables
+  Bool  parseCfg  ( Int argc, TChar* argv[] );                ///< parse configuration file to fill member variables
 
 };// END CLASS DEFINITION TAppEncCfg
Index: trunk/source/App/TAppEncoder/TAppEncTop.cpp
===================================================================
--- trunk/source/App/TAppEncoder/TAppEncTop.cpp	(revision 1357)
+++ trunk/source/App/TAppEncoder/TAppEncTop.cpp	(revision 1386)
@@ -147,4 +147,6 @@
 #if NH_3D
   xSetCamPara              ( vps ); 
+#endif
+#if NH_3D_VSO
   m_ivPicLists.setVPS      ( &vps );
 #endif
@@ -186,23 +188,23 @@
   for (Int d = 0; d < 2; d++)
   {  
-    m_sps3dExtension.setIvMvPredFlag          ( d, m_ivMvPredFlag[d]       );
-    m_sps3dExtension.setIvMvScalingFlag       ( d, m_ivMvScalingFlag[d]    );
+    m_sps3dExtension.setIvDiMcEnabledFlag          ( d, m_ivMvPredFlag[d]       );
+    m_sps3dExtension.setIvMvScalEnabledFlag       ( d, m_ivMvScalingFlag[d]    );
     if (d == 0 )
     {    
-      m_sps3dExtension.setLog2SubPbSizeMinus3   ( d, m_log2SubPbSizeMinus3   );
-      m_sps3dExtension.setIvResPredFlag         ( d, m_ivResPredFlag         );
-      m_sps3dExtension.setDepthRefinementFlag   ( d, m_depthRefinementFlag   );
-      m_sps3dExtension.setViewSynthesisPredFlag ( d, m_viewSynthesisPredFlag );
-      m_sps3dExtension.setDepthBasedBlkPartFlag ( d, m_depthBasedBlkPartFlag );
+      m_sps3dExtension.setLog2IvmcSubPbSizeMinus3   ( d, m_log2SubPbSizeMinus3   );
+      m_sps3dExtension.setIvResPredEnabledFlag         ( d, m_ivResPredFlag         );
+      m_sps3dExtension.setDepthRefEnabledFlag   ( d, m_depthRefinementFlag   );
+      m_sps3dExtension.setVspMcEnabledFlag ( d, m_viewSynthesisPredFlag );
+      m_sps3dExtension.setDbbpEnabledFlag ( d, m_depthBasedBlkPartFlag );
     }
     else
     {    
-      m_sps3dExtension.setMpiFlag               ( d, m_mpiFlag               );
-      m_sps3dExtension.setLog2MpiSubPbSizeMinus3( d, m_log2MpiSubPbSizeMinus3);
-      m_sps3dExtension.setIntraContourFlag      ( d, m_intraContourFlag      );
-      m_sps3dExtension.setIntraSdcWedgeFlag     ( d, m_intraSdcFlag || m_intraWedgeFlag     );
-      m_sps3dExtension.setQtPredFlag            ( d, m_qtPredFlag            );
-      m_sps3dExtension.setInterSdcFlag          ( d, m_interSdcFlag          );
-      m_sps3dExtension.setDepthIntraSkipFlag    ( d, m_depthIntraSkipFlag    );  
+      m_sps3dExtension.setTexMcEnabledFlag               ( d, m_mpiFlag               );
+      m_sps3dExtension.setLog2TexmcSubPbSizeMinus3( d, m_log2MpiSubPbSizeMinus3);
+      m_sps3dExtension.setIntraContourEnabledFlag      ( d, m_intraContourFlag      );
+      m_sps3dExtension.setIntraDcOnlyWedgeEnabledFlag     ( d, m_intraSdcFlag || m_intraWedgeFlag     );
+      m_sps3dExtension.setCqtCuPartPredEnabledFlag            ( d, m_qtPredFlag            );
+      m_sps3dExtension.setInterDcOnlyEnabledFlag          ( d, m_interSdcFlag          );
+      m_sps3dExtension.setSkipIntraEnabledFlag    ( d, m_depthIntraSkipFlag    );  
     }
   }
@@ -276,27 +278,29 @@
     m_cTEncTop.setViewId                       ( vps.getViewId      (  layerId ) );
     m_cTEncTop.setViewIndex                    ( vps.getViewIndex   (  layerId ) );
-#if NH_3D
-    Bool isDepth = ( vps.getDepthId     ( layerId ) != 0 ) ;
-    m_cTEncTop.setIsDepth                      ( isDepth );
+#if NH_3D_VSO
+    Bool isDepth    = ( vps.getDepthId     ( layerId ) != 0  ) ;
+    Bool isAuxDepth = ( vps.getAuxId       ( layerId ) ==  2 ) ; // TBD: define 2 as AUX_DEPTH
+    m_cTEncTop.setIsDepth                  ( isDepth    );
+    m_cTEncTop.setIsAuxDepth               ( isAuxDepth ); 
     //====== Camera Parameters =========
     m_cTEncTop.setCameraParameters             ( &m_cCameraData );     
-#if NH_3D_VSO
     //====== VSO =========
     m_cTEncTop.setRenderModelParameters        ( &m_cRenModStrParser ); 
-    m_cTEncTop.setForceLambdaScaleVSO          ( isDepth ? m_bForceLambdaScaleVSO : false );
-    m_cTEncTop.setLambdaScaleVSO               ( isDepth ? m_dLambdaScaleVSO      : 1     );
-    m_cTEncTop.setVSOMode                      ( isDepth ? m_uiVSOMode            : 0     );
-
-    m_cTEncTop.setAllowNegDist                 ( isDepth ? m_bAllowNegDist        : false );
+    m_cTEncTop.setForceLambdaScaleVSO          ( isDepth || isAuxDepth ? m_bForceLambdaScaleVSO : false );
+    m_cTEncTop.setLambdaScaleVSO               ( isDepth || isAuxDepth ? m_dLambdaScaleVSO      : 1     );
+    m_cTEncTop.setVSOMode                      ( isDepth || isAuxDepth ? m_uiVSOMode            : 0     );
+
+    m_cTEncTop.setAllowNegDist                 ( isDepth || isAuxDepth ? m_bAllowNegDist        : false );
 
     // SAIT_VSO_EST_A0033
-    m_cTEncTop.setUseEstimatedVSD              ( isDepth ? m_bUseEstimatedVSD     : false );
+    m_cTEncTop.setUseEstimatedVSD              ( isDepth || isAuxDepth ? m_bUseEstimatedVSD     : false );
 
     // LGE_WVSO_A0119
-    m_cTEncTop.setUseWVSO                      ( isDepth ? m_bUseWVSO             : false );   
-    m_cTEncTop.setVSOWeight                    ( isDepth ? m_iVSOWeight           : 0     );
-    m_cTEncTop.setVSDWeight                    ( isDepth ? m_iVSDWeight           : 0     );
-    m_cTEncTop.setDWeight                      ( isDepth ? m_iDWeight             : 0     );
+    m_cTEncTop.setUseWVSO                      ( isDepth || isAuxDepth ? m_bUseWVSO             : false );   
+    m_cTEncTop.setVSOWeight                    ( isDepth || isAuxDepth ? m_iVSOWeight           : 0     );
+    m_cTEncTop.setVSDWeight                    ( isDepth || isAuxDepth ? m_iVSDWeight           : 0     );
+    m_cTEncTop.setDWeight                      ( isDepth || isAuxDepth ? m_iDWeight             : 0     );
 #endif // H_3D_VSO
+#if NH_3D
 #if NH_3D_IC
     m_cTEncTop.setUseIC                        ( vps.getViewIndex( layerId ) == 0 || isDepth ? false : m_abUseIC );
@@ -308,5 +312,9 @@
     m_cTEncTop.setUseSDC                       ( isDepth ? m_intraSdcFlag     : false );
     m_cTEncTop.setUseDLT                       ( isDepth ? m_useDLT   : false );
-    m_cTEncTop.setUseQTL                       ( isDepth ? m_bUseQTL  : false );
+#endif
+#if NH_3D_QTL
+    m_cTEncTop.setUseQTL                       ( isDepth || isAuxDepth ? m_bUseQTL  : false );
+#endif
+#if NH_3D
     m_cTEncTop.setSps3dExtension               ( m_sps3dExtension );
 #endif // NH_3D
@@ -378,4 +386,7 @@
     m_cTEncTop.setLambdaModifier                                  ( uiLoop, m_adLambdaModifier[ uiLoop ] );
   }
+  m_cTEncTop.setIntraLambdaModifier                               ( m_adIntraLambdaModifier );
+  m_cTEncTop.setIntraQpFactor                                     ( m_dIntraQpFactor );
+
 #if NH_MV
   m_cTEncTop.setQP                                                ( m_iQP[layerIdInVps] );
@@ -385,5 +396,5 @@
 
   m_cTEncTop.setPad                                               ( m_aiPad );
-
+  m_cTEncTop.setAccessUnitDelimiter                               ( m_AccessUnitDelimiter );
 #if NH_MV
   m_cTEncTop.setMaxTempLayer                                      ( m_maxTempLayerMvc[layerIdInVps] );
@@ -408,9 +419,11 @@
   //====== Motion search ========
   m_cTEncTop.setDisableIntraPUsInInterSlices                      ( m_bDisableIntraPUsInInterSlices );
-  m_cTEncTop.setFastSearch                                        ( m_iFastSearch  );
+  m_cTEncTop.setMotionEstimationSearchMethod                      ( m_motionEstimationSearchMethod  );
   m_cTEncTop.setSearchRange                                       ( m_iSearchRange );
   m_cTEncTop.setBipredSearchRange                                 ( m_bipredSearchRange );
   m_cTEncTop.setClipForBiPredMeEnabled                            ( m_bClipForBiPredMeEnabled );
   m_cTEncTop.setFastMEAssumingSmootherMVEnabled                   ( m_bFastMEAssumingSmootherMVEnabled );
+  m_cTEncTop.setMinSearchWindow                                   ( m_minSearchWindow );
+  m_cTEncTop.setRestrictMESampling                                ( m_bRestrictMESampling );
 
 #if NH_MV
@@ -439,4 +452,7 @@
   m_cTEncTop.setExtendedPrecisionProcessingFlag                   ( m_extendedPrecisionProcessingFlag );
   m_cTEncTop.setHighPrecisionOffsetsEnabledFlag                   ( m_highPrecisionOffsetsEnabledFlag );
+
+  m_cTEncTop.setWeightedPredictionMethod( m_weightedPredictionMethod );
+
   //====== Tool list ========
   m_cTEncTop.setDeltaQpRD                                         ( m_uiDeltaQpRD  );
@@ -463,5 +479,5 @@
   m_cTEncTop.setQuadtreeTUMaxDepthInter                           ( m_uiQuadtreeTUMaxDepthInter );
   m_cTEncTop.setQuadtreeTUMaxDepthIntra                           ( m_uiQuadtreeTUMaxDepthIntra );
-  m_cTEncTop.setUseFastEnc                                        ( m_bUseFastEnc  );
+  m_cTEncTop.setFastInterSearchMode                               ( m_fastInterSearchMode );
   m_cTEncTop.setUseEarlyCU                                        ( m_bUseEarlyCU  );
   m_cTEncTop.setUseFastDecisionForMerge                           ( m_useFastDecisionForMerge  );
@@ -513,9 +529,9 @@
 
   //====== Slice ========
-  m_cTEncTop.setSliceMode                                         ( (SliceConstraint) m_sliceMode );
+  m_cTEncTop.setSliceMode                                         ( m_sliceMode );
   m_cTEncTop.setSliceArgument                                     ( m_sliceArgument            );
 
   //====== Dependent Slice ========
-  m_cTEncTop.setSliceSegmentMode                                  (  (SliceConstraint) m_sliceSegmentMode );
+  m_cTEncTop.setSliceSegmentMode                                  ( m_sliceSegmentMode );
   m_cTEncTop.setSliceSegmentArgument                              ( m_sliceSegmentArgument     );
 
@@ -540,5 +556,5 @@
 
   m_cTEncTop.setIntraSmoothingDisabledFlag                        (!m_enableIntraReferenceSmoothing );
-  m_cTEncTop.setDecodedPictureHashSEIEnabled                      ( m_decodedPictureHashSEIEnabled );
+  m_cTEncTop.setDecodedPictureHashSEIType                         ( m_decodedPictureHashSEIType );
   m_cTEncTop.setRecoveryPointSEIEnabled                           ( m_recoveryPointSEIEnabled );
   m_cTEncTop.setBufferingPeriodSEIEnabled                         ( m_bufferingPeriodSEIEnabled );
@@ -571,7 +587,7 @@
   m_cTEncTop.setTMISEINominalWhiteLevelLumaCodeValue              ( m_nominalWhiteLevelLumaCodeValue );
   m_cTEncTop.setTMISEIExtendedWhiteLevelLumaCodeValue             ( m_extendedWhiteLevelLumaCodeValue );
-  m_cTEncTop.setChromaSamplingFilterHintEnabled                   ( m_chromaSamplingFilterSEIenabled );
-  m_cTEncTop.setChromaSamplingHorFilterIdc                        ( m_chromaSamplingHorFilterIdc );
-  m_cTEncTop.setChromaSamplingVerFilterIdc                        ( m_chromaSamplingVerFilterIdc );
+  m_cTEncTop.setChromaResamplingFilterHintEnabled                 ( m_chromaResamplingFilterSEIenabled );
+  m_cTEncTop.setChromaResamplingHorFilterIdc                      ( m_chromaResamplingHorFilterIdc );
+  m_cTEncTop.setChromaResamplingVerFilterIdc                      ( m_chromaResamplingVerFilterIdc );
   m_cTEncTop.setFramePackingArrangementSEIEnabled                 ( m_framePackingSEIEnabled );
   m_cTEncTop.setFramePackingArrangementSEIType                    ( m_framePackingSEIType );
@@ -590,19 +606,4 @@
   m_cTEncTop.setSOPDescriptionSEIEnabled                          ( m_SOPDescriptionSEIEnabled );
   m_cTEncTop.setScalableNestingSEIEnabled                         ( m_scalableNestingSEIEnabled );
-#if NH_MV
-#if !NH_MV_SEI
-  m_cTEncTop.setSubBitstreamPropSEIEnabled                        ( m_subBistreamPropSEIEnabled );
-  if( m_subBistreamPropSEIEnabled )                               
-  {                                                               
-    m_cTEncTop.setNumAdditionalSubStreams                         ( m_sbPropNumAdditionalSubStreams );
-    m_cTEncTop.setSubBitstreamMode                                ( m_sbPropSubBitstreamMode );
-    m_cTEncTop.setOutputLayerSetIdxToVps                          ( m_sbPropOutputLayerSetIdxToVps );
-    m_cTEncTop.setHighestSublayerId                               ( m_sbPropHighestSublayerId );
-    m_cTEncTop.setAvgBitRate                                      ( m_sbPropAvgBitRate );
-    m_cTEncTop.setMaxBitRate                                      ( m_sbPropMaxBitRate );
-  }
-#endif
-#endif
-
   m_cTEncTop.setTMCTSSEIEnabled                                   ( m_tmctsSEIEnabled );
   m_cTEncTop.setTimeCodeSEIEnabled                                ( m_timeCodeSEIEnabled );
@@ -623,7 +624,8 @@
   m_cTEncTop.setKneeSEIInputKneePoint                             ( m_kneeSEIInputKneePoint );
   m_cTEncTop.setKneeSEIOutputKneePoint                            ( m_kneeSEIOutputKneePoint );
+  m_cTEncTop.setColourRemapInfoSEIFileRoot                        ( m_colourRemapSEIFileRoot );
   m_cTEncTop.setMasteringDisplaySEI                               ( m_masteringDisplay );
 
-#if NH_MV_SEI
+#if NH_MV
   m_cTEncTop.setSeiMessages                                       ( &m_seiMessages ); 
 #endif
@@ -644,8 +646,8 @@
   }
   m_cTEncTop.setLFCrossTileBoundaryFlag                           ( m_bLFCrossTileBoundaryFlag );
-  m_cTEncTop.setWaveFrontSynchro                                  ( m_iWaveFrontSynchro );
+  m_cTEncTop.setEntropyCodingSyncEnabledFlag                      ( m_entropyCodingSyncEnabledFlag );
   m_cTEncTop.setTMVPModeId                                        ( m_TMVPModeId );
   m_cTEncTop.setUseScalingListId                                  ( m_useScalingListId  );
-  m_cTEncTop.setScalingListFile                                   ( m_scalingListFile   );
+  m_cTEncTop.setScalingListFileName                               ( m_scalingListFileName );
   m_cTEncTop.setSignHideFlag                                      ( m_signHideFlag);
 #if KWU_RC_VIEWRC_E0227 || KWU_RC_MADPRED_E0227
@@ -669,4 +671,10 @@
   m_cTEncTop.setInitialQP                                         ( m_RCInitialQP );
   m_cTEncTop.setForceIntraQP                                      ( m_RCForceIntraQP );
+#if U0132_TARGET_BITS_SATURATION
+  m_cTEncTop.setCpbSaturationEnabled                              ( m_RCCpbSaturationEnabled );
+  m_cTEncTop.setCpbSize                                           ( m_RCCpbSize );
+  m_cTEncTop.setInitialCpbFullness                                ( m_RCInitialCpbFullness );
+#endif
+
 #if KWU_RC_MADPRED_E0227
   if(m_cTEncTop.getUseRateCtrl() && !m_cTEncTop.getIsDepth())
@@ -796,5 +804,5 @@
         TEncTop* pcEncTop =  m_acTEncTopList[ layer ]; 
         Int iViewNum      = pcEncTop->getViewIndex(); 
-        Int iContent      = pcEncTop->getIsDepth() ? 1 : 0; 
+        Int iContent      = pcEncTop->getIsDepth() || pcEncTop->getIsAuxDepth() ? 1 : 0; 
         Int iNumOfModels  = m_cRenModStrParser.getNumOfModelsForView(iViewNum, iContent);
 
@@ -843,10 +851,10 @@
 #else
   // Video I/O
-  m_cTVideoIOYuvInputFile.open( m_pchInputFile,     false, m_inputBitDepth, m_MSBExtendedBitDepth, m_internalBitDepth );  // read  mode
+  m_cTVideoIOYuvInputFile.open( m_inputFileName,     false, m_inputBitDepth, m_MSBExtendedBitDepth, m_internalBitDepth );  // read  mode
   m_cTVideoIOYuvInputFile.skipFrames(m_FrameSkip, m_iSourceWidth - m_aiPad[0], m_iSourceHeight - m_aiPad[1], m_InputChromaFormatIDC);
 
-  if (m_pchReconFile)
-  {
-    m_cTVideoIOYuvReconFile.open(m_pchReconFile, true, m_outputBitDepth, m_outputBitDepth, m_internalBitDepth);  // write mode
+  if (!m_reconFileName.empty())
+  {
+    m_cTVideoIOYuvReconFile.open(m_reconFileName, true, m_outputBitDepth, m_outputBitDepth, m_internalBitDepth);  // write mode
   }
 
@@ -917,8 +925,8 @@
 Void TAppEncTop::encode()
 {
-  fstream bitstreamFile(m_pchBitstreamFile, fstream::binary | fstream::out);
+  fstream bitstreamFile(m_bitstreamFileName.c_str(), fstream::binary | fstream::out);
   if (!bitstreamFile)
   {
-    fprintf(stderr, "\nfailed to open bitstream file `%s' for writing\n", m_pchBitstreamFile);
+    fprintf(stderr, "\nfailed to open bitstream file `%s' for writing\n", m_bitstreamFileName.c_str());
     exit(EXIT_FAILURE);
   }
@@ -1028,5 +1036,5 @@
     for ( Int gopId=0; gopId < gopSize; gopId++ )
     {
-#if NH_3D
+#if NH_3D_VSO
       UInt iNextPoc = m_acTEncTopList[0] -> getFrameId( gopId );
       if ( iNextPoc < m_framesToBeEncoded )
@@ -1150,5 +1158,5 @@
   printRateSummary();
 
-#if H_3D_REN_MAX_DEV_OUT
+#if NH_3D_REN_MAX_DEV_OUT
   Double dMaxDispDiff = m_cCameraData.getMaxShiftDeviation(); 
 
@@ -1295,5 +1303,5 @@
   }
 #else
-      if (m_pchReconFile)
+      if (!m_reconFileName.empty())
       {
         m_cTVideoIOYuvReconFile.write( pcPicYuvRecTop, pcPicYuvRecBottom, ipCSC, m_confWinLeft, m_confWinRight, m_confWinTop, m_confWinBottom, NUM_CHROMA_FORMAT, m_isTopFieldFirst );
@@ -1352,5 +1360,5 @@
   }
 #else
-      if (m_pchReconFile)
+      if (!m_reconFileName.empty())
       {
         m_cTVideoIOYuvReconFile.write( pcPicYuvRec, ipCSC, m_confWinLeft, m_confWinRight, m_confWinTop, m_confWinBottom,
@@ -1670,5 +1678,5 @@
           if( m_depthFlag[ curLayerIdInVps ] && ( m_mpiFlag|| m_qtPredFlag || m_intraContourFlag ) ) 
           {          
-            Int nuhLayerIdTex = vps.getLayerIdInNuh( vps.getViewIndex( curLayerIdInNuh ), false ); 
+            Int nuhLayerIdTex = vps.getLayerIdInNuh( vps.getViewIndex( curLayerIdInNuh ), false, 0 ); 
             if ( nuhLayerIdTex == refLayerIdInNuh )
             {
@@ -1696,5 +1704,5 @@
                 for (Int j = 0; j < geCur.m_numActiveRefLayerPics; j++ )
                 {
-                  Int nuhLayerIdDep = vps.getLayerIdInNuh( vps.getViewIndex( vps.getIdRefListLayer( curLayerIdInNuh, geCur.m_interLayerPredLayerIdc[j] ) ), true ); 
+                  Int nuhLayerIdDep = vps.getLayerIdInNuh( vps.getViewIndex( vps.getIdRefListLayer( curLayerIdInNuh, geCur.m_interLayerPredLayerIdc[j] ) ), true, 0 ); 
                   if ( nuhLayerIdDep == refLayerIdInNuh )
                   {
@@ -2063,7 +2071,7 @@
       vps.setLayerIdIncludedFlag( false, lsIdx, layerId ); 
     }
-    for ( Int i = 0; i < m_layerIdsInSets[lsIdx].size(); i++)
+    for ( Int i = 0; i < m_layerIdxInVpsInSets[lsIdx].size(); i++)
     {       
-      vps.setLayerIdIncludedFlag( true, lsIdx, vps.getLayerIdInNuh( m_layerIdsInSets[lsIdx][i] ) ); 
+      vps.setLayerIdIncludedFlag( true, lsIdx, vps.getLayerIdInNuh( m_layerIdxInVpsInSets[lsIdx][i] ) ); 
     } 
   }
Index: trunk/source/App/TAppEncoder/TAppEncTop.h
===================================================================
--- trunk/source/App/TAppEncoder/TAppEncTop.h	(revision 1357)
+++ trunk/source/App/TAppEncoder/TAppEncTop.h	(revision 1386)
@@ -46,5 +46,5 @@
 #include "TLibCommon/AccessUnit.h"
 #include "TAppEncCfg.h"
-#if NH_3D
+#if NH_3D_VSO
 #include "../../Lib/TLibRenderer/TRenTop.h"
 #endif
Index: trunk/source/App/TAppExtractor/TAppExtrCfg.cpp
===================================================================
--- trunk/source/App/TAppExtractor/TAppExtrCfg.cpp	(revision 1357)
+++ trunk/source/App/TAppExtractor/TAppExtrCfg.cpp	(revision 1386)
@@ -58,5 +58,5 @@
     \param argv array of arguments
  */
-Bool TAppExtrCfg::parseCfg( Int argc, Char* argv[] )
+Bool TAppExtrCfg::parseCfg( Int argc, TChar* argv[] )
 {
   bool do_help = false;
Index: trunk/source/App/TAppExtractor/TAppExtrCfg.h
===================================================================
--- trunk/source/App/TAppExtractor/TAppExtrCfg.h	(revision 1357)
+++ trunk/source/App/TAppExtractor/TAppExtrCfg.h	(revision 1386)
@@ -65,5 +65,5 @@
   virtual ~TAppExtrCfg() {}
   
-  Bool  parseCfg        ( Int argc, Char* argv[] );    ///< initialize option class from configuration
+  Bool  parseCfg        ( Int argc, TChar* argv[] );    ///< initialize option class from configuration
 
 protected:
Index: trunk/source/App/TAppRenderer/RendererMain.cpp
===================================================================
--- trunk/source/App/TAppRenderer/RendererMain.cpp	(revision 1357)
+++ trunk/source/App/TAppRenderer/RendererMain.cpp	(revision 1386)
@@ -35,5 +35,5 @@
 #include <time.h>
 #include "../../Lib/TLibCommon/CommonDef.h"
-#if NH_3D
+#if NH_3D_VSO
 #include "TAppRendererTop.h"
 // ====================================================================================================================
Index: trunk/source/App/TAppRenderer/TAppRendererCfg.cpp
===================================================================
--- trunk/source/App/TAppRenderer/TAppRendererCfg.cpp	(revision 1357)
+++ trunk/source/App/TAppRenderer/TAppRendererCfg.cpp	(revision 1386)
@@ -44,5 +44,5 @@
 #include "../../Lib/TAppCommon/program_options_lite.h"
 
-#if NH_3D
+#if NH_3D_VSO
 
 using namespace std;
@@ -111,5 +111,5 @@
 \retval             true when success
 */
-Bool TAppRendererCfg::parseCfg( Int argc, Char* argv[] )
+Bool TAppRendererCfg::parseCfg( Int argc, TChar* argv[] )
 {
   bool do_help = false;
@@ -121,13 +121,13 @@
 
     /* File I/O */
-    ("VideoInputFileBaseName,v",  m_pchVideoInputFileBaseName,  (Char*) 0, "Basename to generate video input file names")
-    ("DepthInputFileBaseName,d",  m_pchDepthInputFileBaseName,  (Char*) 0, "Basename to generate depth input file names")
-    ("SynthOutputFileBaseName,s", m_pchSynthOutputFileBaseName, (Char*) 0, "Basename to generate synthesized output file names")
+    ("VideoInputFileBaseName,v",  m_pchVideoInputFileBaseName,  (TChar*) 0, "Basename to generate video input file names")
+    ("DepthInputFileBaseName,d",  m_pchDepthInputFileBaseName,  (TChar*) 0, "Basename to generate depth input file names")
+    ("SynthOutputFileBaseName,s", m_pchSynthOutputFileBaseName, (TChar*) 0, "Basename to generate synthesized output file names")
     ("ContOutputFileNumbering", m_bContOutputFileNumbering  ,  false   , "Continuous Output File Numbering")
     ("Sweep"                  , m_bSweep                    ,  false   , "Store all views in first Output File")
 
-    ("VideoInputFile_%d,v_%d",  m_pchVideoInputFileList ,    (Char *) 0, MAX_INPUT_VIEW_NUM , "Original Yuv video input file name %d")
-    ("DepthInputFile_%d,d_%d",  m_pchDepthInputFileList ,    (Char *) 0, MAX_INPUT_VIEW_NUM , "Original Yuv depth input file name %d")
-    ("SynthOutputFile_%d,s_%d", m_pchSynthOutputFileList,    (Char *) 0, MAX_OUTPUT_VIEW_NUM, "Synthesized Yuv output file name %d")
+    ("VideoInputFile_%d,v_%d",  m_pchVideoInputFileList ,    (TChar *) 0, MAX_INPUT_VIEW_NUM , "Original Yuv video input file name %d")
+    ("DepthInputFile_%d,d_%d",  m_pchDepthInputFileList ,    (TChar *) 0, MAX_INPUT_VIEW_NUM , "Original Yuv depth input file name %d")
+    ("SynthOutputFile_%d,s_%d", m_pchSynthOutputFileList,    (TChar *) 0, MAX_OUTPUT_VIEW_NUM, "Synthesized Yuv output file name %d")
 
     ("InputBitDepth",           m_inputBitDepth[0],                     8, "Bit-depth of input file")
@@ -146,8 +146,8 @@
 
     /* Camera Specification */
-    ("CameraParameterFile,-cpf", m_pchCameraParameterFile,          (Char *) 0, "Camera Parameter File Name")
-    ("BaseViewCameraNumbers"  , m_pchBaseViewCameraNumbers,        (Char *) 0, "Numbers of base views")
-    ("SynthViewCameraNumbers" , m_pchSynthViewCameraNumbers,       (Char *) 0, "Numbers of views to synthesis")
-    ("ViewConfig"             , m_pchViewConfig,                   (Char *) 0, "View Configuration"               )
+    ("CameraParameterFile,-cpf", m_pchCameraParameterFile,         (TChar *) 0, "Camera Parameter File Name")
+    ("BaseViewCameraNumbers"  , m_pchBaseViewCameraNumbers,        (TChar *) 0, "Numbers of base views")
+    ("SynthViewCameraNumbers" , m_pchSynthViewCameraNumbers,       (TChar *) 0, "Numbers of views to synthesis")
+    ("ViewConfig"             , m_pchViewConfig,                   (TChar *) 0, "View Configuration"               )
 
     /* Renderer Modes */
@@ -458,5 +458,5 @@
 }
 
-Void TAppRendererCfg::xAddNumberToFileName( Char* pchSourceFileName, Char*& rpchTargetFileName, Int iNumberToAdd, UInt uiPrecBefore, UInt uiPrecAfter )
+Void TAppRendererCfg::xAddNumberToFileName( TChar* pchSourceFileName, TChar*& rpchTargetFileName, Int iNumberToAdd, UInt uiPrecBefore, UInt uiPrecAfter )
 {
 
@@ -468,6 +468,6 @@
   }
 
-  Char pchNumberBuffer[2* LOG10_VIEW_NUM_PREC + 2];
-  Char pchPrintBuffer[10];
+  TChar pchNumberBuffer[2* LOG10_VIEW_NUM_PREC + 2];
+  TChar pchPrintBuffer[10];
 
   Double dNumberToAdd = ( (Double) iNumberToAdd ) / VIEW_NUM_PREC;
@@ -488,7 +488,7 @@
   size_t iAddLength = strlen(pchNumberBuffer);
 
-  rpchTargetFileName = (Char*) malloc(iInLength+iAddLength+1);
-
-  Char* pchPlaceHolder = strrchr(pchSourceFileName,'$');
+  rpchTargetFileName = (TChar*) malloc(iInLength+iAddLength+1);
+
+  TChar* pchPlaceHolder = strrchr(pchSourceFileName,'$');
   assert( pchPlaceHolder );
 
Index: trunk/source/App/TAppRenderer/TAppRendererCfg.h
===================================================================
--- trunk/source/App/TAppRenderer/TAppRendererCfg.h	(revision 1357)
+++ trunk/source/App/TAppRenderer/TAppRendererCfg.h	(revision 1386)
@@ -47,5 +47,5 @@
 #include <vector>
 
-#if NH_3D
+#if NH_3D_VSO
 
 // ====================================================================================================================
@@ -59,7 +59,7 @@
 
   //// file I/O ////
-  Char*              m_pchVideoInputFileBaseName;      ///< input video  file base name, placeholder for numbering $$
-  Char*              m_pchDepthInputFileBaseName;      ///< input depth  file base name, placeholder for numbering $$
-  Char*              m_pchSynthOutputFileBaseName;     ///< output synth file base name, placeholder for numbering $$
+  TChar*             m_pchVideoInputFileBaseName;      ///< input video  file base name, placeholder for numbering $$
+  TChar*             m_pchDepthInputFileBaseName;      ///< input depth  file base name, placeholder for numbering $$
+  TChar*             m_pchSynthOutputFileBaseName;     ///< output synth file base name, placeholder for numbering $$
   Bool               m_bContOutputFileNumbering;       ///< use continous numbering instead of view numbering
   Bool               m_bSweep;                         ///< 1: Store view range in file
@@ -73,7 +73,7 @@
 
   // derived
-  std::vector<Char*> m_pchVideoInputFileList;          ///< source file names
-  std::vector<Char*> m_pchDepthInputFileList;          ///< source depth file names
-  std::vector<Char*> m_pchSynthOutputFileList;         ///< output reconstruction file names
+  std::vector<TChar*> m_pchVideoInputFileList;         ///< source file names
+  std::vector<TChar*> m_pchDepthInputFileList;         ///< source depth file names
+  std::vector<TChar*> m_pchSynthOutputFileList;        ///< output reconstruction file names
 
   //// source specification ////
@@ -84,8 +84,8 @@
 
   ////camera specification ////
-  Char*               m_pchCameraParameterFile;         ///< camera parameter file
-  Char*               m_pchSynthViewCameraNumbers;      ///< numbers of views to synthesize
-  Char*               m_pchViewConfig;                  ///< String to setup renderer
-  Char*               m_pchBaseViewCameraNumbers;       ///< numbers of base views
+  TChar*             m_pchCameraParameterFile;         ///< camera parameter file
+  TChar*             m_pchSynthViewCameraNumbers;      ///< numbers of views to synthesize
+  TChar*             m_pchViewConfig;                  ///< String to setup renderer
+  TChar*             m_pchBaseViewCameraNumbers;       ///< numbers of base views
 
   // derived
@@ -123,5 +123,5 @@
   Void xCreateFileNames();
   Void xGetMaxPrecision( IntAry1d adIn, Int& iPrecBefore, Int& iPrecAfter );
-  Void xAddNumberToFileName( Char* pchSourceFileName, Char*& rpchTargetFileName, Int iNumberToAdd, UInt uiPrecBefore, UInt uiPrecAfter );
+  Void xAddNumberToFileName( TChar* pchSourceFileName, TChar*& rpchTargetFileName, Int iNumberToAdd, UInt uiPrecBefore, UInt uiPrecAfter );
 public:
   TAppRendererCfg();
@@ -131,6 +131,6 @@
   Void  create    ();                                         ///< create option handling class
   Void  destroy   ();                                         ///< destroy option handling class
-  Bool  parseCfg  ( Int argc, Char* argv[] );                 ///< parse configuration file to fill member variables
-  Bool  xConfirmParameter(Bool bflag, const Char* message);
+  Bool  parseCfg  ( Int argc, TChar* argv[] );                 ///< parse configuration file to fill member variables
+  Bool  xConfirmParameter(Bool bflag, const TChar* message);
 
 
Index: trunk/source/App/TAppRenderer/TAppRendererTop.cpp
===================================================================
--- trunk/source/App/TAppRenderer/TAppRendererTop.cpp	(revision 1357)
+++ trunk/source/App/TAppRenderer/TAppRendererTop.cpp	(revision 1386)
@@ -41,5 +41,5 @@
 #include "TAppRendererTop.h"
 
-#if NH_3D
+#if NH_3D_VSO
 
 // ====================================================================================================================
@@ -488,5 +488,5 @@
   }
 
-#if H_3D_REN_MAX_DEV_OUT
+#if NH_3D_REN_MAX_DEV_OUT
   Double dMaxDispDiff = m_cCameraData.getMaxShiftDeviation(); 
 
Index: trunk/source/App/TAppRenderer/TAppRendererTop.h
===================================================================
--- trunk/source/App/TAppRenderer/TAppRendererTop.h	(revision 1357)
+++ trunk/source/App/TAppRenderer/TAppRendererTop.h	(revision 1386)
@@ -40,5 +40,5 @@
 #define __TAppRendererTOP__
 #include "../../Lib/TLibCommon/CommonDef.h"
-#if NH_3D
+#if NH_3D_VSO
 #include "../../Lib/TLibRenderer/TRenTop.h"
 #include "../../Lib/TLibVideoIO/TVideoIOYuv.h"
Index: trunk/source/App/utils/convert_NtoMbit_YCbCr.cpp
===================================================================
--- trunk/source/App/utils/convert_NtoMbit_YCbCr.cpp	(revision 1357)
+++ trunk/source/App/utils/convert_NtoMbit_YCbCr.cpp	(revision 1386)
@@ -105,10 +105,10 @@
 
   TComPicYuv frame;
-  frame.create( width, height, chromaFormatIDC, width, height, 0, false);
+  frame.createWithoutCUInfo( width, height, chromaFormatIDC);
 
   Int pad[2] = {0, 0};
 
   TComPicYuv cPicYuvTrueOrg;
-  cPicYuvTrueOrg.create( width, height, chromaFormatIDC, width, height, 0, false );
+  cPicYuvTrueOrg.createWithoutCUInfo( width, height, chromaFormatIDC );
 
   UInt num_frames_processed = 0;
Index: trunk/source/Lib/TAppCommon/TAppComCamPara.cpp
===================================================================
--- trunk/source/Lib/TAppCommon/TAppComCamPara.cpp	(revision 1357)
+++ trunk/source/Lib/TAppCommon/TAppComCamPara.cpp	(revision 1386)
@@ -49,5 +49,5 @@
 #include <functional>
 #include <string>
-#if NH_3D
+#if NH_3D_VSO
 
 
@@ -115,5 +115,5 @@
 
 Void
-TAppComCamPara::convertNumberString( Char* pchViewNumberString, std::vector<Int>& raiViewNumbers, Double dViewNumPrec )
+TAppComCamPara::convertNumberString( TChar* pchViewNumberString, std::vector<Int>& raiViewNumbers, Double dViewNumPrec )
 {
   Bool bStringIsRange = false;
@@ -131,7 +131,7 @@
   }
 
-  Char* pcNextStart = pchViewNumberString;
-  Char* pcEnd       = pcNextStart + iIdx;
-  Char* pcOldStart  = 0;
+  TChar* pcNextStart = pchViewNumberString;
+  TChar* pcEnd       = pcNextStart + iIdx;
+  TChar* pcOldStart  = 0;
 
   while( pcNextStart < pcEnd )
@@ -192,6 +192,8 @@
 
 Void
-TAppComCamPara::xReadCameraParameterFile( Char* pchCfgFileName )
-{
+TAppComCamPara::xReadCameraParameterFile( TChar* pchCfgFileName )
+{
+  assert( pchCfgFileName != NULL );
+
   std::ifstream cCfgStream( pchCfgFileName, std::ifstream::in );
   if( !cCfgStream )
@@ -220,11 +222,11 @@
     }
 
-    Char* pcNextStart = (Char*) cLine.data();
-    Char* pcEnd = pcNextStart + cLine.length();
+    TChar* pcNextStart = (TChar*) cLine.data();
+    TChar* pcEnd = pcNextStart + cLine.length();
 
     std::vector<Double> caNewLine;
     caNewLine.clear();
 
-    Char* pcOldStart = 0;
+    TChar* pcOldStart = 0;
     while( pcNextStart < pcEnd )
     {
@@ -880,5 +882,5 @@
 
         // maximum deviation
-#if H_3D_REN_MAX_DEV_OUT
+#if NH_3D_REN_MAX_DEV_OUT
         m_dMaxShiftDeviation = std::max( m_dMaxShiftDeviation, fabs( Double( (Int) iShiftLuma   ) - dShiftLuma   ) / Double( 1 << m_iLog2Precision ) );        
 #endif
@@ -981,5 +983,5 @@
   m_bCamParsCodedPrecSet      = false;
 
-#if H_3D_REN_MAX_DEV_OUT
+#if NH_3D_REN_MAX_DEV_OUT
   m_dMaxShiftDeviation        = -1; 
 #endif
@@ -1094,5 +1096,5 @@
 }
 
-Void TAppComCamPara::xSetupBaseViews( Char* pchBaseViewNumbers, UInt uiNumBaseViews )
+Void TAppComCamPara::xSetupBaseViews( TChar* pchBaseViewNumbers, UInt uiNumBaseViews )
   {
     // init list
@@ -1142,7 +1144,7 @@
                       UInt   uiStartFrameId,
                       UInt   uiNumFrames,
-                      Char*  pchCfgFileName,
-                      Char*  pchBaseViewNumbers,
-                      Char*  pchSynthViewNumbers,
+                      TChar* pchCfgFileName,
+                      TChar* pchBaseViewNumbers,
+                      TChar* pchSynthViewNumbers,
                       std::vector<Int>* paiSynthViewNumbers,
                       Int    iLog2Precision )
Index: trunk/source/Lib/TAppCommon/TAppComCamPara.h
===================================================================
--- trunk/source/Lib/TAppCommon/TAppComCamPara.h	(revision 1357)
+++ trunk/source/Lib/TAppCommon/TAppComCamPara.h	(revision 1386)
@@ -67,5 +67,5 @@
   Bool                m_bCamParsCodedPrecSet;                 ///< Coded Cam Para precision set for current frame;
   
-#if H_3D_REN_MAX_DEV_OUT
+#if NH_3D_REN_MAX_DEV_OUT
   Double              m_dMaxShiftDeviation;                   ///< Maximum deviation of shifts with integer precision compare to double precision
 #endif
@@ -113,5 +113,5 @@
 
   // functions for reading, initialization, sorting, getting data, etc.
-  Void  xReadCameraParameterFile  ( Char* pchCfgFileName );
+  Void  xReadCameraParameterFile  ( TChar* pchCfgFileName );
   Bool  xGetCameraDataRow         ( Int iView, UInt uiFrame, UInt& ruiFoundLine );
 
@@ -129,5 +129,5 @@
 #endif
   Void  xSetupBaseViewsFromCoded  ();
-  Void  xSetupBaseViews           ( Char* pchBaseViewNumbers, UInt uiNumBaseViews );
+  Void  xSetupBaseViews           ( TChar* pchBaseViewNumbers, UInt uiNumBaseViews );
   Bool  xIsIn                     ( std::vector<Int>& rVec, Int iNumber);
 
@@ -156,7 +156,7 @@
                 UInt    uiStartFrameId,
                 UInt    uiNumFrames,
-                Char*   pchCfgFileName,
-                Char*   pchBaseViewNumbers,
-                Char*   pchSynthViewNumbers,
+                TChar*   pchCfgFileName,
+                TChar*   pchBaseViewNumbers,
+                TChar*   pchSynthViewNumbers,
                 std::vector<Int>* paiSynthViewNumbers,
                 Int     iLog2Precision );
@@ -165,6 +165,6 @@
                 UInt    uiStartFrameId,
                 UInt    uiNumFrames,
-                Char*   pchCfgFileName,
-                Char*   pchSynthViewNumbers,
+                TChar*   pchCfgFileName,
+                TChar*   pchSynthViewNumbers,
                 std::vector<Int>* paiSynthViewNumbers,
                 Int     iLog2Precision
@@ -183,6 +183,6 @@
   Int                 getRelDistLeft            ( Int iSynthViewIdx, Int   iLeftViewIdx, Int iRightViewIdx );
   UInt                getCurFrameId             ()  { return m_iCurrentFrameId;   }
-  static Void         convertNumberString       ( Char* pchViewNumberString, std::vector<Int>& raiViewNumbers, Double dViewNumPrec );
-#if H_3D_REN_MAX_DEV_OUT
+  static Void         convertNumberString       ( TChar* pchViewNumberString, std::vector<Int>& raiViewNumbers, Double dViewNumPrec );
+#if NH_3D_REN_MAX_DEV_OUT
   Double              getMaxShiftDeviation      () { return m_dMaxShiftDeviation; }; 
 #endif
Index: trunk/source/Lib/TAppCommon/program_options_lite.cpp
===================================================================
--- trunk/source/Lib/TAppCommon/program_options_lite.cpp	(revision 1357)
+++ trunk/source/Lib/TAppCommon/program_options_lite.cpp	(revision 1386)
@@ -111,5 +111,5 @@
     }
 
-#if NH_MV_SEI
+#if NH_MV
     static void setOptions(Options::NamesPtrList& opt_list, const std::vector<int> idcs, const string& value, ErrorReporter& error_reporter)
 #else
@@ -121,5 +121,5 @@
       for (Options::NamesPtrList::iterator it = opt_list.begin(); it != opt_list.end(); ++it)
       {
-        #if NH_MV_SEI
+#if NH_MV
           Bool doParsing = (*it)->opt->checkDim( idcs, error_reporter ); 
           if ( doParsing )
@@ -127,8 +127,7 @@
             (*it)->opt->parse(value, idcs, error_reporter);
           }
-          
-        #else
+#else
         (*it)->opt->parse(value, error_reporter);
-        #endif
+#endif
       }
     }
@@ -290,5 +289,5 @@
     bool OptionWriter::storePair(bool allow_long, bool allow_short, const string& name, const string& value)
     {
-#if NH_MV_SEI
+#if NH_MV
       std::vector<int> idcs;             
       
@@ -324,5 +323,5 @@
           found = true;
         }
-#if NH_MV_SEI
+#if NH_MV
         if ( idcs.size() > 0 )
         {
@@ -347,5 +346,5 @@
           found = true;
         }
-#if NH_MV_SEI
+#if NH_MV
         if ( idcs.size() > 0 )
         {
@@ -362,5 +361,5 @@
       }
 
-#if NH_MV_SEI
+#if NH_MV
     if ( !found_idcs )
     {
@@ -370,5 +369,5 @@
       if (!found)
       {
-#if NH_MV_SEI
+#if NH_MV
         if (error_reporter.output_on_unknow_parameter )
         {       
@@ -377,5 +376,5 @@
         error_reporter.error(where())
           << "Unknown option `" << name << "' (value:`" << value << "')\n";
-#if NH_MV_SEI
+#if NH_MV
         }
 #endif
@@ -383,5 +382,5 @@
       }
 
-#if NH_MV_SEI
+#if NH_MV
       setOptions((*opt_it).second, idcs, value, error_reporter);
 #else
Index: trunk/source/Lib/TAppCommon/program_options_lite.h
===================================================================
--- trunk/source/Lib/TAppCommon/program_options_lite.h	(revision 1357)
+++ trunk/source/Lib/TAppCommon/program_options_lite.h	(revision 1386)
@@ -37,5 +37,4 @@
 #include <map>
 #include  "../TLibCommon/CommonDef.h" 
-
 #if NH_MV
 #include <vector>
@@ -78,5 +77,5 @@
     struct ErrorReporter
     {
-#if NH_MV_SEI
+#if NH_MV
       ErrorReporter() : is_errored(0), output_on_unknow_parameter(true)  {}
 #else
@@ -87,5 +86,5 @@
       virtual std::ostream& warn(const std::string& where);
       bool is_errored;
-#if NH_MV_SEI
+#if NH_MV
       bool output_on_unknow_parameter;
 #endif
@@ -105,12 +104,7 @@
     {
 #if NH_MV      
-#if NH_MV_SEI      
       OptionBase(const std::string& name, const std::string& desc, bool duplicate = false, std::vector< int > maxdim = std::vector< int >(0) )
         : opt_string(name), opt_desc(desc), opt_duplicate(duplicate), max_dim( maxdim )
 #else
-      OptionBase(const std::string& name, const std::string& desc, bool duplicate = false)
-        : opt_string(name), opt_desc(desc), opt_duplicate(duplicate)
-#endif
-#else
       OptionBase(const std::string& name, const std::string& desc)
       : opt_string(name), opt_desc(desc)
@@ -121,5 +115,5 @@
 
       /* parse argument arg, to obtain a value for the option */
-#if NH_MV_SEI
+#if NH_MV
       virtual void parse(const std::string& arg, const std::vector<int>& idcs,  ErrorReporter&) = 0;
       
@@ -221,7 +215,5 @@
 #if NH_MV
       bool        opt_duplicate; 
-#if NH_MV_SEI
       std::vector<int> max_dim;
-#endif
 #endif
     };
@@ -232,12 +224,7 @@
     {
 #if NH_MV
-#if NH_MV_SEI
       Option(const std::string& name, T& storage, T default_val, const std::string& desc, bool duplicate = false, std::vector< int > maxdim = std::vector< int >(0) )
         : OptionBase(name, desc, duplicate, maxdim), opt_storage(storage), opt_default_val(default_val)
 #else
-      Option(const std::string& name, T& storage, T default_val, const std::string& desc, bool duplicate = false)
-        : OptionBase(name, desc, duplicate), opt_storage(storage), opt_default_val(default_val)
-#endif
-#else
       Option(const std::string& name, T& storage, T default_val, const std::string& desc)
       : OptionBase(name, desc), opt_storage(storage), opt_default_val(default_val)
@@ -245,5 +232,5 @@
       {}
 
-#if NH_MV_SEI
+#if NH_MV
       void parse(const std::string& arg, const std::vector<int>& idcs, ErrorReporter&);
 #else
@@ -263,5 +250,5 @@
     template<typename T>
     inline void
-#if NH_MV_SEI
+#if NH_MV
     Option<T>::parse(const std::string& arg, const std::vector<int>& idcs, ErrorReporter&)
 #else
@@ -269,5 +256,5 @@
 #endif
     {
-#if NH_MV_SEI
+#if NH_MV
       assert( idcs.size() == 0 ); 
 #endif
@@ -289,66 +276,31 @@
     template<>
     inline void
-#if NH_MV_SEI
+#if NH_MV
     Option<std::string>::parse(const std::string& arg, const std::vector<int>& idcs, ErrorReporter&)
-#else
-    Option<std::string>::parse(const std::string& arg, ErrorReporter&)
-#endif
-    {
-#if NH_MV_SEI
+    {
       assert( idcs.size() == 0 ); 
-#endif
       opt_storage = arg;
     }
+#else
+    Option<std::string>::parse(const std::string& arg, ErrorReporter&)
+    {
+      opt_storage = arg;
+    }
+#endif
 
 #if NH_MV    
     template<>
     inline void
-#if NH_MV_SEI
       Option<char*>::parse(const std::string& arg, const std::vector<int>& idcs, ErrorReporter&)
-#else
-      Option<char*>::parse(const std::string& arg, ErrorReporter&)
-#endif
-    {
-#if NH_MV_SEI
+    {
       assert( idcs.size() == 0 ); 
-#endif
       opt_storage = arg.empty() ? NULL : strdup(arg.c_str()) ;
     }
 
-#if !NH_MV_SEI
-
-    template<>
-    inline void
-      Option< std::vector<char*> >::parse(const std::string& arg, ErrorReporter&)
-    {
-      opt_storage.clear(); 
-
-      char* pcStart = (char*) arg.data();      
-      char* pcEnd = strtok (pcStart," ");
-
-      while (pcEnd != NULL)
-      {
-        size_t uiStringLength = pcEnd - pcStart;
-        char* pcNewStr = (char*) malloc( uiStringLength + 1 );
-        strncpy( pcNewStr, pcStart, uiStringLength); 
-        pcNewStr[uiStringLength] = '\0'; 
-        pcStart = pcEnd+1; 
-        pcEnd = strtok (NULL, " ,.-");
-        opt_storage.push_back( pcNewStr ); 
-      }      
-    }
-#endif
-
     template<>    
     inline void
-#if NH_MV_SEI
       Option< std::vector<double> >::parse(const std::string& arg, const std::vector< int > & idcs, ErrorReporter&)
-#else
-      Option< std::vector<double> >::parse(const std::string& arg, ErrorReporter&)
-#endif
-    {
-#if NH_MV_SEI
+    {
       assert( idcs.size() == 0 ); 
-#endif
       char* pcNextStart = (char*) arg.data();
       char* pcEnd = pcNextStart + arg.length();
@@ -384,5 +336,4 @@
 
 
-#if NH_MV_SEI
     template<>
     inline void
@@ -405,5 +356,5 @@
       xParseVec ( arg, opt_storage[ idcs[0] ][ idcs[1] ] );
     };
-#if SEI_DRI_F0169
+
     template<>
     inline void
@@ -439,50 +390,7 @@
             while( (pcNextStart < pcEnd) && ( *pcNextStart == ' ' || *pcNextStart == '\t' || *pcNextStart == '\r' ) ) pcNextStart++;  
             pcOldStart = pcNextStart; 
-
-        }       
-
-
+        }
     }
-#endif
-#else
-    template<>
-    inline void
-      Option< std::vector<int> >::parse(const std::string& arg, ErrorReporter&)
-    {
-      opt_storage.clear();
-
-
-      char* pcNextStart = (char*) arg.data();
-      char* pcEnd = pcNextStart + arg.length();
-
-      char* pcOldStart = 0; 
-
-      size_t iIdx = 0; 
-
-
-      while (pcNextStart < pcEnd)
-      {
-
-        if ( iIdx < opt_storage.size() )
-        {
-          opt_storage[iIdx] = (int) strtol(pcNextStart, &pcNextStart,10);
-        }
-        else
-        {
-          opt_storage.push_back( (int) strtol(pcNextStart, &pcNextStart,10)) ;
-        }
-        iIdx++; 
-        if ( errno == ERANGE || (pcNextStart == pcOldStart) )
-        {
-          std::cerr << "Error Parsing Integers: `" << arg << "'" << std::endl;
-          exit(EXIT_FAILURE);
-        };   
-        while( (pcNextStart < pcEnd) && ( *pcNextStart == ' ' || *pcNextStart == '\t' || *pcNextStart == '\r' ) ) pcNextStart++;  
-        pcOldStart = pcNextStart;
-      }
-    }
-#endif
-
-#if NH_MV_SEI
+
 
     template<>
@@ -531,38 +439,4 @@
       xParseVec( arg, opt_storage[idcs[0]][idcs[1]] );
     };
-#else
-    template<>
-    inline void
-      Option< std::vector<bool> >::parse(const std::string& arg, ErrorReporter&)
-    {
-      char* pcNextStart = (char*) arg.data();
-      char* pcEnd = pcNextStart + arg.length();
-
-      char* pcOldStart = 0; 
-
-      size_t iIdx = 0; 
-
-      while (pcNextStart < pcEnd)
-      {
-        if ( iIdx < opt_storage.size() )
-        {
-          opt_storage[iIdx] = (strtol(pcNextStart, &pcNextStart,10) != 0);
-        }
-        else
-        {
-          opt_storage.push_back(strtol(pcNextStart, &pcNextStart,10) != 0) ;
-        }
-        iIdx++; 
-
-        if ( errno == ERANGE || (pcNextStart == pcOldStart) )
-        {
-          std::cerr << "Error Parsing Bools: `" << arg << "'" << std::endl;
-          exit(EXIT_FAILURE);
-        };   
-        while( (pcNextStart < pcEnd) && ( *pcNextStart == ' ' || *pcNextStart == '\t' || *pcNextStart == '\r' ) ) pcNextStart++;  
-        pcOldStart = pcNextStart;
-      }
-    }
-#endif
 #endif
     /** Option class for argument handling using a user provided function */
@@ -575,5 +449,5 @@
       {}
 
-#if NH_MV_SEI
+#if NH_MV
       void parse(const std::string& arg, const std::vector<int>& idcs, ErrorReporter& error_reporter)
 #else
@@ -651,5 +525,4 @@
         operator()(const std::string& name, std::vector<T>& storage, T default_val, unsigned uiMaxNum, const std::string& desc = "" )
       {
-#if NH_MV_SEI
         std::vector<T> defVal;
         defVal.resize( uiMaxNum, default_val ); 
@@ -679,33 +552,4 @@
         return *this;
       }
-#else
-        std::string cNameBuffer;
-        std::string cDescBuffer;
-
-        storage.resize(uiMaxNum);
-        for ( unsigned int uiK = 0; uiK < uiMaxNum; uiK++ )
-        {
-          cNameBuffer       .resize( name.size() + 10 );
-          cDescBuffer.resize( desc.size() + 10 );
-
-          Bool duplicate = (uiK != 0); 
-          // isn't there are sprintf function for string??
-          sprintf((char*) cNameBuffer.c_str()       ,name.c_str(),uiK,uiK);
-
-          if ( !duplicate )
-          {          
-            sprintf((char*) cDescBuffer.c_str(),desc.c_str(),uiK,uiK);
-          }
-
-          cNameBuffer.resize( std::strlen(cNameBuffer.c_str()) );  
-          cDescBuffer.resize( std::strlen(cDescBuffer.c_str()) ); 
-          
-
-          parent.addOption(new Option<T>( cNameBuffer, (storage[uiK]), default_val, cDescBuffer, duplicate ));
-        }
-
-        return *this;
-      }
-#endif
 #endif
       /**
Index: trunk/source/Lib/TLibCommon/CommonDef.h
===================================================================
--- trunk/source/Lib/TLibCommon/CommonDef.h	(revision 1357)
+++ trunk/source/Lib/TLibCommon/CommonDef.h	(revision 1386)
@@ -42,4 +42,5 @@
 #include <iostream>
 #include <assert.h>
+#include <limits>
 
 #if _MSC_VER > 1000
@@ -53,6 +54,4 @@
 // 
 #endif // _MSC_VER > 1000
-
-
 #include "TypeDef.h"
 #ifdef _MSC_VER
@@ -75,5 +74,5 @@
 #define HM_VERSION        "16.6"                ///< 
 #else
-#define NV_VERSION        "16.6"                 ///< Current software version
+#define NV_VERSION        "16.7"                 ///< Current software version
 #endif
 // ====================================================================================================================
@@ -141,5 +140,4 @@
 
 static const Int AMVP_MAX_NUM_CANDS =                               2; ///< AMVP: advanced motion vector prediction - max number of final candidates
-static const Int AMVP_MAX_NUM_CANDS_MEM =                           3; ///< AMVP: advanced motion vector prediction - max number of candidates
 static const Int AMVP_DECIMATION_FACTOR =                           4;
 static const Int MRG_MAX_NUM_CANDS =                                5; ///< MERGE
@@ -173,7 +171,5 @@
 #if NH_MV
 static const Int MAX_NUM_LAYER_IDS =                               63;
-#if NH_MV_SEI
 static const Int MAX_NUM_SEIS      =                               1000;
-#endif
 #else
 static const Int MAX_NUM_LAYER_IDS =                               64;
@@ -283,10 +279,8 @@
 static const Int  MAX_NUM_PICS_RPS          =                     16 ; 
 static const Int  MAX_NUM_REF_LAYERS        =                     63 ;  
-#if NH_MV_SEI
+
 static IntAry1d getRangeVec( Int rngStart, Int rngEnd ) { IntAry1d rng; for (Int i = rngStart; i<=rngEnd; i++) rng.push_back(i);  return rng; };
 static const IntAry1d IDR_NAL_UNIT_TYPES   = getRangeVec( NAL_UNIT_CODED_SLICE_IDR_W_RADL, NAL_UNIT_CODED_SLICE_IDR_N_LP ); 
 static const IntAry1d IRAP_NAL_UNIT_TYPES  = getRangeVec( NAL_UNIT_CODED_SLICE_BLA_W_LP  , NAL_UNIT_CODED_SLICE_CRA      ); 
-
-#endif
 #endif
 
@@ -448,5 +442,5 @@
 #endif
 
-#if NH_3D
+#if NH_3D_VSO
 //PICYUV
 #define PICYUV_PAD         16
Index: trunk/source/Lib/TLibCommon/Debug.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/Debug.cpp	(revision 1357)
+++ trunk/source/Lib/TLibCommon/Debug.cpp	(revision 1386)
@@ -49,7 +49,7 @@
 #if DEBUG_STRING
 // these strings are used to reorder the debug output so that the encoder and decoder match.
-const Char *debug_reorder_data_inter_token[MAX_NUM_COMPONENT+1]
+const TChar *debug_reorder_data_inter_token[MAX_NUM_COMPONENT+1]
  = {"Start of channel 0 inter debug\n", "Start of channel 1 inter debug\n", "Start of channel 2 inter debug\n", "End of inter residual debug\n"} ;
-const Char *partSizeToString[NUMBER_OF_PART_SIZES]={"2Nx2N(0)", "2NxN(1)", "Nx2N(2)", "NxN(3)", "2Nx(N/2+3N/2)(4)", "2Nx(3N/2+N/2)(5)", "(N/2+3N/2)x2N(6)", "(3N/2+N/2)x2N(7)"};
+const TChar *partSizeToString[NUMBER_OF_PART_SIZES]={"2Nx2N(0)", "2NxN(1)", "Nx2N(2)", "NxN(3)", "2Nx(N/2+3N/2)(4)", "2Nx(3N/2+N/2)(5)", "(N/2+3N/2)x2N(6)", "(3N/2+N/2)x2N(7)"};
 #endif
 
@@ -179,4 +179,7 @@
   PRINT_CONSTANT(O0043_BEST_EFFORT_DECODING,                                        settingNameWidth, settingValueWidth);
 
+  PRINT_CONSTANT(ME_ENABLE_ROUNDING_OF_MVS,                                         settingNameWidth, settingValueWidth);
+  PRINT_CONSTANT(U0040_MODIFIED_WEIGHTEDPREDICTION_WITH_BIPRED_AND_CLIPPING,        settingNameWidth, settingValueWidth);
+
   //------------------------------------------------
 
@@ -418,5 +421,5 @@
 
 
-Void printBlockToStream( std::ostream &ss, const Char *pLinePrefix, TComYuv &src, const UInt numSubBlocksAcross, const UInt numSubBlocksUp, const UInt defWidth )
+Void printBlockToStream( std::ostream &ss, const TChar *pLinePrefix, TComYuv &src, const UInt numSubBlocksAcross, const UInt numSubBlocksUp, const UInt defWidth )
 {
   const UInt numValidComp=src.getNumberValidComponents();
Index: trunk/source/Lib/TLibCommon/Debug.h
===================================================================
--- trunk/source/Lib/TLibCommon/Debug.h	(revision 1357)
+++ trunk/source/Lib/TLibCommon/Debug.h	(revision 1386)
@@ -47,6 +47,6 @@
 #include <TLibCommon/CommonDef.h>
 #if DEBUG_STRING
-extern const Char *debug_reorder_data_inter_token[MAX_NUM_COMPONENT+1];
-extern const Char *partSizeToString[NUMBER_OF_PART_SIZES];
+extern const TChar *debug_reorder_data_inter_token[MAX_NUM_COMPONENT+1];
+extern const TChar *partSizeToString[NUMBER_OF_PART_SIZES];
 #endif
 
@@ -149,7 +149,7 @@
 UInt getZScanIndex(const UInt x, const UInt y);
 
-//template specialisation for Char types to get it to render as a number
+//template specialisation for SChar/UChar types to get it to render as a number
 template <typename ValueType> inline Void writeValueToStream       (const ValueType &value, std::ostream &stream, const UInt outputWidth) { stream << std::setw(outputWidth) <<      value;  }
-template <>                   inline Void writeValueToStream<Char >(const Char      &value, std::ostream &stream, const UInt outputWidth) { stream << std::setw(outputWidth) <<  Int(value); }
+template <>                   inline Void writeValueToStream<SChar>(const SChar     &value, std::ostream &stream, const UInt outputWidth) { stream << std::setw(outputWidth) <<  Int(value); }
 template <>                   inline Void writeValueToStream<UChar>(const UChar     &value, std::ostream &stream, const UInt outputWidth) { stream << std::setw(outputWidth) << UInt(value); }
 
@@ -231,5 +231,5 @@
 
 template <typename T>
-Void printBlockToStream( std::ostream &ss, const Char *pLinePrefix, const T * blkSrc, const UInt width, const UInt height, const UInt stride, const UInt subBlockWidth=0, const UInt subBlockHeight=0, const UInt defWidth=3 )
+Void printBlockToStream( std::ostream &ss, const TChar *pLinePrefix, const T * blkSrc, const UInt width, const UInt height, const UInt stride, const UInt subBlockWidth=0, const UInt subBlockHeight=0, const UInt defWidth=3 )
 {
   for (UInt y=0; y<height; y++)
@@ -255,5 +255,5 @@
 
 class TComYuv;
-Void printBlockToStream( std::ostream &ss, const Char *pLinePrefix, TComYuv &src, const UInt numSubBlocksAcross=1, const UInt numSubBlocksUp=1, const UInt defWidth=3 );
+Void printBlockToStream( std::ostream &ss, const TChar *pLinePrefix, TComYuv &src, const UInt numSubBlocksAcross=1, const UInt numSubBlocksUp=1, const UInt defWidth=3 );
 
 // ---------------------------------------------------------------------------------------------- //
Index: trunk/source/Lib/TLibCommon/SEI.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/SEI.cpp	(revision 1357)
+++ trunk/source/Lib/TLibCommon/SEI.cpp	(revision 1386)
@@ -32,5 +32,5 @@
  */
 
-/** \file     #SEI.cpp
+/** \file     SEI.cpp
     \brief    helper functions for SEI handling
 */
@@ -38,5 +38,5 @@
 #include "CommonDef.h"
 #include "SEI.h"
-#if NH_MV_SEI
+#if NH_MV
 #include "TComSlice.h"
 #endif
@@ -118,5 +118,5 @@
 
 // Static member
-const Char *SEI::getSEIMessageString(SEI::PayloadType payloadType)
+const TChar *SEI::getSEIMessageString(SEI::PayloadType payloadType)
 {
   switch (payloadType)
@@ -151,7 +151,8 @@
     case SEI::SEGM_RECT_FRAME_PACKING:              return "Segmented rectangular frame packing arrangement";
     case SEI::TEMP_MOTION_CONSTRAINED_TILE_SETS:    return "Temporal motion constrained tile sets";
-    case SEI::CHROMA_SAMPLING_FILTER_HINT:          return "Chroma sampling filter hint";
+    case SEI::CHROMA_RESAMPLING_FILTER_HINT:        return "Chroma sampling filter hint";
+    case SEI::COLOUR_REMAPPING_INFO:                return "Colour remapping info";
+
 #if NH_MV
-    case SEI::COLOUR_REMAPPING_INFO:                     return "Colour remapping information";
     case SEI::DEINTERLACED_FIELD_IDENTIFICATION:         return "Deinterlaced field identification";
     case SEI::LAYERS_NOT_PRESENT:                        return "Layers not present";
@@ -177,5 +178,5 @@
 }
 
-#if NH_MV_SEI
+#if NH_MV
 SEI::SEI()
 {
@@ -223,8 +224,5 @@
     case SEI::CHROMA_SAMPLING_FILTER_HINT:          return new SEIChromaSamplingFilterHint
 #endif
-#if NH_MV_SEI
-#if NH_MV_LAYERS_NOT_PRESENT_SEI
   case SEI::LAYERS_NOT_PRESENT                    :               return new SEILayersNotPresent;
-#endif
   case SEI::INTER_LAYER_CONSTRAINED_TILE_SETS     :               return new SEIInterLayerConstrainedTileSets;
 #if NH_MV_SEI_TBD
@@ -240,7 +238,5 @@
 #endif
   case SEI::THREE_DIMENSIONAL_REFERENCE_DISPLAYS_INFO:            return new SEIThreeDimensionalReferenceDisplaysInfo;
-#if SEI_DRI_F0169
   case SEI::DEPTH_REPRESENTATION_INFO             :               return new SEIDepthRepresentationInfo;
-#endif
   case SEI::MULTIVIEW_SCENE_INFO                  :               return new SEIMultiviewSceneInfo;
   case SEI::MULTIVIEW_ACQUISITION_INFO            :               return new SEIMultiviewAcquisitionInfo;
@@ -249,5 +245,4 @@
   case SEI::ALTERNATIVE_DEPTH_INFO                :               return new SEIAlternativeDepthInfo;
 #endif
-#endif
   default:                                        assert( false ); return NULL;
   }
@@ -266,5 +261,5 @@
 }
 
-Void SEI::setupFromCfgFile( const Char* cfgFile )
+Void SEI::setupFromCfgFile( const TChar* cfgFile )
 {
   assert( false );
@@ -304,5 +299,5 @@
 }
 
-Void SEI::xCheckCfgRange( Bool& wrongConfig, Int val, Int minVal, Int maxVal, const Char* seName )
+Void SEI::xCheckCfgRange( Bool& wrongConfig, Int val, Int minVal, Int maxVal, const TChar* seName )
 {
   if ( val < minVal || val > maxVal  )
@@ -329,5 +324,5 @@
 }
 
-Void SEI::xCheckCfg( Bool& wrongConfig, Bool cond, const Char* errStr )
+Void SEI::xCheckCfg( Bool& wrongConfig, Bool cond, const TChar* errStr )
 {
   if ( !cond  )
@@ -339,7 +334,5 @@
 }
 
-
-#if NH_MV_LAYERS_NOT_PRESENT_SEI
-Void SEILayersNotPresent::setupFromCfgFile(const Char* cfgFile)
+Void SEILayersNotPresent::setupFromCfgFile(const TChar* cfgFile)
 {
   // Set default values
@@ -398,8 +391,8 @@
       return wrongConfig;
   };
-#endif
-
-
-Void SEIInterLayerConstrainedTileSets::setupFromCfgFile(const Char* cfgFile)
+
+
+
+Void SEIInterLayerConstrainedTileSets::setupFromCfgFile(const TChar* cfgFile)
 {
   // Set default values
@@ -483,5 +476,5 @@
 };
 
-Void SEIBspNesting::setupFromCfgFile(const Char* cfgFile)
+Void SEIBspNesting::setupFromCfgFile(const TChar* cfgFile)
 {
   // Set default values
@@ -556,5 +549,5 @@
 };
 
-Void SEIBspInitialArrivalTime::setupFromCfgFile(const Char* cfgFile)
+Void SEIBspInitialArrivalTime::setupFromCfgFile(const TChar* cfgFile)
 {
   // Set default values
@@ -605,5 +598,5 @@
 #endif
 
-Void SEISubBitstreamProperty::setupFromCfgFile(const Char* cfgFile)
+Void SEISubBitstreamProperty::setupFromCfgFile(const TChar* cfgFile)
 {
   // Set default values
@@ -681,5 +674,5 @@
 }
 
-Void SEIAlphaChannelInfo::setupFromCfgFile(const Char* cfgFile)
+Void SEIAlphaChannelInfo::setupFromCfgFile(const TChar* cfgFile)
 {
   // Set default values
@@ -744,5 +737,5 @@
 { };
 
-Void SEIOverlayInfo::setupFromCfgFile(const Char* cfgFile)
+Void SEIOverlayInfo::setupFromCfgFile(const TChar* cfgFile)
 {
   // Set default values
@@ -828,5 +821,5 @@
 
 
-Void SEITemporalMvPredictionConstraints::setupFromCfgFile(const Char* cfgFile)
+Void SEITemporalMvPredictionConstraints::setupFromCfgFile(const TChar* cfgFile)
 {
   // Set default values
@@ -870,5 +863,5 @@
 
 #if NH_MV_SEI_TBD
-Void SEIFrameFieldInfo::setupFromCfgFile(const Char* cfgFile)
+Void SEIFrameFieldInfo::setupFromCfgFile(const TChar* cfgFile)
 {
   // Set default values
@@ -922,5 +915,5 @@
 #endif
 
-Void SEIThreeDimensionalReferenceDisplaysInfo::setupFromCfgFile(const Char* cfgFile)
+Void SEIThreeDimensionalReferenceDisplaysInfo::setupFromCfgFile(const TChar* cfgFile)
 {
   // Set default values
@@ -1018,5 +1011,4 @@
 };
 
-#if SEI_DRI_F0169
 Void SEIDepthRepresentationInfo::setupFromSlice  ( const TComSlice* slice )
 {
@@ -1025,5 +1017,5 @@
 };
 
-Void SEIDepthRepresentationInfo::setupFromCfgFile(const Char* cfgFile)
+Void SEIDepthRepresentationInfo::setupFromCfgFile(const TChar* cfgFile)
 {
   // Set default values
@@ -1195,7 +1187,7 @@
     return wrongConfig;
 }
-#endif
-
-Void SEIMultiviewSceneInfo::setupFromCfgFile(const Char* cfgFile)
+
+
+Void SEIMultiviewSceneInfo::setupFromCfgFile(const TChar* cfgFile)
 {
   // Set default values
@@ -1243,5 +1235,5 @@
 };
 
-Void SEIMultiviewAcquisitionInfo::setupFromCfgFile(const Char* cfgFile)
+Void SEIMultiviewAcquisitionInfo::setupFromCfgFile(const TChar* cfgFile)
 {
   // Set default values
@@ -1405,5 +1397,5 @@
 }
 
-Void SEIMultiviewViewPosition::setupFromCfgFile(const Char* cfgFile)
+Void SEIMultiviewViewPosition::setupFromCfgFile(const TChar* cfgFile)
 {
   // Set default values
@@ -1456,5 +1448,5 @@
 
 #if NH_3D
-Void SEIAlternativeDepthInfo::setupFromCfgFile(const Char* cfgFile)
+Void SEIAlternativeDepthInfo::setupFromCfgFile(const TChar* cfgFile)
 {
   // Set default values
Index: trunk/source/Lib/TLibCommon/SEI.h
===================================================================
--- trunk/source/Lib/TLibCommon/SEI.h	(revision 1357)
+++ trunk/source/Lib/TLibCommon/SEI.h	(revision 1386)
@@ -44,5 +44,5 @@
 
 
-#if NH_MV_SEI
+#if NH_MV
 #include "TAppCommon/program_options_lite.h"
 using namespace std;
@@ -53,5 +53,5 @@
 //! \{
 class TComSPS;
-#if NH_MV_SEI
+#if NH_MV
 class TComSlice;
 class SEIScalableNesting;
@@ -94,8 +94,7 @@
     SEGM_RECT_FRAME_PACKING              = 138,
     TEMP_MOTION_CONSTRAINED_TILE_SETS    = 139,
-    CHROMA_SAMPLING_FILTER_HINT          = 140,
-    KNEE_FUNCTION_INFO                   = 141
-#if NH_MV_SEI
-    ,COLOUR_REMAPPING_INFO                    = 142,
+    CHROMA_RESAMPLING_FILTER_HINT        = 140,
+    KNEE_FUNCTION_INFO                   = 141,
+    COLOUR_REMAPPING_INFO                = 142,
     DEINTERLACED_FIELD_IDENTIFICATION         = 143,
     LAYERS_NOT_PRESENT                        = 160,
@@ -116,16 +115,22 @@
     ,ALTERNATIVE_DEPTH_INFO                    = 181
 #endif
+
+  };
+
+#if NH_MV
+  SEI();
+#else
+  SEI() {}
 #endif
 
-  };
-
-  SEI();
 
   virtual ~SEI() {}
+
+  static const TChar *getSEIMessageString(SEI::PayloadType payloadType);
+
+  virtual PayloadType payloadType() const = 0;
+
+#if NH_MV
   virtual SEI*       getCopy( ) const;
-  static const Char *getSEIMessageString(SEI::PayloadType payloadType );
-  virtual PayloadType payloadType() const = 0;
-
-#if NH_MV_SEI
   static SEI*        getNewSEIMessage         ( SEI::PayloadType payloadType );
   Bool               insertSei                ( Int curLayerId, Int curPoc, Int curTid, Int curNaluType ) const;
@@ -133,10 +138,10 @@
 
   virtual Void       setupFromSlice           ( const TComSlice* slice );
-  virtual Void       setupFromCfgFile         ( const Char* cfgFile );
+  virtual Void       setupFromCfgFile         ( const TChar*   cfgFile );
   virtual Bool       checkCfg                 ( const TComSlice* slice   );
 
   Void               xPrintCfgErrorIntro();
-  Void               xCheckCfgRange           ( Bool& wrongConfig, Int val, Int minVal, Int maxVal, const Char* seName );
-  Void               xCheckCfg                ( Bool& wrongConfig, Bool cond, const Char* errStr );
+  Void               xCheckCfgRange           ( Bool& wrongConfig, Int val, Int minVal, Int maxVal, const TChar* seName );
+  Void               xCheckCfg                ( Bool& wrongConfig, Bool cond, const TChar* errStr );
   Void               xAddGeneralOpts          ( po::Options &opts, IntAry1d defAppLayerIds, IntAry1d defAppPocs, IntAry1d defAppTids, IntAry1d defAppVclNaluTypes,
                                                 Int defSeiNaluId, Int defPositionInSeiNalu, Bool defModifyByEncoder );
@@ -186,11 +191,5 @@
   virtual ~SEIDecodedPictureHash() {}
 
-  enum Method
-  {
-    MD5,
-    CRC,
-    CHECKSUM,
-    RESERVED,
-  } method;
+  HashType method;
 
   TComPictureHash m_pictureHash;
@@ -482,41 +481,60 @@
 };
 
-class SEIChromaSamplingFilterHint : public SEI
-{
-public:
-  PayloadType payloadType() const {return CHROMA_SAMPLING_FILTER_HINT;}
-  SEIChromaSamplingFilterHint() {}
-  virtual ~SEIChromaSamplingFilterHint() {
-    if(m_verChromaFilterIdc == 1)
+class SEIColourRemappingInfo : public SEI
+{
+public:
+
+  struct CRIlut
+  {
+    Int codedValue;
+    Int targetValue;
+    bool operator < (const CRIlut& a) const
     {
-      for(Int i = 0; i < m_numVerticalFilters; i ++)
+      return codedValue < a.codedValue;
+    }
+  };
+
+  PayloadType payloadType() const { return COLOUR_REMAPPING_INFO; }
+  SEIColourRemappingInfo() {}
+  ~SEIColourRemappingInfo() {}
+
+  Void copyFrom( const SEIColourRemappingInfo &seiCriInput)
       {
-        free(m_verFilterCoeff[i]);
-      }
-      free(m_verFilterCoeff);
-      free(m_verTapLengthMinus1);
-    }
-    if(m_horChromaFilterIdc == 1)
-    {
-      for(Int i = 0; i < m_numHorizontalFilters; i ++)
-      {
-        free(m_horFilterCoeff[i]);
-      }
-      free(m_horFilterCoeff);
-      free(m_horTapLengthMinus1);
-    }
+    (*this) = seiCriInput;
   }
+
+  UInt                m_colourRemapId;
+  Bool                m_colourRemapCancelFlag;
+  Bool                m_colourRemapPersistenceFlag;
+  Bool                m_colourRemapVideoSignalInfoPresentFlag;
+  Bool                m_colourRemapFullRangeFlag;
+  Int                 m_colourRemapPrimaries;
+  Int                 m_colourRemapTransferFunction;
+  Int                 m_colourRemapMatrixCoefficients;
+  Int                 m_colourRemapInputBitDepth;
+  Int                 m_colourRemapBitDepth;
+  Int                 m_preLutNumValMinus1[3];
+  std::vector<CRIlut> m_preLut[3];
+  Bool                m_colourRemapMatrixPresentFlag;
+  Int                 m_log2MatrixDenom;
+  Int                 m_colourRemapCoeffs[3][3];
+  Int                 m_postLutNumValMinus1[3];
+  std::vector<CRIlut> m_postLut[3];
+};
+
+class SEIChromaResamplingFilterHint : public SEI
+{
+public:
+  PayloadType payloadType() const {return CHROMA_RESAMPLING_FILTER_HINT;}
+  SEIChromaResamplingFilterHint() {}
+  virtual ~SEIChromaResamplingFilterHint() {}
 
   Int   m_verChromaFilterIdc;
   Int   m_horChromaFilterIdc;
-  Bool  m_verFilteringProcessFlag;
+  Bool                           m_verFilteringFieldProcessingFlag;
   Int   m_targetFormatIdc;
   Bool  m_perfectReconstructionFlag;
-  Int   m_numVerticalFilters;
-  Int*  m_verTapLengthMinus1;
-  Int** m_verFilterCoeff;
-  Int   m_numHorizontalFilters;
-  Int*  m_horTapLengthMinus1;
-  Int** m_horFilterCoeff;
+  std::vector<std::vector<Int> > m_verFilterCoeff;
+  std::vector<std::vector<Int> > m_horFilterCoeff;
 };
 
@@ -530,25 +548,4 @@
     TComSEIMasteringDisplay values;
 };
-
-#if NH_MV
-#if !NH_MV_SEI
-class SEISubBitstreamProperty : public SEI
-{
-public:
-  PayloadType payloadType() const { return SUB_BITSTREAM_PROPERTY; }
-
-  SEISubBitstreamProperty():   m_activeVpsId(-1), m_numAdditionalSubStreams(0) {}
-  virtual ~SEISubBitstreamProperty() {}
-
-  Int  m_activeVpsId;
-  Int  m_numAdditionalSubStreams;
-  std::vector<Int>  m_subBitstreamMode;
-  std::vector<Int>  m_outputLayerSetIdxToVps;
-  std::vector<Int>  m_highestSublayerId;
-  std::vector<Int>  m_avgBitRate;
-  std::vector<Int>  m_maxBitRate;
-};
-#endif
-#endif
 
 typedef std::list<SEI*> SEIMessages;
@@ -658,7 +655,5 @@
 
 };
-
-#if NH_MV_SEI
-#if NH_MV_LAYERS_NOT_PRESENT_SEI
+#if NH_MV
 class SEILayersNotPresent : public SEI
 {
@@ -669,5 +664,5 @@
   SEI* getCopy( ) const { return new SEILayersNotPresent(*this); };
 
-  Void setupFromCfgFile( const Char*      cfgFile );
+  Void setupFromCfgFile( const TChar*     cfgFile );
   Bool checkCfg        ( const TComSlice* slice   );
 
@@ -681,5 +676,4 @@
   }
 };
-#endif
 
 class SEIInterLayerConstrainedTileSets : public SEI
@@ -691,5 +685,5 @@
   SEI* getCopy( ) const { return new SEIInterLayerConstrainedTileSets(*this); };
 
-  Void setupFromCfgFile( const Char*      cfgFile );
+  Void setupFromCfgFile( const TChar*     cfgFile );
   Bool checkCfg        ( const TComSlice* slice   );
 
@@ -733,5 +727,5 @@
   SEI* getCopy( ) const { return new SEIBspNesting(*this); };
 
-  Void setupFromCfgFile( const Char*      cfgFile );
+  Void setupFromCfgFile( const TChar*      cfgFile );
   Void setupFromSlice  ( const TComSlice* slice   );
   Bool checkCfg        ( const TComSlice* slice   );
@@ -752,5 +746,5 @@
   SEI* getCopy( ) const { return new SEIBspInitialArrivalTime(*this); };
 
-  Void setupFromCfgFile( const Char*      cfgFile );
+  Void setupFromCfgFile( const TChar*      cfgFile );
   Void setupFromSlice  ( const TComSlice* slice   );
   Bool checkCfg        ( const TComSlice* slice   );
@@ -769,5 +763,5 @@
   SEI* getCopy( ) const { return new SEISubBitstreamProperty(*this); };
 
-  Void setupFromCfgFile( const Char*      cfgFile );
+  Void setupFromCfgFile( const TChar*     cfgFile );
   Bool checkCfg        ( const TComSlice* slice   );
   Void resizeArrays    ( );
@@ -790,5 +784,5 @@
   SEI* getCopy( ) const { return new SEIAlphaChannelInfo(*this); };
 
-  Void setupFromCfgFile( const Char*      cfgFile );
+  Void setupFromCfgFile( const TChar*     cfgFile );
   Bool checkCfg        ( const TComSlice* slice   );
 
@@ -811,5 +805,5 @@
   SEI* getCopy( ) const { return new SEIOverlayInfo(*this); };
 
-  Void setupFromCfgFile( const Char*      cfgFile );
+  Void setupFromCfgFile( const TChar*     cfgFile );
   Bool checkCfg        ( const TComSlice* slice   );
 
@@ -848,5 +842,5 @@
   SEI* getCopy( ) const { return new SEITemporalMvPredictionConstraints(*this); };
 
-  Void setupFromCfgFile( const Char*      cfgFile );
+  Void setupFromCfgFile( const TChar*     cfgFile );
   Bool checkCfg        ( const TComSlice* slice   );
 
@@ -864,5 +858,5 @@
   SEI* getCopy( ) const { return new SEIFrameFieldInfo(*this); };
 
-  Void setupFromCfgFile( const Char*      cfgFile );
+  Void setupFromCfgFile( const TChar*     cfgFile );
   Void setupFromSlice  ( const TComSlice* slice   );
   Bool checkCfg        ( const TComSlice* slice   );
@@ -882,5 +876,5 @@
   SEI* getCopy( ) const { return new SEIThreeDimensionalReferenceDisplaysInfo(*this); };
 
-  Void setupFromCfgFile( const Char*      cfgFile );
+  Void setupFromCfgFile( const TChar*     cfgFile );
   Bool checkCfg        ( const TComSlice* slice   );
 
@@ -924,5 +918,4 @@
 };
 
-#if SEI_DRI_F0169
 class SEIDepthRepresentationInfo : public SEI
 {
@@ -936,5 +929,5 @@
         SEI* getCopy( ) const { return new SEIDepthRepresentationInfo(*this); };
 
-        Void setupFromCfgFile( const Char*      cfgFile );
+        Void setupFromCfgFile( const TChar*     cfgFile );
         Void setupFromSlice  ( const TComSlice* slice   );
         Bool checkCfg        ( const TComSlice* slice   );
@@ -993,5 +986,5 @@
         IntAry2d       m_depth_nonlinear_representation_model;
 };
-#endif
+
 
 class SEIMultiviewSceneInfo : public SEI
@@ -1003,5 +996,5 @@
   SEI* getCopy( ) const { return new SEIMultiviewSceneInfo(*this); };
 
-  Void setupFromCfgFile( const Char*      cfgFile );
+  Void setupFromCfgFile( const TChar*     cfgFile );
   Bool checkCfg        ( const TComSlice* slice   );
 
@@ -1019,5 +1012,5 @@
   SEI* getCopy( ) const { return new SEIMultiviewAcquisitionInfo(*this); };
 
-  Void setupFromCfgFile( const Char*      cfgFile );
+  Void setupFromCfgFile( const TChar*     cfgFile );
   Bool checkCfg        ( const TComSlice* slice   );
 
@@ -1131,5 +1124,5 @@
   SEI* getCopy( ) const { return new SEIMultiviewViewPosition(*this); };
 
-  Void setupFromCfgFile( const Char*      cfgFile );
+  Void setupFromCfgFile( const TChar*     cfgFile );
   Void setupFromSlice  ( const TComSlice* slice   );
   Bool checkCfg        ( const TComSlice* slice   );
@@ -1148,5 +1141,5 @@
   SEI* getCopy( ) const { return new SEIAlternativeDepthInfo(*this); };
 
-  Void setupFromCfgFile( const Char*      cfgFile );
+  Void setupFromCfgFile( const TChar*     cfgFile );
   Bool checkCfg        ( const TComSlice* slice   );
 
@@ -1357,5 +1350,5 @@
 #endif
 #endif
-
 #endif
+
 //! \}
Index: trunk/source/Lib/TLibCommon/TComBitStream.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComBitStream.cpp	(revision 1357)
+++ trunk/source/Lib/TLibCommon/TComBitStream.cpp	(revision 1386)
@@ -93,7 +93,7 @@
 }
 
-Char* TComOutputBitstream::getByteStream() const
-{
-  return (Char*) &m_fifo.front();
+UChar* TComOutputBitstream::getByteStream() const
+{
+  return (UChar*) &m_fifo.front();
 }
 
@@ -260,5 +260,5 @@
   m_numBitsRead += uiNumberOfBits;
 
-#if ENC_DEC_TRACE && H_MV_ENC_DEC_TRAC
+#if ENC_DEC_TRACE && NH_MV_ENC_DEC_TRAC
   if ( g_traceBitsRead )
   {
Index: trunk/source/Lib/TLibCommon/TComBitStream.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComBitStream.h	(revision 1357)
+++ trunk/source/Lib/TLibCommon/TComBitStream.h	(revision 1386)
@@ -115,5 +115,5 @@
    * bytestream are stored in ascending addresses.
    */
-  Char* getByteStream() const;
+  UChar* getByteStream() const;
 
   /**
Index: trunk/source/Lib/TLibCommon/TComCodingStatistics.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComCodingStatistics.h	(revision 1357)
+++ trunk/source/Lib/TLibCommon/TComCodingStatistics.h	(revision 1386)
@@ -120,7 +120,7 @@
 };
 
-static inline const Char* getName(TComCodingStatisticsType name)
+static inline const TChar* getName(TComCodingStatisticsType name)
 {
-  static const Char *statNames[]=
+  static const TChar *statNames[]=
   {
     "NAL_UNIT_TOTAL_BODY", // This is a special case and is not included in the total sums.
@@ -189,5 +189,5 @@
 #endif
   };
-  assert(STATS__NUM_STATS == sizeof(statNames)/sizeof(Char *) && name < STATS__NUM_STATS);
+  assert(STATS__NUM_STATS == sizeof(statNames)/sizeof(TChar *) && name < STATS__NUM_STATS);
   return statNames[name];
 }
@@ -229,8 +229,8 @@
   }
 
-  static const Char *GetSubClassString(const UInt subClass)
+  static const TChar *GetSubClassString(const UInt subClass)
   {
     assert (subClass<CODING_STATS_NUM_SUBCLASSES);
-    static const Char *strings[1+MAX_NUM_COMPONENT+MAX_NUM_CHANNEL_TYPE]={"-", "Y", "Cb", "Cr", "Luma", "Chroma"};
+    static const TChar *strings[1+MAX_NUM_COMPONENT+MAX_NUM_CHANNEL_TYPE]={"-", "Y", "Cb", "Cr", "Luma", "Chroma"};
     return strings[subClass/CODING_STATS_NUM_WIDTHS];
   }
@@ -289,5 +289,5 @@
     { }
 
-    static Void OutputLine(const Char *pName, const Char sep, UInt width, const Char *pSubClassStr, const SStat &sCABAC, const SStat &sEP)
+    static Void OutputLine(const TChar *pName, const TChar sep, UInt width, const TChar *pSubClassStr, const SStat &sCABAC, const SStat &sEP)
     {
       if (width==0)
@@ -302,5 +302,5 @@
       }
     }
-    static Void OutputLine(const Char *pName, const Char sep, const Char *pWidthString, const Char *pSubClassStr, const SStat &sCABAC, const SStat &sEP)
+    static Void OutputLine(const TChar *pName, const TChar sep, const TChar *pWidthString, const TChar *pSubClassStr, const SStat &sCABAC, const SStat &sEP)
     {
       printf("%c%-45s%c  %6s %6s %12lld %12lld %12lld %12lld %12lld %12lld %12lld (%12lld)%c\n",
@@ -308,5 +308,5 @@
               sCABAC.count, sCABAC.sum, sCABAC.bits, sEP.count, sEP.sum, sEP.bits, sCABAC.bits+sEP.bits, (sCABAC.bits+sEP.bits)/8, sep=='~'?']':' ');
     }
-    static Void OutputLine(const Char *pName, const Char sep, const Char *pWidthString, const Char *pSubClassStr,  const SStat &sEP)
+    static Void OutputLine(const TChar *pName, const TChar sep, const TChar *pWidthString, const TChar *pSubClassStr,  const SStat &sEP)
     {
       printf("%c%-45s%c  %6s %6s %12s %12s %12s %12lld %12lld %12lld %12lld (%12lld)%c\n",
@@ -315,5 +315,5 @@
     }
 
-    static Void OutputDashedLine(const Char *pText)
+    static Void OutputDashedLine(const TChar *pText)
     {
       printf("--%s",pText);
@@ -360,5 +360,5 @@
         SStat cabacSubTotal, epSubTotal;
         Bool bHadClassifiedEntry=false;
-        const Char *pName=getName(TComCodingStatisticsType(i));
+        const TChar *pName=getName(TComCodingStatisticsType(i));
 
         for(UInt c=0; c<CODING_STATS_NUM_SUBCLASSES; c++)
@@ -488,5 +488,5 @@
     static SStat &GetStatisticEP(const std::string &str) { return GetSingletonInstance().data.mappings_ep[str]; }
 
-    static SStat &GetStatisticEP(const Char *pKey) {return GetStatisticEP(std::string(pKey)); }
+    static SStat &GetStatisticEP(const TChar *pKey) {return GetStatisticEP(std::string(pKey)); }
 
     static Void IncrementStatisticEP(const TComCodingStatisticsClassType &stat, const Int numBits, const Int value)
@@ -506,5 +506,5 @@
     }
 
-    static Void IncrementStatisticEP(const Char *pKey, const Int numBits, const Int value)
+    static Void IncrementStatisticEP(const TChar *pKey, const Int numBits, const Int value)
     {
       SStat &s=GetStatisticEP(pKey);
Index: trunk/source/Lib/TLibCommon/TComDataCU.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComDataCU.cpp	(revision 1357)
+++ trunk/source/Lib/TLibCommon/TComDataCU.cpp	(revision 1386)
@@ -160,5 +160,5 @@
   if ( !bDecSubCu )
   {
-    m_phQP               = (Char*     )xMalloc(Char,     uiNumPartition);
+    m_phQP               = (SChar*    )xMalloc(SChar,    uiNumPartition);
     m_puhDepth           = (UChar*    )xMalloc(UChar,    uiNumPartition);
     m_puhWidth           = (UChar*    )xMalloc(UChar,    uiNumPartition);
@@ -171,7 +171,7 @@
     m_ucDISType          = (UChar*)xMalloc(UChar, uiNumPartition);
 #endif
-    m_pePartSize         = new Char[ uiNumPartition ];
+    m_pePartSize         = new SChar[ uiNumPartition ];
     memset( m_pePartSize, NUMBER_OF_PART_SIZES,uiNumPartition * sizeof( *m_pePartSize ) );
-    m_pePredMode         = new Char[ uiNumPartition ];
+    m_pePredMode         = new SChar[ uiNumPartition ];
     m_CUTransquantBypass = new Bool[ uiNumPartition ];
 
@@ -179,5 +179,5 @@
     m_puhMergeIndex      = (UChar* )xMalloc(UChar,  uiNumPartition);
 #if NH_3D_VSP
-    m_piVSPFlag          = (Char*  )xMalloc(Char,   uiNumPartition);
+    m_piVSPFlag          = (SChar* )xMalloc(SChar, uiNumPartition);
 #endif
 #if NH_3D_SPIVMP
@@ -196,7 +196,7 @@
     {
       const RefPicList rpl=RefPicList(i);
-      m_apiMVPIdx[rpl]       = new Char[ uiNumPartition ];
-      m_apiMVPNum[rpl]       = new Char[ uiNumPartition ];
-      memset( m_apiMVPIdx[rpl], -1,uiNumPartition * sizeof( Char ) );
+      m_apiMVPIdx[rpl]       = new SChar[ uiNumPartition ];
+      m_apiMVPNum[rpl]       = new SChar[ uiNumPartition ];
+      memset( m_apiMVPIdx[rpl], -1,uiNumPartition * sizeof( SChar ) );
     }
 
@@ -212,5 +212,5 @@
       const UInt totalSize   = (uiWidth * uiHeight) >> chromaShift;
 
-      m_crossComponentPredictionAlpha[compID] = (Char*  )xMalloc(Char,   uiNumPartition);
+      m_crossComponentPredictionAlpha[compID] = (SChar* )xMalloc(SChar,  uiNumPartition);
       m_puhTransformSkip[compID]              = (UChar* )xMalloc(UChar,  uiNumPartition);
       m_explicitRdpcmMode[compID]             = (UChar* )xMalloc(UChar,  uiNumPartition);
@@ -524,5 +524,5 @@
 }
 
-Bool TComDataCU::isLastSubCUOfCtu(const UInt absPartIdx)
+Bool TComDataCU::isLastSubCUOfCtu(const UInt absPartIdx) const
 {
   const TComSPS &sps=*(getSlice()->getSPS());
@@ -844,5 +844,5 @@
   Int iSizeInUchar = sizeof( UChar  ) * m_uiNumPartition;
   Int iSizeInBool  = sizeof( Bool   ) * m_uiNumPartition;
-  Int sizeInChar = sizeof( Char  ) * m_uiNumPartition;
+  Int sizeInChar = sizeof( SChar  ) * m_uiNumPartition;
 
   memset( m_phQP,              qp,  sizeInChar );
@@ -850,5 +850,5 @@
   memset( m_puhMergeIndex,      0, iSizeInUchar );
 #if NH_3D_VSP
-  memset( m_piVSPFlag,          0, sizeof( Char  ) * m_uiNumPartition );
+  memset( m_piVSPFlag,          0, sizeof( SChar ) * m_uiNumPartition );
 #endif
 #if NH_3D_SPIVMP
@@ -1121,9 +1121,9 @@
 
 // Copy inter prediction info from the biggest CU
-Void TComDataCU::copyInterPredInfoFrom    ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefPicList 
 #if NH_3D_NBDV
-  , Bool bNBDV
-#endif
-)
+Void TComDataCU::copyInterPredInfoFrom    ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefPicList   , Bool bNBDV )
+#else
+Void TComDataCU::copyInterPredInfoFrom    ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefPicList )
+#endif
 {
   m_pcPic              = pcCU->getPic();
@@ -1219,5 +1219,5 @@
   Int iSizeInBool   = sizeof( Bool  ) * uiNumPartition;
 
-  Int sizeInChar  = sizeof( Char ) * uiNumPartition;
+  Int sizeInChar  = sizeof( SChar ) * uiNumPartition;
   memcpy( m_skipFlag   + uiOffset, pcCU->getSkipFlag(),       sizeof( *m_skipFlag )   * uiNumPartition );
 #if NH_3D_DIS
@@ -1233,5 +1233,5 @@
   memcpy( m_puhMergeIndex       + uiOffset, pcCU->getMergeIndex(),        iSizeInUchar );
 #if NH_3D_VSP
-  memcpy( m_piVSPFlag           + uiOffset, pcCU->getVSPFlag(),           sizeof( Char ) * uiNumPartition );
+  memcpy( m_piVSPFlag           + uiOffset, pcCU->getVSPFlag(),           sizeof( SChar ) * uiNumPartition );
   memcpy( m_pDvInfo             + uiOffset, pcCU->getDvInfo(),            sizeof( *m_pDvInfo ) * uiNumPartition );
 #endif
@@ -1335,5 +1335,5 @@
   Int iSizeInUchar  = sizeof( UChar ) * m_uiNumPartition;
   Int iSizeInBool   = sizeof( Bool  ) * m_uiNumPartition;
-  Int sizeInChar  = sizeof( Char ) * m_uiNumPartition;
+  Int sizeInChar  = sizeof( SChar ) * m_uiNumPartition;
 
   memcpy( pCtu->getSkipFlag() + m_absZIdxInCtu, m_skipFlag, sizeof( *m_skipFlag ) * m_uiNumPartition );
@@ -1355,5 +1355,5 @@
   memcpy( pCtu->getMergeIndex()        + m_absZIdxInCtu, m_puhMergeIndex,       iSizeInUchar );
 #if NH_3D_VSP
-  memcpy( pCtu->getVSPFlag()           + m_absZIdxInCtu, m_piVSPFlag,           sizeof( Char ) * m_uiNumPartition );
+  memcpy( pCtu->getVSPFlag()           + m_absZIdxInCtu, m_piVSPFlag,           sizeof( SChar ) * m_uiNumPartition );
 #endif
 #if NH_3D_DBBP
@@ -1447,8 +1447,8 @@
 // --------------------------------------------------------------------------------------------------------------------
 
-TComDataCU* TComDataCU::getPULeft( UInt& uiLPartUnitIdx,
+const TComDataCU* TComDataCU::getPULeft( UInt& uiLPartUnitIdx,
                                    UInt uiCurrPartUnitIdx,
                                    Bool bEnforceSliceRestriction,
-                                   Bool bEnforceTileRestriction )
+                                         Bool bEnforceTileRestriction ) const
 {
   UInt uiAbsPartIdx       = g_auiZscanToRaster[uiCurrPartUnitIdx];
@@ -1479,9 +1479,9 @@
 
 
-TComDataCU* TComDataCU::getPUAbove( UInt& uiAPartUnitIdx,
+const TComDataCU* TComDataCU::getPUAbove( UInt& uiAPartUnitIdx,
                                     UInt uiCurrPartUnitIdx,
                                     Bool bEnforceSliceRestriction,
                                     Bool planarAtCtuBoundary,
-                                    Bool bEnforceTileRestriction )
+                                          Bool bEnforceTileRestriction ) const
 {
   UInt uiAbsPartIdx       = g_auiZscanToRaster[uiCurrPartUnitIdx];
@@ -1517,5 +1517,5 @@
 }
 
-TComDataCU* TComDataCU::getPUAboveLeft( UInt& uiALPartUnitIdx, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction )
+const TComDataCU* TComDataCU::getPUAboveLeft( UInt& uiALPartUnitIdx, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction ) const
 {
   UInt uiAbsPartIdx       = g_auiZscanToRaster[uiCurrPartUnitIdx];
@@ -1564,5 +1564,5 @@
 }
 
-TComDataCU* TComDataCU::getPUBelowLeft(UInt& uiBLPartUnitIdx,  UInt uiCurrPartUnitIdx, UInt uiPartUnitOffset, Bool bEnforceSliceRestriction)
+const TComDataCU* TComDataCU::getPUBelowLeft(UInt& uiBLPartUnitIdx,  UInt uiCurrPartUnitIdx, UInt uiPartUnitOffset, Bool bEnforceSliceRestriction) const
 {
   UInt uiAbsPartIdxLB     = g_auiZscanToRaster[uiCurrPartUnitIdx];
@@ -1608,5 +1608,5 @@
 }
 
-TComDataCU* TComDataCU::getPUAboveRight(UInt&  uiARPartUnitIdx, UInt uiCurrPartUnitIdx, UInt uiPartUnitOffset, Bool bEnforceSliceRestriction)
+const TComDataCU* TComDataCU::getPUAboveRight(UInt&  uiARPartUnitIdx, UInt uiCurrPartUnitIdx, UInt uiPartUnitOffset, Bool bEnforceSliceRestriction) const
 {
   UInt uiAbsPartIdxRT     = g_auiZscanToRaster[uiCurrPartUnitIdx];
@@ -1668,5 +1668,5 @@
 *\returns TComDataCU*   point of TComDataCU of left QpMinCu
 */
-TComDataCU* TComDataCU::getQpMinCuLeft( UInt& uiLPartUnitIdx, UInt uiCurrAbsIdxInCtu )
+const TComDataCU* TComDataCU::getQpMinCuLeft( UInt& uiLPartUnitIdx, UInt uiCurrAbsIdxInCtu ) const
 {
   const UInt numPartInCtuWidth = m_pcPic->getNumPartInCtuWidth();
@@ -1695,5 +1695,5 @@
 *\returns TComDataCU*   point of TComDataCU of above QpMinCu
 */
-TComDataCU* TComDataCU::getQpMinCuAbove( UInt& uiAPartUnitIdx, UInt uiCurrAbsIdxInCtu )
+const TComDataCU* TComDataCU::getQpMinCuAbove( UInt& uiAPartUnitIdx, UInt uiCurrAbsIdxInCtu ) const
 {
   const UInt numPartInCtuWidth = m_pcPic->getNumPartInCtuWidth();
@@ -1721,16 +1721,16 @@
 /** Get reference QP from left QpMinCu or latest coded QP
 *\param   uiCurrAbsIdxInCtu
-*\returns Char   reference QP value
+*\returns SChar   reference QP value
 */
-Char TComDataCU::getRefQP( UInt uiCurrAbsIdxInCtu )
+SChar TComDataCU::getRefQP( UInt uiCurrAbsIdxInCtu ) const
 {
   UInt lPartIdx = MAX_UINT;
   UInt aPartIdx = MAX_UINT;
-  TComDataCU* cULeft  = getQpMinCuLeft ( lPartIdx, m_absZIdxInCtu + uiCurrAbsIdxInCtu );
-  TComDataCU* cUAbove = getQpMinCuAbove( aPartIdx, m_absZIdxInCtu + uiCurrAbsIdxInCtu );
+  const TComDataCU* cULeft  = getQpMinCuLeft ( lPartIdx, m_absZIdxInCtu + uiCurrAbsIdxInCtu );
+  const TComDataCU* cUAbove = getQpMinCuAbove( aPartIdx, m_absZIdxInCtu + uiCurrAbsIdxInCtu );
   return (((cULeft? cULeft->getQP( lPartIdx ): getLastCodedQP( uiCurrAbsIdxInCtu )) + (cUAbove? cUAbove->getQP( aPartIdx ): getLastCodedQP( uiCurrAbsIdxInCtu )) + 1) >> 1);
 }
 
-Int TComDataCU::getLastValidPartIdx( Int iAbsPartIdx )
+Int TComDataCU::getLastValidPartIdx( Int iAbsPartIdx ) const
 {
   Int iLastValidPartIdx = iAbsPartIdx-1;
@@ -1744,5 +1744,5 @@
 }
 
-Char TComDataCU::getLastCodedQP( UInt uiAbsPartIdx )
+SChar TComDataCU::getLastCodedQP( UInt uiAbsPartIdx ) const
 {
   UInt uiQUPartIdxMask = ~((1<<((getSlice()->getSPS()->getMaxTotalCUDepth() - getSlice()->getPPS()->getMaxCuDQPDepth())<<1))-1);
@@ -1784,5 +1784,5 @@
  * \returns true if the CU is coded in lossless coding mode; false if otherwise
  */
-Bool TComDataCU::isLosslessCoded(UInt absPartIdx)
+Bool TComDataCU::isLosslessCoded(UInt absPartIdx) const
 {
   return (getSlice()->getPPS()->getTransquantBypassEnableFlag() && getCUTransquantBypass (absPartIdx));
@@ -1796,5 +1796,5 @@
 *\param   [out] uiModeList pointer to chroma intra modes array
 */
-Void TComDataCU::getAllowedChromaDir( UInt uiAbsPartIdx, UInt uiModeList[NUM_CHROMA_MODE] )
+Void TComDataCU::getAllowedChromaDir( UInt uiAbsPartIdx, UInt uiModeList[NUM_CHROMA_MODE] ) const
 {
   uiModeList[0] = PLANAR_IDX;
@@ -1824,7 +1824,6 @@
 *\returns Number of MPM
 */
-Void TComDataCU::getIntraDirPredictor( UInt uiAbsPartIdx, Int uiIntraDirPred[NUM_MOST_PROBABLE_MODES], const ComponentID compID, Int* piMode  )
-{
-  TComDataCU* pcCULeft, *pcCUAbove;
+Void TComDataCU::getIntraDirPredictor( UInt uiAbsPartIdx, Int uiIntraDirPred[NUM_MOST_PROBABLE_MODES], const ComponentID compID, Int* piMode ) const
+{
   UInt        LeftPartIdx  = MAX_UINT;
   UInt        AbovePartIdx = MAX_UINT;
@@ -1836,5 +1835,5 @@
   const ChromaFormat chForm = getPic()->getChromaFormat();
   // Get intra direction of left PU
-  pcCULeft = getPULeft( LeftPartIdx, m_absZIdxInCtu + uiAbsPartIdx );
+  const TComDataCU *pcCULeft = getPULeft( LeftPartIdx, m_absZIdxInCtu + uiAbsPartIdx );
 
   if (isChroma(compID))
@@ -1848,5 +1847,5 @@
 
   // Get intra direction of above PU
-  pcCUAbove = getPUAbove( AbovePartIdx, m_absZIdxInCtu + uiAbsPartIdx, true, true );
+  const TComDataCU *pcCUAbove = getPUAbove( AbovePartIdx, m_absZIdxInCtu + uiAbsPartIdx, true, true );
 
   if (isChroma(compID))
@@ -1917,7 +1916,7 @@
 }
 
-UInt TComDataCU::getCtxSplitFlag( UInt uiAbsPartIdx, UInt uiDepth )
-{
-  TComDataCU* pcTempCU;
+UInt TComDataCU::getCtxSplitFlag( UInt uiAbsPartIdx, UInt uiDepth ) const
+{
+  const TComDataCU* pcTempCU;
   UInt        uiTempPartIdx;
   UInt        uiCtx;
@@ -1933,5 +1932,5 @@
 }
 
-UInt TComDataCU::getCtxQtCbf( TComTU &rTu, const ChannelType chType )
+UInt TComDataCU::getCtxQtCbf( TComTU &rTu, const ChannelType chType ) const
 {
   const UInt transformDepth = rTu.GetTransformDepthRel();
@@ -1948,5 +1947,5 @@
 }
 
-UInt TComDataCU::getQuadtreeTULog2MinSizeInCU( UInt absPartIdx )
+UInt TComDataCU::getQuadtreeTULog2MinSizeInCU( UInt absPartIdx ) const
 {
   UInt log2CbSize = g_aucConvertToBit[getWidth( absPartIdx )] + 2;
@@ -1975,7 +1974,7 @@
 }
 
-UInt TComDataCU::getCtxSkipFlag( UInt uiAbsPartIdx )
-{
-  TComDataCU* pcTempCU;
+UInt TComDataCU::getCtxSkipFlag( UInt uiAbsPartIdx ) const
+{
+  const TComDataCU* pcTempCU;
   UInt        uiTempPartIdx;
   UInt        uiCtx = 0;
@@ -1994,11 +1993,11 @@
 UInt TComDataCU::getCTXARPWFlag( UInt uiAbsPartIdx )
 {
-  TComDataCU* pcTempCU;
+  const TComDataCU* pcTempCU;
   UInt        uiTempPartIdx;
   UInt        uiCtx = 0;
-  
+
   pcTempCU = getPULeft( uiTempPartIdx, m_absZIdxInCtu + uiAbsPartIdx );
   uiCtx    = ( pcTempCU ) ? ((pcTempCU->getARPW( uiTempPartIdx )==0)?0:1) : 0;
-    return uiCtx;
+  return uiCtx;
 }
 #endif
@@ -2086,5 +2085,5 @@
 
 
-UInt TComDataCU::getCtxInterDir( UInt uiAbsPartIdx )
+UInt TComDataCU::getCtxInterDir( UInt uiAbsPartIdx ) const
 {
   return getDepth( uiAbsPartIdx );
@@ -2092,5 +2091,5 @@
 
 
-UChar TComDataCU::getQtRootCbf( UInt uiIdx )
+UChar TComDataCU::getQtRootCbf( UInt uiIdx ) const
 {
   const UInt numberValidComponents = getPic()->getNumberValidComponents();
@@ -2148,5 +2147,5 @@
 }
 
-Bool TComDataCU::isFirstAbsZorderIdxInDepth (UInt uiAbsPartIdx, UInt uiDepth)
+Bool TComDataCU::isFirstAbsZorderIdxInDepth (UInt uiAbsPartIdx, UInt uiDepth) const
 {
   UInt uiPartNumb = m_pcPic->getNumPartitionsInCtu() >> (uiDepth << 1);
@@ -2376,7 +2375,7 @@
 
 #if NH_3D_VSP
-Void TComDataCU::setVSPFlagSubParts( Char iVSPFlag, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
-{
-  setSubPart<Char>( iVSPFlag, m_piVSPFlag, uiAbsPartIdx, uiDepth, uiPartIdx );
+Void TComDataCU::setVSPFlagSubParts( SChar iVSPFlag, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+  setSubPart<SChar>( iVSPFlag, m_piVSPFlag, uiAbsPartIdx, uiDepth, uiPartIdx );
 }
 template<typename T>
@@ -2523,10 +2522,10 @@
 Void TComDataCU::setMVPIdxSubParts( Int iMVPIdx, RefPicList eRefPicList, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
 {
-  setSubPart<Char>( iMVPIdx, m_apiMVPIdx[eRefPicList], uiAbsPartIdx, uiDepth, uiPartIdx );
+  setSubPart<SChar>( iMVPIdx, m_apiMVPIdx[eRefPicList], uiAbsPartIdx, uiDepth, uiPartIdx );
 }
 
 Void TComDataCU::setMVPNumSubParts( Int iMVPNum, RefPicList eRefPicList, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
 {
-  setSubPart<Char>( iMVPNum, m_apiMVPNum[eRefPicList], uiAbsPartIdx, uiDepth, uiPartIdx );
+  setSubPart<SChar>( iMVPNum, m_apiMVPNum[eRefPicList], uiAbsPartIdx, uiDepth, uiPartIdx );
 }
 
@@ -2561,7 +2560,7 @@
 }
 
-Void TComDataCU::setCrossComponentPredictionAlphaPartRange( Char alphaValue, ComponentID compID, UInt uiAbsPartIdx, UInt uiCoveredPartIdxes )
-{
-  memset((m_crossComponentPredictionAlpha[compID] + uiAbsPartIdx), alphaValue, (sizeof(Char) * uiCoveredPartIdxes));
+Void TComDataCU::setCrossComponentPredictionAlphaPartRange( SChar alphaValue, ComponentID compID, UInt uiAbsPartIdx, UInt uiCoveredPartIdxes )
+{
+  memset((m_crossComponentPredictionAlpha[compID] + uiAbsPartIdx), alphaValue, (sizeof(SChar) * uiCoveredPartIdxes));
 }
 
@@ -2579,5 +2578,5 @@
 }
 
-UChar TComDataCU::getNumPartitions(const UInt uiAbsPartIdx)
+UChar TComDataCU::getNumPartitions(const UInt uiAbsPartIdx) const
 {
   UChar iNumPart = 0;
@@ -2601,5 +2600,5 @@
 // This is for use by a leaf/sub CU object only, with no additional AbsPartIdx
 #if NH_3D_IC || NH_3D_VSP
-Void TComDataCU::getPartIndexAndSize( UInt uiPartIdx, UInt& ruiPartAddr, Int& riWidth, Int& riHeight, UInt uiAbsPartIdx, Bool bLCU)
+Void TComDataCU::getPartIndexAndSize( UInt uiPartIdx, UInt& ruiPartAddr, Int& riWidth, Int& riHeight, UInt uiAbsPartIdx, Bool bLCU) const
 {
   UInt uiNumPartition  = bLCU ? (getWidth(uiAbsPartIdx)*getHeight(uiAbsPartIdx) >> 4) : m_uiNumPartition;
@@ -2645,5 +2644,5 @@
 #else
 
-Void TComDataCU::getPartIndexAndSize( UInt uiPartIdx, UInt& ruiPartAddr, Int& riWidth, Int& riHeight )
+Void TComDataCU::getPartIndexAndSize( UInt uiPartIdx, UInt& ruiPartAddr, Int& riWidth, Int& riHeight )  const
 {
   switch ( m_pePartSize[0] )
@@ -2686,6 +2685,6 @@
 #endif
 
-
-Void TComDataCU::getMvField ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefPicList, TComMvField& rcMvField )
+// static member function
+Void TComDataCU::getMvField ( const TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefPicList, TComMvField& rcMvField )
 {
   if ( pcCU == NULL )  // OUT OF BOUNDARY
@@ -2696,9 +2695,9 @@
   }
 
-  TComCUMvField*  pcCUMvField = pcCU->getCUMvField( eRefPicList );
+  const TComCUMvField*  pcCUMvField = pcCU->getCUMvField( eRefPicList );
   rcMvField.setMvField( pcCUMvField->getMv( uiAbsPartIdx ), pcCUMvField->getRefIdx( uiAbsPartIdx ) );
 }
 
-Void TComDataCU::deriveLeftRightTopIdxGeneral ( UInt uiAbsPartIdx, UInt uiPartIdx, UInt& ruiPartIdxLT, UInt& ruiPartIdxRT )
+Void TComDataCU::deriveLeftRightTopIdxGeneral ( UInt uiAbsPartIdx, UInt uiPartIdx, UInt& ruiPartIdxLT, UInt& ruiPartIdxRT ) const
 {
   ruiPartIdxLT = m_absZIdxInCtu + uiAbsPartIdx;
@@ -2749,5 +2748,5 @@
 }
 
-Void TComDataCU::deriveLeftBottomIdxGeneral( UInt uiAbsPartIdx, UInt uiPartIdx, UInt& ruiPartIdxLB )
+Void TComDataCU::deriveLeftBottomIdxGeneral( UInt uiAbsPartIdx, UInt uiPartIdx, UInt& ruiPartIdxLB ) const
 {
   UInt uiPUHeight = 0;
@@ -2796,5 +2795,5 @@
 }
 
-Void TComDataCU::deriveLeftRightTopIdx ( UInt uiPartIdx, UInt& ruiPartIdxLT, UInt& ruiPartIdxRT )
+Void TComDataCU::deriveLeftRightTopIdx ( UInt uiPartIdx, UInt& ruiPartIdxLT, UInt& ruiPartIdxRT ) const
 {
   ruiPartIdxLT = m_absZIdxInCtu;
@@ -2836,5 +2835,5 @@
 }
 
-Void TComDataCU::deriveLeftBottomIdx( UInt  uiPartIdx,      UInt&      ruiPartIdxLB )
+Void TComDataCU::deriveLeftBottomIdx( UInt  uiPartIdx,      UInt&      ruiPartIdxLB ) const
 {
   ruiPartIdxLB      = g_auiRasterToZscan [g_auiZscanToRaster[ m_absZIdxInCtu ] + ( ((m_puhHeight[0] / m_pcPic->getMinCUHeight())>>1) - 1)*m_pcPic->getNumPartInCtuWidth()];
@@ -2876,5 +2875,5 @@
  * \param [out] ruiPartIdxRB  partition index of neighbouring bottom right block
  */
-Void TComDataCU::deriveRightBottomIdx( UInt uiPartIdx, UInt &ruiPartIdxRB )
+Void TComDataCU::deriveRightBottomIdx( UInt uiPartIdx, UInt &ruiPartIdxRB ) const
 {
   ruiPartIdxRB      = g_auiRasterToZscan [g_auiZscanToRaster[ m_absZIdxInCtu ] + ( ((m_puhHeight[0] / m_pcPic->getMinCUHeight())>>1) - 1)*m_pcPic->getNumPartInCtuWidth() +  m_puhWidth[0] / m_pcPic->getMinCUWidth() - 1];
@@ -2912,5 +2911,5 @@
 }
 
-Bool TComDataCU::hasEqualMotion( UInt uiAbsPartIdx, TComDataCU* pcCandCU, UInt uiCandAbsPartIdx )
+Bool TComDataCU::hasEqualMotion( UInt uiAbsPartIdx, const TComDataCU* pcCandCU, UInt uiCandAbsPartIdx ) const
 {
   if ( getInterDir( uiAbsPartIdx ) != pcCandCU->getInterDir( uiCandAbsPartIdx ) )
@@ -3098,5 +3097,5 @@
 
 
-#if ENC_DEC_TRACE && H_MV_ENC_DEC_TRAC
+#if ENC_DEC_TRACE && NH_MV_ENC_DEC_TRAC
   if ( g_traceMergeCandListConst ) 
   {
@@ -3177,5 +3176,5 @@
   }
 
-#if ENC_DEC_TRACE && H_MV_ENC_DEC_TRAC
+#if ENC_DEC_TRACE && NH_MV_ENC_DEC_TRAC
   if ( g_traceMergeCandListConst )
   {
@@ -3306,5 +3305,5 @@
   //left
   UInt uiLeftPartIdx = 0;
-  TComDataCU* pcCULeft = 0;
+  const TComDataCU* pcCULeft = 0;
   pcCULeft = getPULeft( uiLeftPartIdx, uiPartIdxLB );  
 
@@ -3783,5 +3782,9 @@
 
 //! Construct a list of merging candidates
+#if NH_3D
 Void TComDataCU::getInterMergeCandidates( UInt uiAbsPartIdx, UInt uiPUIdx, TComMvField* pcMvFieldNeighbours, UChar* puhInterDirNeighbours, Int& numValidMergeCand, Int mrgCandIdx )
+#else
+Void TComDataCU::getInterMergeCandidates( UInt uiAbsPartIdx, UInt uiPUIdx, TComMvField* pcMvFieldNeighbours, UChar* puhInterDirNeighbours, Int& numValidMergeCand, Int mrgCandIdx ) const
+#endif
 {
   UInt uiAbsPartAddr = m_absZIdxInCtu + uiAbsPartIdx;
@@ -3811,6 +3814,5 @@
   //left
   UInt uiLeftPartIdx = 0;
-  TComDataCU* pcCULeft = 0;
-  pcCULeft = getPULeft( uiLeftPartIdx, uiPartIdxLB );
+  const TComDataCU *pcCULeft = getPULeft( uiLeftPartIdx, uiPartIdxLB );
 
   Bool isAvailableA1 = pcCULeft &&
@@ -3828,8 +3830,8 @@
     puhInterDirNeighbours[iCount] = pcCULeft->getInterDir( uiLeftPartIdx );
     // get Mv from Left
-    pcCULeft->getMvField( pcCULeft, uiLeftPartIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[iCount<<1] );
+    TComDataCU::getMvField( pcCULeft, uiLeftPartIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[iCount<<1] );
     if ( getSlice()->isInterB() )
     {
-      pcCULeft->getMvField( pcCULeft, uiLeftPartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
+      TComDataCU::getMvField( pcCULeft, uiLeftPartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
     }
     if ( mrgCandIdx == iCount )
@@ -3847,6 +3849,5 @@
   // above
   UInt uiAbovePartIdx = 0;
-  TComDataCU* pcCUAbove = 0;
-  pcCUAbove = getPUAbove( uiAbovePartIdx, uiPartIdxRT );
+  const TComDataCU *pcCUAbove = getPUAbove( uiAbovePartIdx, uiPartIdxRT );
 
   Bool isAvailableB1 = pcCUAbove &&
@@ -3864,8 +3865,8 @@
     puhInterDirNeighbours[iCount] = pcCUAbove->getInterDir( uiAbovePartIdx );
     // get Mv from Left
-    pcCUAbove->getMvField( pcCUAbove, uiAbovePartIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[iCount<<1] );
+    TComDataCU::getMvField( pcCUAbove, uiAbovePartIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[iCount<<1] );
     if ( getSlice()->isInterB() )
     {
-      pcCUAbove->getMvField( pcCUAbove, uiAbovePartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
+      TComDataCU::getMvField( pcCUAbove, uiAbovePartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
     }
     if ( mrgCandIdx == iCount )
@@ -3883,6 +3884,5 @@
   // above right
   UInt uiAboveRightPartIdx = 0;
-  TComDataCU* pcCUAboveRight = 0;
-  pcCUAboveRight = getPUAboveRight( uiAboveRightPartIdx, uiPartIdxRT );
+  const TComDataCU *pcCUAboveRight = getPUAboveRight( uiAboveRightPartIdx, uiPartIdxRT );
 
   Bool isAvailableB0 = pcCUAboveRight &&
@@ -3899,8 +3899,8 @@
     puhInterDirNeighbours[iCount] = pcCUAboveRight->getInterDir( uiAboveRightPartIdx );
     // get Mv from Left
-    pcCUAboveRight->getMvField( pcCUAboveRight, uiAboveRightPartIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[iCount<<1] );
+    TComDataCU::getMvField( pcCUAboveRight, uiAboveRightPartIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[iCount<<1] );
     if ( getSlice()->isInterB() )
     {
-      pcCUAboveRight->getMvField( pcCUAboveRight, uiAboveRightPartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
+      TComDataCU::getMvField( pcCUAboveRight, uiAboveRightPartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
     }
     if ( mrgCandIdx == iCount )
@@ -3918,6 +3918,5 @@
   //left bottom
   UInt uiLeftBottomPartIdx = 0;
-  TComDataCU* pcCULeftBottom = 0;
-  pcCULeftBottom = this->getPUBelowLeft( uiLeftBottomPartIdx, uiPartIdxLB );
+  const TComDataCU *pcCULeftBottom = this->getPUBelowLeft( uiLeftBottomPartIdx, uiPartIdxLB );
 
   Bool isAvailableA0 = pcCULeftBottom &&
@@ -3934,8 +3933,8 @@
     puhInterDirNeighbours[iCount] = pcCULeftBottom->getInterDir( uiLeftBottomPartIdx );
     // get Mv from Left
-    pcCULeftBottom->getMvField( pcCULeftBottom, uiLeftBottomPartIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[iCount<<1] );
+    TComDataCU::getMvField( pcCULeftBottom, uiLeftBottomPartIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[iCount<<1] );
     if ( getSlice()->isInterB() )
     {
-      pcCULeftBottom->getMvField( pcCULeftBottom, uiLeftBottomPartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
+      TComDataCU::getMvField( pcCULeftBottom, uiLeftBottomPartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
     }
     if ( mrgCandIdx == iCount )
@@ -3955,6 +3954,5 @@
   {
     UInt uiAboveLeftPartIdx = 0;
-    TComDataCU* pcCUAboveLeft = 0;
-    pcCUAboveLeft = getPUAboveLeft( uiAboveLeftPartIdx, uiAbsPartAddr );
+    const TComDataCU *pcCUAboveLeft = getPUAboveLeft( uiAboveLeftPartIdx, uiAbsPartAddr );
 
     Bool isAvailableB2 = pcCUAboveLeft &&
@@ -3972,8 +3970,8 @@
       puhInterDirNeighbours[iCount] = pcCUAboveLeft->getInterDir( uiAboveLeftPartIdx );
       // get Mv from Left
-      pcCUAboveLeft->getMvField( pcCUAboveLeft, uiAboveLeftPartIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[iCount<<1] );
+      TComDataCU::getMvField( pcCUAboveLeft, uiAboveLeftPartIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[iCount<<1] );
       if ( getSlice()->isInterB() )
       {
-        pcCUAboveLeft->getMvField( pcCUAboveLeft, uiAboveLeftPartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
+        TComDataCU::getMvField( pcCUAboveLeft, uiAboveLeftPartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
       }
       if ( mrgCandIdx == iCount )
@@ -4166,5 +4164,5 @@
  * \param xP, yP   location of the upper-left corner pixel of the current PU
  */
-Bool TComDataCU::isDiffMER(Int xN, Int yN, Int xP, Int yP)
+Bool TComDataCU::isDiffMER(Int xN, Int yN, Int xP, Int yP) const
 {
 
@@ -4186,5 +4184,5 @@
  * \param nPSW, nPSH    size of the current PU
  */
-Void TComDataCU::getPartPosition( UInt partIdx, Int& xP, Int& yP, Int& nPSW, Int& nPSH)
+Void TComDataCU::getPartPosition( UInt partIdx, Int& xP, Int& yP, Int& nPSW, Int& nPSH) const
 {
   UInt col = m_uiCUPelX;
@@ -4247,5 +4245,5 @@
 }
 
-/** Constructs a list of candidates for AMVP
+/** Constructs a list of candidates for AMVP (See specification, section "Derivation process for motion vector predictor candidates")
  * \param uiPartIdx
  * \param uiPartAddr
@@ -4254,11 +4252,8 @@
  * \param pInfo
  */
-Void TComDataCU::fillMvpCand ( UInt uiPartIdx, UInt uiPartAddr, RefPicList eRefPicList, Int iRefIdx, AMVPInfo* pInfo )
-{
-  TComMv cMvPred;
-  Bool bAddedSmvp = false;
-
+Void TComDataCU::fillMvpCand ( const UInt partIdx, const UInt partAddr, const RefPicList eRefPicList, const Int refIdx, AMVPInfo* pInfo ) const
+{
   pInfo->iN = 0;
-  if (iRefIdx < 0)
+  if (refIdx < 0)
   {
     return;
@@ -4266,63 +4261,61 @@
 
   //-- Get Spatial MV
-  UInt uiPartIdxLT, uiPartIdxRT, uiPartIdxLB;
-  const UInt numPartInCtuWidth  = m_pcPic->getNumPartInCtuWidth();
-  const UInt numPartInCtuHeight = m_pcPic->getNumPartInCtuHeight();
-  Bool bAdded = false;
-
-  deriveLeftRightTopIdx( uiPartIdx, uiPartIdxLT, uiPartIdxRT );
-  deriveLeftBottomIdx( uiPartIdx, uiPartIdxLB );
-
-  TComDataCU* tmpCU = NULL;
-  UInt idx;
-  tmpCU = getPUBelowLeft(idx, uiPartIdxLB);
-  bAddedSmvp = (tmpCU != NULL) && (tmpCU->isInter(idx));
-
-  if (!bAddedSmvp)
-  {
-    tmpCU = getPULeft(idx, uiPartIdxLB);
-    bAddedSmvp = (tmpCU != NULL) && (tmpCU->isInter(idx));
+  UInt partIdxLT, partIdxRT, partIdxLB;
+  deriveLeftRightTopIdx( partIdx, partIdxLT, partIdxRT );
+  deriveLeftBottomIdx( partIdx, partIdxLB );
+
+  Bool isScaledFlagLX = false; /// variable name from specification; true when the PUs below left or left are available (availableA0 || availableA1).
+  {
+    UInt idx;
+    const TComDataCU* tmpCU = getPUBelowLeft(idx, partIdxLB);
+    isScaledFlagLX = (tmpCU != NULL) && (tmpCU->isInter(idx));
+    if (!isScaledFlagLX)
+    {
+      tmpCU = getPULeft(idx, partIdxLB);
+      isScaledFlagLX = (tmpCU != NULL) && (tmpCU->isInter(idx));
+    }
   }
 
   // Left predictor search
-  bAdded = xAddMVPCand( pInfo, eRefPicList, iRefIdx, uiPartIdxLB, MD_BELOW_LEFT);
-  if (!bAdded)
-  {
-    bAdded = xAddMVPCand( pInfo, eRefPicList, iRefIdx, uiPartIdxLB, MD_LEFT );
-  }
-
-  if(!bAdded)
-  {
-    bAdded = xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxLB, MD_BELOW_LEFT);
+  if (isScaledFlagLX)
+  {
+    Bool bAdded = xAddMVPCandUnscaled( *pInfo, eRefPicList, refIdx, partIdxLB, MD_BELOW_LEFT);
     if (!bAdded)
     {
-      xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxLB, MD_LEFT );
+      bAdded = xAddMVPCandUnscaled( *pInfo, eRefPicList, refIdx, partIdxLB, MD_LEFT );
+      if(!bAdded)
+      {
+        bAdded = xAddMVPCandWithScaling( *pInfo, eRefPicList, refIdx, partIdxLB, MD_BELOW_LEFT);
+        if (!bAdded)
+        {
+          xAddMVPCandWithScaling( *pInfo, eRefPicList, refIdx, partIdxLB, MD_LEFT );
+        }
+      }
     }
   }
 
   // Above predictor search
-  bAdded = xAddMVPCand( pInfo, eRefPicList, iRefIdx, uiPartIdxRT, MD_ABOVE_RIGHT);
-
-  if (!bAdded)
-  {
-    bAdded = xAddMVPCand( pInfo, eRefPicList, iRefIdx, uiPartIdxRT, MD_ABOVE);
-  }
-
-  if(!bAdded)
-  {
-    xAddMVPCand( pInfo, eRefPicList, iRefIdx, uiPartIdxLT, MD_ABOVE_LEFT);
-  }
-
-  if(!bAddedSmvp)
-  {
-    bAdded = xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxRT, MD_ABOVE_RIGHT);
+  {
+    Bool bAdded = xAddMVPCandUnscaled( *pInfo, eRefPicList, refIdx, partIdxRT, MD_ABOVE_RIGHT);
     if (!bAdded)
     {
-      bAdded = xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxRT, MD_ABOVE);
-    }
-
-    if(!bAdded)
-    {
-      xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxLT, MD_ABOVE_LEFT);
+      bAdded = xAddMVPCandUnscaled( *pInfo, eRefPicList, refIdx, partIdxRT, MD_ABOVE);
+      if(!bAdded)
+      {
+        xAddMVPCandUnscaled( *pInfo, eRefPicList, refIdx, partIdxLT, MD_ABOVE_LEFT);
+      }
+    }
+  }
+
+  if(!isScaledFlagLX)
+  {
+    Bool bAdded = xAddMVPCandWithScaling( *pInfo, eRefPicList, refIdx, partIdxRT, MD_ABOVE_RIGHT);
+    if (!bAdded)
+    {
+      bAdded = xAddMVPCandWithScaling( *pInfo, eRefPicList, refIdx, partIdxRT, MD_ABOVE);
+      if(!bAdded)
+      {
+        xAddMVPCandWithScaling( *pInfo, eRefPicList, refIdx, partIdxLT, MD_ABOVE_LEFT);
+      }
     }
   }
@@ -4336,47 +4329,52 @@
   }
 
-  if ( getSlice()->getEnableTMVPFlag() )
+  if (pInfo->iN < AMVP_MAX_NUM_CANDS && getSlice()->getEnableTMVPFlag() )
   {
     // Get Temporal Motion Predictor
-    Int iRefIdx_Col = iRefIdx;
+    const UInt numPartInCtuWidth  = m_pcPic->getNumPartInCtuWidth();
+    const UInt numPartInCtuHeight = m_pcPic->getNumPartInCtuHeight();
+#if NH_3D_TMVP
+    Int refIdx_Col = refIdx;
+#else
+    const Int refIdx_Col = refIdx;
+#endif
     TComMv cColMv;
-    UInt uiPartIdxRB;
-    UInt uiAbsPartIdx;
-    UInt uiAbsPartAddr;
-
-    deriveRightBottomIdx( uiPartIdx, uiPartIdxRB );
-    uiAbsPartAddr = m_absZIdxInCtu + uiPartAddr;
+    UInt partIdxRB;
+    UInt absPartIdx;
+
+    deriveRightBottomIdx( partIdx, partIdxRB );
+    UInt absPartAddr = m_absZIdxInCtu + partAddr;
 
     //----  co-located RightBottom Temporal Predictor (H) ---//
-    uiAbsPartIdx = g_auiZscanToRaster[uiPartIdxRB];
+    absPartIdx = g_auiZscanToRaster[partIdxRB];
     Int ctuRsAddr = -1;
-    if (  ( ( m_pcPic->getCtu(m_ctuRsAddr)->getCUPelX() + g_auiRasterToPelX[uiAbsPartIdx] + m_pcPic->getMinCUWidth () ) < m_pcSlice->getSPS()->getPicWidthInLumaSamples () )  // image boundary check
-       && ( ( m_pcPic->getCtu(m_ctuRsAddr)->getCUPelY() + g_auiRasterToPelY[uiAbsPartIdx] + m_pcPic->getMinCUHeight() ) < m_pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
-    {
-      if ( ( uiAbsPartIdx % numPartInCtuWidth < numPartInCtuWidth - 1 ) &&  // is not at the last column of CTU
-           ( uiAbsPartIdx / numPartInCtuWidth < numPartInCtuHeight - 1 ) )  // is not at the last row    of CTU
-      {
-        uiAbsPartAddr = g_auiRasterToZscan[ uiAbsPartIdx + numPartInCtuWidth + 1 ];
+    if (  ( ( m_pcPic->getCtu(m_ctuRsAddr)->getCUPelX() + g_auiRasterToPelX[absPartIdx] + m_pcPic->getMinCUWidth () ) < m_pcSlice->getSPS()->getPicWidthInLumaSamples () )  // image boundary check
+      && ( ( m_pcPic->getCtu(m_ctuRsAddr)->getCUPelY() + g_auiRasterToPelY[absPartIdx] + m_pcPic->getMinCUHeight() ) < m_pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+    {
+      if ( ( absPartIdx % numPartInCtuWidth < numPartInCtuWidth - 1 ) &&  // is not at the last column of CTU
+        ( absPartIdx / numPartInCtuWidth < numPartInCtuHeight - 1 ) )  // is not at the last row    of CTU
+      {
+        absPartAddr = g_auiRasterToZscan[ absPartIdx + numPartInCtuWidth + 1 ];
         ctuRsAddr = getCtuRsAddr();
       }
-      else if ( uiAbsPartIdx % numPartInCtuWidth < numPartInCtuWidth - 1 )  // is not at the last column of CTU But is last row of CTU
-      {
-        uiAbsPartAddr = g_auiRasterToZscan[ (uiAbsPartIdx + numPartInCtuWidth + 1) % m_pcPic->getNumPartitionsInCtu() ];
-      }
-      else if ( uiAbsPartIdx / numPartInCtuWidth < numPartInCtuHeight - 1 ) // is not at the last row of CTU But is last column of CTU
-      {
-        uiAbsPartAddr = g_auiRasterToZscan[ uiAbsPartIdx + 1 ];
+      else if ( absPartIdx % numPartInCtuWidth < numPartInCtuWidth - 1 )  // is not at the last column of CTU But is last row of CTU
+      {
+        absPartAddr = g_auiRasterToZscan[ (absPartIdx + numPartInCtuWidth + 1) % m_pcPic->getNumPartitionsInCtu() ];
+      }
+      else if ( absPartIdx / numPartInCtuWidth < numPartInCtuHeight - 1 ) // is not at the last row of CTU But is last column of CTU
+      {
+        absPartAddr = g_auiRasterToZscan[ absPartIdx + 1 ];
         ctuRsAddr = getCtuRsAddr() + 1;
       }
       else //is the right bottom corner of CTU
       {
-        uiAbsPartAddr = 0;
-      }
-    }
-    if ( ctuRsAddr >= 0 && xGetColMVP( eRefPicList, ctuRsAddr, uiAbsPartAddr, cColMv, iRefIdx_Col
+        absPartAddr = 0;
+      }
+    }
 #if NH_3D_TMVP
-         , 0
-#endif
- ) )
+        if ( ctuRsAddr >= 0 && xGetColMVP( eRefPicList, ctuRsAddr, absPartAddr, cColMv, refIdx_Col  , 0 ) )
+#else
+    if ( ctuRsAddr >= 0 && xGetColMVP( eRefPicList, ctuRsAddr, absPartAddr, cColMv, refIdx_Col ) )
+#endif
     {
       pInfo->m_acMvCand[pInfo->iN++] = cColMv;
@@ -4385,10 +4383,10 @@
     {
       UInt uiPartIdxCenter;
-      xDeriveCenterIdx( uiPartIdx, uiPartIdxCenter );
-      if (xGetColMVP( eRefPicList, getCtuRsAddr(), uiPartIdxCenter,  cColMv, iRefIdx_Col 
+      xDeriveCenterIdx( partIdx, uiPartIdxCenter );
 #if NH_3D_TMVP
-         , 0
-#endif
-))
+      if (xGetColMVP( eRefPicList, getCtuRsAddr(), uiPartIdxCenter,  cColMv, refIdx_Col , 0 )) 
+#else
+      if (xGetColMVP( eRefPicList, getCtuRsAddr(), uiPartIdxCenter,  cColMv, refIdx_Col ))
+#endif
       {
         pInfo->m_acMvCand[pInfo->iN++] = cColMv;
@@ -4396,9 +4394,4 @@
     }
     //----  co-located RightBottom Temporal Predictor  ---//
-  }
-
-  if (pInfo->iN > AMVP_MAX_NUM_CANDS)
-  {
-    pInfo->iN = AMVP_MAX_NUM_CANDS;
   }
 
@@ -4412,5 +4405,5 @@
 
 
-Bool TComDataCU::isBipredRestriction(UInt puIdx)
+Bool TComDataCU::isBipredRestriction(UInt puIdx) const
 {
   Int width = 0;
@@ -4434,5 +4427,5 @@
 
 
-Void TComDataCU::clipMv    (TComMv&  rcMv)
+Void TComDataCU::clipMv    (TComMv&  rcMv) const
 {
   const TComSPS &sps=*(m_pcSlice->getSPS());
@@ -4470,5 +4463,5 @@
 #endif
 
-UInt TComDataCU::getIntraSizeIdx(UInt uiAbsPartIdx)
+UInt TComDataCU::getIntraSizeIdx(UInt uiAbsPartIdx) const
 {
   UInt uiShift = ( m_pePartSize[uiAbsPartIdx]==SIZE_NxN ? 1 : 0 );
@@ -4507,5 +4500,5 @@
  * \returns true if the current the block is skipped
  */
-Bool TComDataCU::isSkipped( UInt uiPartIdx )
+Bool TComDataCU::isSkipped( UInt uiPartIdx ) const
 {
   return ( getSkipFlag( uiPartIdx ) );
@@ -4516,33 +4509,33 @@
 // ====================================================================================================================
 
-Bool TComDataCU::xAddMVPCand( AMVPInfo* pInfo, RefPicList eRefPicList, Int iRefIdx, UInt uiPartUnitIdx, MVP_DIR eDir )
-{
-  TComDataCU* pcTmpCU = NULL;
-  UInt uiIdx;
+Bool TComDataCU::xAddMVPCandUnscaled( AMVPInfo &info, const RefPicList eRefPicList, const Int iRefIdx, const UInt uiPartUnitIdx, const MVP_DIR eDir ) const
+{
+  const TComDataCU* neibCU = NULL;
+  UInt neibPUPartIdx;
   switch( eDir )
   {
     case MD_LEFT:
     {
-      pcTmpCU = getPULeft(uiIdx, uiPartUnitIdx);
+      neibCU = getPULeft(neibPUPartIdx, uiPartUnitIdx);
       break;
     }
     case MD_ABOVE:
     {
-      pcTmpCU = getPUAbove(uiIdx, uiPartUnitIdx);
+      neibCU = getPUAbove(neibPUPartIdx, uiPartUnitIdx);
       break;
     }
     case MD_ABOVE_RIGHT:
     {
-      pcTmpCU = getPUAboveRight(uiIdx, uiPartUnitIdx);
+      neibCU = getPUAboveRight(neibPUPartIdx, uiPartUnitIdx);
       break;
     }
     case MD_BELOW_LEFT:
     {
-      pcTmpCU = getPUBelowLeft(uiIdx, uiPartUnitIdx);
+      neibCU = getPUBelowLeft(neibPUPartIdx, uiPartUnitIdx);
       break;
     }
     case MD_ABOVE_LEFT:
     {
-      pcTmpCU = getPUAboveLeft(uiIdx, uiPartUnitIdx);
+      neibCU = getPUAboveLeft(neibPUPartIdx, uiPartUnitIdx);
       break;
     }
@@ -4553,39 +4546,20 @@
   }
 
-  if ( pcTmpCU == NULL )
+  if ( neibCU == NULL )
   {
     return false;
   }
 
-  if ( pcTmpCU->getCUMvField(eRefPicList)->getRefIdx(uiIdx) >= 0 && m_pcSlice->getRefPic( eRefPicList, iRefIdx)->getPOC() == pcTmpCU->getSlice()->getRefPOC( eRefPicList, pcTmpCU->getCUMvField(eRefPicList)->getRefIdx(uiIdx) ))
-  {
-    TComMv cMvPred = pcTmpCU->getCUMvField(eRefPicList)->getMv(uiIdx);
-
-    pInfo->m_acMvCand[ pInfo->iN++] = cMvPred;
-    return true;
-  }
-
-  RefPicList eRefPicList2nd = REF_PIC_LIST_0;
-  if(       eRefPicList == REF_PIC_LIST_0 )
-  {
-    eRefPicList2nd = REF_PIC_LIST_1;
-  }
-  else if ( eRefPicList == REF_PIC_LIST_1)
-  {
-    eRefPicList2nd = REF_PIC_LIST_0;
-  }
-
-
-  Int iCurrRefPOC = m_pcSlice->getRefPic( eRefPicList, iRefIdx)->getPOC();
-  Int iNeibRefPOC;
-
-
-  if( pcTmpCU->getCUMvField(eRefPicList2nd)->getRefIdx(uiIdx) >= 0 )
-  {
-    iNeibRefPOC = pcTmpCU->getSlice()->getRefPOC( eRefPicList2nd, pcTmpCU->getCUMvField(eRefPicList2nd)->getRefIdx(uiIdx) );
-    if( iNeibRefPOC == iCurrRefPOC ) // Same Reference Frame But Diff List//
-    {
-      TComMv cMvPred = pcTmpCU->getCUMvField(eRefPicList2nd)->getMv(uiIdx);
-      pInfo->m_acMvCand[ pInfo->iN++] = cMvPred;
+  const Int        currRefPOC     = m_pcSlice->getRefPic( eRefPicList, iRefIdx)->getPOC();
+  const RefPicList eRefPicList2nd = (eRefPicList == REF_PIC_LIST_0) ? REF_PIC_LIST_1 : REF_PIC_LIST_0;
+
+  for(Int predictorSource=0; predictorSource<2; predictorSource++) // examine the indicated reference picture list, then if not available, examine the other list.
+  {
+    const RefPicList eRefPicListIndex = (predictorSource==0) ? eRefPicList : eRefPicList2nd;
+    const Int        neibRefIdx       = neibCU->getCUMvField(eRefPicListIndex)->getRefIdx(neibPUPartIdx);
+
+    if ( neibRefIdx >= 0 && currRefPOC == neibCU->getSlice()->getRefPOC( eRefPicListIndex, neibRefIdx ))
+    {
+      info.m_acMvCand[info.iN++] = neibCU->getCUMvField(eRefPicListIndex)->getMv(neibPUPartIdx);
       return true;
     }
@@ -4602,33 +4576,33 @@
  * \returns Bool
  */
-Bool TComDataCU::xAddMVPCandOrder( AMVPInfo* pInfo, RefPicList eRefPicList, Int iRefIdx, UInt uiPartUnitIdx, MVP_DIR eDir )
-{
-  TComDataCU* pcTmpCU = NULL;
-  UInt uiIdx;
+Bool TComDataCU::xAddMVPCandWithScaling( AMVPInfo &info, const RefPicList eRefPicList, const Int iRefIdx, const UInt uiPartUnitIdx, const MVP_DIR eDir ) const
+{
+  const TComDataCU* neibCU = NULL;
+  UInt neibPUPartIdx;
   switch( eDir )
   {
   case MD_LEFT:
     {
-      pcTmpCU = getPULeft(uiIdx, uiPartUnitIdx);
+      neibCU = getPULeft(neibPUPartIdx, uiPartUnitIdx);
       break;
     }
   case MD_ABOVE:
     {
-      pcTmpCU = getPUAbove(uiIdx, uiPartUnitIdx);
+      neibCU = getPUAbove(neibPUPartIdx, uiPartUnitIdx);
       break;
     }
   case MD_ABOVE_RIGHT:
     {
-      pcTmpCU = getPUAboveRight(uiIdx, uiPartUnitIdx);
+      neibCU = getPUAboveRight(neibPUPartIdx, uiPartUnitIdx);
       break;
     }
   case MD_BELOW_LEFT:
     {
-      pcTmpCU = getPUBelowLeft(uiIdx, uiPartUnitIdx);
+      neibCU = getPUBelowLeft(neibPUPartIdx, uiPartUnitIdx);
       break;
     }
   case MD_ABOVE_LEFT:
     {
-      pcTmpCU = getPUAboveLeft(uiIdx, uiPartUnitIdx);
+      neibCU = getPUAboveLeft(neibPUPartIdx, uiPartUnitIdx);
       break;
     }
@@ -4639,44 +4613,29 @@
   }
 
-  if ( pcTmpCU == NULL )
+  if ( neibCU == NULL )
   {
     return false;
   }
 
-  RefPicList eRefPicList2nd = REF_PIC_LIST_0;
-  if(       eRefPicList == REF_PIC_LIST_0 )
-  {
-    eRefPicList2nd = REF_PIC_LIST_1;
-  }
-  else if ( eRefPicList == REF_PIC_LIST_1)
-  {
-    eRefPicList2nd = REF_PIC_LIST_0;
-  }
-
-  Int iCurrPOC = m_pcSlice->getPOC();
-  Int iCurrRefPOC = m_pcSlice->getRefPic( eRefPicList, iRefIdx)->getPOC();
-  Int iNeibPOC = iCurrPOC;
-  Int iNeibRefPOC;
-  Bool bIsCurrRefLongTerm = m_pcSlice->getRefPic( eRefPicList, iRefIdx)->getIsLongTerm();
-  Bool bIsNeibRefLongTerm = false;
-
-  //---------------  V1 (END) ------------------//
-  if( pcTmpCU->getCUMvField(eRefPicList)->getRefIdx(uiIdx) >= 0)
-  {
-    iNeibRefPOC = pcTmpCU->getSlice()->getRefPOC( eRefPicList, pcTmpCU->getCUMvField(eRefPicList)->getRefIdx(uiIdx) );
-    TComMv cMvPred = pcTmpCU->getCUMvField(eRefPicList)->getMv(uiIdx);
-    TComMv rcMv;
-
-    bIsNeibRefLongTerm = pcTmpCU->getSlice()->getRefPic( eRefPicList, pcTmpCU->getCUMvField(eRefPicList)->getRefIdx(uiIdx) )->getIsLongTerm();
-    if ( bIsCurrRefLongTerm == bIsNeibRefLongTerm )
-    {
-      if ( bIsCurrRefLongTerm || bIsNeibRefLongTerm )
-      {
-        rcMv = cMvPred;
-      }
-      else
-      {
-        Int iScale = xGetDistScaleFactor( iCurrPOC, iCurrRefPOC, iNeibPOC, iNeibRefPOC );
-        if ( iScale == 4096 )
+  const RefPicList eRefPicList2nd = (eRefPicList == REF_PIC_LIST_0) ? REF_PIC_LIST_1 : REF_PIC_LIST_0;
+
+  const Int  currPOC            = m_pcSlice->getPOC();
+  const Int  currRefPOC         = m_pcSlice->getRefPic( eRefPicList, iRefIdx)->getPOC();
+  const Bool bIsCurrRefLongTerm = m_pcSlice->getRefPic( eRefPicList, iRefIdx)->getIsLongTerm();
+  const Int  neibPOC            = currPOC;
+
+  for(Int predictorSource=0; predictorSource<2; predictorSource++) // examine the indicated reference picture list, then if not available, examine the other list.
+  {
+    const RefPicList eRefPicListIndex = (predictorSource==0) ? eRefPicList : eRefPicList2nd;
+    const Int        neibRefIdx       = neibCU->getCUMvField(eRefPicListIndex)->getRefIdx(neibPUPartIdx);
+    if( neibRefIdx >= 0)
+    {
+      const Bool bIsNeibRefLongTerm = neibCU->getSlice()->getRefPic( eRefPicListIndex, neibRefIdx )->getIsLongTerm();
+
+      if ( bIsCurrRefLongTerm == bIsNeibRefLongTerm )
+      {
+        const TComMv &cMvPred = neibCU->getCUMvField(eRefPicListIndex)->getMv(neibPUPartIdx);
+        TComMv rcMv;
+        if ( bIsCurrRefLongTerm /* || bIsNeibRefLongTerm*/ )
         {
           rcMv = cMvPred;
@@ -4684,82 +4643,52 @@
         else
         {
-          rcMv = cMvPred.scaleMv( iScale );
+          const Int neibRefPOC = neibCU->getSlice()->getRefPOC( eRefPicListIndex, neibRefIdx );
+          const Int scale      = xGetDistScaleFactor( currPOC, currRefPOC, neibPOC, neibRefPOC );
+          if ( scale == 4096 )
+          {
+            rcMv = cMvPred;
+          }
+          else
+          {
+            rcMv = cMvPred.scaleMv( scale );
+          }
         }
-      }
-
-      pInfo->m_acMvCand[ pInfo->iN++] = rcMv;
-      return true;
-    }
-  }
-  //---------------------- V2(END) --------------------//
-  if( pcTmpCU->getCUMvField(eRefPicList2nd)->getRefIdx(uiIdx) >= 0)
-  {
-    iNeibRefPOC = pcTmpCU->getSlice()->getRefPOC( eRefPicList2nd, pcTmpCU->getCUMvField(eRefPicList2nd)->getRefIdx(uiIdx) );
-    TComMv cMvPred = pcTmpCU->getCUMvField(eRefPicList2nd)->getMv(uiIdx);
-    TComMv rcMv;
-
-    bIsNeibRefLongTerm = pcTmpCU->getSlice()->getRefPic( eRefPicList2nd, pcTmpCU->getCUMvField(eRefPicList2nd)->getRefIdx(uiIdx) )->getIsLongTerm();
-    if ( bIsCurrRefLongTerm == bIsNeibRefLongTerm )
-    {
-      if ( bIsCurrRefLongTerm || bIsNeibRefLongTerm )
-      {
-        rcMv = cMvPred;
-      }
-      else
-      {
-        Int iScale = xGetDistScaleFactor( iCurrPOC, iCurrRefPOC, iNeibPOC, iNeibRefPOC );
-        if ( iScale == 4096 )
-        {
-          rcMv = cMvPred;
-        }
-        else
-        {
-          rcMv = cMvPred.scaleMv( iScale );
-        }
-      }
-
-      pInfo->m_acMvCand[ pInfo->iN++] = rcMv;
-      return true;
-    }
-  }
-  //---------------------- V3(END) --------------------//
+
+        info.m_acMvCand[info.iN++] = rcMv;
+        return true;
+      }
+    }
+  }
   return false;
 }
 
-Bool TComDataCU::xGetColMVP( RefPicList eRefPicList, Int ctuRsAddr, Int uiPartUnitIdx, TComMv& rcMv, Int& riRefIdx 
 #if NH_3D_TMVP
-  , Bool bMRG
-#endif
-)
-{
-  UInt uiAbsPartAddr = uiPartUnitIdx;
-
-  RefPicList  eColRefPicList;
-  Int iColPOC, iColRefPOC, iCurrPOC, iCurrRefPOC, iScale;
-  TComMv cColMv;
+Bool TComDataCU::xGetColMVP( const RefPicList eRefPicList, const Int ctuRsAddr, const Int partUnitIdx, TComMv& rcMv, Int& refIdx, Bool bMRG  ) const
+#else
+Bool TComDataCU::xGetColMVP( const RefPicList eRefPicList, const Int ctuRsAddr, const Int partUnitIdx, TComMv& rcMv, const Int refIdx ) const
+#endif
+{
+  const UInt absPartAddr = partUnitIdx;
 
   // use coldir.
-  TComPic *pColPic = getSlice()->getRefPic( RefPicList(getSlice()->isInterB() ? 1-getSlice()->getColFromL0Flag() : 0), getSlice()->getColRefIdx());
-  TComDataCU *pColCtu = pColPic->getCtu( ctuRsAddr );
-  if(pColCtu->getPic()==0||pColCtu->getPartitionSize(uiPartUnitIdx)==NUMBER_OF_PART_SIZES)
+  const TComPic    * const pColPic = getSlice()->getRefPic( RefPicList(getSlice()->isInterB() ? 1-getSlice()->getColFromL0Flag() : 0), getSlice()->getColRefIdx());
+  const TComDataCU * const pColCtu = pColPic->getCtu( ctuRsAddr );
+  if(pColCtu->getPic()==0 || pColCtu->getPartitionSize(partUnitIdx)==NUMBER_OF_PART_SIZES)
   {
     return false;
   }
-  iCurrPOC = m_pcSlice->getPOC();
-  iColPOC = pColCtu->getSlice()->getPOC();
-
-  if (!pColCtu->isInter(uiAbsPartAddr))
+
+  if (!pColCtu->isInter(absPartAddr))
   {
     return false;
   }
 
-  eColRefPicList = getSlice()->getCheckLDC() ? eRefPicList : RefPicList(getSlice()->getColFromL0Flag());
-
-  Int iColRefIdx = pColCtu->getCUMvField(RefPicList(eColRefPicList))->getRefIdx(uiAbsPartAddr);
+  RefPicList eColRefPicList = getSlice()->getCheckLDC() ? eRefPicList : RefPicList(getSlice()->getColFromL0Flag());
+  Int iColRefIdx            = pColCtu->getCUMvField(RefPicList(eColRefPicList))->getRefIdx(absPartAddr);
 
   if (iColRefIdx < 0 )
   {
     eColRefPicList = RefPicList(1 - eColRefPicList);
-    iColRefIdx = pColCtu->getCUMvField(RefPicList(eColRefPicList))->getRefIdx(uiAbsPartAddr);
+    iColRefIdx = pColCtu->getCUMvField(RefPicList(eColRefPicList))->getRefIdx(absPartAddr);
 
     if (iColRefIdx < 0 )
@@ -4769,12 +4698,10 @@
   }
 
-  // Scale the vector.
-  iColRefPOC = pColCtu->getSlice()->getRefPOC(eColRefPicList, iColRefIdx);
-  cColMv = pColCtu->getCUMvField(eColRefPicList)->getMv(uiAbsPartAddr);
-
-  iCurrRefPOC = m_pcSlice->getRefPic(eRefPicList, riRefIdx)->getPOC();
-
-  Bool bIsCurrRefLongTerm = m_pcSlice->getRefPic(eRefPicList, riRefIdx)->getIsLongTerm();
-  Bool bIsColRefLongTerm = pColCtu->getSlice()->getIsUsedAsLongTerm(eColRefPicList, iColRefIdx);
+#if NH_3D_TMVP
+  Bool bIsCurrRefLongTerm = m_pcSlice->getRefPic(eRefPicList, refIdx)->getIsLongTerm();
+#else
+  const Bool bIsCurrRefLongTerm = m_pcSlice->getRefPic(eRefPicList, refIdx)->getIsLongTerm();
+#endif
+  const Bool bIsColRefLongTerm  = pColCtu->getSlice()->getIsUsedAsLongTerm(eColRefPicList, iColRefIdx);
 
   if ( bIsCurrRefLongTerm != bIsColRefLongTerm )
@@ -4784,7 +4711,6 @@
     if(bMRG && iAlterRefIdx > 0)
     {
-      riRefIdx = iAlterRefIdx;
-      bIsCurrRefLongTerm = m_pcSlice->getRefPic(eRefPicList, riRefIdx)->getIsLongTerm();
-      iCurrRefPOC = m_pcSlice->getRefPic(eRefPicList, riRefIdx)->getPOC();
+      refIdx = iAlterRefIdx;
+      bIsCurrRefLongTerm = m_pcSlice->getRefPic(eRefPicList, refIdx)->getIsLongTerm();
       assert(bIsCurrRefLongTerm == bIsColRefLongTerm);
     }
@@ -4792,30 +4718,36 @@
     {
 #endif
-    return false;
+      return false;
 #if NH_3D_TMVP
     }
 #endif
   }
-
+  // Scale the vector.
+  const TComMv &cColMv = pColCtu->getCUMvField(eColRefPicList)->getMv(absPartAddr);
+
+#if NH_3D_TMVP
   if ( bIsCurrRefLongTerm || bIsColRefLongTerm )
+#else
+  if ( bIsCurrRefLongTerm /*|| bIsColRefLongTerm*/ )
+#endif
   {
 #if NH_3D_TMVP
-    Int iCurrViewId    = m_pcSlice->getViewId (); 
-    Int iCurrRefViewId = m_pcSlice->getRefPic(eRefPicList, riRefIdx)->getViewId (); 
-    Int iColViewId     = pColCtu->getSlice()->getViewId(); 
-    Int iColRefViewId  = pColCtu->getSlice()->getRefPic( eColRefPicList, pColCtu->getCUMvField(eColRefPicList)->getRefIdx(uiAbsPartAddr))->getViewId(); 
-    iScale = 4096;
+    const Int iCurrViewId    = m_pcSlice->getViewId (); 
+    const Int iCurrRefViewId = m_pcSlice->getRefPic(eRefPicList, refIdx)->getViewId (); 
+    const Int iColViewId     = pColCtu->getSlice()->getViewId(); 
+    const Int iColRefViewId  = pColCtu->getSlice()->getRefPic( eColRefPicList, pColCtu->getCUMvField(eColRefPicList)->getRefIdx(absPartAddr))->getViewId(); 
+    Int scale = 4096;
     if ( iCurrRefViewId != iCurrViewId && iColViewId != iColRefViewId )
     {
-      iScale = xGetDistScaleFactor( iCurrViewId, iCurrRefViewId, iColViewId, iColRefViewId );
-    }
-    if ( bMRG && iScale != 4096 && m_pcSlice->getIvMvScalingFlag( ) ) 
-    {
-      rcMv = cColMv.scaleMv( iScale );
+      scale = xGetDistScaleFactor( iCurrViewId, iCurrRefViewId, iColViewId, iColRefViewId );
+    }
+    if ( bMRG && scale != 4096 && m_pcSlice->getIvMvScalingFlag( ) ) 
+    {
+      rcMv = cColMv.scaleMv( scale );
     }
     else
     {
 #endif
-    rcMv = cColMv;
+      rcMv = cColMv;
 #if NH_3D_TMVP
     }
@@ -4824,6 +4756,10 @@
   else
   {
-    iScale = xGetDistScaleFactor(iCurrPOC, iCurrRefPOC, iColPOC, iColRefPOC);
-    if ( iScale == 4096 )
+    const Int currPOC    = m_pcSlice->getPOC();
+    const Int colPOC     = pColCtu->getSlice()->getPOC();
+    const Int colRefPOC  = pColCtu->getSlice()->getRefPOC(eColRefPicList, iColRefIdx);
+    const Int currRefPOC = m_pcSlice->getRefPic(eRefPicList, refIdx)->getPOC();
+    const Int scale      = xGetDistScaleFactor(currPOC, currRefPOC, colPOC, colRefPOC);
+    if ( scale == 4096 )
     {
       rcMv = cColMv;
@@ -4831,5 +4767,5 @@
     else
     {
-      rcMv = cColMv.scaleMv( iScale );
+      rcMv = cColMv.scaleMv( scale );
     }
   }
@@ -4838,4 +4774,5 @@
 }
 
+// Static member
 Int TComDataCU::xGetDistScaleFactor(Int iCurrPOC, Int iCurrRefPOC, Int iColPOC, Int iColRefPOC)
 {
@@ -4857,5 +4794,5 @@
 }
 
-Void TComDataCU::xDeriveCenterIdx( UInt uiPartIdx, UInt& ruiPartIdxCenter )
+Void TComDataCU::xDeriveCenterIdx( UInt uiPartIdx, UInt& ruiPartIdxCenter ) const
 {
   UInt uiPartAddr;
@@ -5001,5 +4938,5 @@
   
   UInt uiMidPart, uiPartNeighbor;  
-  TComDataCU* pcCUNeighbor;
+  const TComDataCU* pcCUNeighbor;
   Bool bDepAvail = false;
   Pel *pDepth  = this->getPic()->getPicYuvRec()->getAddr(COMPONENT_Y);
@@ -5133,5 +5070,5 @@
 #if NH_3D_NBDV_REF
         TComPic* picDepth = NULL;   
-#if H_3D_FCO_VSP_DONBDV_E0163
+#if H_3D_FCO
         picDepth  = getSlice()->getIvPic(true, getSlice()->getViewIndex() );
         if ( picDepth->getPicYuvRec() != NULL  )  
@@ -5161,8 +5098,12 @@
   UInt uiIdx = 0;
   Bool        bCheckMcpDv = false;   
-  TComDataCU* pcTmpCU     = NULL;
+  const TComDataCU* pcTmpCU     = NULL;
 
   //// ******* Get disparity from left block ******* /////
+#if NH_3D_FIX_TICKET_91
+    pcTmpCU = getPULeft(uiIdx, uiPartIdxLB);
+#else
   pcTmpCU = getPULeft(uiIdx, uiPartIdxLB, true, false);
+#endif
   bCheckMcpDv = true; 
   if ( xCheckSpatialNBDV( pcTmpCU, uiIdx, pDInfo, bCheckMcpDv, &cIDVInfo, DVFROM_LEFT
@@ -5199,5 +5140,5 @@
           pDInfo->m_aVIdxCan = cIDVInfo.m_aVIdxCan[iList][ curPos ];
 #if NH_3D_NBDV_REF
-#if H_3D_FCO_VSP_DONBDV_E0163
+#if H_3D_FCO
           TComPic* picDepth  = NULL;
 
@@ -5238,5 +5179,5 @@
 #if NH_3D_NBDV_REF
     TComPic* picDepth = NULL;
-#if H_3D_FCO_VSP_DONBDV_E0163
+#if H_3D_FCO
     picDepth  = getSlice()->getIvPic(true, getSlice()->getViewIndex() );
     if ( picDepth->getPicYuvRec() != NULL )  
@@ -5307,5 +5248,5 @@
 
 
-Bool TComDataCU::xCheckSpatialNBDV( TComDataCU* pcTmpCU, UInt uiIdx, DisInfo* pNbDvInfo, Bool bSearchForMvpDv, IDVInfo* paIDVInfo, UInt uiMvpDvPos
+Bool TComDataCU::xCheckSpatialNBDV( const TComDataCU* pcTmpCU, UInt uiIdx, DisInfo* pNbDvInfo, Bool bSearchForMvpDv, IDVInfo* paIDVInfo, UInt uiMvpDvPos
 #if NH_3D_NBDV_REF
 , Bool bDepthRefine 
@@ -5332,5 +5273,5 @@
           TComPic* picDepth = NULL;
           assert(getSlice()->getRefPic(eRefPicList, refId)->getPOC() == getSlice()->getPOC());            
-#if H_3D_FCO_VSP_DONBDV_E0163
+#if H_3D_FCO
           picDepth  = getSlice()->getIvPic(true, getSlice()->getViewIndex() );
           if ( picDepth->getPicYuvRec() != NULL )  
@@ -5466,11 +5407,7 @@
     }
 
-#if NH_3D_FIX_NBDV_COL
     // The picture pColCU->getSlice()->getRefPic(eColRefPicList, iColRefIdx) might not be in DPB anymore
     // So don't access it directly.
     iColRefViewIdx = pColCU->getSlice()->getVPS()->getViewOrderIdx( pColCU->getSlice()->getRefLayerId( eColRefPicList, iColRefIdx ) );       
-#else
-    iColRefViewIdx = pColCU->getSlice()->getRefPic(eColRefPicList, iColRefIdx)->getViewIndex();
-#endif
 
 
@@ -6065,5 +6002,5 @@
   Int depthRefViewIdx = pcCU->getDvInfo(partAddr).m_aVIdxCan;
   
-#if H_3D_FCO_VSP_DONBDV_E0163
+#if H_3D_FCO
   TComPic* pRefPicBaseDepth = 0;
   Bool     bIsCurrDepthCoded = false;
@@ -6100,5 +6037,5 @@
   pcCU->clipMv(cDv);
 
-#if H_3D_FCO_VSP_DONBDV_E0163
+#if H_3D_FCO
   if ( bIsCurrDepthCoded )
   {
Index: trunk/source/Lib/TLibCommon/TComDataCU.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComDataCU.h	(revision 1357)
+++ trunk/source/Lib/TLibCommon/TComDataCU.h	(revision 1386)
@@ -112,9 +112,9 @@
   UChar*         m_ucDISType;
 #endif
-  Char*          m_pePartSize;         ///< array of partition sizes
-  Char*          m_pePredMode;         ///< array of prediction modes
-  Char*          m_crossComponentPredictionAlpha[MAX_NUM_COMPONENT]; ///< array of cross-component prediction alpha values
+  SChar*          m_pePartSize;         ///< array of partition sizes
+  SChar*        m_pePredMode;                           ///< array of prediction modes
+  SChar*        m_crossComponentPredictionAlpha[MAX_NUM_COMPONENT]; ///< array of cross-component prediction alpha values
   Bool*          m_CUTransquantBypass;   ///< array of cu_transquant_bypass flags
-  Char*          m_phQP;               ///< array of QP values
+  SChar*        m_phQP;                                 ///< array of QP values
   UChar*         m_ChromaQpAdj;        ///< array of chroma QP adjustments (indexed). when value = 0, cu_chroma_qp_offset_flag=0; when value>0, indicates cu_chroma_qp_offset_flag=1 and cu_chroma_qp_offset_idx=value-1
   UInt           m_codedChromaQpAdj;
@@ -125,5 +125,5 @@
   TCoeff*        m_pcTrCoeff[MAX_NUM_COMPONENT];       ///< array of transform coefficient buffers (0->Y, 1->Cb, 2->Cr)
 #if ADAPTIVE_QP_SELECTION
-  TCoeff*        m_pcArlCoeff[MAX_NUM_COMPONENT];  // ARL coefficient buffer (0->Y, 1->Cb, 2->Cr)
+  TCoeff*       m_pcArlCoeff[MAX_NUM_COMPONENT];        ///< ARL coefficient buffer (0->Y, 1->Cb, 2->Cr)
   Bool           m_ArlCoeffIsAliasedAllocation;  ///< ARL coefficient buffer is an alias of the global buffer and must not be free()'d
 #endif
@@ -154,8 +154,8 @@
   Bool          m_bIsMergeAMP;
 #endif
-  UChar*        m_puhIntraDir[MAX_NUM_CHANNEL_TYPE]; // 0-> Luma, 1-> Chroma
+  UChar*        m_puhIntraDir[MAX_NUM_CHANNEL_TYPE];
   UChar*        m_puhInterDir;        ///< array of inter directions
-  Char*         m_apiMVPIdx[NUM_REF_PIC_LIST_01];       ///< array of motion vector predictor candidates
-  Char*         m_apiMVPNum[NUM_REF_PIC_LIST_01];       ///< array of number of possible motion vectors predictors
+  SChar*        m_apiMVPIdx[NUM_REF_PIC_LIST_01];       ///< array of motion vector predictor candidates
+  SChar*        m_apiMVPNum[NUM_REF_PIC_LIST_01];       ///< array of number of possible motion vectors predictors
   Bool*         m_pbIPCMFlag;         ///< array of intra_pcm flags
 #if NH_3D_NBDV
@@ -163,5 +163,5 @@
 #endif
 #if NH_3D_VSP
-  Char*         m_piVSPFlag;          ///< array of VSP flags to indicate whehter a block uses VSP or not  ///< 0: non-VSP; 1: VSP
+  SChar*        m_piVSPFlag;          ///< array of VSP flags to indicate whehter a block uses VSP or not  ///< 0: non-VSP; 1: VSP
 #endif
 #if NH_3D_SPIVMP
@@ -208,5 +208,5 @@
   UInt          m_uiTotalBits;        ///< sum of partition bits
   UInt          m_uiTotalBins;        ///< sum of partition bins
-  Char          m_codedQP;
+  SChar         m_codedQP;
 #if NH_3D_MLC
   DisInfo         m_cDefaultDisInfo;    ///< Default disparity information for initializing
@@ -219,7 +219,8 @@
 protected:
 
-  /// add possible motion vector predictor candidates
-  Bool          xAddMVPCand           ( AMVPInfo* pInfo, RefPicList eRefPicList, Int iRefIdx, UInt uiPartUnitIdx, MVP_DIR eDir );
-  Bool          xAddMVPCandOrder      ( AMVPInfo* pInfo, RefPicList eRefPicList, Int iRefIdx, UInt uiPartUnitIdx, MVP_DIR eDir );
+  /// adds a single possible motion vector predictor candidate
+  Bool          xAddMVPCandUnscaled           ( AMVPInfo &info, const RefPicList eRefPicList, const Int iRefIdx, const UInt uiPartUnitIdx, const MVP_DIR eDir ) const;
+  Bool          xAddMVPCandWithScaling        ( AMVPInfo &info, const RefPicList eRefPicList, const Int iRefIdx, const UInt uiPartUnitIdx, const MVP_DIR eDir ) const;
+
 #if NH_3D_VSP
   Bool          xAddVspCand( Int mrgCandIdx, DisInfo* pDInfo, Int& iCount);
@@ -229,18 +230,17 @@
 #endif
 
-  Void          deriveRightBottomIdx        ( UInt uiPartIdx, UInt& ruiPartIdxRB );
-  Bool          xGetColMVP( RefPicList eRefPicList, Int ctuRsAddr, Int uiPartUnitIdx, TComMv& rcMv, Int& riRefIdx
+  Void          deriveRightBottomIdx          ( UInt uiPartIdx, UInt& ruiPartIdxRB ) const;
+
 #if NH_3D_TMVP
-  ,  Bool bMRG = true
-#endif
- );
-
+  Bool          xGetColMVP                    ( const RefPicList eRefPicList, const Int ctuRsAddr, const Int partUnitIdx, TComMv& rcMv, Int& refIdx, Bool bMRG = true  ) const;
+#else
+  Bool          xGetColMVP                    ( const RefPicList eRefPicList, const Int ctuRsAddr, const Int partUnitIdx, TComMv& rcMv, const Int refIdx ) const;
+#endif
 
   /// compute scaling factor from POC difference
 #if !NH_3D_ARP
-  Int           xGetDistScaleFactor   ( Int iCurrPOC, Int iCurrRefPOC, Int iColPOC, Int iColRefPOC );
-#endif
-
-  Void xDeriveCenterIdx( UInt uiPartIdx, UInt& ruiPartIdxCenter );
+  static Int    xGetDistScaleFactor           ( Int iCurrPOC, Int iCurrRefPOC, Int iColPOC, Int iColRefPOC );
+#endif
+  Void          xDeriveCenterIdx              ( UInt uiPartIdx, UInt& ruiPartIdxCenter ) const;
 
 #if NH_3D_VSP
@@ -249,4 +249,9 @@
 
 public:
+
+#if NH_3D_ARP
+  static Int    xGetDistScaleFactor           ( Int iCurrPOC, Int iCurrRefPOC, Int iColPOC, Int iColRefPOC );
+#endif
+
   TComDataCU();
   virtual ~TComDataCU();
@@ -255,8 +260,4 @@
   // create / destroy / initialize / copy
   // -------------------------------------------------------------------------------------------------------------------
-#if NH_3D_ARP
-  /// compute scaling factor from POC difference
-  Int           xGetDistScaleFactor   ( Int iCurrPOC, Int iCurrRefPOC, Int iColPOC, Int iColRefPOC );
-#endif 
   Void          create                ( ChromaFormat chromaFormatIDC, UInt uiNumPartition, UInt uiWidth, UInt uiHeight, Bool bDecSubCu, Int unitSize
 #if ADAPTIVE_QP_SELECTION
@@ -275,9 +276,9 @@
 
   Void          copySubCU             ( TComDataCU* pcCU, UInt uiPartUnitIdx );
-  Void          copyInterPredInfoFrom ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefPicList 
 #if NH_3D_NBDV
-  , Bool bNBDV = false
-#endif
-);
+    Void          copyInterPredInfoFrom ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefPicList, Bool bNBDV = false );
+#else
+  Void          copyInterPredInfoFrom ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefPicList );
+#endif
   Void          copyPartFrom          ( TComDataCU* pcCU, UInt uiPartUnitIdx, UInt uiDepth );
 
@@ -315,6 +316,6 @@
   // -------------------------------------------------------------------------------------------------------------------
 
-  Char*         getPartitionSize      ()                        { return m_pePartSize;        }
-  PartSize      getPartitionSize      ( UInt uiIdx )            { return static_cast<PartSize>( m_pePartSize[uiIdx] ); }
+  SChar*        getPartitionSize              ( )                                                          { return m_pePartSize;                       }
+  PartSize      getPartitionSize              ( UInt uiIdx ) const                                         { return static_cast<PartSize>( m_pePartSize[uiIdx] ); }
   Void          setPartitionSize      ( UInt uiIdx, PartSize uh){ m_pePartSize[uiIdx] = uh;   }
   Void          setPartSizeSubParts   ( PartSize eMode, UInt uiAbsPartIdx, UInt uiDepth );
@@ -326,5 +327,5 @@
   
   Bool*         getSkipFlag            ()                        { return m_skipFlag;          }
-  Bool          getSkipFlag            (UInt idx)                { return m_skipFlag[idx];     }
+  Bool          getSkipFlag                   ( UInt idx ) const                                           { return m_skipFlag[idx];                    }
   Void          setSkipFlag           ( UInt idx, Bool skip)     { m_skipFlag[idx] = skip;   }
   Void          setSkipFlagSubParts   ( Bool skip, UInt absPartIdx, UInt depth );
@@ -340,12 +341,12 @@
   Void         setDISTypeSubParts    ( UChar ucDISType, UInt uiAbsPartIdx, UInt uiDepth );
 #endif
-  Char*         getPredictionMode     ()                        { return m_pePredMode;        }
-  PredMode      getPredictionMode     ( UInt uiIdx )            { return static_cast<PredMode>( m_pePredMode[uiIdx] ); }
+  SChar*        getPredictionMode             ( )                                                          { return m_pePredMode;                       }
+  PredMode      getPredictionMode             ( UInt uiIdx ) const                                         { return static_cast<PredMode>( m_pePredMode[uiIdx] ); }
   Void          setPredictionMode     ( UInt uiIdx, PredMode uh){ m_pePredMode[uiIdx] = uh;   }
   Void          setPredModeSubParts   ( PredMode eMode, UInt uiAbsPartIdx, UInt uiDepth );
 
 #if NH_3D_DBBP
-  Bool*         getDBBPFlag           ()                        { return m_pbDBBPFlag;               }
-  Bool          getDBBPFlag           ( UInt uiIdx )            { return m_pbDBBPFlag[uiIdx];        }
+  Bool*         getDBBPFlag           ()                        const { return m_pbDBBPFlag;               }
+  Bool          getDBBPFlag           ( UInt uiIdx )            const { return m_pbDBBPFlag[uiIdx];        }
   Void          setDBBPFlag           ( UInt uiIdx, Bool b )    { m_pbDBBPFlag[uiIdx] = b;           }
   Void          setDBBPFlagSubParts   ( Bool bDBBPFlag, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
@@ -353,29 +354,29 @@
 #endif
 
-  Char*         getCrossComponentPredictionAlpha( ComponentID compID )             { return m_crossComponentPredictionAlpha[compID];         }
-  Char          getCrossComponentPredictionAlpha( UInt uiIdx, ComponentID compID ) { return m_crossComponentPredictionAlpha[compID][uiIdx];  }
+  SChar*        getCrossComponentPredictionAlpha( ComponentID compID )                                     { return m_crossComponentPredictionAlpha[compID];        }
+  SChar         getCrossComponentPredictionAlpha( UInt uiIdx, ComponentID compID )                         { return m_crossComponentPredictionAlpha[compID][uiIdx]; }
 
   Bool*         getCUTransquantBypass ()                        { return m_CUTransquantBypass;        }
-  Bool          getCUTransquantBypass( UInt uiIdx )             { return m_CUTransquantBypass[uiIdx]; }
+  Bool          getCUTransquantBypass         ( UInt uiIdx ) const                                         { return m_CUTransquantBypass[uiIdx];        }
 
   UChar*        getWidth              ()                        { return m_puhWidth;          }
-  UChar         getWidth              ( UInt uiIdx )            { return m_puhWidth[uiIdx];   }
+  UChar         getWidth                      ( UInt uiIdx ) const                                         { return m_puhWidth[uiIdx];                  }
   Void          setWidth              ( UInt uiIdx, UChar  uh ) { m_puhWidth[uiIdx] = uh;     }
 
   UChar*        getHeight             ()                        { return m_puhHeight;         }
-  UChar         getHeight             ( UInt uiIdx )            { return m_puhHeight[uiIdx];  }
+  UChar         getHeight                     ( UInt uiIdx ) const                                         { return m_puhHeight[uiIdx];                 }
   Void          setHeight             ( UInt uiIdx, UChar  uh ) { m_puhHeight[uiIdx] = uh;    }
 
   Void          setSizeSubParts       ( UInt uiWidth, UInt uiHeight, UInt uiAbsPartIdx, UInt uiDepth );
 
-  Char*         getQP                 ()                        { return m_phQP;              }
-  Char          getQP                 ( UInt uiIdx ) const      { return m_phQP[uiIdx];       }
-  Void          setQP                 ( UInt uiIdx, Char value ){ m_phQP[uiIdx] =  value;     }
+  SChar*        getQP                         ( )                                                          { return m_phQP;                             }
+  SChar         getQP                         ( UInt uiIdx ) const                                         { return m_phQP[uiIdx];                      }
+  Void          setQP                         ( UInt uiIdx, SChar value )                                  { m_phQP[uiIdx] =  value;                    }
   Void          setQPSubParts         ( Int qp,   UInt uiAbsPartIdx, UInt uiDepth );
-  Int           getLastValidPartIdx   ( Int iAbsPartIdx );
-  Char          getLastCodedQP        ( UInt uiAbsPartIdx );
+  Int           getLastValidPartIdx           ( Int iAbsPartIdx ) const;
+  SChar         getLastCodedQP                ( UInt uiAbsPartIdx ) const;
   Void          setQPSubCUs           ( Int qp, UInt absPartIdx, UInt depth, Bool &foundNonZeroCbf );
-  Void          setCodedQP            ( Char qp )               { m_codedQP = qp;             }
-  Char          getCodedQP            ()                        { return m_codedQP;           }
+  Void          setCodedQP                    ( SChar qp )                                                 { m_codedQP = qp;                            }
+  SChar         getCodedQP                    ( ) const                                                    { return m_codedQP;                          }
 
   UChar*        getChromaQpAdj        ()                        { return m_ChromaQpAdj;       } ///< array of chroma QP adjustments (indexed). when value = 0, cu_chroma_qp_offset_flag=0; when value>0, indicates cu_chroma_qp_offset_flag=1 and cu_chroma_qp_offset_idx=value-1
@@ -383,30 +384,31 @@
   Void          setChromaQpAdj        (Int idx, UChar val)      { m_ChromaQpAdj[idx] = val;   } ///< When val = 0,   cu_chroma_qp_offset_flag=0; when val>0,   indicates cu_chroma_qp_offset_flag=1 and cu_chroma_qp_offset_idx=val-1
   Void          setChromaQpAdjSubParts( UChar val, Int absPartIdx, Int depth );
-  Void          setCodedChromaQpAdj   ( Char qp )               { m_codedChromaQpAdj = qp;    }
-  Char          getCodedChromaQpAdj   ()                        { return m_codedChromaQpAdj;  }
-
-  Bool          isLosslessCoded       ( UInt absPartIdx );
+  Void          setCodedChromaQpAdj           ( SChar qp )                                                 { m_codedChromaQpAdj = qp;                   }
+  SChar         getCodedChromaQpAdj           ( ) const                                                    { return m_codedChromaQpAdj;                 }
+
+  Bool          isLosslessCoded               ( UInt absPartIdx ) const;
 
   UChar*        getTransformIdx       ()                        { return m_puhTrIdx;          }
-  UChar         getTransformIdx       ( UInt uiIdx )            { return m_puhTrIdx[uiIdx];   }
+  UChar         getTransformIdx               ( UInt uiIdx ) const                                         { return m_puhTrIdx[uiIdx];                  }
   Void          setTrIdxSubParts      ( UInt uiTrIdx, UInt uiAbsPartIdx, UInt uiDepth );
 
   UChar*        getTransformSkip      ( ComponentID compID )    { return m_puhTransformSkip[compID];}
-  UChar         getTransformSkip      ( UInt uiIdx, ComponentID compID)    { return m_puhTransformSkip[compID][uiIdx];}
+  UChar         getTransformSkip              ( UInt uiIdx, ComponentID compID ) const                     { return m_puhTransformSkip[compID][uiIdx];  }
   Void          setTransformSkipSubParts  ( UInt useTransformSkip, ComponentID compID, UInt uiAbsPartIdx, UInt uiDepth);
   Void          setTransformSkipSubParts  ( const UInt useTransformSkip[MAX_NUM_COMPONENT], UInt uiAbsPartIdx, UInt uiDepth );
 
   UChar*        getExplicitRdpcmMode      ( ComponentID component ) { return m_explicitRdpcmMode[component]; }
-  UChar         getExplicitRdpcmMode      ( ComponentID component, UInt partIdx ) {return m_explicitRdpcmMode[component][partIdx]; }
+  UChar         getExplicitRdpcmMode          ( ComponentID component, UInt partIdx ) const                { return m_explicitRdpcmMode[component][partIdx]; }
   Void          setExplicitRdpcmModePartRange ( UInt rdpcmMode, ComponentID compID, UInt uiAbsPartIdx, UInt uiCoveredPartIdxes );
 
-  Bool          isRDPCMEnabled         ( UInt uiAbsPartIdx )  { return getSlice()->getSPS()->getSpsRangeExtension().getRdpcmEnabledFlag(isIntra(uiAbsPartIdx) ? RDPCM_SIGNAL_IMPLICIT : RDPCM_SIGNAL_EXPLICIT); }
-
-  Void          setCrossComponentPredictionAlphaPartRange    ( Char alphaValue, ComponentID compID, UInt uiAbsPartIdx, UInt uiCoveredPartIdxes );
+  Bool          isRDPCMEnabled                ( UInt uiAbsPartIdx ) const                                  { return getSlice()->getSPS()->getSpsRangeExtension().getRdpcmEnabledFlag(isIntra(uiAbsPartIdx) ? RDPCM_SIGNAL_IMPLICIT : RDPCM_SIGNAL_EXPLICIT); }
+
+  Void          setCrossComponentPredictionAlphaPartRange ( SChar alphaValue, ComponentID compID, UInt uiAbsPartIdx, UInt uiCoveredPartIdxes );
   Void          setTransformSkipPartRange                    ( UInt useTransformSkip, ComponentID compID, UInt uiAbsPartIdx, UInt uiCoveredPartIdxes );
 
-  UInt          getQuadtreeTULog2MinSizeInCU( UInt uiIdx );
+  UInt          getQuadtreeTULog2MinSizeInCU  ( UInt uiIdx ) const;
 
   TComCUMvField* getCUMvField         ( RefPicList e )          { return  &m_acCUMvField[e];  }
+  const TComCUMvField* getCUMvField           ( RefPicList e ) const                                       { return &m_acCUMvField[e];                  }
 
   TCoeff*       getCoeff              (ComponentID component)   { return m_pcTrCoeff[component]; }
@@ -417,10 +419,10 @@
   Pel*          getPCMSample          ( ComponentID component ) { return m_pcIPCMSample[component]; }
 
-  UChar         getCbf    ( UInt uiIdx, ComponentID eType )                  { return m_puhCbf[eType][uiIdx];  }
+  UChar         getCbf                        ( UInt uiIdx, ComponentID eType ) const                      { return m_puhCbf[eType][uiIdx];             }
   UChar*        getCbf    ( ComponentID eType )                              { return m_puhCbf[eType];         }
-  UChar         getCbf    ( UInt uiIdx, ComponentID eType, UInt uiTrDepth )  { return ( ( getCbf( uiIdx, eType ) >> uiTrDepth ) & 0x1 ); }
+  UChar         getCbf                        ( UInt uiIdx, ComponentID eType, UInt uiTrDepth ) const      { return ( ( getCbf( uiIdx, eType ) >> uiTrDepth ) & 0x1 ); }
   Void          setCbf    ( UInt uiIdx, ComponentID eType, UChar uh )        { m_puhCbf[eType][uiIdx] = uh;    }
   Void          clearCbf  ( UInt uiIdx, ComponentID eType, UInt uiNumParts );
-  UChar         getQtRootCbf          ( UInt uiIdx );
+  UChar         getQtRootCbf                  ( UInt uiIdx ) const;
 
   Void          setCbfSubParts        ( const UInt uiCbf[MAX_NUM_COMPONENT],  UInt uiAbsPartIdx, UInt uiDepth           );
@@ -436,10 +438,10 @@
 
   Bool*         getMergeFlag          ()                        { return m_pbMergeFlag;               }
-  Bool          getMergeFlag          ( UInt uiIdx )            { return m_pbMergeFlag[uiIdx];        }
+  Bool          getMergeFlag                  ( UInt uiIdx ) const                                         { return m_pbMergeFlag[uiIdx];               }
   Void          setMergeFlag          ( UInt uiIdx, Bool b )    { m_pbMergeFlag[uiIdx] = b;           }
   Void          setMergeFlagSubParts  ( Bool bMergeFlag, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
 
   UChar*        getMergeIndex         ()                        { return m_puhMergeIndex;                         }
-  UChar         getMergeIndex         ( UInt uiIdx )            { return m_puhMergeIndex[uiIdx];                  }
+  UChar         getMergeIndex                 ( UInt uiIdx ) const                                         { return m_puhMergeIndex[uiIdx];             }
   Void          setMergeIndex         ( UInt uiIdx, UInt uiMergeIndex ) { m_puhMergeIndex[uiIdx] = uiMergeIndex;  }
   Void          setMergeIndexSubParts ( UInt uiMergeIndex, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
@@ -453,5 +455,5 @@
 #if AMP_MRG
   Void          setMergeAMP( Bool b )      { m_bIsMergeAMP = b; }
-  Bool          getMergeAMP( )             { return m_bIsMergeAMP; }
+  Bool          getMergeAMP                   ( ) const                                                    { return m_bIsMergeAMP;                      }
 #endif
 
@@ -465,9 +467,9 @@
 
   UChar*        getInterDir           ()                        { return m_puhInterDir;               }
-  UChar         getInterDir           ( UInt uiIdx )            { return m_puhInterDir[uiIdx];        }
+  UChar         getInterDir                   ( UInt uiIdx ) const                                         { return m_puhInterDir[uiIdx];               }
   Void          setInterDir           ( UInt uiIdx, UChar  uh ) { m_puhInterDir[uiIdx] = uh;          }
   Void          setInterDirSubParts   ( UInt uiDir,  UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
   Bool*         getIPCMFlag           ()                        { return m_pbIPCMFlag;               }
-  Bool          getIPCMFlag           (UInt uiIdx )             { return m_pbIPCMFlag[uiIdx];        }
+  Bool          getIPCMFlag                   ( UInt uiIdx ) const                                         { return m_pbIPCMFlag[uiIdx];                }
   Void          setIPCMFlag           (UInt uiIdx, Bool b )     { m_pbIPCMFlag[uiIdx] = b;           }
   Void          setIPCMFlagSubParts   (Bool bIpcmFlag, UInt uiAbsPartIdx, UInt uiDepth);
@@ -482,5 +484,5 @@
 #if NH_3D_NBDV
   Void          xDeriveRightBottomNbIdx(Int &uiLCUIdxRBNb, Int &uiPartIdxRBNb );
-  Bool          xCheckSpatialNBDV (TComDataCU* pcTmpCU, UInt uiIdx, DisInfo* pNbDvInfo, Bool bSearchForMvpDv, IDVInfo* paMvpDvInfo,
+  Bool          xCheckSpatialNBDV (const TComDataCU* pcTmpCU, UInt uiIdx, DisInfo* pNbDvInfo, Bool bSearchForMvpDv, IDVInfo* paMvpDvInfo,
                                    UInt uiMvpDvPos
 #if NH_3D_NBDV_REF
@@ -525,6 +527,6 @@
 #endif
 #if NH_3D_ARP
-  UChar*        getARPW            ()                        { return m_puhARPW;               }
-  UChar         getARPW            ( UInt uiIdx )            { return m_puhARPW[uiIdx];        }
+  UChar*        getARPW            ()              const          { return m_puhARPW;               }
+  UChar         getARPW            ( UInt uiIdx )  const          { return m_puhARPW[uiIdx];        }
   Void          setARPW            ( UInt uiIdx, UChar w )   { m_puhARPW[uiIdx] = w;           }
   Void          setARPWSubParts    ( UChar w, UInt uiAbsPartIdx, UInt uiDepth );
@@ -536,7 +538,7 @@
   Void          setICFlagSubParts  ( Bool bICFlag,  UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
   Bool          isICFlagRequired   ( UInt uiAbsPartIdx );
-  Void          getPartIndexAndSize( UInt uiPartIdx, UInt& ruiPartAddr, Int& riWidth, Int& riHeight, UInt uiAbsPartIdx = 0, Bool bLCU = false);
+  Void          getPartIndexAndSize( UInt uiPartIdx, UInt& ruiPartAddr, Int& riWidth, Int& riHeight, UInt uiAbsPartIdx = 0, Bool bLCU = false) const;
 #elif NH_3D_VSP
-  Void          getPartIndexAndSize( UInt uiPartIdx, UInt& ruiPartAddr, Int& riWidth, Int& riHeight, UInt uiAbsPartIdx = 0, Bool bLCU = false);
+  Void          getPartIndexAndSize( UInt uiPartIdx, UInt& ruiPartAddr, Int& riWidth, Int& riHeight, UInt uiAbsPartIdx = 0, Bool bLCU = false) const;
 #else
   // -------------------------------------------------------------------------------------------------------------------
@@ -544,8 +546,8 @@
   // -------------------------------------------------------------------------------------------------------------------
 
-  Void          getPartIndexAndSize   ( UInt uiPartIdx, UInt& ruiPartAddr, Int& riWidth, Int& riHeight ); // This is for use by a leaf/sub CU object only, with no additional AbsPartIdx
-#endif
-  UChar         getNumPartitions      ( const UInt uiAbsPartIdx = 0 );
-  Bool          isFirstAbsZorderIdxInDepth (UInt uiAbsPartIdx, UInt uiDepth);
+  Void          getPartIndexAndSize           ( UInt uiPartIdx, UInt& ruiPartAddr, Int& riWidth, Int& riHeight ) const; // This is for use by a leaf/sub CU object only, with no additional AbsPartIdx
+#endif
+  UChar         getNumPartitions              ( const UInt uiAbsPartIdx = 0 ) const;
+  Bool          isFirstAbsZorderIdxInDepth    ( UInt uiAbsPartIdx, UInt uiDepth ) const;
 
 #if NH_3D_DMM
@@ -575,28 +577,29 @@
   // -------------------------------------------------------------------------------------------------------------------
 
-  Void          getMvField            ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefPicList, TComMvField& rcMvField );
-
-  Void          fillMvpCand           ( UInt uiPartIdx, UInt uiPartAddr, RefPicList eRefPicList, Int iRefIdx, AMVPInfo* pInfo );
-  Bool          isDiffMER             ( Int xN, Int yN, Int xP, Int yP);
-  Void          getPartPosition       ( UInt partIdx, Int& xP, Int& yP, Int& nPSW, Int& nPSH);
+  static Void   getMvField                    ( const TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefPicList, TComMvField& rcMvField );
+
+  Void          fillMvpCand                   ( const UInt uiPartIdx, const UInt uiPartAddr, const RefPicList eRefPicList, const Int iRefIdx, AMVPInfo* pInfo ) const;
+  Bool          isDiffMER                     ( Int xN, Int yN, Int xP, Int yP ) const;
+  Void          getPartPosition               ( UInt partIdx, Int& xP, Int& yP, Int& nPSW, Int& nPSH ) const;
 
   Void          setMVPIdx             ( RefPicList eRefPicList, UInt uiIdx, Int iMVPIdx)  { m_apiMVPIdx[eRefPicList][uiIdx] = iMVPIdx;  }
-  Int           getMVPIdx             ( RefPicList eRefPicList, UInt uiIdx)               { return m_apiMVPIdx[eRefPicList][uiIdx];     }
-  Char*         getMVPIdx             ( RefPicList eRefPicList )                          { return m_apiMVPIdx[eRefPicList];            }
+  Int           getMVPIdx                     ( RefPicList eRefPicList, UInt uiIdx) const                  { return m_apiMVPIdx[eRefPicList][uiIdx];    }
+  SChar*        getMVPIdx                     ( RefPicList eRefPicList )                                   { return m_apiMVPIdx[eRefPicList];           }
 
   Void          setMVPNum             ( RefPicList eRefPicList, UInt uiIdx, Int iMVPNum ) { m_apiMVPNum[eRefPicList][uiIdx] = iMVPNum;  }
-  Int           getMVPNum             ( RefPicList eRefPicList, UInt uiIdx )              { return m_apiMVPNum[eRefPicList][uiIdx];     }
-  Char*         getMVPNum             ( RefPicList eRefPicList )                          { return m_apiMVPNum[eRefPicList];            }
+  Int           getMVPNum                     ( RefPicList eRefPicList, UInt uiIdx ) const                 { return m_apiMVPNum[eRefPicList][uiIdx];    }
+  SChar*        getMVPNum                     ( RefPicList eRefPicList )                                   { return m_apiMVPNum[eRefPicList];           }
 
   Void          setMVPIdxSubParts     ( Int iMVPIdx, RefPicList eRefPicList, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
   Void          setMVPNumSubParts     ( Int iMVPNum, RefPicList eRefPicList, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
 
-  Void          clipMv                ( TComMv&     rcMv     );
+  Void          clipMv                        ( TComMv&     rcMv     ) const;
+
 #if NH_MV
   Void          checkMvVertRest (TComMv&  rcMv,  RefPicList eRefPicList, int iRefIdx );
 #endif
-  Void          getMvPredLeft         ( TComMv&     rcMvPred )   { rcMvPred = m_cMvFieldA.getMv(); }
-  Void          getMvPredAbove        ( TComMv&     rcMvPred )   { rcMvPred = m_cMvFieldB.getMv(); }
-  Void          getMvPredAboveRight   ( TComMv&     rcMvPred )   { rcMvPred = m_cMvFieldC.getMv(); }
+  Void          getMvPredLeft                 ( TComMv&     rcMvPred ) const                               { rcMvPred = m_cMvFieldA.getMv();            }
+  Void          getMvPredAbove                ( TComMv&     rcMvPred ) const                               { rcMvPred = m_cMvFieldB.getMv();            }
+  Void          getMvPredAboveRight           ( TComMv&     rcMvPred ) const                               { rcMvPred = m_cMvFieldC.getMv();            }
 #if NH_3D
   Void          compressMV            ( Int scale );
@@ -618,34 +621,38 @@
   Bool          CUIsFromSameSliceAndTile    ( const TComDataCU *pCU /* Can be NULL */) const;
   Bool          CUIsFromSameSliceTileAndWavefrontRow( const TComDataCU *pCU /* Can be NULL */) const;
-  Bool          isLastSubCUOfCtu(const UInt absPartIdx);
-
-
-  TComDataCU*   getPULeft                   ( UInt&  uiLPartUnitIdx,
+  Bool          isLastSubCUOfCtu              ( const UInt absPartIdx ) const;
+
+
+  const TComDataCU*   getPULeft               ( UInt& uiLPartUnitIdx,
                                               UInt uiCurrPartUnitIdx,
                                               Bool bEnforceSliceRestriction=true,
-                                              Bool bEnforceTileRestriction=true );
-  TComDataCU*   getPUAbove                  ( UInt&  uiAPartUnitIdx,
+                                                Bool  bEnforceTileRestriction=true ) const;
+
+  const TComDataCU*   getPUAbove              ( UInt& uiAPartUnitIdx,
                                               UInt uiCurrPartUnitIdx,
                                               Bool bEnforceSliceRestriction=true,
                                               Bool planarAtCTUBoundary = false,
-                                              Bool bEnforceTileRestriction=true );
-  TComDataCU*   getPUAboveLeft              ( UInt&  uiALPartUnitIdx, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction=true );
-
-  TComDataCU*   getQpMinCuLeft              ( UInt&  uiLPartUnitIdx , UInt uiCurrAbsIdxInCtu );
-  TComDataCU*   getQpMinCuAbove             ( UInt&  uiAPartUnitIdx , UInt uiCurrAbsIdxInCtu );
-  Char          getRefQP                    ( UInt   uiCurrAbsIdxInCtu                       );
+                                                Bool  bEnforceTileRestriction=true ) const;
+
+  const TComDataCU*   getPUAboveLeft          ( UInt&  uiALPartUnitIdx, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction=true ) const;
+
+  const TComDataCU*   getQpMinCuLeft          ( UInt&  uiLPartUnitIdx,  UInt uiCurrAbsIdxInCtu ) const;
+  const TComDataCU*   getQpMinCuAbove         ( UInt&  uiAPartUnitIdx,  UInt uiCurrAbsIdxInCtu ) const;
 
   /// returns CU and part index of the PU above the top row of the current uiCurrPartUnitIdx of the CU, at a horizontal offset (to the right) of uiPartUnitOffset (in parts)
-  TComDataCU*   getPUAboveRight             ( UInt&  uiARPartUnitIdx, UInt uiCurrPartUnitIdx, UInt uiPartUnitOffset = 1, Bool bEnforceSliceRestriction=true );
+  const TComDataCU*   getPUAboveRight         ( UInt&  uiARPartUnitIdx, UInt uiCurrPartUnitIdx, UInt uiPartUnitOffset = 1, Bool bEnforceSliceRestriction=true ) const;
   /// returns CU and part index of the PU left of the lefthand column of the current uiCurrPartUnitIdx of the CU, at a vertical offset (below) of uiPartUnitOffset (in parts)
-  TComDataCU*   getPUBelowLeft              ( UInt&  uiBLPartUnitIdx, UInt uiCurrPartUnitIdx, UInt uiPartUnitOffset = 1, Bool bEnforceSliceRestriction=true );
-
-  Void          deriveLeftRightTopIdx       ( UInt uiPartIdx, UInt& ruiPartIdxLT, UInt& ruiPartIdxRT );
-  Void          deriveLeftBottomIdx         ( UInt uiPartIdx, UInt& ruiPartIdxLB );
-
-  Bool          hasEqualMotion              ( UInt uiAbsPartIdx, TComDataCU* pcCandCU, UInt uiCandAbsPartIdx );
+  const TComDataCU*   getPUBelowLeft          ( UInt&  uiBLPartUnitIdx, UInt uiCurrPartUnitIdx, UInt uiPartUnitOffset = 1, Bool bEnforceSliceRestriction=true ) const;
+
+  SChar         getRefQP                      ( UInt uiCurrAbsIdxInCtu ) const;
+
+  Void          deriveLeftRightTopIdx         ( UInt uiPartIdx, UInt& ruiPartIdxLT, UInt& ruiPartIdxRT ) const;
+  Void          deriveLeftBottomIdx           ( UInt uiPartIdx, UInt& ruiPartIdxLB ) const;
+
 #if NH_3D
   Bool          hasEqualMotion              ( Int dirA, const TComMvField* mvFieldA,  Int dirB, const TComMvField* mvFieldB  );
 #endif
+  Bool          hasEqualMotion                ( UInt uiAbsPartIdx, const TComDataCU* pcCandCU, UInt uiCandAbsPartIdx ) const;
+
 #if NH_3D_MLC
   Bool          getAvailableFlagA1() { return m_bAvailableFlagA1;   }
@@ -670,23 +677,26 @@
   , Int& numValidMergeCand, Int mrgCandIdx = -1 );
 #endif
+#if NH_3D
   Void          getInterMergeCandidates       ( UInt uiAbsPartIdx, UInt uiPUIdx, TComMvField* pcMFieldNeighbours, UChar* puhInterDirNeighbours, Int& numValidMergeCand, Int mrgCandIdx = -1 );
+#else
+  Void          getInterMergeCandidates       ( UInt uiAbsPartIdx, UInt uiPUIdx, TComMvField* pcMFieldNeighbours, UChar* puhInterDirNeighbours, Int& numValidMergeCand, Int mrgCandIdx = -1 ) const;
+#endif
 
 #if NH_3D_VSP
 #if NH_3D_SPIVMP
-  Bool*         getSPIVMPFlag        ()                        { return m_pbSPIVMPFlag;          }
-  Bool          getSPIVMPFlag        ( UInt uiIdx )            { return m_pbSPIVMPFlag[uiIdx];   }
+  Bool*         getSPIVMPFlag        ()                        const { return m_pbSPIVMPFlag;          }
+  Bool          getSPIVMPFlag        ( UInt uiIdx )            const { return m_pbSPIVMPFlag[uiIdx];   }
   Void          setSPIVMPFlag        ( UInt uiIdx, Bool n )     { m_pbSPIVMPFlag[uiIdx] = n;      }
   Void          setSPIVMPFlagSubParts( Bool bSPIVMPFlag, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
 #endif
 
-  Char*         getVSPFlag        ()                        { return m_piVSPFlag;          }
-  Char          getVSPFlag        ( UInt uiIdx )            { return m_piVSPFlag[uiIdx];   }
+  SChar*        getVSPFlag        ()                        const { return m_piVSPFlag;          }
+  SChar         getVSPFlag        ( UInt uiIdx )            const { return m_piVSPFlag[uiIdx];   }
   Void          setVSPFlag        ( UInt uiIdx, Int n )     { m_piVSPFlag[uiIdx] = n;      }
-  Void          setVSPFlagSubParts( Char iVSPFlag, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
+  Void          setVSPFlagSubParts( SChar iVSPFlag, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
   Void          setMvFieldPUForVSP    ( TComDataCU* cu, UInt partAddr, Int width, Int height, RefPicList refPicList, Int refIdx, Int &vspSize );
 #endif
-  Void          deriveLeftRightTopIdxGeneral  ( UInt uiAbsPartIdx, UInt uiPartIdx, UInt& ruiPartIdxLT, UInt& ruiPartIdxRT );
-  Void          deriveLeftBottomIdxGeneral    ( UInt uiAbsPartIdx, UInt uiPartIdx, UInt& ruiPartIdxLB );
-
+  Void          deriveLeftRightTopIdxGeneral  ( UInt uiAbsPartIdx, UInt uiPartIdx, UInt& ruiPartIdxLT, UInt& ruiPartIdxRT ) const;
+  Void          deriveLeftBottomIdxGeneral    ( UInt uiAbsPartIdx, UInt uiPartIdx, UInt& ruiPartIdxLB ) const;
   // -------------------------------------------------------------------------------------------------------------------
   // member functions for modes
@@ -695,6 +705,6 @@
   Bool          isIntra            ( UInt uiPartIdx )  const { return m_pePredMode[ uiPartIdx ] == MODE_INTRA;                                              }
   Bool          isInter            ( UInt uiPartIdx )  const { return m_pePredMode[ uiPartIdx ] == MODE_INTER;                                              }
-  Bool          isSkipped          ( UInt uiPartIdx );                                                     ///< returns true, if the partiton is skipped
-  Bool          isBipredRestriction( UInt puIdx );
+  Bool          isSkipped                     ( UInt uiPartIdx ) const; ///< returns true, if the partiton is skipped
+  Bool          isBipredRestriction           ( UInt puIdx     ) const;
 
   // -------------------------------------------------------------------------------------------------------------------
@@ -702,8 +712,8 @@
   // -------------------------------------------------------------------------------------------------------------------
 
-  UInt          getIntraSizeIdx                 ( UInt uiAbsPartIdx                                       );
-
-  Void          getAllowedChromaDir             ( UInt uiAbsPartIdx, UInt* uiModeList );
-  Void          getIntraDirPredictor            ( UInt uiAbsPartIdx, Int uiIntraDirPred[NUM_MOST_PROBABLE_MODES], const ComponentID compID, Int* piMode = NULL );
+  UInt          getIntraSizeIdx               ( UInt uiAbsPartIdx ) const;
+
+  Void          getAllowedChromaDir           ( UInt uiAbsPartIdx, UInt* uiModeList ) const;
+  Void          getIntraDirPredictor          ( UInt uiAbsPartIdx, Int uiIntraDirPred[NUM_MOST_PROBABLE_MODES], const ComponentID compID, Int* piMode = NULL ) const;
 
   // -------------------------------------------------------------------------------------------------------------------
@@ -711,9 +721,9 @@
   // -------------------------------------------------------------------------------------------------------------------
 
-  UInt          getCtxSplitFlag                 ( UInt   uiAbsPartIdx, UInt uiDepth                   );
-  UInt          getCtxQtCbf                     ( TComTU &rTu, const ChannelType chType );
-
-  UInt          getCtxSkipFlag                  ( UInt   uiAbsPartIdx                                 );
-  UInt          getCtxInterDir                  ( UInt   uiAbsPartIdx                                 );
+  UInt          getCtxSplitFlag               ( UInt   uiAbsPartIdx, UInt uiDepth     ) const;
+  UInt          getCtxQtCbf                   ( TComTU &rTu, const ChannelType chType ) const;
+
+  UInt          getCtxSkipFlag                ( UInt   uiAbsPartIdx ) const;
+  UInt          getCtxInterDir                ( UInt   uiAbsPartIdx ) const;
 #if NH_3D_ARP
   UInt          getCTXARPWFlag                  ( UInt   uiAbsPartIdx                                 );
Index: trunk/source/Lib/TLibCommon/TComInterpolationFilter.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComInterpolationFilter.cpp	(revision 1357)
+++ trunk/source/Lib/TLibCommon/TComInterpolationFilter.cpp	(revision 1386)
@@ -360,9 +360,10 @@
  * \param  bitDepth   Bit depth
  */
-Void TComInterpolationFilter::filterHor(const ComponentID compID, Pel *src, Int srcStride, Pel *dst, Int dstStride, Int width, Int height, Int frac, Bool isLast, const ChromaFormat fmt, const Int bitDepth 
-#if NH_3D_ARP
-    , Bool filterType
-#endif
-)
+#if NH_3D_ARP
+Void TComInterpolationFilter::filterHor(const ComponentID compID, Pel *src, Int srcStride, Pel *dst, Int dstStride, Int width, Int height, Int frac, Bool isLast, const ChromaFormat fmt, const Int bitDepth, Bool filterType )
+#else
+Void TComInterpolationFilter::filterHor(const ComponentID compID, Pel *src, Int srcStride, Pel *dst, Int dstStride, Int width, Int height, Int frac, Bool isLast, const ChromaFormat fmt, const Int bitDepth )
+#endif 
+
 {
   if ( frac == 0 )
@@ -423,9 +424,9 @@
  * \param  bitDepth   Bit depth
  */
-Void TComInterpolationFilter::filterVer(const ComponentID compID, Pel *src, Int srcStride, Pel *dst, Int dstStride, Int width, Int height, Int frac, Bool isFirst, Bool isLast, const ChromaFormat fmt, const Int bitDepth 
-#if NH_3D_ARP
-    , Bool filterType
-#endif
-)
+#if NH_3D_ARP
+Void TComInterpolationFilter::filterVer(const ComponentID compID, Pel *src, Int srcStride, Pel *dst, Int dstStride, Int width, Int height, Int frac, Bool isFirst, Bool isLast, const ChromaFormat fmt, const Int bitDepth, Bool filterType )
+#else
+Void TComInterpolationFilter::filterVer(const ComponentID compID, Pel *src, Int srcStride, Pel *dst, Int dstStride, Int width, Int height, Int frac, Bool isFirst, Bool isLast, const ChromaFormat fmt, const Int bitDepth )
+#endif
 {
   if ( frac == 0 )
Index: trunk/source/Lib/TLibCommon/TComInterpolationFilter.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComInterpolationFilter.h	(revision 1357)
+++ trunk/source/Lib/TLibCommon/TComInterpolationFilter.h	(revision 1386)
@@ -82,14 +82,15 @@
   ~TComInterpolationFilter() {}
 
-  Void filterHor(const ComponentID compID, Pel *src, Int srcStride, Pel *dst, Int dstStride, Int width, Int height, Int frac,               Bool isLast, const ChromaFormat fmt, const Int bitDepth 
 #if NH_3D_ARP
-    , Bool filterType = false
+  Void filterHor(const ComponentID compID, Pel *src, Int srcStride, Pel *dst, Int dstStride, Int width, Int height, Int frac,               Bool isLast, const ChromaFormat fmt, const Int bitDepth , Bool filterType = false );
+#else
+  Void filterHor(const ComponentID compID, Pel *src, Int srcStride, Pel *dst, Int dstStride, Int width, Int height, Int frac,               Bool isLast, const ChromaFormat fmt, const Int bitDepth );
 #endif
-);
-  Void filterVer(const ComponentID compID, Pel *src, Int srcStride, Pel *dst, Int dstStride, Int width, Int height, Int frac, Bool isFirst, Bool isLast, const ChromaFormat fmt, const Int bitDepth 
+
 #if NH_3D_ARP
-    , Bool filterType = false
+  Void filterVer(const ComponentID compID, Pel *src, Int srcStride, Pel *dst, Int dstStride, Int width, Int height, Int frac,               Bool isFirst, Bool isLast, const ChromaFormat fmt, const Int bitDepth , Bool filterType = false );
+#else
+  Void filterVer(const ComponentID compID, Pel *src, Int srcStride, Pel *dst, Int dstStride, Int width, Int height, Int frac,               Bool isFirst, Bool isLast, const ChromaFormat fmt, const Int bitDepth );
 #endif
-);
 };
 
Index: trunk/source/Lib/TLibCommon/TComLoopFilter.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComLoopFilter.cpp	(revision 1357)
+++ trunk/source/Lib/TLibCommon/TComLoopFilter.cpp	(revision 1386)
@@ -365,5 +365,4 @@
   UInt uiY           = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[ uiAbsZorderIdx ] ];
 
-  TComDataCU* pcTempCU;
   UInt        uiTempPartIdx;
 
@@ -380,5 +379,5 @@
   if ( m_stLFCUParam.bLeftEdge )
   {
-    pcTempCU = pcCU->getPULeft( uiTempPartIdx, uiAbsZorderIdx, !pcCU->getSlice()->getLFCrossSliceBoundaryFlag(), !m_bLFCrossTileBoundary);
+    const TComDataCU* pcTempCU = pcCU->getPULeft( uiTempPartIdx, uiAbsZorderIdx, !pcCU->getSlice()->getLFCrossSliceBoundaryFlag(), !m_bLFCrossTileBoundary);
 
     if ( pcTempCU != NULL )
@@ -402,5 +401,5 @@
   if ( m_stLFCUParam.bTopEdge )
   {
-    pcTempCU = pcCU->getPUAbove( uiTempPartIdx, uiAbsZorderIdx, !pcCU->getSlice()->getLFCrossSliceBoundaryFlag(), false, !m_bLFCrossTileBoundary);
+    const TComDataCU* pcTempCU = pcCU->getPUAbove( uiTempPartIdx, uiAbsZorderIdx, !pcCU->getSlice()->getLFCrossSliceBoundaryFlag(), false, !m_bLFCrossTileBoundary);
 
     if ( pcTempCU != NULL )
@@ -425,5 +424,5 @@
 
   UInt uiPartP;
-  TComDataCU* pcCUP;
+  const TComDataCU* pcCUP;
   UInt uiBs = 0;
 
@@ -459,13 +458,12 @@
       {
         Int iRefIdx;
-        TComPic *piRefP0, *piRefP1, *piRefQ0, *piRefQ1;
         iRefIdx = pcCUP->getCUMvField(REF_PIC_LIST_0)->getRefIdx(uiPartP);
-        piRefP0 = (iRefIdx < 0) ? NULL : pcCUP->getSlice()->getRefPic(REF_PIC_LIST_0, iRefIdx);
+        const TComPic *piRefP0 = (iRefIdx < 0) ? NULL : pcCUP->getSlice()->getRefPic(REF_PIC_LIST_0, iRefIdx);
         iRefIdx = pcCUP->getCUMvField(REF_PIC_LIST_1)->getRefIdx(uiPartP);
-        piRefP1 = (iRefIdx < 0) ? NULL : pcCUP->getSlice()->getRefPic(REF_PIC_LIST_1, iRefIdx);
+        const TComPic *piRefP1 = (iRefIdx < 0) ? NULL : pcCUP->getSlice()->getRefPic(REF_PIC_LIST_1, iRefIdx);
         iRefIdx = pcCUQ->getCUMvField(REF_PIC_LIST_0)->getRefIdx(uiPartQ);
-        piRefQ0 = (iRefIdx < 0) ? NULL : pcSlice->getRefPic(REF_PIC_LIST_0, iRefIdx);
+        const TComPic *piRefQ0 = (iRefIdx < 0) ? NULL : pcSlice->getRefPic(REF_PIC_LIST_0, iRefIdx);
         iRefIdx = pcCUQ->getCUMvField(REF_PIC_LIST_1)->getRefIdx(uiPartQ);
-        piRefQ1 = (iRefIdx < 0) ? NULL : pcSlice->getRefPic(REF_PIC_LIST_1, iRefIdx);
+        const TComPic *piRefQ1 = (iRefIdx < 0) ? NULL : pcSlice->getRefPic(REF_PIC_LIST_1, iRefIdx);
 
         TComMv pcMvP0 = pcCUP->getCUMvField(REF_PIC_LIST_0)->getMv(uiPartP);
@@ -530,9 +528,8 @@
       {
         Int iRefIdx;
-        TComPic *piRefP0, *piRefQ0;
         iRefIdx = pcCUP->getCUMvField(REF_PIC_LIST_0)->getRefIdx(uiPartP);
-        piRefP0 = (iRefIdx < 0) ? NULL : pcCUP->getSlice()->getRefPic(REF_PIC_LIST_0, iRefIdx);
+        const TComPic *piRefP0 = (iRefIdx < 0) ? NULL : pcCUP->getSlice()->getRefPic(REF_PIC_LIST_0, iRefIdx);
         iRefIdx = pcCUQ->getCUMvField(REF_PIC_LIST_0)->getRefIdx(uiPartQ);
-        piRefQ0 = (iRefIdx < 0) ? NULL : pcSlice->getRefPic(REF_PIC_LIST_0, iRefIdx);
+        const TComPic *piRefQ0 = (iRefIdx < 0) ? NULL : pcSlice->getRefPic(REF_PIC_LIST_0, iRefIdx);
         TComMv pcMvP0 = pcCUP->getCUMvField(REF_PIC_LIST_0)->getMv(uiPartP);
         TComMv pcMvQ0 = pcCUQ->getCUMvField(REF_PIC_LIST_0)->getMv(uiPartQ);
@@ -583,5 +580,5 @@
   UInt  uiPartPIdx = 0;
   UInt  uiPartQIdx = 0;
-  TComDataCU* pcCUP = pcCU;
+  const TComDataCU* pcCUP = pcCU;
   TComDataCU* pcCUQ = pcCU;
   Int  betaOffsetDiv2 = pcCUQ->getSlice()->getDeblockingFilterBetaOffsetDiv2();
@@ -758,5 +755,5 @@
       UInt  uiPartQIdx = uiBsAbsIdx;
       // Derive neighboring PU index
-      TComDataCU* pcCUP;
+      const TComDataCU* pcCUP;
       UInt  uiPartPIdx;
 
Index: trunk/source/Lib/TLibCommon/TComMotionInfo.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComMotionInfo.cpp	(revision 1357)
+++ trunk/source/Lib/TLibCommon/TComMotionInfo.cpp	(revision 1386)
@@ -66,5 +66,5 @@
   m_pcMv     = new TComMv[ uiNumPartition ];
   m_pcMvd    = new TComMv[ uiNumPartition ];
-  m_piRefIdx = new Char  [ uiNumPartition ];
+  m_piRefIdx = new SChar [ uiNumPartition ];
 
   m_uiNumPartition = uiNumPartition;
@@ -321,5 +321,5 @@
 Void TComCUMvField::setAllRefIdx ( Int iRefIdx, PartSize eCUMode, Int iPartAddr, UInt uiDepth, Int iPartIdx )
 {
-  setAll(m_piRefIdx, static_cast<Char>(iRefIdx), eCUMode, iPartAddr, uiDepth, iPartIdx);
+  setAll(m_piRefIdx, static_cast<SChar>(iRefIdx), eCUMode, iPartAddr, uiDepth, iPartIdx);
 }
 
@@ -358,5 +358,5 @@
  * \param scale      Factor by which to subsample motion information
  */
-Void TComCUMvField::compress(Char* pePredMode, Int scale)
+Void TComCUMvField::compress(SChar* pePredMode, Int scale)
 {
   Int N = scale * scale;
@@ -381,5 +381,5 @@
 
 #if NH_MV
-Void TComCUMvField::print(Char* pePredMode)
+Void TComCUMvField::print(SChar* pePredMode)
 {
   for ( Int uiPartIdx = 0; uiPartIdx < m_uiNumPartition; uiPartIdx += 1 )
Index: trunk/source/Lib/TLibCommon/TComMotionInfo.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComMotionInfo.h	(revision 1357)
+++ trunk/source/Lib/TLibCommon/TComMotionInfo.h	(revision 1386)
@@ -57,5 +57,5 @@
 typedef struct _AMVPInfo
 {
-  TComMv m_acMvCand[ AMVP_MAX_NUM_CANDS_MEM ];  ///< array of motion vector predictor candidates
+  TComMv m_acMvCand[ AMVP_MAX_NUM_CANDS ];  ///< array of motion vector predictor candidates
   Int    iN;                                ///< number of motion vector predictor candidates
 } AMVPInfo;
@@ -122,5 +122,5 @@
   TComMv*   m_pcMv;
   TComMv*   m_pcMvd;
-  Char*     m_piRefIdx;
+  SChar*    m_piRefIdx;
   UInt      m_uiNumPartition;
   AMVPInfo  m_cAMVPInfo;
@@ -188,7 +188,7 @@
   }
   
-  Void compress(Char* pePredMode, Int scale); 
+  Void compress(SChar* pePredMode, Int scale);
 #if NH_MV
-  Void print   (Char* pePredMode);
+  Void print   (SChar* pePredMode);
 #endif
 };
Index: trunk/source/Lib/TLibCommon/TComMv.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComMv.h	(revision 1357)
+++ trunk/source/Lib/TLibCommon/TComMv.h	(revision 1386)
@@ -100,15 +100,12 @@
   Void  setHor    ( Short i )                   { m_iHor = i;                               }
   Void  setVer    ( Short i )                   { m_iVer = i;                               }
-  Void  setZero   ()                            { m_iHor = m_iVer = 0; 
- #if NH_3D_NBDV
-   m_bIDV = false; m_iIDVHor = m_iIDVVer = 0;
-   m_iIDVVId = 0; 
-#endif
- }
-#if NH_3D_NBDV
+#if NH_3D_NBDV
+  Void  setZero   ()                            { m_iHor = m_iVer = 0; m_bIDV = false; m_iIDVHor = m_iIDVVer = 0; m_iIDVVId = 0;  }
   Void   setIDVHor  (Short i)                    {m_iIDVHor = i;}
   Void   setIDVVer  (Short i)                    {m_iIDVVer = i;}
   Void   setIDVFlag (Bool b )                    {m_bIDV    = b;}
   Void   setIDVVId  (Short i)                    {m_iIDVVId = i;}
+#else
+  Void  setZero   ()                            { m_iHor = m_iVer = 0;  }
 #endif
   // ------------------------------------------------------------------------------------------------------------------
@@ -145,4 +142,7 @@
   }
 
+#if NH_3D
+#if ME_ENABLE_ROUNDING_OF_MVS
+
   const TComMv& operator>>= (const Int i)
   {
@@ -151,4 +151,28 @@
     return  *this;
   }
+#endif
+#endif
+
+#if !ME_ENABLE_ROUNDING_OF_MVS
+  const TComMv& operator>>= (const Int i)
+  {
+    m_iHor >>= i;
+    m_iVer >>= i;
+    return  *this;
+  }
+#endif
+
+#if ME_ENABLE_ROUNDING_OF_MVS
+  //! shift right with rounding
+  Void divideByPowerOf2 (const Int i)
+  {
+    Int offset = (i == 0) ? 0 : 1 << (i - 1);
+    m_iHor += offset;
+    m_iVer += offset;
+
+    m_iHor >>= i;
+    m_iVer >>= i;
+  }
+#endif
 
   const TComMv& operator<<= (const Int i)
Index: trunk/source/Lib/TLibCommon/TComPattern.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComPattern.cpp	(revision 1357)
+++ trunk/source/Lib/TLibCommon/TComPattern.cpp	(revision 1386)
@@ -66,9 +66,9 @@
 
 /// constrained intra prediction
-Bool  isAboveLeftAvailable  ( TComDataCU* pcCU, UInt uiPartIdxLT );
-Int   isAboveAvailable      ( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxRT, Bool* bValidFlags );
-Int   isLeftAvailable       ( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxLB, Bool* bValidFlags );
-Int   isAboveRightAvailable ( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxRT, Bool* bValidFlags );
-Int   isBelowLeftAvailable  ( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxLB, Bool* bValidFlags );
+Bool  isAboveLeftAvailable  ( const TComDataCU* pcCU, UInt uiPartIdxLT );
+Int   isAboveAvailable      ( const TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxRT, Bool* bValidFlags );
+Int   isLeftAvailable       ( const TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxLB, Bool* bValidFlags );
+Int   isAboveRightAvailable ( const TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxRT, Bool* bValidFlags );
+Int   isBelowLeftAvailable  ( const TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxLB, Bool* bValidFlags );
 
 
@@ -566,9 +566,9 @@
 }
 
-Bool isAboveLeftAvailable( TComDataCU* pcCU, UInt uiPartIdxLT )
+Bool isAboveLeftAvailable( const TComDataCU* pcCU, UInt uiPartIdxLT )
 {
   Bool bAboveLeftFlag;
   UInt uiPartAboveLeft;
-  TComDataCU* pcCUAboveLeft = pcCU->getPUAboveLeft( uiPartAboveLeft, uiPartIdxLT );
+  const TComDataCU* pcCUAboveLeft = pcCU->getPUAboveLeft( uiPartAboveLeft, uiPartIdxLT );
   if(pcCU->getSlice()->getPPS()->getConstrainedIntraPred())
   {
@@ -582,5 +582,5 @@
 }
 
-Int isAboveAvailable( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxRT, Bool *bValidFlags )
+Int isAboveAvailable( const TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxRT, Bool *bValidFlags )
 {
   const UInt uiRasterPartBegin = g_auiZscanToRaster[uiPartIdxLT];
@@ -593,5 +593,5 @@
   {
     UInt uiPartAbove;
-    TComDataCU* pcCUAbove = pcCU->getPUAbove( uiPartAbove, g_auiRasterToZscan[uiRasterPart] );
+    const TComDataCU* pcCUAbove = pcCU->getPUAbove( uiPartAbove, g_auiRasterToZscan[uiRasterPart] );
     if(pcCU->getSlice()->getPPS()->getConstrainedIntraPred())
     {
@@ -623,5 +623,5 @@
 }
 
-Int isLeftAvailable( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxLB, Bool *bValidFlags )
+Int isLeftAvailable( const TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxLB, Bool *bValidFlags )
 {
   const UInt uiRasterPartBegin = g_auiZscanToRaster[uiPartIdxLT];
@@ -634,5 +634,5 @@
   {
     UInt uiPartLeft;
-    TComDataCU* pcCULeft = pcCU->getPULeft( uiPartLeft, g_auiRasterToZscan[uiRasterPart] );
+    const TComDataCU* pcCULeft = pcCU->getPULeft( uiPartLeft, g_auiRasterToZscan[uiRasterPart] );
     if(pcCU->getSlice()->getPPS()->getConstrainedIntraPred())
     {
@@ -665,5 +665,5 @@
 }
 
-Int isAboveRightAvailable( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxRT, Bool *bValidFlags )
+Int isAboveRightAvailable( const TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxRT, Bool *bValidFlags )
 {
   const UInt uiNumUnitsInPU = g_auiZscanToRaster[uiPartIdxRT] - g_auiZscanToRaster[uiPartIdxLT] + 1;
@@ -674,5 +674,5 @@
   {
     UInt uiPartAboveRight;
-    TComDataCU* pcCUAboveRight = pcCU->getPUAboveRight( uiPartAboveRight, uiPartIdxRT, uiOffset );
+    const TComDataCU* pcCUAboveRight = pcCU->getPUAboveRight( uiPartAboveRight, uiPartIdxRT, uiOffset );
     if(pcCU->getSlice()->getPPS()->getConstrainedIntraPred())
     {
@@ -705,5 +705,5 @@
 }
 
-Int isBelowLeftAvailable( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxLB, Bool *bValidFlags )
+Int isBelowLeftAvailable( const TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxLB, Bool *bValidFlags )
 {
   const UInt uiNumUnitsInPU = (g_auiZscanToRaster[uiPartIdxLB] - g_auiZscanToRaster[uiPartIdxLT]) / pcCU->getPic()->getNumPartInCtuWidth() + 1;
@@ -714,5 +714,5 @@
   {
     UInt uiPartBelowLeft;
-    TComDataCU* pcCUBelowLeft = pcCU->getPUBelowLeft( uiPartBelowLeft, uiPartIdxLB, uiOffset );
+    const TComDataCU* pcCUBelowLeft = pcCU->getPUBelowLeft( uiPartBelowLeft, uiPartIdxLB, uiOffset );
     if(pcCU->getSlice()->getPPS()->getConstrainedIntraPred())
     {
Index: trunk/source/Lib/TLibCommon/TComPattern.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComPattern.h	(revision 1357)
+++ trunk/source/Lib/TLibCommon/TComPattern.h	(revision 1386)
@@ -69,4 +69,8 @@
     return  m_piROIOrigin;
   }
+  __inline const Pel*  getROIOrigin() const
+  {
+    return  m_piROIOrigin;
+  }
 
   /// set parameters from Pel buffer for accessing neighbouring pixels
@@ -93,15 +97,16 @@
   // ROI & pattern information, (ROI = &pattern[AboveOffset][LeftOffset])
   Pel*  getROIY()                 { return m_cPatternY.getROIOrigin();    }
-  Int   getROIYWidth()            { return m_cPatternY.m_iROIWidth;       }
-  Int   getROIYHeight()           { return m_cPatternY.m_iROIHeight;      }
-  Int   getPatternLStride()       { return m_cPatternY.m_iPatternStride;  }
-  Int   getBitDepthY()            { return m_cPatternY.m_bitDepth; }
+  const Pel*  getROIY() const     { return m_cPatternY.getROIOrigin();    }
+  Int   getROIYWidth() const      { return m_cPatternY.m_iROIWidth;       }
+  Int   getROIYHeight() const     { return m_cPatternY.m_iROIHeight;      }
+  Int   getPatternLStride() const { return m_cPatternY.m_iPatternStride;  }
+  Int   getBitDepthY() const      { return m_cPatternY.m_bitDepth;        }
 
 #if NH_3D_IC
-  Bool  getICFlag()               { return m_bICFlag; }
+  Bool  getICFlag()               const { return m_bICFlag; }
   Void  setICFlag( Bool bICFlag ) { m_bICFlag = bICFlag; }
 #endif
 #if NH_3D_SDC_INTER
-  Bool  getSDCMRSADFlag()         { return m_bSDCMRSADFlag; }
+  Bool  getSDCMRSADFlag()         const { return m_bSDCMRSADFlag; }
   Void  setSDCMRSADFlag( Bool bSDCMRSADFlag )    { m_bSDCMRSADFlag = bSDCMRSADFlag; }
 #endif
Index: trunk/source/Lib/TLibCommon/TComPic.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComPic.cpp	(revision 1357)
+++ trunk/source/Lib/TLibCommon/TComPic.cpp	(revision 1386)
@@ -60,5 +60,5 @@
 , m_viewId                                (0)
 , m_bPicOutputFlag                        (false)
-#if NH_3D
+#if NH_3D_VSO
 , m_viewIndex                             (0)
 , m_isDepth                               (false)
@@ -449,11 +449,7 @@
           m_abTIVRINCurrRL[curCandPic][iColRefDir][iColRefIdx] = false;
           Int iColViewIdx    = pcCandColSlice->getViewIndex();
-#if H_3D_FIX_ARP_CHECK_NOT_IN_DPB
           // The picture pcCandColSlice->getRefPic((RefPicList)iColRefDir, iColRefIdx) might not be in DPB anymore
           // So don't access it directly.
           Int iColRefViewIdx = pcCandColSlice->getVPS()->getViewOrderIdx( pcCandColSlice->getRefLayerId( (RefPicList)iColRefDir, iColRefIdx ) );       
-#else
-          Int iColRefViewIdx = pcCandColSlice->getRefPic((RefPicList)iColRefDir, iColRefIdx)->getViewIndex();
-#endif
           if(iColViewIdx == iColRefViewIdx)
           {
@@ -993,14 +989,14 @@
 }
 
-#if NH_3D
-TComPicYuv* TComPicLists::getPicYuv( Int viewIndex, Bool depthFlag, Int poc, Bool recon )
+#if NH_3D_VSO
+TComPicYuv* TComPicLists::getPicYuv( Int viewIndex, Bool depthFlag, Int auxId, Int poc, Bool recon )
 {  
-  Int layerIdInNuh = m_vps->getLayerIdInNuh( viewIndex, depthFlag ); 
+  Int layerIdInNuh = m_vps->getLayerIdInNuh( viewIndex, depthFlag, auxId ); 
   return getPicYuv( layerIdInNuh, poc, recon );
 }
 
-TComPic* TComPicLists::getPic( Int viewIndex, Bool depthFlag, Int poc )
-{
-  return getPic   ( m_vps->getLayerIdInNuh( viewIndex, depthFlag ), poc );
+TComPic* TComPicLists::getPic( Int viewIndex, Bool depthFlag, Int auxId, Int poc )
+{
+  return getPic   ( m_vps->getLayerIdInNuh( viewIndex, depthFlag, auxId ), poc );
 }
 
Index: trunk/source/Lib/TLibCommon/TComPic.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComPic.h	(revision 1357)
+++ trunk/source/Lib/TLibCommon/TComPic.h	(revision 1386)
@@ -154,5 +154,5 @@
   TComDecodedRps        m_decodedRps;
 #endif
-#if NH_3D
+#if NH_3D_VSO
   Int                   m_viewIndex;
   Bool                  m_isDepth;
@@ -189,4 +189,5 @@
 
   TComPicSym*   getPicSym()           { return  &m_picSym;    }
+  const TComPicSym* getPicSym() const { return  &m_picSym;    }
   TComSlice*    getSlice(Int i)       { return  m_picSym.getSlice(i);  }
   Int           getPOC() const        { return  m_picSym.getSlice(m_uiCurrSliceIdx)->getPOC();  }
@@ -247,11 +248,11 @@
 #if NH_MV
    Void          setLayerId            ( Int layerId )    { m_layerId      = layerId; }
-   Int           getLayerId            ()                 { return m_layerId;    }
+   Int           getLayerId            () const           { return m_layerId;    }
    
    Void          setViewId             ( Int viewId )     { m_viewId = viewId;   }
-   Int           getViewId             ()                 { return m_viewId;     }
+   Int           getViewId             () const           { return m_viewId;     }
 
    Void          setPicOutputFlag(Bool b)                 { m_bPicOutputFlag = b;      }
-   Bool          getPicOutputFlag()                       { return m_bPicOutputFlag ;  }
+   Bool          getPicOutputFlag() const                 { return m_bPicOutputFlag ;  }
 
    Bool          getPocResetPeriodId();
@@ -310,7 +311,7 @@
    Void          print( Int outputLevel );
 
-#if NH_3D
+#if NH_3D_VSO
    Void          setViewIndex          ( Int viewIndex )  { m_viewIndex = viewIndex;   }
-   Int           getViewIndex          ()                 { return m_viewIndex;     }
+   Int           getViewIndex          () const           { return m_viewIndex;     }
 
    Void          setIsDepth            ( Bool isDepth )   { m_isDepth = isDepth; }
@@ -403,5 +404,5 @@
   TComList<TComSubDpb*>       m_subDpbs; 
   Bool                        m_printPicOutput; 
-#if NH_3D                     
+#if NH_3D_VSO
   const TComVPS*              m_vps; 
 #endif
@@ -447,8 +448,8 @@
   Void                   print(); 
 
-#if NH_3D                                   
+#if NH_3D_VSO
   Void                   setVPS                        ( const TComVPS* vps ) { m_vps = vps;  }; 
-  TComPic*               getPic                        ( Int viewIndex, Bool depthFlag, Int poc );
-  TComPicYuv*            getPicYuv                     ( Int viewIndex, Bool depthFlag, Int poc, Bool recon );
+  TComPic*               getPic                        ( Int viewIndex, Bool depthFlag, Int auxId, Int poc );
+  TComPicYuv*            getPicYuv                     ( Int viewIndex, Bool depthFlag, Int auxId, Int poc, Bool recon );
 #endif  
 
Index: trunk/source/Lib/TLibCommon/TComPicSym.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComPicSym.cpp	(revision 1357)
+++ trunk/source/Lib/TLibCommon/TComPicSym.cpp	(revision 1386)
@@ -140,12 +140,18 @@
   clearSliceBuffer();
 
+  if (m_pictureCtuArray)
+  {
   for (Int i = 0; i < m_numCtusInFrame; i++)
   {
+      if (m_pictureCtuArray[i])
+      {
     m_pictureCtuArray[i]->destroy();
     delete m_pictureCtuArray[i];
     m_pictureCtuArray[i] = NULL;
   }
+    }
   delete [] m_pictureCtuArray;
   m_pictureCtuArray = NULL;
+  }
 
   delete [] m_ctuTsToRsAddrMap;
Index: trunk/source/Lib/TLibCommon/TComPicYuv.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComPicYuv.cpp	(revision 1357)
+++ trunk/source/Lib/TLibCommon/TComPicYuv.cpp	(revision 1386)
@@ -79,56 +79,76 @@
 
 
-Void TComPicYuv::create ( const Int iPicWidth,                ///< picture width
-                          const Int iPicHeight,               ///< picture height
+Void TComPicYuv::createWithoutCUInfo ( const Int picWidth,                 ///< picture width
+                                       const Int picHeight,                ///< picture height
+                                       const ChromaFormat chromaFormatIDC, ///< chroma format
+                                       const Bool bUseMargin,              ///< if true, then a margin of uiMaxCUWidth+16 and uiMaxCUHeight+16 is created around the image.
+                                       const UInt maxCUWidth,              ///< used for margin only
+                                       const UInt maxCUHeight)             ///< used for margin only
+
+{
+  m_picWidth          = picWidth;
+  m_picHeight         = picHeight;
+
+#if NH_3D_IV_MERGE
+  m_iCuWidth        = maxCUWidth;
+  m_iCuHeight       = maxCUHeight;
+
+  m_iNumCuInWidth   = picWidth / m_iCuWidth;
+  m_iNumCuInWidth  += ( picHeight % m_iCuWidth ) ? 1 : 0;
+  // Check if m_iBaseUnitWidth and m_iBaseUnitHeight need to be derived here
+#endif
+
+  m_chromaFormatIDC   = chromaFormatIDC;
+  m_marginX          = (bUseMargin?maxCUWidth:0) + 16;   // for 16-byte alignment
+  m_marginY          = (bUseMargin?maxCUHeight:0) + 16;  // margin for 8-tap filter and infinite padding
+  m_bIsBorderExtended = false;
+
+  // assign the picture arrays and set up the ptr to the top left of the original picture
+  for(UInt comp=0; comp<getNumberValidComponents(); comp++)
+  {
+    const ComponentID ch=ComponentID(comp);
+    m_apiPicBuf[comp] = (Pel*)xMalloc( Pel, getStride(ch) * getTotalHeight(ch));
+    m_piPicOrg[comp]  = m_apiPicBuf[comp] + (m_marginY >> getComponentScaleY(ch)) * getStride(ch) + (m_marginX >> getComponentScaleX(ch));
+  }
+  // initialize pointers for unused components to NULL
+  for(UInt comp=getNumberValidComponents();comp<MAX_NUM_COMPONENT; comp++)
+  {
+    m_apiPicBuf[comp] = NULL;
+    m_piPicOrg[comp]  = NULL;
+  }
+
+  for(Int chan=0; chan<MAX_NUM_CHANNEL_TYPE; chan++)
+    {
+    m_ctuOffsetInBuffer[chan]   = NULL;
+    m_subCuOffsetInBuffer[chan] = NULL;
+    }
+  }
+
+
+
+Void TComPicYuv::create ( const Int picWidth,                 ///< picture width
+                          const Int picHeight,                ///< picture height
                           const ChromaFormat chromaFormatIDC, ///< chroma format
-                          const UInt uiMaxCUWidth,            ///< used for generating offsets to CUs. Can use iPicWidth if no offsets are required
-                          const UInt uiMaxCUHeight,           ///< used for generating offsets to CUs. Can use iPicHeight if no offsets are required
-                          const UInt uiMaxCUDepth,            ///< used for generating offsets to CUs. Can use 0 if no offsets are required
+                          const UInt maxCUWidth,              ///< used for generating offsets to CUs.
+                          const UInt maxCUHeight,             ///< used for generating offsets to CUs.
+                          const UInt maxCUDepth,              ///< used for generating offsets to CUs.
                           const Bool bUseMargin)              ///< if true, then a margin of uiMaxCUWidth+16 and uiMaxCUHeight+16 is created around the image.
 
 {
-  m_iPicWidth         = iPicWidth;
-  m_iPicHeight        = iPicHeight;
+  createWithoutCUInfo(picWidth, picHeight, chromaFormatIDC, bUseMargin, maxCUWidth, maxCUHeight);
 
 #if NH_3D_IV_MERGE
-  m_iCuWidth        = uiMaxCUWidth;
-  m_iCuHeight       = uiMaxCUHeight;
-
-  m_iNumCuInWidth   = m_iPicWidth / m_iCuWidth;
-  m_iNumCuInWidth  += ( m_iPicWidth % m_iCuWidth ) ? 1 : 0;
-
-  m_iBaseUnitWidth  = uiMaxCUWidth  >> uiMaxCUDepth;
-  m_iBaseUnitHeight = uiMaxCUHeight >> uiMaxCUDepth;
-#endif
-
-  m_chromaFormatIDC   = chromaFormatIDC;
-  m_iMarginX          = (bUseMargin?uiMaxCUWidth:0) + 16;   // for 16-byte alignment
-  m_iMarginY          = (bUseMargin?uiMaxCUHeight:0) + 16;  // margin for 8-tap filter and infinite padding
-  m_bIsBorderExtended = false;
-
-  // assign the picture arrays and set up the ptr to the top left of the original picture
-  {
-    Int chan=0;
-    for(; chan<getNumberValidComponents(); chan++)
-    {
-      const ComponentID ch=ComponentID(chan);
-      m_apiPicBuf[chan] = (Pel*)xMalloc( Pel, getStride(ch)       * getTotalHeight(ch));
-      m_piPicOrg[chan]  = m_apiPicBuf[chan] + (m_iMarginY >> getComponentScaleY(ch))   * getStride(ch)       + (m_iMarginX >> getComponentScaleX(ch));
-    }
-    for(;chan<MAX_NUM_COMPONENT; chan++)
-    {
-      m_apiPicBuf[chan] = NULL;
-      m_piPicOrg[chan]  = NULL;
-    }
-  }
-
-
-  const Int numCuInWidth  = m_iPicWidth  / uiMaxCUWidth  + (m_iPicWidth  % uiMaxCUWidth  != 0);
-  const Int numCuInHeight = m_iPicHeight / uiMaxCUHeight + (m_iPicHeight % uiMaxCUHeight != 0);
-  for(Int chan=0; chan<2; chan++)
-  {
-    const ComponentID ch=ComponentID(chan);
-    const Int ctuHeight=uiMaxCUHeight>>getComponentScaleY(ch);
-    const Int ctuWidth=uiMaxCUWidth>>getComponentScaleX(ch);
+  m_iBaseUnitWidth  = maxCUWidth  >> maxCUDepth;
+  m_iBaseUnitHeight = maxCUHeight >> maxCUDepth;
+#endif
+
+
+  const Int numCuInWidth  = m_picWidth  / maxCUWidth  + (m_picWidth  % maxCUWidth  != 0);
+  const Int numCuInHeight = m_picHeight / maxCUHeight + (m_picHeight % maxCUHeight != 0);
+  for(Int chan=0; chan<MAX_NUM_CHANNEL_TYPE; chan++)
+  {
+    const ChannelType ch= ChannelType(chan);
+    const Int ctuHeight = maxCUHeight>>getChannelTypeScaleY(ch);
+    const Int ctuWidth  = maxCUWidth>>getChannelTypeScaleX(ch);
     const Int stride = getStride(ch);
 
@@ -143,9 +163,9 @@
     }
 
-    m_subCuOffsetInBuffer[chan] = new Int[(size_t)1 << (2 * uiMaxCUDepth)];
-
-    const Int numSubBlockPartitions=(1<<uiMaxCUDepth);
-    const Int minSubBlockHeight    =(ctuHeight >> uiMaxCUDepth);
-    const Int minSubBlockWidth     =(ctuWidth  >> uiMaxCUDepth);
+    m_subCuOffsetInBuffer[chan] = new Int[(size_t)1 << (2 * maxCUDepth)];
+
+    const Int numSubBlockPartitions=(1<<maxCUDepth);
+    const Int minSubBlockHeight    =(ctuHeight >> maxCUDepth);
+    const Int minSubBlockWidth     =(ctuWidth  >> maxCUDepth);
 
     for (Int buRow = 0; buRow < numSubBlockPartitions; buRow++)
@@ -153,9 +173,8 @@
       for (Int buCol = 0; buCol < numSubBlockPartitions; buCol++)
       {
-        m_subCuOffsetInBuffer[chan][(buRow << uiMaxCUDepth) + buCol] = stride  * buRow * minSubBlockHeight + buCol * minSubBlockWidth;
-      }
-    }
-  }
-  return;
+        m_subCuOffsetInBuffer[chan][(buRow << maxCUDepth) + buCol] = stride  * buRow * minSubBlockHeight + buCol * minSubBlockWidth;
+      }
+    }
+  }
 }
 
@@ -164,12 +183,12 @@
 Void TComPicYuv::destroy()
 {
-  for(Int chan=0; chan<MAX_NUM_COMPONENT; chan++)
-  {
-    m_piPicOrg[chan] = NULL;
-
-    if( m_apiPicBuf[chan] )
-    {
-      xFree( m_apiPicBuf[chan] );
-      m_apiPicBuf[chan] = NULL;
+  for(Int comp=0; comp<MAX_NUM_COMPONENT; comp++)
+  {
+    m_piPicOrg[comp] = NULL;
+
+    if( m_apiPicBuf[comp] )
+    {
+      xFree( m_apiPicBuf[comp] );
+      m_apiPicBuf[comp] = NULL;
     }
   }
@@ -194,14 +213,30 @@
 Void  TComPicYuv::copyToPic (TComPicYuv*  pcPicYuvDst) const
 {
-  assert( m_iPicWidth  == pcPicYuvDst->getWidth(COMPONENT_Y)  );
-  assert( m_iPicHeight == pcPicYuvDst->getHeight(COMPONENT_Y) );
   assert( m_chromaFormatIDC == pcPicYuvDst->getChromaFormat() );
 
-  for(Int chan=0; chan<getNumberValidComponents(); chan++)
-  {
-    const ComponentID ch=ComponentID(chan);
-    ::memcpy ( pcPicYuvDst->getBuf(ch), m_apiPicBuf[ch], sizeof (Pel) * getStride(ch) * getTotalHeight(ch));
-  }
-  return;
+  for(Int comp=0; comp<getNumberValidComponents(); comp++)
+  {
+    const ComponentID compId=ComponentID(comp);
+    const Int width     = getWidth(compId);
+    const Int height    = getHeight(compId);
+    const Int strideSrc = getStride(compId);
+    assert(pcPicYuvDst->getWidth(compId) == width);
+    assert(pcPicYuvDst->getHeight(compId) == height);
+    if (strideSrc==pcPicYuvDst->getStride(compId))
+  {
+      ::memcpy ( pcPicYuvDst->getBuf(compId), getBuf(compId), sizeof(Pel)*strideSrc*getTotalHeight(compId));
+    }
+    else
+    {
+      const Pel *pSrc       = getAddr(compId);
+            Pel *pDest      = pcPicYuvDst->getAddr(compId);
+      const UInt strideDest = pcPicYuvDst->getStride(compId);
+
+      for(Int y=0; y<height; y++, pSrc+=strideSrc, pDest+=strideDest)
+      {
+        ::memcpy(pDest, pSrc, width*sizeof(Pel));
+      }
+    }
+  }
 }
 
@@ -214,40 +249,40 @@
   }
 
-  for(Int chan=0; chan<getNumberValidComponents(); chan++)
-  {
-    const ComponentID ch=ComponentID(chan);
-    Pel *piTxt=getAddr(ch); // piTxt = point to (0,0) of image within bigger picture.
-    const Int iStride=getStride(ch);
-    const Int iWidth=getWidth(ch);
-    const Int iHeight=getHeight(ch);
-    const Int iMarginX=getMarginX(ch);
-    const Int iMarginY=getMarginY(ch);
+  for(Int comp=0; comp<getNumberValidComponents(); comp++)
+  {
+    const ComponentID compId=ComponentID(comp);
+    Pel *piTxt=getAddr(compId); // piTxt = point to (0,0) of image within bigger picture.
+    const Int stride=getStride(compId);
+    const Int width=getWidth(compId);
+    const Int height=getHeight(compId);
+    const Int marginX=getMarginX(compId);
+    const Int marginY=getMarginY(compId);
 
     Pel*  pi = piTxt;
     // do left and right margins
-    for (Int y = 0; y < iHeight; y++)
-    {
-      for (Int x = 0; x < iMarginX; x++ )
-      {
-        pi[ -iMarginX + x ] = pi[0];
-        pi[    iWidth + x ] = pi[iWidth-1];
-      }
-      pi += iStride;
+    for (Int y = 0; y < height; y++)
+    {
+      for (Int x = 0; x < marginX; x++ )
+      {
+        pi[ -marginX + x ] = pi[0];
+        pi[    width + x ] = pi[width-1];
+      }
+      pi += stride;
     }
 
     // pi is now the (0,height) (bottom left of image within bigger picture
-    pi -= (iStride + iMarginX);
+    pi -= (stride + marginX);
     // pi is now the (-marginX, height-1)
-    for (Int y = 0; y < iMarginY; y++ )
-    {
-      ::memcpy( pi + (y+1)*iStride, pi, sizeof(Pel)*(iWidth + (iMarginX<<1)) );
+    for (Int y = 0; y < marginY; y++ )
+    {
+      ::memcpy( pi + (y+1)*stride, pi, sizeof(Pel)*(width + (marginX<<1)) );
     }
 
     // pi is still (-marginX, height-1)
-    pi -= ((iHeight-1) * iStride);
+    pi -= ((height-1) * stride);
     // pi is now (-marginX, 0)
-    for (Int y = 0; y < iMarginY; y++ )
-    {
-      ::memcpy( pi - (y+1)*iStride, pi, sizeof(Pel)*(iWidth + (iMarginX<<1)) );
+    for (Int y = 0; y < marginY; y++ )
+    {
+      ::memcpy( pi - (y+1)*stride, pi, sizeof(Pel)*(width + (marginX<<1)) );
     }
   }
@@ -259,35 +294,52 @@
 
 // NOTE: This function is never called, but may be useful for developers.
-Void TComPicYuv::dump (const Char* pFileName, const BitDepths &bitDepths, Bool bAdd) const
-{
-  FILE* pFile;
-  if (!bAdd)
-  {
-    pFile = fopen (pFileName, "wb");
-  }
-  else
-  {
-    pFile = fopen (pFileName, "ab");
-  }
-
-
-  for(Int chan = 0; chan < getNumberValidComponents(); chan++)
-  {
-    const ComponentID  ch     = ComponentID(chan);
-    const Int          shift  = bitDepths.recon[toChannelType(ch)] - 8;
-    const Int          offset = (shift>0)?(1<<(shift-1)):0;
-    const Pel         *pi     = getAddr(ch);
-    const Int          stride = getStride(ch);
-    const Int          height = getHeight(ch);
-    const Int          width  = getWidth(ch);
-
+Void TComPicYuv::dump (const std::string &fileName, const BitDepths &bitDepths, const Bool bAppend, const Bool bForceTo8Bit) const
+{
+  FILE *pFile = fopen (fileName.c_str(), bAppend?"ab":"wb");
+
+  Bool is16bit=false;
+  for(Int comp = 0; comp < getNumberValidComponents() && !bForceTo8Bit; comp++)
+  {
+    if (bitDepths.recon[toChannelType(ComponentID(comp))]>8)
+  {
+      is16bit=true;
+    }
+  }
+
+  for(Int comp = 0; comp < getNumberValidComponents(); comp++)
+  {
+    const ComponentID  compId = ComponentID(comp);
+    const Pel         *pi     = getAddr(compId);
+    const Int          stride = getStride(compId);
+    const Int          height = getHeight(compId);
+    const Int          width  = getWidth(compId);
+
+    if (is16bit)
+    {
     for (Int y = 0; y < height; y++ )
     {
       for (Int x = 0; x < width; x++ )
       {
-        UChar uc = (UChar)Clip3<Pel>(0, 255, (pi[x]+offset)>>shift);
+          UChar uc = (UChar)((pi[x]>>0) & 0xff);
         fwrite( &uc, sizeof(UChar), 1, pFile );
+          uc = (UChar)((pi[x]>>8) & 0xff);
+          fwrite( &uc, sizeof(UChar), 1, pFile );
       }
       pi += stride;
+    }
+  }
+    else
+    {
+      const Int shift  = bitDepths.recon[toChannelType(compId)] - 8;
+      const Int offset = (shift>0)?(1<<(shift-1)):0;
+      for (Int y = 0; y < height; y++ )
+      {
+        for (Int x = 0; x < width; x++ )
+        {
+          UChar uc = (UChar)Clip3<Pel>(0, 255, (pi[x]+offset)>>shift);
+          fwrite( &uc, sizeof(UChar), 1, pFile );
+        }
+        pi += stride;
+      }
     }
   }
Index: trunk/source/Lib/TLibCommon/TComPicYuv.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComPicYuv.h	(revision 1357)
+++ trunk/source/Lib/TLibCommon/TComPicYuv.h	(revision 1386)
@@ -69,6 +69,6 @@
   // ------------------------------------------------------------------------------------------------
 
-  Int   m_iPicWidth;                                ///< Width of picture in pixels
-  Int   m_iPicHeight;                               ///< Height of picture in pixels
+  Int   m_picWidth;                                 ///< Width of picture in pixels
+  Int   m_picHeight;                                ///< Height of picture in pixels
   ChromaFormat m_chromaFormatIDC;                   ///< Chroma Format
 
@@ -76,6 +76,6 @@
   Int*  m_subCuOffsetInBuffer[MAX_NUM_CHANNEL_TYPE];///< Gives an offset in the buffer for a given sub-CU (and channel), relative to start of CTU
 
-  Int   m_iMarginX;                                 ///< margin of Luma channel (chroma's may be smaller, depending on ratio)
-  Int   m_iMarginY;                                 ///< margin of Luma channel (chroma's may be smaller, depending on ratio)
+  Int   m_marginX;                                  ///< margin of Luma channel (chroma's may be smaller, depending on ratio)
+  Int   m_marginY;                                  ///< margin of Luma channel (chroma's may be smaller, depending on ratio)
 
   Bool  m_bIsBorderExtended;
@@ -100,11 +100,18 @@
   // ------------------------------------------------------------------------------------------------
 
-  Void          create            (const Int iPicWidth,
-                                   const Int iPicHeight,
+  Void          create            (const Int picWidth,
+                                   const Int picHeight,
                                    const ChromaFormat chromaFormatIDC,
-                                   const UInt uiMaxCUWidth,  ///< used for generating offsets to CUs. Can use iPicWidth if no offsets are required
-                                   const UInt uiMaxCUHeight, ///< used for generating offsets to CUs. Can use iPicHeight if no offsets are required
-                                   const UInt uiMaxCUDepth,  ///< used for generating offsets to CUs. Can use 0 if no offsets are required
+                                   const UInt maxCUWidth,  ///< used for generating offsets to CUs.
+                                   const UInt maxCUHeight, ///< used for generating offsets to CUs.
+                                   const UInt maxCUDepth,  ///< used for generating offsets to CUs.
                                    const Bool bUseMargin);   ///< if true, then a margin of uiMaxCUWidth+16 and uiMaxCUHeight+16 is created around the image.
+
+  Void          createWithoutCUInfo(const Int picWidth,
+                                    const Int picHeight,
+                                    const ChromaFormat chromaFormatIDC,
+                                    const Bool bUseMargin=false, ///< if true, then a margin of uiMaxCUWidth+16 and uiMaxCUHeight+16 is created around the image.
+                                    const UInt maxCUWidth=0,   ///< used for margin only
+                                    const UInt maxCUHeight=0); ///< used for margin only
 
   Void          destroy           ();
@@ -118,14 +125,17 @@
   // ------------------------------------------------------------------------------------------------
 
-  Int           getWidth          (const ComponentID id) const { return  m_iPicWidth >> getComponentScaleX(id);   }
-  Int           getHeight         (const ComponentID id) const { return  m_iPicHeight >> getComponentScaleY(id);  }
+  Int           getWidth          (const ComponentID id) const { return  m_picWidth >> getComponentScaleX(id);   }
+  Int           getHeight         (const ComponentID id) const { return  m_picHeight >> getComponentScaleY(id);  }
   ChromaFormat  getChromaFormat   ()                     const { return m_chromaFormatIDC; }
   UInt          getNumberValidComponents() const { return ::getNumberValidComponents(m_chromaFormatIDC); }
 
-  Int           getStride         (const ComponentID id) const { return ((m_iPicWidth     ) + (m_iMarginX  <<1)) >> getComponentScaleX(id); }
-  Int           getTotalHeight    (const ComponentID id) const { return ((m_iPicHeight    ) + (m_iMarginY  <<1)) >> getComponentScaleY(id); }
-
-  Int           getMarginX        (const ComponentID id) const { return m_iMarginX >> getComponentScaleX(id);  }
-  Int           getMarginY        (const ComponentID id) const { return m_iMarginY >> getComponentScaleY(id);  }
+  Int           getStride         (const ComponentID id) const { return ((m_picWidth     ) + (m_marginX  <<1)) >> getComponentScaleX(id); }
+private:
+  Int           getStride         (const ChannelType id) const { return ((m_picWidth     ) + (m_marginX  <<1)) >> getChannelTypeScaleX(id); }
+public:
+  Int           getTotalHeight    (const ComponentID id) const { return ((m_picHeight    ) + (m_marginY  <<1)) >> getComponentScaleY(id); }
+
+  Int           getMarginX        (const ComponentID id) const { return m_marginX >> getComponentScaleX(id);  }
+  Int           getMarginY        (const ComponentID id) const { return m_marginY >> getComponentScaleY(id);  }
 
   // ------------------------------------------------------------------------------------------------
@@ -135,4 +145,5 @@
   //  Access starting position of picture buffer with margin
   Pel*          getBuf            (const ComponentID ch)       { return  m_apiPicBuf[ch];   }
+  const Pel*    getBuf            (const ComponentID ch) const { return  m_apiPicBuf[ch];   }
 
   //  Access starting position of original picture
@@ -151,4 +162,7 @@
   UInt          getComponentScaleY(const ComponentID id) const { return ::getComponentScaleY(id, m_chromaFormatIDC); }
 
+  UInt          getChannelTypeScaleX(const ChannelType id) const { return ::getChannelTypeScaleX(id, m_chromaFormatIDC); }
+  UInt          getChannelTypeScaleY(const ChannelType id) const { return ::getChannelTypeScaleY(id, m_chromaFormatIDC); }
+
   // ------------------------------------------------------------------------------------------------
   //  Miscellaneous
@@ -162,5 +176,5 @@
 
   //  Dump picture
-  Void          dump              (const Char* pFileName, const BitDepths &bitDepths, Bool bAdd = false) const ;
+  Void          dump              (const std::string &fileName, const BitDepths &bitDepths, const Bool bAppend=false, const Bool bForceTo8Bit=false) const ;
 
   // Set border extension flag
@@ -169,8 +183,10 @@
   Bool          getBorderExtension( )     { return m_bIsBorderExtended; }
 #endif
-#if NH_3D
+#if NH_3D_VSO
   // Set Function 
   Void  setLumaTo    ( Pel pVal );  
   Void  setChromaTo  ( Pel pVal );  
+#endif
+#if NH_3D
 #if NH_3D_IV_MERGE
   // sample to block and block to sample conversion
Index: trunk/source/Lib/TLibCommon/TComPicYuvMD5.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComPicYuvMD5.cpp	(revision 1357)
+++ trunk/source/Lib/TLibCommon/TComPicYuvMD5.cpp	(revision 1386)
@@ -209,5 +209,5 @@
 std::string hashToString(const TComPictureHash &digest, Int numChar)
 {
-  static const Char* hex = "0123456789abcdef";
+  static const TChar* hex = "0123456789abcdef";
   std::string result;
 
Index: trunk/source/Lib/TLibCommon/TComPrediction.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComPrediction.cpp	(revision 1357)
+++ trunk/source/Lib/TLibCommon/TComPrediction.cpp	(revision 1386)
@@ -562,5 +562,4 @@
       Int RefPOCL0 = pcCU->getSlice()->getRefPic(REF_PIC_LIST_0, pcCU->getCUMvField(REF_PIC_LIST_0)->getRefIdx(PartAddr))->getPOC();
       Int RefPOCL1 = pcCU->getSlice()->getRefPic(REF_PIC_LIST_1, pcCU->getCUMvField(REF_PIC_LIST_1)->getRefIdx(PartAddr))->getPOC();
-#if NH_MV_FIX_TICKET_106
 #if NH_MV
       Int layerIdL0 = pcCU->getSlice()->getRefPic(REF_PIC_LIST_0, pcCU->getCUMvField(REF_PIC_LIST_0)->getRefIdx(PartAddr))->getLayerId();
@@ -573,11 +572,4 @@
 #else
       if(RefPOCL0 == RefPOCL1 && pcCU->getCUMvField(REF_PIC_LIST_0)->getMv(PartAddr) == pcCU->getCUMvField(REF_PIC_LIST_1)->getMv(PartAddr))
-#endif
-#else
-#if NH_3D_ARP
-      if(!pcCU->getARPW(PartAddr) && RefPOCL0 == RefPOCL1 && pcCU->getCUMvField(REF_PIC_LIST_0)->getMv(PartAddr) == pcCU->getCUMvField(REF_PIC_LIST_1)->getMv(PartAddr))
-#else
-      if(RefPOCL0 == RefPOCL1 && pcCU->getCUMvField(REF_PIC_LIST_0)->getMv(PartAddr) == pcCU->getCUMvField(REF_PIC_LIST_1)->getMv(PartAddr))
-#endif
 #endif
       {
@@ -1139,4 +1131,7 @@
   Int         iHeight;
   UInt        uiPartAddr;
+  const TComSlice *pSlice    = pcCU->getSlice();
+  const SliceType  sliceType = pSlice->getSliceType();
+  const TComPPS   &pps       = *(pSlice->getPPS());
 
   if ( iPartIdx >= 0 )
@@ -1147,21 +1142,18 @@
     {
 #endif
-      if ( eRefPicList != REF_PIC_LIST_X )
-      {
-        if( pcCU->getSlice()->getPPS()->getUseWP())
-        {
-          xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred, true );
-        }
-        else
-        {
-          xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred );
-        }
-        if ( pcCU->getSlice()->getPPS()->getUseWP() )
-        {
-          xWeightedPredictionUni( pcCU, pcYuvPred, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred );
-        }
+     if ( eRefPicList != REF_PIC_LIST_X )
+     {
+      if( (sliceType == P_SLICE && pps.getUseWP()) || (sliceType == B_SLICE && pps.getWPBiPred()))
+      {
+        xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred, true );
+        xWeightedPredictionUni( pcCU, pcYuvPred, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred );
       }
       else
       {
+        xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred );
+      }
+     }
+     else
+     {
 #if NH_3D_SPIVMP
         if ( pcCU->getSPIVMPFlag(uiPartAddr)!=0)  
@@ -1235,15 +1227,12 @@
     if ( eRefPicList != REF_PIC_LIST_X )
     {
-      if( pcCU->getSlice()->getPPS()->getUseWP())
+      if( (sliceType == P_SLICE && pps.getUseWP()) || (sliceType == B_SLICE && pps.getWPBiPred()))
       {
         xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred, true );
+        xWeightedPredictionUni( pcCU, pcYuvPred, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred );
       }
       else
       {
         xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred );
-      }
-      if ( pcCU->getSlice()->getPPS()->getUseWP() )
-      {
-        xWeightedPredictionUni( pcCU, pcYuvPred, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred );
       }
     }
@@ -1317,5 +1306,5 @@
   pcCU->clipMv(cMv);
 
-#if ENC_DEC_TRACE && H_MV_ENC_DEC_TRAC
+#if ENC_DEC_TRACE && NH_MV_ENC_DEC_TRAC
   if ( g_traceMotionInfoBeforUniPred  )
   {
@@ -1449,12 +1438,12 @@
       Int iCurrPOC    = pcCU->getSlice()->getPOC();
       Int iColRefPOC  = pcCU->getSlice()->getRefPOC( eRefPicList, iRefIdx );
-    Int iCurrRefPOC = pcCU->getSlice()->getRefPOC( eRefPicList, arpRefIdx );
-      Int iScale = pcCU-> xGetDistScaleFactor(iCurrPOC, iCurrRefPOC, iCurrPOC, iColRefPOC);
+      Int iCurrRefPOC = pcCU->getSlice()->getRefPOC( eRefPicList, arpRefIdx );
+      Int iScale      = pcCU->xGetDistScaleFactor(iCurrPOC, iCurrRefPOC, iCurrPOC, iColRefPOC);
       if ( iScale != 4096 )
       {
         cMv = cMv.scaleMv( iScale );
       }
-    iRefIdx = arpRefIdx;
-  }
+      iRefIdx = arpRefIdx;
+    }
 
   pcCU->clipMv(cMv);
@@ -1830,4 +1819,5 @@
 
 
+#if NH_3D
 Void TComPrediction::xPredInterBlk(const ComponentID compID, TComDataCU *cu, TComPicYuv *refPic, UInt partAddr, TComMv *mv, Int width, Int height, TComYuv *dstPic, Bool bi, const Int bitDepth 
 #if NH_3D_ARP
@@ -1838,4 +1828,7 @@
 #endif
 )
+#else
+Void TComPrediction::xPredInterBlk(const ComponentID compID, TComDataCU *cu, TComPicYuv *refPic, UInt partAddr, TComMv *mv, Int width, Int height, TComYuv *dstPic, Bool bi, const Int bitDepth )
+#endif
 {
 #if NH_MV
@@ -1873,25 +1866,34 @@
   if ( yFrac == 0 )
   {
+#if NH_3D
+    m_if.filterHor(compID, ref, refStride, dst,  dstStride, cxWidth, cxHeight, xFrac, !bi 
 #if NH_3D_IC
-    m_if.filterHor(compID, ref, refStride, dst,  dstStride, cxWidth, cxHeight, xFrac, !bi || bICFlag, chFmt, bitDepth
-#else
-    m_if.filterHor(compID, ref, refStride, dst,  dstStride, cxWidth, cxHeight, xFrac, !bi, chFmt, bitDepth
-#endif
+     || bICFlag
+#endif
+    , chFmt, bitDepth
 #if NH_3D_ARP 
     , filterType
 #endif 
 );
+#else
+    m_if.filterHor(compID, ref, refStride, dst,  dstStride, cxWidth, cxHeight, xFrac, !bi, chFmt, bitDepth );
+#endif
   }
   else if ( xFrac == 0 )
   {
+#if NH_3D
+  m_if.filterVer(compID, ref, refStride, dst, dstStride, cxWidth, cxHeight, yFrac, true, !bi 
 #if NH_3D_IC
-    m_if.filterVer(compID, ref, refStride, dst, dstStride, cxWidth, cxHeight, yFrac, true, !bi || bICFlag, chFmt, bitDepth
-#else
-    m_if.filterVer(compID, ref, refStride, dst, dstStride, cxWidth, cxHeight, yFrac, true, !bi, chFmt, bitDepth
-#endif
+    || bICFlag
+#endif
+    , chFmt, bitDepth
 #if NH_3D_ARP
     , filterType
 #endif
 );
+#else
+    m_if.filterVer(compID, ref, refStride, dst, dstStride, cxWidth, cxHeight, yFrac, true, !bi, chFmt, bitDepth );
+
+#endif
   }
   else
@@ -1902,18 +1904,23 @@
     const Int vFilterSize = isLuma(compID) ? NTAPS_LUMA : NTAPS_CHROMA;
 
-    m_if.filterHor(compID, ref - ((vFilterSize>>1) -1)*refStride, refStride, tmp, tmpStride, cxWidth, cxHeight+vFilterSize-1, xFrac, false,      chFmt, bitDepth
 #if NH_3D_ARP 
-    , filterType
+    m_if.filterHor(compID, ref - ((vFilterSize>>1) -1)*refStride, refStride, tmp, tmpStride, cxWidth, cxHeight+vFilterSize-1, xFrac, false,      chFmt, bitDepth, filterType );
+#else
+    m_if.filterHor(compID, ref - ((vFilterSize>>1) -1)*refStride, refStride, tmp, tmpStride, cxWidth, cxHeight+vFilterSize-1, xFrac, false,      chFmt, bitDepth );
 #endif 
-);
+
+#if NH_3D
+    m_if.filterVer(compID, tmp + ((vFilterSize>>1) -1)*tmpStride, tmpStride, dst, dstStride, cxWidth, cxHeight,               yFrac, false, !bi
 #if NH_3D_IC
-    m_if.filterVer(compID, tmp + ((vFilterSize>>1) -1)*tmpStride, tmpStride, dst, dstStride, cxWidth, cxHeight,               yFrac, false, !bi || bICFlag, chFmt, bitDepth
-#else
-    m_if.filterVer(compID, tmp + ((vFilterSize>>1) -1)*tmpStride, tmpStride, dst, dstStride, cxWidth, cxHeight,               yFrac, false, !bi, chFmt, bitDepth
-#endif
+    || bICFlag
+#endif
+    , chFmt, bitDepth
 #if NH_3D_ARP
     , filterType
 #endif 
 );
+#else
+    m_if.filterVer(compID, tmp + ((vFilterSize>>1) -1)*tmpStride, tmpStride, dst, dstStride, cxWidth, cxHeight,               yFrac, false, !bi, chFmt, bitDepth );
+#endif
   }
 
@@ -1954,6 +1961,5 @@
 }
 
-Void TComPrediction::xWeightedAverage( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, Int iRefIdx0, Int iRefIdx1, UInt uiPartIdx, Int iWidth, Int iHeight, TComYuv* pcYuvDst, const BitDepths &clipBitDepths
- )
+Void TComPrediction::xWeightedAverage( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, Int iRefIdx0, Int iRefIdx1, UInt uiPartIdx, Int iWidth, Int iHeight, TComYuv* pcYuvDst, const BitDepths &clipBitDepths )
 {
   if( iRefIdx0 >= 0 && iRefIdx1 >= 0 )
Index: trunk/source/Lib/TLibCommon/TComPrediction.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComPrediction.h	(revision 1357)
+++ trunk/source/Lib/TLibCommon/TComPrediction.h	(revision 1386)
@@ -115,4 +115,5 @@
 #endif
 
+#if NH_3D
   Void xPredInterBlk(const ComponentID compID, TComDataCU *cu, TComPicYuv *refPic, UInt partAddr, TComMv *mv, Int width, Int height, TComYuv *dstPic, Bool bi, const Int bitDepth
 #if NH_3D_ARP
@@ -123,5 +124,7 @@
 #endif
  );
-
+#else
+  Void xPredInterBlk(const ComponentID compID, TComDataCU *cu, TComPicYuv *refPic, UInt partAddr, TComMv *mv, Int width, Int height, TComYuv *dstPic, Bool bi, const Int bitDepth );
+#endif
 #if NH_3D_VSP
   Void xPredInterUniSubPU        ( TComDataCU *cu, UInt uiPartAddr, Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Bool bi, Int widthSubPU=4, Int heightSubPU=4 );
Index: trunk/source/Lib/TLibCommon/TComRdCost.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComRdCost.cpp	(revision 1357)
+++ trunk/source/Lib/TLibCommon/TComRdCost.cpp	(revision 1386)
@@ -41,5 +41,5 @@
 #include "TComRom.h"
 #include "TComRdCost.h"
-#if NH_3D
+#if NH_3D_VSO
 #include "TComDataCU.h"
 #include "TComRectangle.h"
@@ -64,11 +64,13 @@
 // Calculate RD functions
 #if NH_3D_VSO
-Double TComRdCost::calcRdCost( UInt uiBits, Dist uiDistortion, Bool bFlag, DFunc eDFunc )
+Double TComRdCost::calcRdCost( Double numBits, Dist intDistortion, DFunc eDFunc )
+{
+  Double distortion = (Double) intDistortion;
 #else
-Double TComRdCost::calcRdCost( UInt uiBits, Distortion uiDistortion, Bool bFlag, DFunc eDFunc )
-#endif
-{
-  Double dRdCost = 0.0;
-  Double dLambda = 0.0;
+Double TComRdCost::calcRdCost( Double numBits, Double distortion, DFunc eDFunc )
+{
+#endif
+  
+  Double lambda = 1.0;
 
   switch ( eDFunc )
@@ -78,15 +80,11 @@
       break;
     case DF_SAD:
-#if RExt__HIGH_BIT_DEPTH_SUPPORT
-      dLambda = m_dLambdaMotionSAD[0]; // 0 is valid, because for lossless blocks, the cost equation is modified to compensate.
-#else
-      dLambda = (Double)m_uiLambdaMotionSAD[0]; // 0 is valid, because for lossless blocks, the cost equation is modified to compensate.
-#endif
+      lambda = m_dLambdaMotionSAD[0]; // 0 is valid, because for lossless blocks, the cost equation is modified to compensate.
       break;
     case DF_DEFAULT:
-      dLambda =         m_dLambda;
+      lambda = m_dLambda;
       break;
     case DF_SSE_FRAME:
-      dLambda =         m_dFrameLambda;
+      lambda = m_dFrameLambda;
       break;
     default:
@@ -95,119 +93,31 @@
   }
 
-  if (bFlag) //NOTE: this "bFlag" is never true
-  {
-    // Intra8x8, Intra4x4 Block only...
+#if NH_MV
+  // D_PRINT_INDENT( g_traceRDCost,  "Dist: " + n2s(distortion) + " Bits: " + n2s(numBits) + " RD Cost: " + n2s(dRdCost)); 
+   D_PRINT_INDENT( g_traceRDCost,  "Dist: " + n2s(distortion) + " Bits: " + n2s(numBits) ); 
+#endif
+
+  if (eDFunc == DF_SAD)
+  {
     if (m_costMode != COST_STANDARD_LOSSY)
     {
-      dRdCost = (Double(uiDistortion) / dLambda) + Double(uiBits); // all lossless costs would have uiDistortion=0, and therefore this cost function can be used.
+      return ((distortion * 65536.0) / lambda) + numBits; // all lossless costs would have uiDistortion=0, and therefore this cost function can be used.
     }
     else
     {
-      dRdCost = (((Double)uiDistortion) + ((Double)uiBits * dLambda));
+      return distortion + (((numBits * lambda) ) / 65536.0);
     }
   }
   else
   {
-    if (eDFunc == DF_SAD)
-    {
-      if (m_costMode != COST_STANDARD_LOSSY)
-      {
-        dRdCost = ((Double(uiDistortion) * 65536) / dLambda) + Double(uiBits); // all lossless costs would have uiDistortion=0, and therefore this cost function can be used.
-      }
-      else
-      {
-        dRdCost = floor(Double(uiDistortion) + (floor((Double(uiBits) * dLambda) + 0.5) / 65536.0));
-      }
+    if (m_costMode != COST_STANDARD_LOSSY)
+    {
+      return (distortion / lambda) + numBits; // all lossless costs would have uiDistortion=0, and therefore this cost function can be used.
     }
     else
     {
-      if (m_costMode != COST_STANDARD_LOSSY)
-      {
-        dRdCost = (Double(uiDistortion) / dLambda) + Double(uiBits); // all lossless costs would have uiDistortion=0, and therefore this cost function can be used.
-      }
-      else
-      {
-        dRdCost = floor(Double(uiDistortion) + (Double(uiBits) * dLambda) + 0.5);
-      }
-    }
-  }
-
-#if NH_MV
-  D_PRINT_INDENT( g_traceRDCost,  "Dist: " + n2s(uiDistortion) + " Bits: " + n2s(uiBits) + " RD Cost: " + n2s(dRdCost)); 
-#endif
-  return dRdCost;
-}
-
-#if NH_3D_VSO
-Double TComRdCost::calcRdCost64( UInt64 uiBits, Dist64 uiDistortion, Bool bFlag, DFunc eDFunc )
-#else
-Double TComRdCost::calcRdCost64( UInt64 uiBits, UInt64 uiDistortion, Bool bFlag, DFunc eDFunc )
-#endif
-{
-  Double dRdCost = 0.0;
-  Double dLambda = 0.0;
-
-  switch ( eDFunc )
-  {
-    case DF_SSE:
-      assert(0);
-      break;
-    case DF_SAD:
-#if RExt__HIGH_BIT_DEPTH_SUPPORT
-      dLambda = m_dLambdaMotionSAD[0]; // 0 is valid, because for lossless blocks, the cost equation is modified to compensate.
-#else
-      dLambda = (Double)m_uiLambdaMotionSAD[0]; // 0 is valid, because for lossless blocks, the cost equation is modified to compensate.
-#endif
-      break;
-    case DF_DEFAULT:
-      dLambda =         m_dLambda;
-      break;
-    case DF_SSE_FRAME:
-      dLambda =         m_dFrameLambda;
-      break;
-    default:
-      assert (0);
-      break;
-  }
-
-  if (bFlag) //NOTE: this "bFlag" is never true
-  {
-    // Intra8x8, Intra4x4 Block only...
-    if (m_costMode != COST_STANDARD_LOSSY)
-    {
-      dRdCost = (Double(uiDistortion) / dLambda) + Double(uiBits); // all lossless costs would have uiDistortion=0, and therefore this cost function can be used.
-    }
-    else
-    {
-      dRdCost = (((Double)(Int64)uiDistortion) + ((Double)(Int64)uiBits * dLambda));
-    }
-  }
-  else
-  {
-    if (eDFunc == DF_SAD)
-    {
-      if (m_costMode != COST_STANDARD_LOSSY)
-      {
-        dRdCost = ((Double(uiDistortion) * 65536) / dLambda) + Double(uiBits); // all lossless costs would have uiDistortion=0, and therefore this cost function can be used.
-      }
-      else
-      {
-        dRdCost = floor(Double(uiDistortion) + (floor((Double(uiBits) * dLambda) + 0.5) / 65536.0));
-      }
-    }
-    else
-    {
-      if (m_costMode != COST_STANDARD_LOSSY)
-      {
-        dRdCost = (Double(uiDistortion) / dLambda) + Double(uiBits); // all lossless costs would have uiDistortion=0, and therefore this cost function can be used.
-      }
-      else
-      {
-        dRdCost = floor(Double(uiDistortion) + (Double(uiBits) * dLambda) + 0.5);
-      }
-    }
-  }
-
-  return dRdCost;
+      return distortion + (numBits * lambda);
+    }
+  }
 }
 
@@ -216,5 +126,4 @@
   m_dLambda           = dLambda;
   m_sqrtLambda        = sqrt(m_dLambda);
-#if RExt__HIGH_BIT_DEPTH_SUPPORT
   m_dLambdaMotionSAD[0] = 65536.0 * m_sqrtLambda;
   m_dLambdaMotionSSE[0] = 65536.0 * m_dLambda;
@@ -226,15 +135,4 @@
   m_dLambdaMotionSAD[1] = 65536.0 * sqrt(dLambda);
   m_dLambdaMotionSSE[1] = 65536.0 * dLambda;
-#else
-  m_uiLambdaMotionSAD[0] = (UInt)floor(65536.0 * m_sqrtLambda);
-  m_uiLambdaMotionSSE[0] = (UInt)floor(65536.0 * m_dLambda   );
-#if FULL_NBIT
-  dLambda = 0.57 * pow(2.0, ((LOSSLESS_AND_MIXED_LOSSLESS_RD_COST_TEST_QP_PRIME - 12) / 3.0));
-#else
-  dLambda = 0.57 * pow(2.0, ((LOSSLESS_AND_MIXED_LOSSLESS_RD_COST_TEST_QP_PRIME - 12 - 6 * (bitDepths.recon[CHANNEL_TYPE_LUMA] - 8)) / 3.0));
-#endif
-  m_uiLambdaMotionSAD[1] = (UInt)floor(65536.0 * sqrt(dLambda));
-  m_uiLambdaMotionSSE[1] = (UInt)floor(65536.0 * dLambda   );
-#endif
 }
 
@@ -298,9 +196,5 @@
   m_costMode                   = COST_STANDARD_LOSSY;
 
-#if RExt__HIGH_BIT_DEPTH_SUPPORT
-  m_dCost                      = 0;
-#else
-  m_uiCost                     = 0;
-#endif
+  m_motionLambda               = 0;
   m_iCostScale                 = 0;
 
@@ -370,8 +264,9 @@
   // initialize
   rcDistParam.iSubShift  = 0;
+  rcDistParam.m_maximumDistortionForEarlyExit = std::numeric_limits<Distortion>::max();
 }
 
 // Setting the Distortion Parameter for Inter (ME)
-Void TComRdCost::setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, DistParam& rcDistParam )
+Void TComRdCost::setDistParam( const TComPattern* const pcPatternKey, const Pel* piRefY, Int iRefStride, DistParam& rcDistParam )
 {
   // set Original & Curr Pointer / Stride
@@ -386,4 +281,5 @@
   rcDistParam.iRows    = pcPatternKey->getROIYHeight();
   rcDistParam.DistFunc = m_afpDistortFunc[DF_SAD + g_aucConvertToBit[ rcDistParam.iCols ] + 1 ];
+  rcDistParam.m_maximumDistortionForEarlyExit = std::numeric_limits<Distortion>::max();
 
   if (rcDistParam.iCols == 12)
@@ -411,5 +307,5 @@
 
 // Setting the Distortion Parameter for Inter (subpel ME with step)
-Void TComRdCost::setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, Int iStep, DistParam& rcDistParam, Bool bHADME )
+Void TComRdCost::setDistParam( const TComPattern* const pcPatternKey, const Pel* piRefY, Int iRefStride, Int iStep, DistParam& rcDistParam, Bool bHADME )
 {
   // set Original & Curr Pointer / Stride
@@ -427,4 +323,6 @@
   rcDistParam.iRows    = pcPatternKey->getROIYHeight();
 
+  rcDistParam.m_maximumDistortionForEarlyExit = std::numeric_limits<Distortion>::max();
+
   // set distortion function
   if ( !bHADME )
@@ -459,5 +357,5 @@
 }
 
-Void TComRdCost::setDistParam( DistParam& rcDP, Int bitDepth, Pel* p1, Int iStride1, Pel* p2, Int iStride2, Int iWidth, Int iHeight, Bool bHadamard )
+Void TComRdCost::setDistParam( DistParam& rcDP, Int bitDepth, const Pel* p1, Int iStride1, const Pel* p2, Int iStride2, Int iWidth, Int iHeight, Bool bHadamard )
 {
   rcDP.pOrg       = p1;
@@ -471,4 +369,5 @@
   rcDP.bitDepth   = bitDepth;
   rcDP.DistFunc   = m_afpDistortFunc[ ( bHadamard ? DF_HADS : DF_SADS ) + g_aucConvertToBit[ iWidth ] + 1 ];
+  rcDP.m_maximumDistortionForEarlyExit = std::numeric_limits<Distortion>::max();
 #if NH_3D_DBBP
   if( m_bUseMask )
@@ -479,5 +378,5 @@
 }
 
-Distortion TComRdCost::calcHAD( Int bitDepth, Pel* pi0, Int iStride0, Pel* pi1, Int iStride1, Int iWidth, Int iHeight )
+Distortion TComRdCost::calcHAD( Int bitDepth, const Pel* pi0, Int iStride0, const Pel* pi1, Int iStride1, Int iWidth, Int iHeight )
 {
   Distortion uiSum = 0;
@@ -550,5 +449,5 @@
 
 
-Distortion TComRdCost::getDistPart( Int bitDepth, Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, const ComponentID compID, DFunc eDFunc )
+Distortion TComRdCost::getDistPart( Int bitDepth, const Pel* piCur, Int iCurStride,  const Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, const ComponentID compID, DFunc eDFunc )
 {
   DistParam cDtParam;
@@ -604,6 +503,7 @@
 
   cDtParam.bitDepth   = bitDepth;
-
+#if NH_3D
   cDtParam.bUseIC       = false;
+#endif
 #if NH_3D_SDC_INTER
   cDtParam.bUseSDCMRSAD = false;
@@ -663,6 +563,6 @@
 UInt TComRdCost::xGetMaskedSSE( DistParam* pcDtParam )
 {
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
   Int  iRows   = pcDtParam->iRows;
   Int  iCols   = pcDtParam->iCols;
@@ -701,6 +601,6 @@
 #endif
   
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
   Int  iRows   = pcDtParam->iRows;
   Int  iCols   = pcDtParam->iCols;
@@ -729,8 +629,8 @@
 UInt TComRdCost::xGetMaskedVSD( DistParam* pcDtParam )
 {
-  Pel* piOrg    = pcDtParam->pOrg;
-  Pel* piCur    = pcDtParam->pCur;
-  Pel* piVirRec = pcDtParam->pVirRec;
-  Pel* piVirOrg = pcDtParam->pVirOrg;
+  const Pel* piOrg    = pcDtParam->pOrg;
+  const Pel* piCur    = pcDtParam->pCur;
+  const Pel* piVirRec = pcDtParam->pVirRec;
+  const Pel* piVirOrg = pcDtParam->pVirOrg;
   Int  iRows    = pcDtParam->iRows;
   Int  iCols    = pcDtParam->iCols;
@@ -786,12 +686,12 @@
   const Pel* piOrg   = pcDtParam->pOrg;
   const Pel* piCur   = pcDtParam->pCur;
-  Int  iRows   = pcDtParam->iRows;
-  Int  iCols   = pcDtParam->iCols;
-  Int  iStrideCur = pcDtParam->iStrideCur;
-  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  const Int  iCols           = pcDtParam->iCols;
+  const Int  iStrideCur      = pcDtParam->iStrideCur;
+  const Int  iStrideOrg      = pcDtParam->iStrideOrg;
+  const UInt distortionShift = DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth - 8);
 
   Distortion uiSum = 0;
 
-  for( ; iRows != 0; iRows-- )
+  for(Int iRows = pcDtParam->iRows ; iRows != 0; iRows-- )
   {
     for (Int n = 0; n < iCols; n++ )
@@ -799,9 +699,13 @@
       uiSum += abs( piOrg[n] - piCur[n] );
     }
-    piOrg += iStrideOrg;
-    piCur += iStrideCur;
-  }
-
-  return ( uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8) );
+    if (pcDtParam->m_maximumDistortionForEarlyExit < ( uiSum >> distortionShift ))
+    {
+      return ( uiSum >> distortionShift );
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum >> distortionShift );
 }
 
@@ -1403,6 +1307,6 @@
     return TComRdCostWeightPrediction::xGetSADw( pcDtParam );
   }
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
   Int  iRows   = pcDtParam->iRows;
   Int  iCols   = pcDtParam->iCols;
@@ -1451,6 +1355,6 @@
     return TComRdCostWeightPrediction::xGetSADw( pcDtParam );
   }
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
   Int  iRows   = pcDtParam->iRows;
   Int  iSubShift  = pcDtParam->iSubShift;
@@ -1508,6 +1412,6 @@
     return TComRdCostWeightPrediction::xGetSADw( pcDtParam );
   }
-  Pel* piOrg      = pcDtParam->pOrg;
-  Pel* piCur      = pcDtParam->pCur;
+  const Pel* piOrg      = pcDtParam->pOrg;
+  const Pel* piCur      = pcDtParam->pCur;
   Int  iRows      = pcDtParam->iRows;
   Int  iSubShift  = pcDtParam->iSubShift;
@@ -1577,6 +1481,6 @@
     return TComRdCostWeightPrediction::xGetSADw( pcDtParam );
   }
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
   Int  iRows   = pcDtParam->iRows;
   Int  iSubShift  = pcDtParam->iSubShift;
@@ -1670,6 +1574,6 @@
     return TComRdCostWeightPrediction::xGetSADw( pcDtParam );
   }
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
   Int  iRows   = pcDtParam->iRows;
   Int  iSubShift  = pcDtParam->iSubShift;
@@ -1748,6 +1652,6 @@
 UInt TComRdCost::xGetSAD16Nic( DistParam* pcDtParam )
 {
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
   Int  iRows   = pcDtParam->iRows;
   Int  iCols   = pcDtParam->iCols;
@@ -1845,6 +1749,6 @@
     return TComRdCostWeightPrediction::xGetSADw( pcDtParam );
   }
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
   Int  iRows   = pcDtParam->iRows;
   Int  iSubShift  = pcDtParam->iSubShift;
@@ -1987,6 +1891,6 @@
     return TComRdCostWeightPrediction::xGetSADw( pcDtParam );
   }
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
   Int  iRows   = pcDtParam->iRows;
   Int  iSubShift  = pcDtParam->iSubShift;
@@ -2104,6 +2008,6 @@
     return TComRdCostWeightPrediction::xGetSADw( pcDtParam );
   }
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
   Int  iRows   = pcDtParam->iRows;
   Int  iSubShift  = pcDtParam->iSubShift;
@@ -2343,6 +2247,6 @@
   }
 
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
   Int  iRows   = pcDtParam->iRows;
   Int  iSubShift  = pcDtParam->iSubShift;
@@ -2879,5 +2783,5 @@
 #if NH_3D_VSO
 //SAIT_VSO_EST_A0033
-UInt TComRdCost::getVSDEstimate( Int dDM, Pel* pOrg, Int iOrgStride,  Pel* pVirRec, Pel* pVirOrg, Int iVirStride, Int x, Int y )
+UInt TComRdCost::getVSDEstimate( Int dDM, const Pel* pOrg, Int iOrgStride, const Pel* pVirRec, const Pel* pVirOrg, Int iVirStride, Int x, Int y )
 { 
   // change to use bit depth from DistParam struct
@@ -2894,8 +2798,8 @@
 UInt TComRdCost::xGetVSD( DistParam* pcDtParam )
 {
-  Pel* piOrg    = pcDtParam->pOrg;
-  Pel* piCur    = pcDtParam->pCur;
-  Pel* piVirRec = pcDtParam->pVirRec;
-  Pel* piVirOrg = pcDtParam->pVirOrg;
+  const Pel* piOrg    = pcDtParam->pOrg;
+  const Pel* piCur    = pcDtParam->pCur;
+  const Pel* piVirRec = pcDtParam->pVirRec;
+  const Pel* piVirOrg = pcDtParam->pVirOrg;
   Int  iRows    = pcDtParam->iRows;
   Int  iCols    = pcDtParam->iCols;
@@ -2925,8 +2829,8 @@
 UInt TComRdCost::xGetVSD4( DistParam* pcDtParam )
 {
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
-  Pel* piVirRec = pcDtParam->pVirRec;
-  Pel* piVirOrg = pcDtParam->pVirOrg;
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
+  const Pel* piVirRec = pcDtParam->pVirRec;
+  const Pel* piVirOrg = pcDtParam->pVirOrg;
   Int  iRows   = pcDtParam->iRows;
   Int  iStrideOrg = pcDtParam->iStrideOrg;
@@ -2955,8 +2859,8 @@
 UInt TComRdCost::xGetVSD8( DistParam* pcDtParam )
 {
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
-  Pel* piVirRec = pcDtParam->pVirRec;
-  Pel* piVirOrg = pcDtParam->pVirOrg;
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
+  const Pel* piVirRec = pcDtParam->pVirRec;
+  const Pel* piVirOrg = pcDtParam->pVirOrg;
   Int  iRows   = pcDtParam->iRows;
   Int  iStrideOrg = pcDtParam->iStrideOrg;
@@ -2985,8 +2889,8 @@
 UInt TComRdCost::xGetVSD16( DistParam* pcDtParam )
 {
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
-  Pel* piVirRec = pcDtParam->pVirRec;
-  Pel* piVirOrg = pcDtParam->pVirOrg;
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
+  const Pel* piVirRec = pcDtParam->pVirRec;
+  const Pel* piVirOrg = pcDtParam->pVirOrg;
   Int  iRows   = pcDtParam->iRows;
   Int  iStrideOrg = pcDtParam->iStrideOrg;
@@ -3015,8 +2919,8 @@
 UInt TComRdCost::xGetVSD16N( DistParam* pcDtParam )
 {
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
-  Pel* piVirRec = pcDtParam->pVirRec;
-  Pel* piVirOrg = pcDtParam->pVirOrg;
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
+  const Pel* piVirRec = pcDtParam->pVirRec;
+  const Pel* piVirOrg = pcDtParam->pVirOrg;
   Int  iRows   = pcDtParam->iRows;
   Int  iCols   = pcDtParam->iCols;
@@ -3049,8 +2953,8 @@
 UInt TComRdCost::xGetVSD32( DistParam* pcDtParam )
 {
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
-  Pel* piVirRec = pcDtParam->pVirRec;
-  Pel* piVirOrg = pcDtParam->pVirOrg;
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
+  const Pel* piVirRec = pcDtParam->pVirRec;
+  const Pel* piVirOrg = pcDtParam->pVirOrg;
   Int  iRows   = pcDtParam->iRows;
   Int  iStrideOrg = pcDtParam->iStrideOrg;
@@ -3079,8 +2983,8 @@
 UInt TComRdCost::xGetVSD64( DistParam* pcDtParam )
 {
-  Pel* piOrg      = pcDtParam->pOrg;
-  Pel* piCur      = pcDtParam->pCur;
-  Pel* piVirRec   = pcDtParam->pVirRec;
-  Pel* piVirOrg   = pcDtParam->pVirOrg;
+  const Pel* piOrg      = pcDtParam->pOrg;
+  const Pel* piCur      = pcDtParam->pCur;
+  const Pel* piVirRec   = pcDtParam->pVirRec;
+  const Pel* piVirOrg   = pcDtParam->pVirOrg;
   Int  iRows      = pcDtParam->iRows;
   Int  iStrideOrg = pcDtParam->iStrideOrg;
@@ -3113,5 +3017,5 @@
 // --------------------------------------------------------------------------------------------------------------------
 
-Distortion TComRdCost::xCalcHADs2x2( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
+Distortion TComRdCost::xCalcHADs2x2( const Pel *piOrg, const Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
 {
   Distortion satd = 0;
@@ -3135,5 +3039,5 @@
 }
 
-Distortion TComRdCost::xCalcHADs4x4( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
+Distortion TComRdCost::xCalcHADs4x4( const Pel *piOrg, const Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
 {
   Int k;
@@ -3231,5 +3135,5 @@
 }
 
-Distortion TComRdCost::xCalcHADs8x8( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
+Distortion TComRdCost::xCalcHADs8x8( const Pel *piOrg, const Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
 {
   Int k, i, j, jj;
@@ -3348,11 +3252,11 @@
 #endif
 
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
-  Int  iRows   = pcDtParam->iRows;
-  Int  iCols   = pcDtParam->iCols;
-  Int  iStrideCur = pcDtParam->iStrideCur;
-  Int  iStrideOrg = pcDtParam->iStrideOrg;
-  Int  iStep  = pcDtParam->iStep;
+  const Pel* piOrg      = pcDtParam->pOrg;
+  const Pel* piCur      = pcDtParam->pCur;
+  const Int  iRows      = pcDtParam->iRows;
+  const Int  iCols      = pcDtParam->iCols;
+  const Int  iStrideCur = pcDtParam->iStrideCur;
+  const Int  iStrideOrg = pcDtParam->iStrideOrg;
+  const Int  iStep      = pcDtParam->iStep;
 
   Int  x, y;
@@ -3418,6 +3322,7 @@
     return TComRdCostWeightPrediction::xGetHADsw( pcDtParam );
   }
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
+  
   Int  iRows   = pcDtParam->iRows;
   Int  iCols   = pcDtParam->iCols;
@@ -3449,12 +3354,21 @@
   iDeltaC = (iOrigAvg - iCurAvg)/iRows/iCols;
 
+  const Int orgMaxSize = MAX_CU_SIZE*MAX_CU_SIZE;
+  assert( iRows * iCols <= orgMaxSize ); 
+  
+  Pel orgMinusDeltaDc[ orgMaxSize ];
+  Pel* tempOrgMinusDeltaDc = orgMinusDeltaDc; 
+  
   for ( y=0; y<iRows; y++ )
   {
     for ( x=0; x<iCols; x++ )
     {        
-      piOrg[x] -= iDeltaC;
-    }
-    piOrg += iStrideOrg;
-  }
+      tempOrgMinusDeltaDc[x] = (piOrg[x] - iDeltaC);
+    }
+    piOrg               += iStrideOrg;
+    tempOrgMinusDeltaDc += iStrideOrg;
+  }
+
+  tempOrgMinusDeltaDc = orgMinusDeltaDc; 
 
   piOrg   = pcDtParam->pOrg;
@@ -3472,8 +3386,8 @@
       for ( x=0; x<iCols; x+= 8 )
       {
-        uiSum += xCalcHADs8x8( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+        uiSum += xCalcHADs8x8( &tempOrgMinusDeltaDc[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
       }
-      piOrg += iOffsetOrg;
-      piCur += iOffsetCur;
+      tempOrgMinusDeltaDc += iOffsetOrg;
+      piCur               += iOffsetCur;
     }
   }
@@ -3487,8 +3401,8 @@
       for ( x=0; x<iCols; x+= 16 )
       {
-        uiSum += xCalcHADs16x4( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+        uiSum += xCalcHADs16x4( &tempOrgMinusDeltaDc[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
       }
-      piOrg += iOffsetOrg;
-      piCur += iOffsetCur;
+      tempOrgMinusDeltaDc += iOffsetOrg;
+      piCur               += iOffsetCur;
     }
   }
@@ -3501,8 +3415,8 @@
       for ( x=0; x<iCols; x+= 4 )
       {
-        uiSum += xCalcHADs4x16( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+        uiSum += xCalcHADs4x16( &tempOrgMinusDeltaDc[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
       }
-      piOrg += iOffsetOrg;
-      piCur += iOffsetCur;
+      tempOrgMinusDeltaDc += iOffsetOrg;
+      piCur               += iOffsetCur;
     }
   }
@@ -3517,8 +3431,8 @@
       for ( x=0; x<iCols; x+= 4 )
       {
-        uiSum += xCalcHADs4x4( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+        uiSum += xCalcHADs4x4( &tempOrgMinusDeltaDc[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
       }
-      piOrg += iOffsetOrg;
-      piCur += iOffsetCur;
+      tempOrgMinusDeltaDc += iOffsetOrg;
+      piCur               += iOffsetCur;
     }
   }
@@ -3531,8 +3445,8 @@
       for ( x=0; x<iCols; x+=2 )
       {
-        uiSum += xCalcHADs2x2( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+        uiSum += xCalcHADs2x2( &tempOrgMinusDeltaDc[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
       }
-      piOrg += iOffsetOrg;
-      piCur += iOffsetCur;
+      tempOrgMinusDeltaDc += iOffsetOrg;
+      piCur               += iOffsetCur;
     }
   }
@@ -3540,15 +3454,4 @@
   {
     assert(false);
-  }
-
-  piOrg   = pcDtParam->pOrg;
-
-  for ( y=0; y<iRows; y++ )
-  {
-    for ( x=0; x<iCols; x++ )
-    {        
-      piOrg[x] += iDeltaC;
-    }
-    piOrg += iStrideOrg;
   }
 
Index: trunk/source/Lib/TLibCommon/TComRdCost.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComRdCost.h	(revision 1357)
+++ trunk/source/Lib/TLibCommon/TComRdCost.h	(revision 1386)
@@ -46,5 +46,5 @@
 #include "TComSlice.h"
 #include "TComRdCostWeightPrediction.h"
-#if NH_3D
+#if NH_3D_VSO
 #include "../TLibRenderer/TRenModel.h"
 #include "TComYuv.h"
@@ -57,5 +57,5 @@
 class DistParam;
 class TComPattern;
-#if NH_3D
+#if NH_3D_VSO
 class TComRdCost; 
 #endif
@@ -68,8 +68,7 @@
 typedef Distortion (*FpDistFunc) (DistParam*); // TODO: can this pointer be replaced with a reference? - there are no NULL checks on pointer.
 
-#if NH_3D
+
 #if NH_3D_VSO
 typedef Dist (TComRdCost::*FpDistFuncVSO) ( Int, Int, Pel*, Int, Pel*, Int, UInt, UInt, Bool );
-#endif
 #endif
 // ====================================================================================================================
@@ -81,6 +80,6 @@
 {
 public:
-  Pel*  pOrg;
-  Pel*  pCur;
+  const Pel*            pOrg;
+  const Pel*            pCur;
   Int   iStrideOrg;
   Int   iStrideCur;
@@ -104,6 +103,9 @@
 
   Bool            bApplyWeight;     // whether weighted prediction is used or not
-  WPScalingParam  *wpCur;           // weighted prediction scaling parameters for current ref
+  Bool                  bIsBiPred;
+
+  const WPScalingParam *wpCur;           // weighted prediction scaling parameters for current ref
   ComponentID     compIdx;
+  Distortion            m_maximumDistortionForEarlyExit; /// During cost calculations, if distortion exceeds this value, cost calculations may early-terminate.
 
   // (vertical) subsampling shift (for reducing complexity)
@@ -112,15 +114,20 @@
 
   DistParam()
+   : pOrg(NULL),
+     pCur(NULL),
+     iStrideOrg(0),
+     iStrideCur(0),
+     iRows(0),
+     iCols(0),
+     iStep(1),
+     DistFunc(NULL),
+     bitDepth(0),
+     bApplyWeight(false),
+     bIsBiPred(false),
+     wpCur(NULL),
+     compIdx(MAX_NUM_COMPONENT),
+     m_maximumDistortionForEarlyExit(std::numeric_limits<Distortion>::max()),
+     iSubShift(0)
   {
-    pOrg = NULL;
-    pCur = NULL;
-    iStrideOrg = 0;
-    iStrideCur = 0;
-    iRows = 0;
-    iCols = 0;
-    iStep = 1;
-    DistFunc = NULL;
-    iSubShift = 0;
-    bitDepth = 0;
 #if NH_3D_VSO
     // SAIT_VSO_EST_A0033
@@ -146,11 +153,6 @@
   Double                  m_dLambda;
   Double                  m_sqrtLambda;
-#if RExt__HIGH_BIT_DEPTH_SUPPORT
   Double                  m_dLambdaMotionSAD[2 /* 0=standard, 1=for transquant bypass when mixed-lossless cost evaluation enabled*/];
   Double                  m_dLambdaMotionSSE[2 /* 0=standard, 1=for transquant bypass when mixed-lossless cost evaluation enabled*/];
-#else
-  UInt                    m_uiLambdaMotionSAD[2 /* 0=standard, 1=for transquant bypass when mixed-lossless cost evaluation enabled*/];
-  UInt                    m_uiLambdaMotionSSE[2 /* 0=standard, 1=for transquant bypass when mixed-lossless cost evaluation enabled*/];
-#endif
   Double                  m_dFrameLambda;
 #if NH_3D_VSO
@@ -161,9 +163,5 @@
   // for motion cost
   TComMv                  m_mvPredictor;
-#if RExt__HIGH_BIT_DEPTH_SUPPORT
-  Double                  m_dCost;
-#else
-  UInt                    m_uiCost;
-#endif
+  Double                  m_motionLambda;
   Int                     m_iCostScale;
 #if NH_3D_DBBP
@@ -175,10 +173,10 @@
   virtual ~TComRdCost();
 #if NH_3D_VSO
-  Double  calcRdCost  ( UInt   uiBits, Dist   uiDistortion, Bool bFlag = false, DFunc eDFunc = DF_DEFAULT );
-  Double  calcRdCost64( UInt64 uiBits, Dist64 uiDistortion, Bool bFlag = false, DFunc eDFunc = DF_DEFAULT );
+  Double  calcRdCost64( UInt64 uiBits , Dist64 uiDistortion, Bool bFlag = false, DFunc eDFunc = DF_DEFAULT );
+  Double  calcRdCost( Double numBits, Dist intDistortion, DFunc eDFunc  = DF_DEFAULT );
 #else
-  Double  calcRdCost  ( UInt   uiBits, Distortion uiDistortion, Bool bFlag = false, DFunc eDFunc = DF_DEFAULT );
-  Double  calcRdCost64( UInt64 uiBits, UInt64 uiDistortion, Bool bFlag = false, DFunc eDFunc = DF_DEFAULT );
-#endif
+  Double calcRdCost( Double numBits, Double distortion, DFunc eDFunc = DF_DEFAULT );
+#endif
+
 
   Void    setDistortionWeight  ( const ComponentID compID, const Double distortionWeight ) { m_distortionWeight[compID] = distortionWeight; }
@@ -202,7 +200,7 @@
 
   Void    setDistParam( UInt uiBlkWidth, UInt uiBlkHeight, DFunc eDFunc, DistParam& rcDistParam );
-  Void    setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride,            DistParam& rcDistParam );
-  Void    setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, Int iStep, DistParam& rcDistParam, Bool bHADME=false );
-  Void    setDistParam( DistParam& rcDP, Int bitDepth, Pel* p1, Int iStride1, Pel* p2, Int iStride2, Int iWidth, Int iHeight, Bool bHadamard = false );
+  Void    setDistParam( const TComPattern* const pcPatternKey, const Pel* piRefY, Int iRefStride,            DistParam& rcDistParam );
+  Void    setDistParam( const TComPattern* const pcPatternKey, const Pel* piRefY, Int iRefStride, Int iStep, DistParam& rcDistParam, Bool bHADME=false );
+  Void    setDistParam( DistParam& rcDP, Int bitDepth, const Pel* p1, Int iStride1, const Pel* p2, Int iStride2, Int iWidth, Int iHeight, Bool bHadamard = false );
 
 #if NH_3D_DBBP
@@ -210,5 +208,5 @@
 #endif
 
-  Distortion calcHAD(Int bitDepth, Pel* pi0, Int iStride0, Pel* pi1, Int iStride1, Int iWidth, Int iHeight );
+  Distortion calcHAD(Int bitDepth, const Pel* pi0, Int iStride0, const Pel* pi1, Int iStride1, Int iWidth, Int iHeight );
 
 #if NH_3D_ENC_DEPTH
@@ -218,9 +216,5 @@
   // for motion cost
   static UInt    xGetExpGolombNumberOfBits( Int iVal );
-#if RExt__HIGH_BIT_DEPTH_SUPPORT
-  Void    getMotionCost( Bool bSad, Int iAdd, Bool bIsTransquantBypass ) { m_dCost = (bSad ? m_dLambdaMotionSAD[(bIsTransquantBypass && m_costMode==COST_MIXED_LOSSLESS_LOSSY_CODING) ?1:0] + iAdd : m_dLambdaMotionSSE[(bIsTransquantBypass && m_costMode==COST_MIXED_LOSSLESS_LOSSY_CODING)?1:0] + iAdd); }
-#else
-  Void    getMotionCost( Bool bSad, Int iAdd, Bool bIsTransquantBypass ) { m_uiCost = (bSad ? m_uiLambdaMotionSAD[(bIsTransquantBypass && m_costMode==COST_MIXED_LOSSLESS_LOSSY_CODING) ?1:0] + iAdd : m_uiLambdaMotionSSE[(bIsTransquantBypass && m_costMode==COST_MIXED_LOSSLESS_LOSSY_CODING)?1:0] + iAdd); }
-#endif
+  Void    selectMotionLambda( Bool bSad, Int iAdd, Bool bIsTransquantBypass ) { m_motionLambda = (bSad ? m_dLambdaMotionSAD[(bIsTransquantBypass && m_costMode==COST_MIXED_LOSSLESS_LOSSY_CODING) ?1:0] + iAdd : m_dLambdaMotionSSE[(bIsTransquantBypass && m_costMode==COST_MIXED_LOSSLESS_LOSSY_CODING)?1:0] + iAdd); }
   Void    setPredictor( TComMv& rcMv )
   {
@@ -228,18 +222,10 @@
   }
   Void    setCostScale( Int iCostScale )    { m_iCostScale = iCostScale; }
-  __inline Distortion getCost( Int x, Int y )
+  Distortion getCost( UInt b )                 { return Distortion(( m_motionLambda * b ) / 65536.0); }
+  Distortion getCostOfVectorWithPredictor( const Int x, const Int y )
   {
-#if RExt__HIGH_BIT_DEPTH_SUPPORT
-    return Distortion((m_dCost * getBits(x, y)) / 65536.0);
-#else
-    return m_uiCost * getBits(x, y) >> 16;
-#endif
+    return Distortion((m_motionLambda * getBitsOfVectorWithPredictor(x, y)) / 65536.0);
   }
-#if RExt__HIGH_BIT_DEPTH_SUPPORT
-  Distortion getCost( UInt b )                 { return Distortion(( m_dCost * b ) / 65536.0); }
-#else
-  Distortion getCost( UInt b )                 { return ( m_uiCost * b ) >> 16; }
-#endif
-  UInt    getBits( Int x, Int y )
+  UInt getBitsOfVectorWithPredictor( const Int x, const Int y )
   {
     return xGetExpGolombNumberOfBits((x << m_iCostScale) - m_mvPredictor.getHor())
@@ -299,7 +285,7 @@
 
   static Distortion xGetHADs          ( DistParam* pcDtParam );
-  static Distortion xCalcHADs2x2      ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
-  static Distortion xCalcHADs4x4      ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
-  static Distortion xCalcHADs8x8      ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
+  static Distortion xCalcHADs2x2      ( const Pel *piOrg, const Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
+  static Distortion xCalcHADs4x4      ( const Pel *piOrg, const Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
+  static Distortion xCalcHADs8x8      ( const Pel *piOrg, const Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
 #if NH_3D_DBBP
   static UInt xGetMaskedSSE     ( DistParam* pcDtParam );
@@ -311,5 +297,5 @@
 public:
 
-  Distortion   getDistPart(Int bitDepth, Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, const ComponentID compID, DFunc eDFunc = DF_SSE );
+  Distortion   getDistPart(Int bitDepth, const Pel* piCur, Int iCurStride, const Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, const ComponentID compID, DFunc eDFunc = DF_SSE );
 
 #if KWU_RC_MADPRED_E0227
@@ -320,5 +306,5 @@
   // SAIT_VSO_EST_A0033
   UInt        getDistPartVSD( TComDataCU* pcCu, UInt uiPartOffset, Int bitDepth, Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, Bool bHad, DFunc eDFunc = DF_VSD); 
-  static UInt getVSDEstimate( Int dDM, Pel* pOrg, Int iOrgStride,  Pel* pVirRec, Pel* pVirOrg, Int iVirStride, Int x, Int y );
+  static UInt getVSDEstimate( Int dDM, const Pel* pOrg, Int iOrgStride,  const Pel* pVirRec, const Pel* pVirOrg, Int iVirStride, Int x, Int y );
 
 private:
Index: trunk/source/Lib/TLibCommon/TComRdCostWeightPrediction.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComRdCostWeightPrediction.cpp	(revision 1357)
+++ trunk/source/Lib/TLibCommon/TComRdCostWeightPrediction.cpp	(revision 1386)
@@ -70,7 +70,9 @@
   const Int             shift      = wpCur.shift;
   const Int             round      = wpCur.round;
+  const Int        distortionShift = DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
 
   Distortion uiSum = 0;
 
+#if !U0040_MODIFIED_WEIGHTEDPREDICTION_WITH_BIPRED_AND_CLIPPING
   for(Int iRows = pcDtParam->iRows; iRows != 0; iRows-- )
   {
@@ -80,4 +82,8 @@
 
       uiSum += abs( piOrg[n] - pred );
+    }
+    if (pcDtParam->m_maximumDistortionForEarlyExit <  ( uiSum >> distortionShift))
+    {
+      return uiSum >> distortionShift;
     }
     piOrg += iStrideOrg;
@@ -86,6 +92,137 @@
 
   pcDtParam->compIdx = MAX_NUM_COMPONENT;  // reset for DEBUG (assert test)
-
-  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
+#else
+  // Default weight
+  if (w0 == 1 << shift)
+  {
+    // no offset
+    if (offset == 0)
+    {
+      for(Int iRows = pcDtParam->iRows; iRows != 0; iRows-- )
+      {
+        for (Int n = 0; n < iCols; n++ )
+        {
+          uiSum += abs( piOrg[n] - piCur[n] );
+        }
+        if (pcDtParam->m_maximumDistortionForEarlyExit <  ( uiSum >> distortionShift))
+        {
+          return uiSum >> distortionShift;
+        }
+        piOrg += iStrideOrg;
+        piCur += iStrideCur;
+      }
+    }
+    else
+    {
+      // Lets not clip for the bipredictive case since clipping should be done after
+      // combining both elements. Unfortunately the code uses the suboptimal "subtraction"
+      // method, which is faster but introduces the clipping issue (therefore Bipred is suboptimal).
+      if (pcDtParam->bIsBiPred)
+      {
+        for(Int iRows = pcDtParam->iRows; iRows != 0; iRows-- )
+        {
+          for (Int n = 0; n < iCols; n++ )
+          {
+            uiSum += abs( piOrg[n] - (piCur[n] + offset) );
+          }
+          if (pcDtParam->m_maximumDistortionForEarlyExit <  ( uiSum >> distortionShift))
+          {
+            return uiSum >> distortionShift;
+          }
+
+          piOrg += iStrideOrg;
+          piCur += iStrideCur;
+        }
+      }
+      else
+      {
+        const Pel iMaxValue = (Pel) ((1 << pcDtParam->bitDepth) - 1);
+        for(Int iRows = pcDtParam->iRows; iRows != 0; iRows-- )
+        {
+          for (Int n = 0; n < iCols; n++ )
+          {
+            const Pel pred = Clip3((Pel) 0, iMaxValue, (Pel) (piCur[n] + offset)) ;
+
+            uiSum += abs( piOrg[n] - pred );
+          }
+          if (pcDtParam->m_maximumDistortionForEarlyExit <  ( uiSum >> distortionShift))
+          {
+            return uiSum >> distortionShift;
+          }
+          piOrg += iStrideOrg;
+          piCur += iStrideCur;
+        }
+      }
+    }
+  }
+  else
+  {
+    // Lets not clip for the bipredictive case since clipping should be done after
+    // combining both elements. Unfortunately the code uses the suboptimal "subtraction"
+    // method, which is faster but introduces the clipping issue (therefore Bipred is suboptimal).
+    if (pcDtParam->bIsBiPred)
+    {
+      for(Int iRows = pcDtParam->iRows; iRows != 0; iRows-- )
+      {
+        for (Int n = 0; n < iCols; n++ )
+        {
+          const Pel pred = ( (w0*piCur[n] + round) >> shift ) + offset ;
+          uiSum += abs( piOrg[n] - pred );
+        }
+        if (pcDtParam->m_maximumDistortionForEarlyExit <  ( uiSum >> distortionShift))
+        {
+          return uiSum >> distortionShift;
+        }
+
+        piOrg += iStrideOrg;
+        piCur += iStrideCur;
+      }
+    }
+    else
+    {
+      const Pel iMaxValue = (Pel) ((1 << pcDtParam->bitDepth) - 1);
+
+      if (offset == 0)
+      {
+        for(Int iRows = pcDtParam->iRows; iRows != 0; iRows-- )
+        {
+          for (Int n = 0; n < iCols; n++ )
+          {
+            const Pel pred = Clip3((Pel) 0, iMaxValue, (Pel) (( (w0*piCur[n] + round) >> shift ))) ;
+
+            uiSum += abs( piOrg[n] - pred );
+          }
+          if (pcDtParam->m_maximumDistortionForEarlyExit <  ( uiSum >> distortionShift))
+          {
+            return uiSum >> distortionShift;
+          }
+          piOrg += iStrideOrg;
+          piCur += iStrideCur;
+        }
+      }
+      else
+      {
+        for(Int iRows = pcDtParam->iRows; iRows != 0; iRows-- )
+        {
+          for (Int n = 0; n < iCols; n++ )
+          {
+            const Pel pred = Clip3((Pel) 0, iMaxValue, (Pel) (( (w0*piCur[n] + round) >> shift ) + offset)) ;
+
+            uiSum += abs( piOrg[n] - pred );
+          }
+          if (pcDtParam->m_maximumDistortionForEarlyExit <  ( uiSum >> distortionShift))
+          {
+            return uiSum >> distortionShift;
+          }
+          piOrg += iStrideOrg;
+          piCur += iStrideCur;
+        }
+      }
+    }
+  }
+  //pcDtParam->compIdx = MAX_NUM_COMPONENT;  // reset for DEBUG (assert test)
+#endif
+
+  return uiSum >> distortionShift;
 }
 
@@ -119,4 +256,5 @@
   Distortion sum = 0;
 
+#if !U0040_MODIFIED_WEIGHTEDPREDICTION_WITH_BIPRED_AND_CLIPPING
   for(Int iRows = pcDtParam->iRows ; iRows != 0; iRows-- )
   {
@@ -132,4 +270,38 @@
 
   pcDtParam->compIdx = MAX_NUM_COMPONENT; // reset for DEBUG (assert test)
+#else
+  if (pcDtParam->bIsBiPred)
+  {
+    for(Int iRows = pcDtParam->iRows ; iRows != 0; iRows-- )
+    {
+      for (Int n = 0; n < iCols; n++ )
+      {
+        const Pel pred     = ( (w0*piCur[n] + round) >> shift ) + offset ;
+        const Pel residual = piOrg[n] - pred;
+        sum += ( Distortion(residual) * Distortion(residual) ) >> distortionShift;
+      }
+      piOrg += iStrideOrg;
+      piCur += iStrideCur;
+    }
+  }
+  else
+  {
+    const Pel iMaxValue = (Pel) ((1 << pcDtParam->bitDepth) - 1);
+
+    for(Int iRows = pcDtParam->iRows ; iRows != 0; iRows-- )
+    {
+      for (Int n = 0; n < iCols; n++ )
+      {
+        const Pel pred     = Clip3((Pel) 0, iMaxValue, (Pel) (( (w0*piCur[n] + round) >> shift ) + offset)) ;
+        const Pel residual = piOrg[n] - pred;
+        sum += ( Distortion(residual) * Distortion(residual) ) >> distortionShift;
+      }
+      piOrg += iStrideOrg;
+      piCur += iStrideCur;
+    }
+  }
+
+  //pcDtParam->compIdx = MAX_NUM_COMPONENT; // reset for DEBUG (assert test)
+#endif
 
   return sum;
@@ -416,5 +588,5 @@
   const ComponentID compIdx    = pcDtParam->compIdx;
   assert(compIdx<MAX_NUM_COMPONENT);
-  const WPScalingParam  wpCur    = pcDtParam->wpCur[compIdx];
+  const WPScalingParam &wpCur  = pcDtParam->wpCur[compIdx];
 
   Distortion uiSum = 0;
Index: trunk/source/Lib/TLibCommon/TComRom.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComRom.cpp	(revision 1357)
+++ trunk/source/Lib/TLibCommon/TComRom.cpp	(revision 1386)
@@ -47,5 +47,5 @@
 //! \ingroup TLibCommon
 //! \{
-const Char* nalUnitTypeToString(NalUnitType type)
+const TChar* nalUnitTypeToString(NalUnitType type)
 {
   switch (type)
@@ -221,5 +221,5 @@
   }
 #if NH_MV
-#if H_MV_HLS_PTL_LIMITS 
+#if NH_MV_HLS_PTL_LIMITS 
  g_generalTierAndLevelLimits[ Level::LEVEL1   ] = TComGeneralTierAndLevelLimits(    36864,     350,  MIN_INT,   16,   1,   1 );
  g_generalTierAndLevelLimits[ Level::LEVEL2   ] = TComGeneralTierAndLevelLimits(   122880,    1500,  MIN_INT,   16,   1,   1 );
@@ -532,5 +532,5 @@
 // Misc.
 // ====================================================================================================================
-Char  g_aucConvertToBit  [ MAX_CU_SIZE+1 ];
+SChar  g_aucConvertToBit  [ MAX_CU_SIZE+1 ];
 #if ENC_DEC_TRACE
 FILE*  g_hTrace = NULL; // Set to NULL to open up a file. Set to stdout to use the current output
@@ -540,5 +540,5 @@
 Bool   g_bJustDoIt = false;
 UInt64 g_nSymbolCounter = 0;
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
 Bool g_traceCU = false; 
 Bool g_tracePU = false; 
@@ -582,5 +582,5 @@
 const UInt g_uiMinInGroup[ LAST_SIGNIFICANT_GROUPS ] = {0,1,2,3,4,6,8,12,16,24};
 const UInt g_uiGroupIdx[ MAX_TU_SIZE ]   = {0,1,2,3,4,4,5,5,6,6,6,6,7,7,7,7,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9};
-const Char *MatrixType[SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM] =
+const TChar *MatrixType[SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM] =
 {
   {
@@ -617,5 +617,5 @@
   },
 };
-const Char *MatrixType_DC[SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM] =
+const TChar *MatrixType_DC[SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM] =
 {
   {
@@ -671,7 +671,7 @@
 const UInt g_scalingListSize   [SCALING_LIST_SIZE_NUM] = {16,64,256,1024};
 const UInt g_scalingListSizeX  [SCALING_LIST_SIZE_NUM] = { 4, 8, 16,  32};
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
 #if ENC_DEC_TRACE
-Void tracePSHeader( const Char* psName, Int layerId )
+Void tracePSHeader( const TChar* psName, Int layerId )
 {  
   if ( !g_disableHLSTrace  ) 
@@ -727,5 +727,5 @@
   }  
 }
-Void writeToTraceFile( const Char* symbolName, Int val, Bool doIt )
+Void writeToTraceFile( const TChar* symbolName, Int val, Bool doIt )
 {
   if ( ( ( g_nSymbolCounter >= COUNTER_START && g_nSymbolCounter <= COUNTER_END )|| g_bJustDoIt ) && doIt  ) 
@@ -749,5 +749,5 @@
   return g_nSymbolCounter; 
 }
-Void writeToTraceFile( const Char* symbolName, Bool doIt )
+Void writeToTraceFile( const TChar* symbolName, Bool doIt )
 {
   if ( ( ( g_nSymbolCounter >= COUNTER_START && g_nSymbolCounter <= COUNTER_END )|| g_bJustDoIt ) && doIt  ) 
Index: trunk/source/Lib/TLibCommon/TComRom.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComRom.h	(revision 1357)
+++ trunk/source/Lib/TLibCommon/TComRom.h	(revision 1386)
@@ -112,5 +112,5 @@
 // ====================================================================================================================
 extern const TMatrixCoeff g_as_DST_MAT_4 [TRANSFORM_NUMBER_OF_DIRECTIONS][4][4];
-#if H_MV_HLS_PTL_LIMITS
+#if NH_MV_HLS_PTL_LIMITS
 class TComGeneralTierAndLevelLimits
 {
@@ -149,5 +149,5 @@
 // Misc.
 // ====================================================================================================================
-extern       Char   g_aucConvertToBit  [ MAX_CU_SIZE+1 ];   // from width to log2(width)-2
+extern       SChar   g_aucConvertToBit  [ MAX_CU_SIZE+1 ];   // from width to log2(width)-2
 #if NH_MV
 // Change later
@@ -172,5 +172,5 @@
 #define DTRACE_CABAC_R( x,y ) if ( ( g_nSymbolCounter >= COUNTER_START && g_nSymbolCounter <= COUNTER_END )|| g_bJustDoIt ) fprintf( g_hTrace, x,    y );
 #define DTRACE_CABAC_N        if ( ( g_nSymbolCounter >= COUNTER_START && g_nSymbolCounter <= COUNTER_END )|| g_bJustDoIt ) fprintf( g_hTrace, "\n"    );
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
  extern Bool   g_traceCU; 
  extern Bool   g_tracePU ; 
@@ -206,7 +206,7 @@
 #define D_PRINT_INC_INDENT( b, str ) prinStrIncIndent( b, str );
 #define D_PRINT_INDENT( b, str )     printStrIndent   ( b, str);
- Void           tracePSHeader   ( const Char* psName, Int layerId ); 
- Void           writeToTraceFile( const Char* symbolName, Int val, Bool doIt );
- Void           writeToTraceFile( const Char* symbolName, Bool doIt );
+ Void           tracePSHeader   ( const TChar* psName, Int layerId ); 
+ Void           writeToTraceFile( const TChar* symbolName, Int val, Bool doIt );
+ Void           writeToTraceFile( const TChar* symbolName, Bool doIt );
  UInt64         incSymbolCounter();          
  Void           stopAtPos       ( Int poc, Int layerId, Int cuPelX, Int cuPelY, Int cuWidth, Int cuHeight );           
@@ -243,7 +243,8 @@
 #endif
 #endif
-const Char* nalUnitTypeToString(NalUnitType type);
-extern const Char *MatrixType[SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM];
-extern const Char *MatrixType_DC[SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM];
+const TChar* nalUnitTypeToString(NalUnitType type);
+
+extern const TChar *MatrixType[SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM];
+extern const TChar *MatrixType_DC[SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM];
 extern const Int g_quantTSDefault4x4[4*4];
 extern const Int g_quantIntraDefault8x8[8*8];
Index: trunk/source/Lib/TLibCommon/TComSampleAdaptiveOffset.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComSampleAdaptiveOffset.cpp	(revision 1357)
+++ trunk/source/Lib/TLibCommon/TComSampleAdaptiveOffset.cpp	(revision 1386)
@@ -324,5 +324,5 @@
       m_signLineBuf1 = NULL;
     }
-    m_signLineBuf1 = new Char[m_lineBufWidth+1];
+    m_signLineBuf1 = new SChar[m_lineBufWidth+1];
 
     if (m_signLineBuf2)
@@ -331,5 +331,5 @@
       m_signLineBuf2 = NULL;
     }
-    m_signLineBuf2 = new Char[m_lineBufWidth+1];
+    m_signLineBuf2 = new SChar[m_lineBufWidth+1];
   }
 
@@ -338,5 +338,5 @@
   Int x,y, startX, startY, endX, endY, edgeType;
   Int firstLineStartX, firstLineEndX, lastLineStartX, lastLineEndX;
-  Char signLeft, signRight, signDown;
+  SChar signLeft, signRight, signDown;
 
   Pel* srcLine = srcBlk;
@@ -352,8 +352,8 @@
       for (y=0; y< height; y++)
       {
-        signLeft = (Char)sgn(srcLine[startX] - srcLine[startX-1]);
+        signLeft = (SChar)sgn(srcLine[startX] - srcLine[startX-1]);
         for (x=startX; x< endX; x++)
         {
-          signRight = (Char)sgn(srcLine[x] - srcLine[x+1]); 
+          signRight = (SChar)sgn(srcLine[x] - srcLine[x+1]);
           edgeType =  signRight + signLeft;
           signLeft  = -signRight;
@@ -370,5 +370,5 @@
     {
       offset += 2;
-      Char *signUpLine = m_signLineBuf1;
+      SChar *signUpLine = m_signLineBuf1;
 
       startY = isAboveAvail ? 0 : 1;
@@ -383,5 +383,5 @@
       for (x=0; x< width; x++)
       {
-        signUpLine[x] = (Char)sgn(srcLine[x] - srcLineAbove[x]);
+        signUpLine[x] = (SChar)sgn(srcLine[x] - srcLineAbove[x]);
       }
 
@@ -393,5 +393,5 @@
         for (x=0; x< width; x++)
         {
-          signDown  = (Char)sgn(srcLine[x] - srcLineBelow[x]);
+          signDown  = (SChar)sgn(srcLine[x] - srcLineBelow[x]);
           edgeType = signDown + signUpLine[x];
           signUpLine[x]= -signDown;
@@ -408,5 +408,5 @@
     {
       offset += 2;
-      Char *signUpLine, *signDownLine, *signTmpLine;
+      SChar *signUpLine, *signDownLine, *signTmpLine;
 
       signUpLine  = m_signLineBuf1;
@@ -420,5 +420,5 @@
       for (x=startX; x< endX+1; x++)
       {
-        signUpLine[x] = (Char)sgn(srcLineBelow[x] - srcLine[x- 1]);
+        signUpLine[x] = (SChar)sgn(srcLineBelow[x] - srcLine[x- 1]);
       }
 
@@ -444,5 +444,5 @@
         for (x=startX; x<endX; x++)
         {
-          signDown =  (Char)sgn(srcLine[x] - srcLineBelow[x+ 1]);
+          signDown =  (SChar)sgn(srcLine[x] - srcLineBelow[x+ 1]);
           edgeType =  signDown + signUpLine[x];
           resLine[x] = Clip3<Int>(0, maxSampleValueIncl, srcLine[x] + offset[edgeType]);
@@ -450,5 +450,5 @@
           signDownLine[x+1] = -signDown;
         }
-        signDownLine[startX] = (Char)sgn(srcLineBelow[startX] - srcLine[startX-1]);
+        signDownLine[startX] = (SChar)sgn(srcLineBelow[startX] - srcLine[startX-1]);
 
         signTmpLine  = signUpLine;
@@ -475,5 +475,5 @@
     {
       offset += 2;
-      Char *signUpLine = m_signLineBuf1+1;
+      SChar *signUpLine = m_signLineBuf1+1;
 
       startX = isLeftAvail ? 0 : 1;
@@ -484,5 +484,5 @@
       for (x=startX-1; x< endX; x++)
       {
-        signUpLine[x] = (Char)sgn(srcLineBelow[x] - srcLine[x+1]);
+        signUpLine[x] = (SChar)sgn(srcLineBelow[x] - srcLine[x+1]);
       }
 
@@ -507,10 +507,10 @@
         for(x= startX; x< endX; x++)
         {
-          signDown =  (Char)sgn(srcLine[x] - srcLineBelow[x-1]);
+          signDown =  (SChar)sgn(srcLine[x] - srcLineBelow[x-1]);
           edgeType =  signDown + signUpLine[x];
           resLine[x] = Clip3<Int>(0, maxSampleValueIncl, srcLine[x] + offset[edgeType]);
           signUpLine[x-1] = -signDown;
         }
-        signUpLine[endX-1] = (Char)sgn(srcLineBelow[endX-1] - srcLine[endX]);
+        signUpLine[endX-1] = (SChar)sgn(srcLineBelow[endX-1] - srcLine[endX]);
         srcLine  += srcStride;
         resLine += resStride;
Index: trunk/source/Lib/TLibCommon/TComSampleAdaptiveOffset.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComSampleAdaptiveOffset.h	(revision 1357)
+++ trunk/source/Lib/TLibCommon/TComSampleAdaptiveOffset.h	(revision 1386)
@@ -96,6 +96,6 @@
 
   Int m_lineBufWidth;
-  Char* m_signLineBuf1;
-  Char* m_signLineBuf2;
+  SChar* m_signLineBuf1;
+  SChar* m_signLineBuf2;
   ChromaFormat m_chromaFormatIDC;
 private:
Index: trunk/source/Lib/TLibCommon/TComSlice.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComSlice.cpp	(revision 1357)
+++ trunk/source/Lib/TLibCommon/TComSlice.cpp	(revision 1386)
@@ -118,5 +118,5 @@
 , m_viewId                        (0)
 , m_viewIndex                     (0)
-#if NH_3D
+#if NH_3D_VSO
 , m_isDepth                       (false)
 #endif
@@ -452,6 +452,4 @@
 Void TComSlice::setRefPicList( TComList<TComPic*>& rcListPic, Bool checkNumPocTotalCurr )
 {
-  if (!checkNumPocTotalCurr)
-  {
     if (m_eSliceType == I_SLICE)
     {
@@ -459,9 +457,8 @@
       ::memset( m_aiNumRefIdx,   0, sizeof ( m_aiNumRefIdx ));
 
+    if (!checkNumPocTotalCurr)
+    {
       return;
     }
-
-    m_aiNumRefIdx[REF_PIC_LIST_0] = getNumRefIdx(REF_PIC_LIST_0);
-    m_aiNumRefIdx[REF_PIC_LIST_1] = getNumRefIdx(REF_PIC_LIST_1);
   }
 
@@ -536,7 +533,4 @@
     if (m_eSliceType == I_SLICE)
     {
-      ::memset( m_apcRefPicList, 0, sizeof (m_apcRefPicList));
-      ::memset( m_aiNumRefIdx,   0, sizeof ( m_aiNumRefIdx ));
-
       return;
     }
@@ -545,7 +539,4 @@
     // general tier and level limit:
     assert(numPicTotalCurr <= 8);
-
-    m_aiNumRefIdx[0] = getNumRefIdx(REF_PIC_LIST_0);
-    m_aiNumRefIdx[1] = getNumRefIdx(REF_PIC_LIST_1);
   }
 
@@ -1932,5 +1923,7 @@
   for ( Int i = 0; i < MAX_VPS_OUTPUTLAYER_SETS; i++)
   {
+#if !NH_3D_FIX_TICKET_107
     m_layerSetIdxForOlsMinus1[i]  = -1; 
+#endif
     for ( Int j = 0; j < MAX_VPS_NUH_LAYER_ID_PLUS1; j++)
     {
@@ -2191,6 +2184,6 @@
 }
 
-#if NH_3D
-Int TComVPS::getLayerIdInNuh( Int viewIndex, Bool depthFlag ) const
+#if NH_3D_VSO
+Int TComVPS::getLayerIdInNuh( Int viewIndex, Bool depthFlag, Int auxId ) const
 {
   Int foundLayerIdinNuh = -1; 
@@ -2199,5 +2192,9 @@
   {
     Int layerIdInNuh = getLayerIdInNuh( layerIdInVps ); 
+#if !NH_3D
+    if( ( getViewIndex( layerIdInNuh ) == viewIndex ) && ( getAuxId( layerIdInNuh ) == ( depthFlag ? 2 : 0 ) )  )
+#else
     if( ( getViewIndex( layerIdInNuh ) == viewIndex ) && ( getDepthId( layerIdInNuh ) == ( depthFlag ? 1 : 0 ) )  )
+#endif
     {
       foundLayerIdinNuh = layerIdInNuh; 
@@ -2207,5 +2204,6 @@
   return foundLayerIdinNuh;
 }
-
+#endif
+#if NH_3D
 Void TComVPS::createCamPars(Int iNumViews)
 {
@@ -2767,5 +2765,5 @@
     m_uiSpsMaxLatencyIncreasePlus1[i] = 0;
 #else
-    m_uiMaxLatencyIncrease[i] = 0;
+    m_uiMaxLatencyIncreasePlus1[i] = 0;
 #endif
     m_uiMaxDecPicBuffering[i] = 1;
@@ -3676,5 +3674,5 @@
     }
     tempRefPicInListsFlag = (getFirstTRefIdx(REF_PIC_LIST_0) >= 0 || getFirstTRefIdx(REF_PIC_LIST_1) >= 0) && getDefaultRefViewIdxAvailableFlag();
-    m_nARPStepNum = tempRefPicInListsFlag ?  H_3D_ARP_WFNR : 0;
+    m_nARPStepNum = tempRefPicInListsFlag ? 3 : 0;
   }
 
@@ -3866,5 +3864,5 @@
 }
 #endif
-#if NH_3D
+#if NH_3D_QTL
 Void TComSlice::setIvPicLists( TComPicLists* m_ivPicLists )
 {  
@@ -3873,8 +3871,10 @@
     for ( Int depthId = 0; depthId < 2; depthId++ )
     {
-      m_ivPicsCurrPoc[ depthId ][ i ] = ( i <= m_viewIndex ) ? m_ivPicLists->getPic( i, ( depthId == 1) , getPOC() ) : NULL;
+      m_ivPicsCurrPoc[ depthId ][ i ] = ( i <= m_viewIndex ) ? m_ivPicLists->getPic( i, ( depthId == 1) , 0, getPOC() ) : NULL;
     }        
   }  
 }
+#endif
+#if NH_3D
 Void TComSlice::setDepthToDisparityLUTs()
 { 
@@ -3937,5 +3937,5 @@
   {
     Int iInVoi = vps->getVoiInVps( i ); 
-#if ENC_DEC_TRACE && H_MV_ENC_DEC_TRAC
+#if ENC_DEC_TRACE && NH_MV_ENC_DEC_TRAC
     if ( g_traceCameraParameters )
     {
@@ -4320,22 +4320,22 @@
   const TComSps3dExtension* sps3dExt = getSPS()->getSps3dExtension();
 
-  m_ivMvPredFlag           = sps3dExt->getIvMvPredFlag         ( depthFlag ) && nRLLG0                       ;                             
-  m_ivMvScalingFlag        = sps3dExt->getIvMvScalingFlag      ( depthFlag )                                 ;                             
-  m_ivResPredFlag          = sps3dExt->getIvResPredFlag        ( depthFlag ) && nRLLG0                       ;                               
-  m_depthRefinementFlag    = sps3dExt->getDepthRefinementFlag  ( depthFlag )           && getInCompPredFlag() && m_cpAvailableFlag;
-  m_viewSynthesisPredFlag  = sps3dExt->getViewSynthesisPredFlag( depthFlag ) && nRLLG0 && getInCompPredFlag() && m_cpAvailableFlag;
-  m_depthBasedBlkPartFlag  = sps3dExt->getDepthBasedBlkPartFlag( depthFlag )           && getInCompPredFlag();                          
-  m_mpiFlag                = sps3dExt->getMpiFlag              ( depthFlag )           && getInCompPredFlag();
-  m_intraContourFlag       = sps3dExt->getIntraContourFlag     ( depthFlag )           && getInCompPredFlag();
-  m_intraSdcWedgeFlag      = sps3dExt->getIntraSdcWedgeFlag    ( depthFlag )                                 ;                          
-  m_qtPredFlag             = sps3dExt->getQtPredFlag           ( depthFlag )           && getInCompPredFlag();
-  m_interSdcFlag           = sps3dExt->getInterSdcFlag         ( depthFlag )                                 ;  
-  m_depthIntraSkipFlag     = sps3dExt->getDepthIntraSkipFlag   ( depthFlag )                                 ;                          
-
-  m_subPbSize              =  1 << ( sps3dExt->getLog2SubPbSizeMinus3   ( depthFlag ) + 3 );  
-  m_mpiSubPbSize           =  1 << ( sps3dExt->getLog2MpiSubPbSizeMinus3( depthFlag ) + 3 );
-
-
-#if H_3D_OUTPUT_ACTIVE_TOOLS
+  m_ivMvPredFlag           = sps3dExt->getIvDiMcEnabledFlag          ( depthFlag ) && nRLLG0                       ;                             
+  m_ivMvScalingFlag        = sps3dExt->getIvMvScalEnabledFlag        ( depthFlag )                                 ;                             
+  m_ivResPredFlag          = sps3dExt->getIvResPredEnabledFlag       ( depthFlag ) && nRLLG0                       ;                               
+  m_depthRefinementFlag    = sps3dExt->getDepthRefEnabledFlag        ( depthFlag )           && getInCompPredFlag() && m_cpAvailableFlag;
+  m_viewSynthesisPredFlag  = sps3dExt->getVspMcEnabledFlag           ( depthFlag ) && nRLLG0 && getInCompPredFlag() && m_cpAvailableFlag;
+  m_depthBasedBlkPartFlag  = sps3dExt->getDbbpEnabledFlag            ( depthFlag )           && getInCompPredFlag();                          
+  m_mpiFlag                = sps3dExt->getTexMcEnabledFlag           ( depthFlag )           && getInCompPredFlag();
+  m_intraContourFlag       = sps3dExt->getIntraContourEnabledFlag    ( depthFlag )           && getInCompPredFlag();
+  m_intraSdcWedgeFlag      = sps3dExt->getIntraDcOnlyWedgeEnabledFlag( depthFlag )                                 ;                          
+  m_qtPredFlag             = sps3dExt->getCqtCuPartPredEnabledFlag   ( depthFlag )           && getInCompPredFlag();
+  m_interSdcFlag           = sps3dExt->getInterDcOnlyEnabledFlag     ( depthFlag )                                 ;  
+  m_depthIntraSkipFlag     = sps3dExt->getSkipIntraEnabledFlag       ( depthFlag )                                 ;                          
+
+  m_subPbSize              =  1 << ( sps3dExt->getLog2IvmcSubPbSizeMinus3 ( depthFlag ) + 3 );  
+  m_mpiSubPbSize           =  1 << ( sps3dExt->getLog2TexmcSubPbSizeMinus3( depthFlag ) + 3 );
+
+
+#if NH_3D_OUTPUT_ACTIVE_TOOLS
   std::cout << "Layer:                  :" << getLayerId()             << std::endl;
   std::cout << "DepthFlag:              :" << getIsDepth()             << std::endl;
@@ -4415,13 +4415,13 @@
     if( !getIsDepth() )
     {
-      m_inCmpPredAvailFlag = sps3dExt->getViewSynthesisPredFlag( getIsDepth() ) || 
-        sps3dExt->getDepthBasedBlkPartFlag( getIsDepth() ) || 
-        sps3dExt->getDepthRefinementFlag  ( getIsDepth() );                            
+      m_inCmpPredAvailFlag = sps3dExt->getVspMcEnabledFlag( getIsDepth() ) || 
+        sps3dExt->getDbbpEnabledFlag( getIsDepth() ) || 
+        sps3dExt->getDepthRefEnabledFlag  ( getIsDepth() );                            
     }
     else
     {
-      m_inCmpPredAvailFlag = sps3dExt->getIntraContourFlag( getIsDepth() ) || 
-        sps3dExt->getQtPredFlag( getIsDepth() ) || 
-        sps3dExt->getMpiFlag( getIsDepth() );                                  
+      m_inCmpPredAvailFlag = sps3dExt->getIntraContourEnabledFlag( getIsDepth() ) || 
+        sps3dExt->getCqtCuPartPredEnabledFlag( getIsDepth() ) || 
+        sps3dExt->getTexMcEnabledFlag( getIsDepth() );                                  
     }
   }
@@ -4545,11 +4545,11 @@
 }
 
-Bool TComScalingList::xParseScalingList(Char* pchFile)
+Bool TComScalingList::xParseScalingList(const std::string &fileName)
 {
   static const Int LINE_SIZE=1024;
   FILE *fp = NULL;
-  Char line[LINE_SIZE];
-
-  if (pchFile == NULL)
+  TChar line[LINE_SIZE];
+
+  if (fileName.empty())
   {
     fprintf(stderr, "Error: no scaling list file specified. Help on scaling lists being output\n");
@@ -4560,7 +4560,7 @@
     return true;
   }
-  else if ((fp = fopen(pchFile,"r")) == (FILE*)NULL)
-  {
-    fprintf(stderr, "Error: cannot open scaling list file %s for reading\n",pchFile);
+  else if ((fp = fopen(fileName.c_str(),"r")) == (FILE*)NULL)
+  {
+    fprintf(stderr, "Error: cannot open scaling list file %s for reading\n", fileName.c_str());
     return true;
   }
@@ -4590,6 +4590,6 @@
           while ((!feof(fp)) && (!bFound))
           {
-            Char *ret = fgets(line, LINE_SIZE, fp);
-            Char *findNamePosition= ret==NULL ? NULL : strstr(line, MatrixType[sizeIdc][listIdc]);
+            TChar *ret = fgets(line, LINE_SIZE, fp);
+            TChar *findNamePosition= ret==NULL ? NULL : strstr(line, MatrixType[sizeIdc][listIdc]);
             // This could be a match against the DC string as well, so verify it isn't
             if (findNamePosition!= NULL && (MatrixType_DC[sizeIdc][listIdc]==NULL || strstr(line, MatrixType_DC[sizeIdc][listIdc])==NULL))
@@ -4600,5 +4600,5 @@
           if (!bFound)
           {
-            fprintf(stderr, "Error: cannot find Matrix %s from scaling list file %s\n", MatrixType[sizeIdc][listIdc], pchFile);
+            fprintf(stderr, "Error: cannot find Matrix %s from scaling list file %s\n", MatrixType[sizeIdc][listIdc], fileName.c_str());
             return true;
           }
@@ -4609,10 +4609,10 @@
           if (fscanf(fp, "%d,", &data)!=1)
           {
-            fprintf(stderr, "Error: cannot read value #%d for Matrix %s from scaling list file %s at file position %ld\n", i, MatrixType[sizeIdc][listIdc], pchFile, ftell(fp));
+            fprintf(stderr, "Error: cannot read value #%d for Matrix %s from scaling list file %s at file position %ld\n", i, MatrixType[sizeIdc][listIdc], fileName.c_str(), ftell(fp));
             return true;
           }
           if (data<0 || data>255)
           {
-            fprintf(stderr, "Error: QMatrix entry #%d of value %d for Matrix %s from scaling list file %s at file position %ld is out of range (0 to 255)\n", i, data, MatrixType[sizeIdc][listIdc], pchFile, ftell(fp));
+            fprintf(stderr, "Error: QMatrix entry #%d of value %d for Matrix %s from scaling list file %s at file position %ld is out of range (0 to 255)\n", i, data, MatrixType[sizeIdc][listIdc], fileName.c_str(), ftell(fp));
             return true;
           }
@@ -4630,6 +4630,6 @@
             while ((!feof(fp)) && (!bFound))
             {
-              Char *ret = fgets(line, LINE_SIZE, fp);
-              Char *findNamePosition= ret==NULL ? NULL : strstr(line, MatrixType_DC[sizeIdc][listIdc]);
+              TChar *ret = fgets(line, LINE_SIZE, fp);
+              TChar *findNamePosition= ret==NULL ? NULL : strstr(line, MatrixType_DC[sizeIdc][listIdc]);
               if (findNamePosition!= NULL)
               {
@@ -4640,5 +4640,5 @@
             if (!bFound)
             {
-              fprintf(stderr, "Error: cannot find DC Matrix %s from scaling list file %s\n", MatrixType_DC[sizeIdc][listIdc], pchFile);
+              fprintf(stderr, "Error: cannot find DC Matrix %s from scaling list file %s\n", MatrixType_DC[sizeIdc][listIdc], fileName.c_str());
               return true;
             }
@@ -4647,10 +4647,10 @@
           if (fscanf(fp, "%d,", &data)!=1)
           {
-            fprintf(stderr, "Error: cannot read DC %s from scaling list file %s at file position %ld\n", MatrixType_DC[sizeIdc][listIdc], pchFile, ftell(fp));
+            fprintf(stderr, "Error: cannot read DC %s from scaling list file %s at file position %ld\n", MatrixType_DC[sizeIdc][listIdc], fileName.c_str(), ftell(fp));
             return true;
           }
           if (data<0 || data>255)
           {
-            fprintf(stderr, "Error: DC value %d for Matrix %s from scaling list file %s at file position %ld is out of range (0 to 255)\n", data, MatrixType[sizeIdc][listIdc], pchFile, ftell(fp));
+            fprintf(stderr, "Error: DC value %d for Matrix %s from scaling list file %s at file position %ld is out of range (0 to 255)\n", data, MatrixType[sizeIdc][listIdc], fileName.c_str(), ftell(fp));
             return true;
           }
Index: trunk/source/Lib/TLibCommon/TComSlice.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComSlice.h	(revision 1357)
+++ trunk/source/Lib/TLibCommon/TComSlice.h	(revision 1386)
@@ -292,5 +292,5 @@
   Void       checkDcOfMatrix();
   Void       processRefMatrix(UInt sizeId, UInt listId , UInt refListId );
-  Bool       xParseScalingList(Char* pchFile);
+  Bool       xParseScalingList(const std::string &fileName);
 #if NH_MV
   Void       inferFrom                      ( const TComScalingList& srcScLi );
@@ -1384,8 +1384,9 @@
   /// VPS EXTENSION 2 SYNTAX ELEMENTS
   Int     getDepthId                   ( Int layerIdInNuh)             const    { return getScalabilityId( getLayerIdInVps(layerIdInNuh), DEPTH_ID ); }
-#if NH_3D                                                             
+#if NH_3D_VSO                                                             
   Bool    getVpsDepthFlag              ( Int layerIdInNuh)             const    { return (getDepthId( layerIdInNuh ) > 0);  }
-  Int     getLayerIdInNuh              ( Int viewIndex, Bool depthFlag ) const;   
-          
+  Int     getLayerIdInNuh              ( Int viewIndex, Bool depthFlag, Int auxId ) const;   
+#endif
+#if NH_3D
   Void    createCamPars                ( Int iNumViews );  
   Void    initCamParaVPS               ( Int vOIdxInVps, Int numCp, Bool cpInSliceSegmentHeaderFlag, Int* cpRefVoi, Int** aaiScale, Int** aaiOffset );                                                
@@ -1426,5 +1427,5 @@
 #endif
 
-  template <typename T, typename S, typename U> Void xPrintArray( const Char* name, Int numElemDim1, U idx, S numElemDim2, T vec, Bool printNumber, Bool printIdx = true ) const
+  template <typename T, typename S, typename U> Void xPrintArray( const TChar* name, Int numElemDim1, U idx, S numElemDim2, T vec, Bool printNumber, Bool printIdx = true ) const
   {
     std::cout << std::endl; 
@@ -1810,78 +1811,78 @@
     for (Int d = 0; d < 2; d++)
     {
-      m_ivMvPredFlag          [d] = false; 
-      m_ivMvScalingFlag       [d] = false; 
-      m_log2SubPbSizeMinus3   [d] = 3; 
-      m_ivResPredFlag         [d] = false; 
-      m_depthRefinementFlag   [d] = false; 
-      m_viewSynthesisPredFlag [d] = false; 
-      m_depthBasedBlkPartFlag [d] = false; 
-      m_mpiFlag               [d] = false; 
-      m_log2MpiSubPbSizeMinus3[d] = 3; 
-      m_intraContourFlag      [d] = false; 
-      m_intraSdcWedgeFlag     [d] = false; 
-      m_qtPredFlag            [d] = false; 
-      m_interSdcFlag          [d] = false; 
-      m_depthIntraSkipFlag    [d] = false;   
+      m_ivDiMcEnabledFlag          [d] = false; 
+      m_ivMvScalEnabledFlag       [d] = false; 
+      m_log2IvmcSubPbSizeMinus3   [d] = 3; 
+      m_ivResPredEnabledFlag         [d] = false; 
+      m_depthRefEnabledFlag   [d] = false; 
+      m_vspMcEnabledFlag [d] = false; 
+      m_dbbpEnabledFlag [d] = false; 
+      m_texMcEnabledFlag               [d] = false; 
+      m_log2TexmcSubPbSizeMinus3[d] = 3; 
+      m_intraContourEnabledFlag      [d] = false; 
+      m_intraDcOnlyWedgeEnabledFlag     [d] = false; 
+      m_cqtCuPartPredEnabledFlag            [d] = false; 
+      m_interDcOnlyEnabledFlag          [d] = false; 
+      m_skipIntraEnabledFlag    [d] = false;   
     }
   }
 
-  Void          setIvMvPredFlag( Int d, Bool flag )         { m_ivMvPredFlag[d] = flag;             }
-  Bool          getIvMvPredFlag( Int d ) const              { return m_ivMvPredFlag[d];             }
-
-  Void          setIvMvScalingFlag( Int d, Bool flag )      { m_ivMvScalingFlag[d] = flag;          }
-  Bool          getIvMvScalingFlag( Int d ) const           { return m_ivMvScalingFlag[d];          }
-
-  Void          setLog2SubPbSizeMinus3( Int d, Int  val )   { m_log2SubPbSizeMinus3[d] = val;       }
-  Int           getLog2SubPbSizeMinus3( Int d ) const       { return m_log2SubPbSizeMinus3[d];      }
-
-  Void          setIvResPredFlag( Int d, Bool flag )        { m_ivResPredFlag[d] = flag;            }
-  Bool          getIvResPredFlag( Int d ) const             { return m_ivResPredFlag[d];            }
-
-  Void          setDepthRefinementFlag( Int d, Bool flag )  { m_depthRefinementFlag[d] = flag;      }
-  Bool          getDepthRefinementFlag( Int d ) const       { return m_depthRefinementFlag[d];      }
-
-  Void          setViewSynthesisPredFlag( Int d, Bool flag ) { m_viewSynthesisPredFlag[d] = flag;   }
-  Bool          getViewSynthesisPredFlag( Int d ) const     { return m_viewSynthesisPredFlag[d];    }
-
-  Void          setDepthBasedBlkPartFlag( Int d, Bool flag ) { m_depthBasedBlkPartFlag[d] = flag;   }
-  Bool          getDepthBasedBlkPartFlag( Int d ) const     { return m_depthBasedBlkPartFlag[d];    }
-
-  Void          setMpiFlag( Int d, Bool flag )              { m_mpiFlag[d] = flag;                  }
-  Bool          getMpiFlag( Int d ) const                   { return m_mpiFlag[d];                  }
-
-  Void          setLog2MpiSubPbSizeMinus3( Int d, Int  val ) { m_log2MpiSubPbSizeMinus3[d] = val;   }
-  Int           getLog2MpiSubPbSizeMinus3( Int d ) const    { return m_log2MpiSubPbSizeMinus3[d];   }
-
-  Void          setIntraContourFlag( Int d, Bool flag )     { m_intraContourFlag[d] = flag;         }
-  Bool          getIntraContourFlag( Int d ) const          { return m_intraContourFlag[d];         }
-
-  Void          setIntraSdcWedgeFlag( Int d, Bool flag )    { m_intraSdcWedgeFlag[d] = flag;        }
-  Bool          getIntraSdcWedgeFlag( Int d ) const         { return m_intraSdcWedgeFlag[d];        }
-
-  Void          setQtPredFlag( Int d, Bool flag )           { m_qtPredFlag[d] = flag;               }
-  Bool          getQtPredFlag( Int d ) const                { return m_qtPredFlag[d];               }
-
-  Void          setInterSdcFlag( Int d, Bool flag )         { m_interSdcFlag[d] = flag;             }
-  Bool          getInterSdcFlag( Int d ) const              { return m_interSdcFlag[d];             }
-
-  Void          setDepthIntraSkipFlag( Int d, Bool flag )   { m_depthIntraSkipFlag[d] = flag;       }
-  Bool          getDepthIntraSkipFlag( Int d ) const        { return m_depthIntraSkipFlag[d];       }
+  Void          setIvDiMcEnabledFlag( Int d, Bool flag )        { m_ivDiMcEnabledFlag[d] = flag;             }
+  Bool          getIvDiMcEnabledFlag( Int d ) const             { return m_ivDiMcEnabledFlag[d];             }
+
+  Void          setIvMvScalEnabledFlag( Int d, Bool flag )      { m_ivMvScalEnabledFlag[d] = flag;          }
+  Bool          getIvMvScalEnabledFlag( Int d ) const           { return m_ivMvScalEnabledFlag[d];          }
+
+  Void          setLog2IvmcSubPbSizeMinus3( Int d, Int  val )   { m_log2IvmcSubPbSizeMinus3[d] = val;       }
+  Int           getLog2IvmcSubPbSizeMinus3( Int d ) const       { return m_log2IvmcSubPbSizeMinus3[d];      }
+
+  Void          setIvResPredEnabledFlag( Int d, Bool flag )     { m_ivResPredEnabledFlag[d] = flag;            }
+  Bool          getIvResPredEnabledFlag( Int d ) const          { return m_ivResPredEnabledFlag[d];            }
+
+  Void          setDepthRefEnabledFlag( Int d, Bool flag )      { m_depthRefEnabledFlag[d] = flag;      }
+  Bool          getDepthRefEnabledFlag( Int d ) const           { return m_depthRefEnabledFlag[d];      }
+
+  Void          setVspMcEnabledFlag( Int d, Bool flag )         { m_vspMcEnabledFlag[d] = flag;   }
+  Bool          getVspMcEnabledFlag( Int d ) const              { return m_vspMcEnabledFlag[d];    }
+
+  Void          setDbbpEnabledFlag( Int d, Bool flag )          { m_dbbpEnabledFlag[d] = flag;   }
+  Bool          getDbbpEnabledFlag( Int d ) const               { return m_dbbpEnabledFlag[d];    }
+
+  Void          setTexMcEnabledFlag( Int d, Bool flag )         { m_texMcEnabledFlag[d] = flag;                  }
+  Bool          getTexMcEnabledFlag( Int d ) const              { return m_texMcEnabledFlag[d];                  }
+
+  Void          setLog2TexmcSubPbSizeMinus3( Int d, Int  val )  { m_log2TexmcSubPbSizeMinus3[d] = val;   }
+  Int           getLog2TexmcSubPbSizeMinus3( Int d ) const      { return m_log2TexmcSubPbSizeMinus3[d];   }
+
+  Void          setIntraContourEnabledFlag( Int d, Bool flag )  { m_intraContourEnabledFlag[d] = flag;         }
+  Bool          getIntraContourEnabledFlag( Int d ) const       { return m_intraContourEnabledFlag[d];         }
+
+  Void          setIntraDcOnlyWedgeEnabledFlag( Int d, Bool flag ) { m_intraDcOnlyWedgeEnabledFlag[d] = flag;        }
+  Bool          getIntraDcOnlyWedgeEnabledFlag( Int d ) const      { return m_intraDcOnlyWedgeEnabledFlag[d];        }
+
+  Void          setCqtCuPartPredEnabledFlag( Int d, Bool flag )    { m_cqtCuPartPredEnabledFlag[d] = flag;               }
+  Bool          getCqtCuPartPredEnabledFlag( Int d ) const         { return m_cqtCuPartPredEnabledFlag[d];               }
+
+  Void          setInterDcOnlyEnabledFlag( Int d, Bool flag )      { m_interDcOnlyEnabledFlag[d] = flag;             }
+  Bool          getInterDcOnlyEnabledFlag( Int d ) const           { return m_interDcOnlyEnabledFlag[d];             }
+
+  Void          setSkipIntraEnabledFlag( Int d, Bool flag )        { m_skipIntraEnabledFlag[d] = flag;       }
+  Bool          getSkipIntraEnabledFlag( Int d ) const             { return m_skipIntraEnabledFlag[d];       }
 private:
 
-  Bool        m_ivMvPredFlag          [2];
-  Bool        m_ivMvScalingFlag       [2];
-  Int         m_log2SubPbSizeMinus3   [2];
-  Bool        m_ivResPredFlag         [2];
-  Bool        m_depthRefinementFlag   [2];
-  Bool        m_viewSynthesisPredFlag [2];
-  Bool        m_depthBasedBlkPartFlag [2];
-  Bool        m_mpiFlag               [2];
-  Int         m_log2MpiSubPbSizeMinus3[2];
-  Bool        m_intraContourFlag      [2];
-  Bool        m_intraSdcWedgeFlag     [2];
-  Bool        m_qtPredFlag            [2];
-  Bool        m_interSdcFlag          [2];
-  Bool        m_depthIntraSkipFlag    [2];  
+  Bool        m_ivDiMcEnabledFlag          [2];
+  Bool        m_ivMvScalEnabledFlag        [2];
+  Int         m_log2IvmcSubPbSizeMinus3    [2];
+  Bool        m_ivResPredEnabledFlag       [2];
+  Bool        m_depthRefEnabledFlag        [2];
+  Bool        m_vspMcEnabledFlag           [2];
+  Bool        m_dbbpEnabledFlag            [2];
+  Bool        m_texMcEnabledFlag           [2];
+  Int         m_log2TexmcSubPbSizeMinus3   [2];
+  Bool        m_intraContourEnabledFlag    [2];
+  Bool        m_intraDcOnlyWedgeEnabledFlag[2];
+  Bool        m_cqtCuPartPredEnabledFlag   [2];
+  Bool        m_interDcOnlyEnabledFlag     [2];
+  Bool        m_skipIntraEnabledFlag       [2];  
 };
 
@@ -1955,7 +1956,6 @@
 #if NH_MV
   UInt             m_uiSpsMaxLatencyIncreasePlus1[MAX_TLAYER];  
-  // Calling a member m_uiMaxLatencyIncrease although it is m_uiMaxLatencyIncreasePlus1 is really bad style.  
 #else
-  UInt             m_uiMaxLatencyIncrease[MAX_TLAYER];  // Really max latency increase plus 1 (value 0 expresses no limit)
+  UInt             m_uiMaxLatencyIncreasePlus1[MAX_TLAYER];
 #endif
 
@@ -2135,5 +2135,4 @@
   Bool                   getScalingListPresentFlag() const                                               { return m_scalingListPresentFlag;                                     }
   Void                   setScalingListPresentFlag( Bool b )                                             { m_scalingListPresentFlag  = b;                                       }
-  Void                   setScalingList( TComScalingList *scalingList);
   TComScalingList&       getScalingList()                                                                { return m_scalingList;                                                }
   const TComScalingList& getScalingList() const                                                          { return m_scalingList;                                                }
@@ -2146,6 +2145,6 @@
   Int                    getSpsMaxLatencyPictures( Int i )  const                                       { return ( getSpsMaxNumReorderPics(i) + getSpsMaxLatencyIncreasePlus1(i)-1); }
 #else
-  UInt                   getMaxLatencyIncrease(UInt tlayer) const                                        { return m_uiMaxLatencyIncrease[tlayer];                               }
-  Void                   setMaxLatencyIncrease( UInt ui , UInt tlayer)                                   { m_uiMaxLatencyIncrease[tlayer] = ui;                                 }
+  UInt                   getMaxLatencyIncreasePlus1(UInt tlayer) const                                   { return m_uiMaxLatencyIncreasePlus1[tlayer];                          }
+  Void                   setMaxLatencyIncreasePlus1( UInt ui , UInt tlayer)                              { m_uiMaxLatencyIncreasePlus1[tlayer] = ui;                            }
 #endif
 
@@ -2166,30 +2165,4 @@
   const TComSPSRExt&     getSpsRangeExtension() const                                                    { return m_spsRangeExtension;                                          }
   TComSPSRExt&           getSpsRangeExtension()                                                          { return m_spsRangeExtension;                                          }
-
-  // Sequence parameter set range extension syntax
-  // WAS: getUseResidualRotation and setUseResidualRotation
-  // Now getSpsRangeExtension().getTransformSkipRotationEnabledFlag and getSpsRangeExtension().setTransformSkipRotationEnabledFlag
-
-  // WAS: getUseSingleSignificanceMapContext and setUseSingleSignificanceMapContext
-  // Now: getSpsRangeExtension().getTransformSkipContextEnabledFlag and getSpsRangeExtension().setTransformSkipContextEnabledFlag
-
-  // WAS: getUseResidualDPCM and setUseResidualDPCM
-  // Now: getSpsRangeExtension().getRdpcmEnabledFlag and getSpsRangeExtension().setRdpcmEnabledFlag and
-
-  // WAS: getUseExtendedPrecision and setUseExtendedPrecision
-  // Now: getSpsRangeExtension().getExtendedPrecisionProcessingFlag and getSpsRangeExtension().setExtendedPrecisionProcessingFlag
-
-  // WAS: getDisableIntraReferenceSmoothing and setDisableIntraReferenceSmoothing
-  // Now: getSpsRangeExtension().getIntraSmoothingDisabledFlag and getSpsRangeExtension().setIntraSmoothingDisabledFlag
-
-  // WAS: getUseHighPrecisionPredictionWeighting and setUseHighPrecisionPredictionWeighting
-  // Now: getSpsRangeExtension().getHighPrecisionOffsetsEnabledFlag and getSpsRangeExtension().setHighPrecisionOffsetsEnabledFlag
-
-  // WAS: getUseGolombRiceParameterAdaptation and setUseGolombRiceParameterAdaptation
-  // Now: getSpsRangeExtension().getPersistentRiceAdaptationEnabledFlag and getSpsRangeExtension().setPersistentRiceAdaptationEnabledFlag
-
-  // WAS: getAlignCABACBeforeBypass and setAlignCABACBeforeBypass
-  // Now: getSpsRangeExtension().getCabacBypassAlignmentEnabledFlag and getSpsRangeExtension().setCabacBypassAlignmentEnabledFlag
-
 
 #if NH_MV
@@ -2274,6 +2247,4 @@
   virtual ~TComRefPicListModification();
 
-  Void    create();
-  Void    destroy();
 
   Bool    getRefPicListModificationFlagL0() const        { return m_refPicListModificationFlagL0;                                  }
@@ -2299,8 +2270,7 @@
   Void    setListEntryL0( Int i, Int  val )                      { m_RefPicSetIdxL0[i] = val;                                          } 
   Void    setListEntryL1( Int i, Int  val )                      { m_RefPicSetIdxL1[i] = val;                                          } 
-
-
 #endif
 };
+
 
 /// PPS RExt class
@@ -2556,26 +2526,4 @@
   const TComPPSRExt&     getPpsRangeExtension() const                                     { return m_ppsRangeExtension;                   }
   TComPPSRExt&           getPpsRangeExtension()                                           { return m_ppsRangeExtension;                   }
-
-  // WAS: getTransformSkipLog2MaxSize and setTransformSkipLog2MaxSize
-  // Now: getPpsRangeExtension().getLog2MaxTransformSkipBlockSize and getPpsRangeExtension().setLog2MaxTransformSkipBlockSize
-
-  // WAS: getUseCrossComponentPrediction and setUseCrossComponentPrediction
-  // Now: getPpsRangeExtension().getCrossComponentPredictionEnabledFlag and getPpsRangeExtension().setCrossComponentPredictionEnabledFlag
-
-  // WAS: clearChromaQpAdjTable
-  // Now: getPpsRangeExtension().clearChromaQpOffsetList
-
-  // WAS: getMaxCuChromaQpAdjDepth and setMaxCuChromaQpAdjDepth
-  // Now: getPpsRangeExtension().getDiffCuChromaQpOffsetDepth and getPpsRangeExtension().setDiffCuChromaQpOffsetDepth
-
-  // WAS: getChromaQpAdjTableSize
-  // Now: getPpsRangeExtension().getChromaQpOffsetListLen
-
-  // WAS: getChromaQpAdjTableAt and setChromaQpAdjTableAt
-  // Now: getPpsRangeExtension().getChromaQpOffsetListEntry and getPpsRangeExtension().setChromaQpOffsetListEntry
-
-  // WAS: getSaoOffsetBitShift and setSaoOffsetBitShift
-  // Now: getPpsRangeExtension().getLog2SaoOffsetScale and getPpsRangeExtension().setLog2SaoOffsetScale
-
 #if NH_MV
   Void    setLayerId( Int  val )                                                     { m_layerId = val;                                           }
@@ -2753,5 +2701,5 @@
   Int        m_viewId;
   Int        m_viewIndex; 
-#if NH_3D
+#if NH_3D_VSO
   Bool       m_isDepth;
 #endif
@@ -2805,5 +2753,9 @@
   Bool       m_cpAvailableFlag; 
   Int        m_numViews; 
+#endif
+#if NH_3D_QTL
   TComPic*   m_ivPicsCurrPoc [2][MAX_NUM_LAYERS];  
+#endif
+#if NH_3D
   Int**      m_depthToDisparityB; 
   Int**      m_depthToDisparityF; 
@@ -2876,4 +2828,5 @@
   Int                         getPOC() const                                         { return m_iPOC;                                                }
   Int                         getSliceQp() const                                     { return m_iSliceQp;                                            }
+  Bool                        getUseWeightedPrediction() const                       { return( (m_eSliceType==P_SLICE && testWeightPred()) || (m_eSliceType==B_SLICE && testWeightBiPred()) ); }
   Bool                        getDependentSliceSegmentFlag() const                   { return m_dependentSliceSegmentFlag;                           }
   Void                        setDependentSliceSegmentFlag(Bool val)                 { m_dependentSliceSegmentFlag = val;                            }
@@ -2892,5 +2845,6 @@
   TComPic*                    getPic()                                               { return m_pcPic;                                               }
   TComPic*                    getRefPic( RefPicList e, Int iRefIdx)                  { return m_apcRefPicList[e][iRefIdx];                           }
-  Int                         getRefPOC( RefPicList e, Int iRefIdx)                  { return m_aiRefPOCList[e][iRefIdx];                            }
+  const TComPic*              getRefPic( RefPicList e, Int iRefIdx) const            { return m_apcRefPicList[e][iRefIdx];                           }
+  Int                         getRefPOC( RefPicList e, Int iRefIdx) const            { return m_aiRefPOCList[e][iRefIdx];                            }
 #if NH_3D
   Bool                        getInCmpPredAvailFlag( )                 const         { return m_inCmpPredAvailFlag;                                  }
@@ -2901,5 +2855,8 @@
   Int                         getNumCurCmpLIds( )                      const         { return (Int) m_inCmpRefViewIdcs.size();                       }
   TComPic*                    getIvPic( Bool depthFlag, Int viewIndex) const         { return  m_ivPicsCurrPoc[ depthFlag ? 1 : 0 ][ viewIndex ];    }
+#endif
+#if NH_3D_QTL
   TComPic*                    getTexturePic       ()                                 { return  m_ivPicsCurrPoc[0][ m_viewIndex ];                    }
+
 #endif                            
 #if NH_3D_IC                                                                                                                                          
@@ -3180,5 +3137,5 @@
 
   Void                        setEnableTMVPFlag( Bool   b )                          { m_enableTMVPFlag = b;                                         }
-  Bool                        getEnableTMVPFlag()                                    { return m_enableTMVPFlag;                                      }
+  Bool                        getEnableTMVPFlag() const                              { return m_enableTMVPFlag;                                      }
 
   Void                        setEncCABACTableIdx( SliceType idx )                   { m_encCABACTableIdx = idx;                                     }
@@ -3206,9 +3163,14 @@
   Int                         getFirstTRefIdx        ( RefPicList e )                { return  m_aiFirstTRefIdx[e];                                  }
   Void                        setFirstTRefIdx        ( RefPicList e, Int i )         { m_aiFirstTRefIdx[e]    = i;                                   }
-  Bool                        getArpRefPicAvailable  ( RefPicList e, Int viewIdx)    { return m_arpRefPicAvailable[e][getVPS()->getLayerIdInNuh(viewIdx, 0)]; }
+
+  Bool                        getArpRefPicAvailable  ( RefPicList e, Int viewIdx)    { return m_arpRefPicAvailable[e][getVPS()->getLayerIdInNuh(viewIdx, false, 0 )]; }
   IntAry1d                    getPocsInCurrRPSs()                                    { return m_pocsInCurrRPSs;                                      } 
-#endif                                                                                                                                               
+#endif                        
+#endif
+#if NH_3D_VSO
   Void                        setIsDepth            ( Bool isDepth )                 { m_isDepth = isDepth;                                          }
   Bool                        getIsDepth            () const                         { return m_isDepth;                                             }
+#endif
+#if NH_3D
   Void                        setCamparaSlice       ( Int** aaiScale = 0, Int** aaiOffset = 0 );      
 
@@ -3230,5 +3192,9 @@
   Int                         getCpInvOff( Int j )                                   { return m_aaiCodedOffset[1][j];                                }
                                                                                                                                                         
+#endif
+#if NH_3D_QTL
   Void                        setIvPicLists( TComPicLists* m_ivPicLists );                                                                              
+#endif
+#if NH_3D
   Void                        setDepthToDisparityLUTs();                                                                                                
                                                                                                                                                         
Index: trunk/source/Lib/TLibCommon/TComWeightPrediction.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComWeightPrediction.cpp	(revision 1357)
+++ trunk/source/Lib/TLibCommon/TComWeightPrediction.cpp	(revision 1386)
@@ -55,4 +55,15 @@
 }
 
+static inline Pel noWeightUnidir( Pel P0, Int round, Int shift, Int offset, Int clipBD)
+{
+  return ClipBD( ( ((P0 + IF_INTERNAL_OFFS) + round) >> shift ) + offset, clipBD );
+}
+
+static inline Pel noWeightOffsetUnidir( Pel P0, Int round, Int shift, Int clipBD)
+{
+  return ClipBD( ( ((P0 + IF_INTERNAL_OFFS) + round) >> shift ), clipBD );
+}
+
+
 // ====================================================================================================================
 // Class definition
@@ -154,5 +165,4 @@
     const Int  shiftNum    = std::max<Int>(2, (IF_INTERNAL_PREC - clipBD));
     const Int  shift       = wp0[compID].shift + shiftNum;
-    const Int  round       = (shift > 0) ? (1<<(shift-1)) : 0;
     const UInt iSrc0Stride = pcYuvSrc0->getStride(compID);
     const UInt iDstStride  = pcYuvDst->getStride(compID);
@@ -162,4 +172,7 @@
     const Int  iWidth      = uiWidth>>csx;
 
+    if (w0 != 1 << wp0[compID].shift)
+    {
+      const Int  round       = (shift > 0) ? (1<<(shift-1)) : 0;
     for (Int y = iHeight-1; y >= 0; y-- )
     {
@@ -178,4 +191,49 @@
       pSrc0 += iSrc0Stride;
       pDst  += iDstStride;
+    }
+  }
+    else
+    {
+      const Int  round       = (shiftNum > 0) ? (1<<(shiftNum-1)) : 0;
+      if (offset == 0)
+      {
+        for (Int y = iHeight-1; y >= 0; y-- )
+        {
+          Int x = iWidth-1;
+          for ( ; x >= 3; )
+          {
+            pDst[x] = noWeightOffsetUnidir(pSrc0[x], round, shiftNum, clipBD); x--;
+            pDst[x] = noWeightOffsetUnidir(pSrc0[x], round, shiftNum, clipBD); x--;
+            pDst[x] = noWeightOffsetUnidir(pSrc0[x], round, shiftNum, clipBD); x--;
+            pDst[x] = noWeightOffsetUnidir(pSrc0[x], round, shiftNum, clipBD); x--;
+          }
+          for( ; x >= 0; x--)
+          {
+            pDst[x] = noWeightOffsetUnidir(pSrc0[x], round, shiftNum, clipBD);
+          }
+          pSrc0 += iSrc0Stride;
+          pDst  += iDstStride;
+        }
+      }
+      else
+      {
+        for (Int y = iHeight-1; y >= 0; y-- )
+        {
+          Int x = iWidth-1;
+          for ( ; x >= 3; )
+          {
+            pDst[x] = noWeightUnidir(pSrc0[x], round, shiftNum, offset, clipBD); x--;
+            pDst[x] = noWeightUnidir(pSrc0[x], round, shiftNum, offset, clipBD); x--;
+            pDst[x] = noWeightUnidir(pSrc0[x], round, shiftNum, offset, clipBD); x--;
+            pDst[x] = noWeightUnidir(pSrc0[x], round, shiftNum, offset, clipBD); x--;
+          }
+          for( ; x >= 0; x--)
+          {
+            pDst[x] = noWeightUnidir(pSrc0[x], round, shiftNum, offset, clipBD);
+          }
+          pSrc0 += iSrc0Stride;
+          pDst  += iDstStride;
+        }
+      }
     }
   }
@@ -197,8 +255,8 @@
         TComSlice *const pcSlice  = pcCU->getSlice();
   const Bool             wpBiPred = pcCU->getSlice()->getPPS()->getWPBiPred();
-  const Bool             bBiDir   = (iRefIdx0>=0 && iRefIdx1>=0);
-  const Bool             bUniDir  = !bBiDir;
-
-  if ( bUniDir || wpBiPred )
+  const Bool             bBiPred  = (iRefIdx0>=0 && iRefIdx1>=0);
+  const Bool             bUniPred = !bBiPred;
+
+  if ( bUniPred || wpBiPred )
   { // explicit --------------------
     if ( iRefIdx0 >= 0 )
@@ -228,6 +286,6 @@
   const Bool bUseHighPrecisionPredictionWeighting = pcSlice->getSPS()->getSpsRangeExtension().getHighPrecisionOffsetsEnabledFlag();
 
-  if ( bBiDir )
-  { // Bi-Dir case
+  if ( bBiPred )
+  { // Bi-predictive case
     for ( Int yuv=0 ; yuv<numValidComponent ; yuv++ )
     {
@@ -248,5 +306,5 @@
   }
   else
-  {  // Unidir
+  {  // UniPred
     WPScalingParam *const pwp = (iRefIdx0>=0) ? wp0 : wp1 ;
 
Index: trunk/source/Lib/TLibCommon/TComYuv.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComYuv.cpp	(revision 1357)
+++ trunk/source/Lib/TLibCommon/TComYuv.cpp	(revision 1386)
@@ -124,5 +124,5 @@
   {
     ::memcpy( pDst, pSrc, sizeof(Pel)*iWidth);
-#if ENC_DEC_TRACE && H_MV_ENC_DEC_TRAC
+#if ENC_DEC_TRACE && NH_MV_ENC_DEC_TRAC
     if ( g_traceCopyBack && compID == COMPONENT_Y)
     { 
Index: trunk/source/Lib/TLibCommon/TComYuv.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComYuv.h	(revision 1357)
+++ trunk/source/Lib/TLibCommon/TComYuv.h	(revision 1386)
@@ -204,6 +204,8 @@
   UInt         getComponentScaleX         (const ComponentID id) const { return ::getComponentScaleX(id, m_chromaFormatIDC); }
   UInt         getComponentScaleY         (const ComponentID id) const { return ::getComponentScaleY(id, m_chromaFormatIDC); }
+#if NH_3D_VSO
+  Void         addClipPartLuma( Int bitDepth, TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize );
+#endif
 #if NH_3D
-  Void         addClipPartLuma( Int bitDepth, TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize );
 #if NH_3D_ARP
   Void         addARP                     ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth , UInt uiHeight , Bool bClip, const BitDepths &clipBitDepths );
Index: trunk/source/Lib/TLibCommon/TypeDef.h
===================================================================
--- trunk/source/Lib/TLibCommon/TypeDef.h	(revision 1357)
+++ trunk/source/Lib/TLibCommon/TypeDef.h	(revision 1386)
@@ -32,5 +32,5 @@
  */
 /** \file     TypeDef.h
-    \brief    Define basic types, new types and enumerations
+    \brief    Define macros, basic types, new types and enumerations
 */
 #ifndef __TYPEDEF__
@@ -64,18 +64,14 @@
 /////////////////////////////////////////////////////////////////////////////////////////
 #if NH_MV
-#define NH_MV_SEI_TBD                             0
-#define NH_MV_SEI                                 1
-#define NH_MV_FIX_TICKET_106                      1 // Identical motion check.
+// Recent bug fixes
+#define NH_3D_FIX_TICKET_107                     1 // Clean up. 
+#define NH_3D_FIX_TICKET_91                      1 // NBDV availability in case of tiles.
+// Things that needs to be fixed also in the Specification ...
 #define NH_MV_FIX_NO_REF_PICS_CHECK               1 // !!SPEC!!
 #define NH_MV_FIX_INIT_NUM_ACTIVE_REF_LAYER_PICS  1 // Derivation of NumActiveRefLayerPIcs. !!SPEC!!
 #define NH_MV_FIX_NUM_POC_TOTAL_CUR               1 // Derivation of NumPocTotalCur for IDR pictures. !!SPEC!!
-#define NH_MV_LAYERS_NOT_PRESENT_SEI              1 // Layers not present SEI message JCTMV-M0043
-#if NH_MV_SEI
-#define SEI_DRI_F0169 1
-#endif
-#endif
-#if NH_3D
-#define H_3D_FIX_ARP_CHECK_NOT_IN_DPB     1
-#define NH_3D_FIX_NBDV_COL                1
+// To be done 
+#define NH_MV_HLS_PTL_LIMITS                       0
+#define NH_MV_SEI_TBD                             0
 #endif
 /////////////////////////////////////////////////////////////////////////////////////////
@@ -83,5 +79,5 @@
 /////////////////////////////////////////////////////////////////////////////////////////
 #if NH_MV
-#define H_MV_ENC_DEC_TRAC                 1  //< CU/PU level tracking
+#define NH_MV_ENC_DEC_TRAC                 1  //< CU/PU level tracking
 #if NH_3D
 #define NH_3D_INTEGER_MV_DEPTH            1
@@ -104,4 +100,5 @@
                                              // SEC_ARP_VIEW_REF_CHECK_J0037    Signaling iv_res_pred_weight_idx when the current slice has both view and temporal reference picture(s), JCT3V-J0037 item1
                                              // SEC_ARP_REM_ENC_RESTRICT_K0035    Removal of encoder restriction of ARP, JCT3V-K0035
+#define NH_3D_QTL                          1
 #define NH_3D_QTLPC                        1   // OL_QTLIMIT_PREDCODING_B0068 //JCT3V-B0068
                                               // HHI_QTLPC_RAU_OFF_C0160 JCT3V-C0160 change 2: quadtree limitation and predictive coding switched off in random access units
@@ -275,22 +272,32 @@
                                               // MTK_FAST_TEXTURE_ENCODING_E0173
 //HLS
-                                             // HHI_DEPENDENCY_SIGNALLING_I1_J0107
-                                             // HHI_TOOL_PARAMETERS_I2_J0107
-                                             // HHI_VPS_3D_EXTENSION_I3_J0107
-                                             // HHI_INTER_COMP_PRED_K0052
-                                             // HHI_RES_PRED_K0052
-                                             // HHI_CAM_PARA_K0052
-                                             // H_3D_DIRECT_DEP_TYPE
+                                              // HHI_DEPENDENCY_SIGNALLING_I1_J0107
+                                              // HHI_TOOL_PARAMETERS_I2_J0107
+                                              // HHI_VPS_3D_EXTENSION_I3_J0107
+                                              // HHI_INTER_COMP_PRED_K0052
+                                              // HHI_RES_PRED_K0052
+                                              // HHI_CAM_PARA_K0052
+                                              // H_3D_DIRECT_DEP_TYPE
+#endif // NH_3D
+#if NH_MV
+////////////////////////
+/// Consider Removal 
+////////////////////////
 // Rate Control
 #define KWU_FIX_URQ                       0
 #define KWU_RC_VIEWRC_E0227               0  ///< JCT3V-E0227, view-wise target bitrate allocation
 #define KWU_RC_MADPRED_E0227              0  ///< JCT3V-E0227, inter-view MAD prediction
-#endif // NH_3D
+#define NH_MV_HLS_PTL_LIMITS               0
+#if NH_3D
+// Unclear Fix
+#define H_3D_PPS_FIX_DEPTH                     0
+#endif
+#endif
 /////////////////////////////////////////////////////////////////////////////////////////
 ///////////////////////////////////   DERIVED DEFINES ///////////////////////////////////
 /////////////////////////////////////////////////////////////////////////////////////////
 #if NH_3D
-#define H_3D_OUTPUT_ACTIVE_TOOLS               0
-#define H_3D_REN_MAX_DEV_OUT                   0
+#define NH_3D_OUTPUT_ACTIVE_TOOLS               0
+#define NH_3D_REN_MAX_DEV_OUT                   0
 #endif
 ///// ***** VIEW SYNTHESIS OPTIMIZAION *********
@@ -307,8 +314,4 @@
 #define DVFROM_ABOVE                      1
 #define IDV_CANDS                         2
-#endif
-///// ***** ADVANCED INTERVIEW RESIDUAL PREDICTION *********
-#if NH_3D_ARP
-#define H_3D_ARP_WFNR                     3
 #endif
 /////////////////////////////////////////////////////////////////////////////////////
@@ -325,20 +328,5 @@
 #if NH_3D_DBBP
 #define DBBP_INVALID_SHORT                (-4)
-#define DBBP_PACK_MODE               SIZE_2NxN
-#endif
-///// ***** FCO *********
-#if H_3D_FCO
-#define H_3D_FCO_VSP_DONBDV_E0163               1   // Adaptive depth reference for flexible coding order
-#else
-#define H_3D_FCO_VSP_DONBDV_E0163               0   // Adaptive depth reference for flexible coding order
-#endif
-#if H_3D
-#define PPS_FIX_DEPTH                           1
-#endif
-/////////////////////////////////////////////////////////////////////////////////
-///////////////////////////////////   MV_HEVC HLS  //////////////////////////////
-/////////////////////////////////////////////////////////////////////////////////
-// TBD: Check if integration is necessary.
-#define H_MV_HLS_PTL_LIMITS                  0
+#endif
 /////////////////////////////////////////////////////////////////////////////////////////
 ///////////////////////////////////   HM RELATED DEFINES ////////////////////////////////
@@ -373,4 +361,5 @@
 #define DECODER_CHECK_SUBSTREAM_AND_SLICE_TRAILING_BYTES  1 ///< TODO: integrate this macro into a broader conformance checking system.
 #define T0196_SELECTIVE_RDOQ                              1 ///< selective RDOQ
+#define U0040_MODIFIED_WEIGHTEDPREDICTION_WITH_BIPRED_AND_CLIPPING 1
 // ====================================================================================================================
 // Tool Switches
@@ -389,4 +378,5 @@
 #define MATRIX_MULT                                       0 ///< Brute force matrix multiplication instead of partial butterfly
 #define O0043_BEST_EFFORT_DECODING                        0 ///< 0 (default) = disable code related to best effort decoding, 1 = enable code relating to best effort decoding [ decode-side only ].
+#define ME_ENABLE_ROUNDING_OF_MVS                         1 ///< 0 (default) = disables rounding of motion vectors when right shifted,  1 = enables rounding
 #define RDOQ_CHROMA_LAMBDA                                1 ///< F386: weighting of chroma for RDOQ
 // This can be enabled by the makefile
@@ -394,4 +384,5 @@
 #define RExt__HIGH_BIT_DEPTH_SUPPORT                                           0 ///< 0 (default) use data type definitions for 8-10 bit video, 1 = use larger data types to allow for up to 16-bit video (originally developed as part of N0188)
 #endif
+#define U0132_TARGET_BITS_SATURATION                      1 ///< Rate control with target bits saturation method
 // ====================================================================================================================
 // Derived macros
@@ -443,10 +434,7 @@
 typedef       void                Void;
 typedef       bool                Bool;
-#ifdef __arm__
-typedef       signed char         Char;
-#else
-typedef       char                Char;
-#endif
-typedef       unsigned char       UChar;
+typedef       char                TChar; // Used for text/characters
+typedef       signed char         SChar; // Signed 8-bit values
+typedef       unsigned char       UChar; // Unsigned 8-bit values
 typedef       short               Short;
 typedef       unsigned short      UShort;
@@ -576,4 +564,18 @@
   IPCOLOURSPACE_RGBtoGBR                = 3,
   NUMBER_INPUT_COLOUR_SPACE_CONVERSIONS = 4
+};
+enum MATRIX_COEFFICIENTS // Table E.5 (Matrix coefficients)
+{
+  MATRIX_COEFFICIENTS_RGB                           = 0,
+  MATRIX_COEFFICIENTS_BT709                         = 1,
+  MATRIX_COEFFICIENTS_UNSPECIFIED                   = 2,
+  MATRIX_COEFFICIENTS_RESERVED_BY_ITUISOIEC         = 3,
+  MATRIX_COEFFICIENTS_USFCCT47                      = 4,
+  MATRIX_COEFFICIENTS_BT601_625                     = 5,
+  MATRIX_COEFFICIENTS_BT601_525                     = 6,
+  MATRIX_COEFFICIENTS_SMPTE240                      = 7,
+  MATRIX_COEFFICIENTS_YCGCO                         = 8,
+  MATRIX_COEFFICIENTS_BT2020_NON_CONSTANT_LUMINANCE = 9,
+  MATRIX_COEFFICIENTS_BT2020_CONSTANT_LUMINANCE     = 10,
 };
 enum DeblockEdgeDir
@@ -713,7 +715,9 @@
 enum MESearchMethod
 {
-  FULL_SEARCH                = 0,     ///< Full search
-  DIAMOND                    = 1,     ///< Fast search
-  SELECTIVE                  = 2      ///< Selective search
+  MESEARCH_FULL              = 0,
+  MESEARCH_DIAMOND           = 1,
+  MESEARCH_SELECTIVE         = 2,
+  MESEARCH_DIAMOND_ENHANCED  = 3,
+  MESEARCH_NUMBER_OF_METHODS = 4
 };
 /// coefficient scanning type used in ACS
@@ -760,4 +764,14 @@
   FIXED_NUMBER_OF_BYTES  = 2,          ///< Limit maximum number of bytes in a slice / slice segment
   FIXED_NUMBER_OF_TILES  = 3,          ///< slices / slice segments span an integer number of tiles
+  NUMBER_OF_SLICE_CONSTRAINT_MODES = 4
+};
+// For use with decoded picture hash SEI messages, generated by encoder.
+enum HashType
+{
+  HASHTYPE_MD5             = 0,
+  HASHTYPE_CRC             = 1,
+  HASHTYPE_CHECKSUM        = 2,
+  HASHTYPE_NONE            = 3,
+  NUMBER_OF_HASHTYPES      = 4
 };
 enum SAOMode //mode
@@ -860,4 +874,19 @@
   COST_LOSSLESS_CODING             = 2,
   COST_MIXED_LOSSLESS_LOSSY_CODING = 3
+};
+enum WeightedPredictionMethod
+{
+  WP_PER_PICTURE_WITH_SIMPLE_DC_COMBINED_COMPONENT                          =0,
+  WP_PER_PICTURE_WITH_SIMPLE_DC_PER_COMPONENT                               =1,
+  WP_PER_PICTURE_WITH_HISTOGRAM_AND_PER_COMPONENT                           =2,
+  WP_PER_PICTURE_WITH_HISTOGRAM_AND_PER_COMPONENT_AND_CLIPPING              =3,
+  WP_PER_PICTURE_WITH_HISTOGRAM_AND_PER_COMPONENT_AND_CLIPPING_AND_EXTENSION=4
+};
+enum FastInterSearchMode
+{
+  FASTINTERSEARCH_DISABLED = 0,
+  FASTINTERSEARCH_MODE1    = 1, // TODO: assign better names to these.
+  FASTINTERSEARCH_MODE2    = 2,
+  FASTINTERSEARCH_MODE3    = 3
 };
 enum SPSExtensionFlagIndex
@@ -961,5 +990,5 @@
 };
 #endif
-#if NH_3D
+#if NH_3D_VSO
 // Renderer
 enum BlenMod
Index: trunk/source/Lib/TLibDecoder/SEIread.cpp
===================================================================
--- trunk/source/Lib/TLibDecoder/SEIread.cpp	(revision 1357)
+++ trunk/source/Lib/TLibDecoder/SEIread.cpp	(revision 1386)
@@ -63,5 +63,5 @@
 #endif
 
-Void SEIReader::sei_read_code(std::ostream *pOS, UInt uiLength, UInt& ruiCode, const Char *pSymbolName)
+Void SEIReader::sei_read_code(std::ostream *pOS, UInt uiLength, UInt& ruiCode, const TChar *pSymbolName)
 {
   READ_CODE(uiLength, ruiCode, pSymbolName);
@@ -72,5 +72,5 @@
 }
 
-Void SEIReader::sei_read_uvlc(std::ostream *pOS, UInt& ruiCode, const Char *pSymbolName)
+Void SEIReader::sei_read_uvlc(std::ostream *pOS, UInt& ruiCode, const TChar *pSymbolName)
 {
   READ_UVLC(ruiCode, pSymbolName);
@@ -81,5 +81,5 @@
 }
 
-Void SEIReader::sei_read_svlc(std::ostream *pOS, Int& ruiCode, const Char *pSymbolName)
+Void SEIReader::sei_read_svlc(std::ostream *pOS, Int& ruiCode, const TChar *pSymbolName)
 {
   READ_SVLC(ruiCode, pSymbolName);
@@ -90,5 +90,5 @@
 }
 
-Void SEIReader::sei_read_flag(std::ostream *pOS, UInt& ruiCode, const Char *pSymbolName)
+Void SEIReader::sei_read_flag(std::ostream *pOS, UInt& ruiCode, const TChar *pSymbolName)
 {
   READ_FLAG(ruiCode, pSymbolName);
@@ -99,5 +99,6 @@
 }
 
-Void SEIReader::sei_read_string(std::ostream *pOS, UInt uiBufSize, UChar* pucCode, UInt& ruiLength, const Char *pSymbolName)
+#if NH_MV
+Void SEIReader::sei_read_string(std::ostream *pOS, UInt uiBufSize, UChar* pucCode, UInt& ruiLength, const TChar *pSymbolName)
 {
   READ_STRING(uiBufSize, pucCode, ruiLength, pSymbolName);
@@ -107,6 +108,4 @@
   }
 }
-
-#if NH_MV_SEI
 inline Void SEIReader::output_sei_message_header(SEI &sei, std::ostream *pDecodedMessageOutputStream, UInt payloadSize)
 #else
@@ -118,5 +117,5 @@
     std::string seiMessageHdr(SEI::getSEIMessageString(sei.payloadType())); seiMessageHdr+=" SEI message";
     (*pDecodedMessageOutputStream) << std::setfill('-') << std::setw(seiMessageHdr.size()) << "-" << std::setfill(' ') << "\n" << seiMessageHdr << " (" << payloadSize << " bytes)"<< "\n";
-#if NH_MV_SEI
+#if NH_MV
     (*pDecodedMessageOutputStream) << std::setfill(' ') << "LayerId: " << m_layerId << std::setw(2) << " Picture: " << m_decOrder << std::setw( 5 ) << std::endl;
 #endif
@@ -133,5 +132,5 @@
  * unmarshal a single SEI message from bitstream bs
  */
-#if NH_MV_LAYERS_NOT_PRESENT_SEI
+#if NH_MV
 Void SEIReader::parseSEImessage(TComInputBitstream* bs, SEIMessages& seis, const NalUnitType nalUnitType, const TComVPS *vps, const TComSPS *sps, std::ostream *pDecodedMessageOutputStream)
 #else
@@ -144,5 +143,5 @@
   do
   {
-#if NH_MV_LAYERS_NOT_PRESENT_SEI
+#if NH_MV
     xReadSEImessage(seis, nalUnitType, vps, sps, pDecodedMessageOutputStream);
 #else
@@ -158,5 +157,5 @@
 }
 
-#if NH_MV_LAYERS_NOT_PRESENT_SEI
+#if NH_MV
 Void SEIReader::xReadSEImessage(SEIMessages& seis, const NalUnitType nalUnitType, const TComVPS *vps, const TComSPS *sps, std::ostream *pDecodedMessageOutputStream)
 #else
@@ -281,5 +280,5 @@
     case SEI::SCALABLE_NESTING:
       sei = new SEIScalableNesting;
-#if NH_MV_LAYERS_NOT_PRESENT_SEI
+#if NH_MV
       xParseSEIScalableNesting((SEIScalableNesting&) *sei, nalUnitType, payloadSize, vps, sps, pDecodedMessageOutputStream);
 #else
@@ -295,7 +294,7 @@
       xParseSEITimeCode((SEITimeCode&) *sei, payloadSize, pDecodedMessageOutputStream);
       break;
-    case SEI::CHROMA_SAMPLING_FILTER_HINT:
-      sei = new SEIChromaSamplingFilterHint;
-      xParseSEIChromaSamplingFilterHint((SEIChromaSamplingFilterHint&) *sei, payloadSize/*, sps*/, pDecodedMessageOutputStream);
+    case SEI::CHROMA_RESAMPLING_FILTER_HINT:
+      sei = new SEIChromaResamplingFilterHint;
+      xParseSEIChromaResamplingFilterHint((SEIChromaResamplingFilterHint&) *sei, payloadSize, pDecodedMessageOutputStream);
       //}
       break;
@@ -304,15 +303,13 @@
       xParseSEIKneeFunctionInfo((SEIKneeFunctionInfo&) *sei, payloadSize, pDecodedMessageOutputStream);
       break;
+    case SEI::COLOUR_REMAPPING_INFO:
+      sei = new SEIColourRemappingInfo;
+      xParseSEIColourRemappingInfo((SEIColourRemappingInfo&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
     case SEI::MASTERING_DISPLAY_COLOUR_VOLUME:
       sei = new SEIMasteringDisplayColourVolume;
       xParseSEIMasteringDisplayColourVolume((SEIMasteringDisplayColourVolume&) *sei, payloadSize, pDecodedMessageOutputStream);
       break;
-#if !NH_MV_SEI
-    case SEI::SUB_BITSTREAM_PROPERTY:
-      sei = new SEISubBitstreamProperty;
-      xParseSEISubBitstreamProperty((SEISubBitstreamProperty&) *sei, payloadSize, pDecodedMessageOutputStream );
-      break;
-#else
-#if NH_MV_LAYERS_NOT_PRESENT_SEI
+#if NH_MV
     case SEI::LAYERS_NOT_PRESENT:
       if (!vps)
@@ -326,5 +323,4 @@
       }
       break;
-#endif
     case SEI::INTER_LAYER_CONSTRAINED_TILE_SETS:
       sei = new SEIInterLayerConstrainedTileSets;
@@ -367,10 +363,8 @@
       xParseSEIThreeDimensionalReferenceDisplaysInfo((SEIThreeDimensionalReferenceDisplaysInfo&) *sei, payloadSize, pDecodedMessageOutputStream );
       break;
-#if SEI_DRI_F0169
     case SEI::DEPTH_REPRESENTATION_INFO:
         sei = new SEIDepthRepresentationInfo;
         xParseSEIDepthRepresentationInfo((SEIDepthRepresentationInfo&) *sei, payloadSize, pDecodedMessageOutputStream );
         break;
-#endif
     case SEI::MULTIVIEW_SCENE_INFO:
       sei = new SEIMultiviewSceneInfo;
@@ -531,12 +525,12 @@
   UInt val;
   sei_read_code( pDecodedMessageOutputStream, 8, val, "hash_type");
-  sei.method = static_cast<SEIDecodedPictureHash::Method>(val); bytesRead++;
-
-  const Char *traceString="\0";
+  sei.method = static_cast<HashType>(val); bytesRead++;
+
+  const TChar *traceString="\0";
   switch (sei.method)
   {
-    case SEIDecodedPictureHash::MD5: traceString="picture_md5"; break;
-    case SEIDecodedPictureHash::CRC: traceString="picture_crc"; break;
-    case SEIDecodedPictureHash::CHECKSUM: traceString="picture_checksum"; break;
+    case HASHTYPE_MD5: traceString="picture_md5"; break;
+    case HASHTYPE_CRC: traceString="picture_crc"; break;
+    case HASHTYPE_CHECKSUM: traceString="picture_checksum"; break;
     default: assert(false); break;
   }
@@ -916,5 +910,5 @@
 }
 
-#if NH_MV_LAYERS_NOT_PRESENT_SEI
+#if NH_MV
 Void SEIReader::xParseSEIScalableNesting(SEIScalableNesting& sei, const NalUnitType nalUnitType, UInt payloadSize, const TComVPS *vps, const TComSPS *sps, std::ostream *pDecodedMessageOutputStream)
 #else
@@ -962,5 +956,5 @@
   do
   {
-#if NH_MV_LAYERS_NOT_PRESENT_SEI
+#if NH_MV
     xReadSEImessage(sei.m_nestedSEIs, nalUnitType, vps, sps, pDecodedMessageOutputStream);
 #else
@@ -974,35 +968,4 @@
   }
 }
-
-#if NH_MV
-#if !NH_MV_SEI
-Void SEIReader::xParseSEISubBitstreamProperty(SEISubBitstreamProperty &sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream )
-{
-  UInt code;
-  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
-  sei_read_code( pDecodedMessageOutputStream, 4, code, "active_vps_id" );                      sei.m_activeVpsId = code;
-  sei_read_uvlc( pDecodedMessageOutputStream, code, "num_additional_sub_streams_minus1" );     sei.m_numAdditionalSubStreams = code + 1;
-
-  xResizeSubBitstreamPropertySeiArrays(sei);
-  for( Int i = 0; i < sei.m_numAdditionalSubStreams; i++ )
-  {
-    sei_read_code( pDecodedMessageOutputStream,   2, code, "sub_bitstream_mode[i]"           ); sei.m_subBitstreamMode[i] = code;
-    sei_read_uvlc( pDecodedMessageOutputStream,  code, "output_layer_set_idx_to_vps[i]"      ); sei.m_outputLayerSetIdxToVps[i] = code;
-    sei_read_code( pDecodedMessageOutputStream,   3, code, "highest_sub_layer_id[i]"         ); sei.m_highestSublayerId[i] = code;
-    sei_read_code( pDecodedMessageOutputStream,  16, code, "avg_bit_rate[i]"                 ); sei.m_avgBitRate[i] = code;
-    sei_read_code( pDecodedMessageOutputStream,  16, code, "max_bit_rate[i]"                 ); sei.m_maxBitRate[i] = code;
-  }
-}
-
-Void SEIReader::xResizeSubBitstreamPropertySeiArrays(SEISubBitstreamProperty &sei)
-{
-  sei.m_subBitstreamMode.resize( sei.m_numAdditionalSubStreams );
-  sei.m_outputLayerSetIdxToVps.resize( sei.m_numAdditionalSubStreams );
-  sei.m_highestSublayerId.resize( sei.m_numAdditionalSubStreams );
-  sei.m_avgBitRate.resize( sei.m_numAdditionalSubStreams );
-  sei.m_maxBitRate.resize( sei.m_numAdditionalSubStreams );
-}
-#endif
-#endif
 
 
@@ -1123,5 +1086,5 @@
 }
 
-Void SEIReader::xParseSEIChromaSamplingFilterHint(SEIChromaSamplingFilterHint& sei, UInt payloadSize/*, TComSPS* sps*/, std::ostream *pDecodedMessageOutputStream)
+Void SEIReader::xParseSEIChromaResamplingFilterHint(SEIChromaResamplingFilterHint& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
 {
   UInt uiCode;
@@ -1130,5 +1093,5 @@
   sei_read_code( pDecodedMessageOutputStream, 8, uiCode, "ver_chroma_filter_idc"); sei.m_verChromaFilterIdc = uiCode;
   sei_read_code( pDecodedMessageOutputStream, 8, uiCode, "hor_chroma_filter_idc"); sei.m_horChromaFilterIdc = uiCode;
-  sei_read_flag( pDecodedMessageOutputStream, uiCode, "ver_filtering_process_flag"); sei.m_verFilteringProcessFlag = uiCode;
+  sei_read_flag( pDecodedMessageOutputStream, uiCode, "ver_filtering_field_processing_flag"); sei.m_verFilteringFieldProcessingFlag = uiCode;
   if(sei.m_verChromaFilterIdc == 1 || sei.m_horChromaFilterIdc == 1)
   {
@@ -1136,14 +1099,13 @@
     if(sei.m_verChromaFilterIdc == 1)
     {
-      sei_read_uvlc( pDecodedMessageOutputStream, uiCode, "num_vertical_filters"); sei.m_numVerticalFilters = uiCode;
-      if(sei.m_numVerticalFilters > 0)
-      {
-        sei.m_verTapLengthMinus1 = (Int*)malloc(sei.m_numVerticalFilters * sizeof(Int));
-        sei.m_verFilterCoeff = (Int**)malloc(sei.m_numVerticalFilters * sizeof(Int*));
-        for(Int i = 0; i < sei.m_numVerticalFilters; i ++)
-        {
-          sei_read_uvlc( pDecodedMessageOutputStream, uiCode, "ver_tap_length_minus_1"); sei.m_verTapLengthMinus1[i] = uiCode;
-          sei.m_verFilterCoeff[i] = (Int*)malloc(sei.m_verTapLengthMinus1[i] * sizeof(Int));
-          for(Int j = 0; j < sei.m_verTapLengthMinus1[i]; j ++)
+      UInt numVerticalFilters;
+      sei_read_uvlc( pDecodedMessageOutputStream, numVerticalFilters, "num_vertical_filters"); sei.m_verFilterCoeff.resize(numVerticalFilters);
+      if(numVerticalFilters > 0)
+      {
+        for(Int i = 0; i < numVerticalFilters; i++)
+        {
+          UInt verTapLengthMinus1;
+          sei_read_uvlc( pDecodedMessageOutputStream, verTapLengthMinus1, "ver_tap_length_minus_1"); sei.m_verFilterCoeff[i].resize(verTapLengthMinus1+1);
+          for(Int j = 0; j < (verTapLengthMinus1 + 1); j++)
           {
             sei_read_svlc( pDecodedMessageOutputStream, sei.m_verFilterCoeff[i][j], "ver_filter_coeff");
@@ -1154,14 +1116,13 @@
     if(sei.m_horChromaFilterIdc == 1)
     {
-      sei_read_uvlc( pDecodedMessageOutputStream, uiCode, "num_horizontal_filters"); sei.m_numHorizontalFilters = uiCode;
-      if(sei.m_numHorizontalFilters  > 0)
-      {
-        sei.m_horTapLengthMinus1 = (Int*)malloc(sei.m_numHorizontalFilters * sizeof(Int));
-        sei.m_horFilterCoeff = (Int**)malloc(sei.m_numHorizontalFilters * sizeof(Int*));
-        for(Int i = 0; i < sei.m_numHorizontalFilters; i ++)
-        {
-          sei_read_uvlc( pDecodedMessageOutputStream, uiCode, "hor_tap_length_minus_1"); sei.m_horTapLengthMinus1[i] = uiCode;
-          sei.m_horFilterCoeff[i] = (Int*)malloc(sei.m_horTapLengthMinus1[i] * sizeof(Int));
-          for(Int j = 0; j < sei.m_horTapLengthMinus1[i]; j ++)
+      UInt numHorizontalFilters;
+      sei_read_uvlc( pDecodedMessageOutputStream, numHorizontalFilters, "num_horizontal_filters"); sei.m_horFilterCoeff.resize(numHorizontalFilters);
+      if(numHorizontalFilters  > 0)
+      {
+        for(Int i = 0; i < numHorizontalFilters; i++)
+        {
+          UInt horTapLengthMinus1;
+          sei_read_uvlc( pDecodedMessageOutputStream, horTapLengthMinus1, "hor_tap_length_minus_1"); sei.m_horFilterCoeff[i].resize(horTapLengthMinus1+1);
+          for(Int j = 0; j < (horTapLengthMinus1 + 1); j++)
           {
             sei_read_svlc( pDecodedMessageOutputStream, sei.m_horFilterCoeff[i][j], "hor_filter_coeff");
@@ -1200,4 +1161,94 @@
 }
 
+Void SEIReader::xParseSEIColourRemappingInfo(SEIColourRemappingInfo& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt  uiVal;
+  Int   iVal;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  sei_read_uvlc( pDecodedMessageOutputStream, uiVal, "colour_remap_id" );          sei.m_colourRemapId = uiVal;
+  sei_read_flag( pDecodedMessageOutputStream, uiVal, "colour_remap_cancel_flag" ); sei.m_colourRemapCancelFlag = uiVal;
+  if( !sei.m_colourRemapCancelFlag ) 
+  {
+    sei_read_flag( pDecodedMessageOutputStream, uiVal, "colour_remap_persistence_flag" );                sei.m_colourRemapPersistenceFlag = uiVal;
+    sei_read_flag( pDecodedMessageOutputStream, uiVal, "colour_remap_video_signal_info_present_flag" );  sei.m_colourRemapVideoSignalInfoPresentFlag = uiVal;
+    if ( sei.m_colourRemapVideoSignalInfoPresentFlag )
+    {
+      sei_read_flag( pDecodedMessageOutputStream, uiVal,    "colour_remap_full_range_flag" );            sei.m_colourRemapFullRangeFlag = uiVal;
+      sei_read_code( pDecodedMessageOutputStream, 8, uiVal, "colour_remap_primaries" );                  sei.m_colourRemapPrimaries = uiVal;
+      sei_read_code( pDecodedMessageOutputStream, 8, uiVal, "colour_remap_transfer_function" );          sei.m_colourRemapTransferFunction = uiVal;
+      sei_read_code( pDecodedMessageOutputStream, 8, uiVal, "colour_remap_matrix_coefficients" );        sei.m_colourRemapMatrixCoefficients = uiVal;
+    }
+    sei_read_code( pDecodedMessageOutputStream, 8, uiVal, "colour_remap_input_bit_depth" );              sei.m_colourRemapInputBitDepth = uiVal;
+    sei_read_code( pDecodedMessageOutputStream, 8, uiVal, "colour_remap_bit_depth" );                    sei.m_colourRemapBitDepth = uiVal;
+  
+    for( Int c=0 ; c<3 ; c++ )
+    {
+      sei_read_code( pDecodedMessageOutputStream, 8, uiVal, "pre_lut_num_val_minus1[c]" ); sei.m_preLutNumValMinus1[c] = (uiVal==0) ? 1 : uiVal;
+      sei.m_preLut[c].resize(sei.m_preLutNumValMinus1[c]+1);
+      if( uiVal> 0 )
+      {
+        for ( Int i=0 ; i<=sei.m_preLutNumValMinus1[c] ; i++ )
+        {
+          sei_read_code( pDecodedMessageOutputStream, (( sei.m_colourRemapInputBitDepth   + 7 ) >> 3 ) << 3, uiVal, "pre_lut_coded_value[c][i]" );  sei.m_preLut[c][i].codedValue  = uiVal;
+          sei_read_code( pDecodedMessageOutputStream, (( sei.m_colourRemapBitDepth + 7 ) >> 3 ) << 3, uiVal, "pre_lut_target_value[c][i]" ); sei.m_preLut[c][i].targetValue = uiVal;
+        }
+      }
+      else // pre_lut_num_val_minus1[c] == 0
+      {
+        sei.m_preLut[c][0].codedValue  = 0;
+        sei.m_preLut[c][0].targetValue = 0;
+        sei.m_preLut[c][1].codedValue  = (1 << sei.m_colourRemapInputBitDepth) - 1 ;
+        sei.m_preLut[c][1].targetValue = (1 << sei.m_colourRemapBitDepth) - 1 ;
+      }
+    }
+
+    sei_read_flag( pDecodedMessageOutputStream, uiVal,      "colour_remap_matrix_present_flag" ); sei.m_colourRemapMatrixPresentFlag = uiVal;
+    if( sei.m_colourRemapMatrixPresentFlag )
+    {
+      sei_read_code( pDecodedMessageOutputStream, 4, uiVal, "log2_matrix_denom" ); sei.m_log2MatrixDenom = uiVal;
+      for ( Int c=0 ; c<3 ; c++ )
+      {
+        for ( Int i=0 ; i<3 ; i++ )
+        {
+          sei_read_svlc( pDecodedMessageOutputStream, iVal, "colour_remap_coeffs[c][i]" ); sei.m_colourRemapCoeffs[c][i] = iVal;
+        }
+      }
+    }
+    else // setting default matrix (I3)
+    {
+      sei.m_log2MatrixDenom = 10;
+      for ( Int c=0 ; c<3 ; c++ )
+      {
+        for ( Int i=0 ; i<3 ; i++ )
+        {
+          sei.m_colourRemapCoeffs[c][i] = (c==i) << sei.m_log2MatrixDenom;
+        }
+      }
+    }
+    for( Int c=0 ; c<3 ; c++ )
+    {
+      sei_read_code( pDecodedMessageOutputStream, 8, uiVal, "post_lut_num_val_minus1[c]" ); sei.m_postLutNumValMinus1[c] = (uiVal==0) ? 1 : uiVal;
+      sei.m_postLut[c].resize(sei.m_postLutNumValMinus1[c]+1);
+      if( uiVal > 0 )
+      {
+        for ( Int i=0 ; i<=sei.m_postLutNumValMinus1[c] ; i++ )
+        {
+          sei_read_code( pDecodedMessageOutputStream, (( sei.m_colourRemapBitDepth + 7 ) >> 3 ) << 3, uiVal, "post_lut_coded_value[c][i]" );  sei.m_postLut[c][i].codedValue = uiVal;
+          sei_read_code( pDecodedMessageOutputStream, (( sei.m_colourRemapBitDepth + 7 ) >> 3 ) << 3, uiVal, "post_lut_target_value[c][i]" ); sei.m_postLut[c][i].targetValue = uiVal;
+        }
+      }
+      else
+      {
+        sei.m_postLut[c][0].codedValue  = 0;
+        sei.m_postLut[c][0].targetValue = 0;
+        sei.m_postLut[c][1].targetValue = (1 << sei.m_colourRemapBitDepth) - 1;
+        sei.m_postLut[c][1].codedValue  = (1 << sei.m_colourRemapBitDepth) - 1;
+      }
+    }
+  }
+}
+
+
 Void SEIReader::xParseSEIMasteringDisplayColourVolume(SEIMasteringDisplayColourVolume& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
 {
@@ -1221,6 +1272,5 @@
   sei_read_code( pDecodedMessageOutputStream, 32, code, "min_display_mastering_luminance" ); sei.values.minLuminance = code;
 }
-
-#if NH_MV_LAYERS_NOT_PRESENT_SEI
+#if NH_MV
 Void SEIReader::xParseSEILayersNotPresent(SEILayersNotPresent &sei, UInt payloadSize, const TComVPS *vps, std::ostream *pDecodedMessageOutputStream)
 {
@@ -1239,5 +1289,4 @@
   }
 };
-#endif
 
 Void SEIReader::xParseSEIInterLayerConstrainedTileSets(SEIInterLayerConstrainedTileSets& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
@@ -1506,5 +1555,4 @@
 };
 
-#if SEI_DRI_F0169
 Void SEIReader::xParseSEIDepthRepInfoElement(double& f,std::ostream *pDecodedMessageOutputStream)
 {
@@ -1609,5 +1657,5 @@
     }
 }
-#endif
+
 Void SEIReader::xParseSEIMultiviewSceneInfo(SEIMultiviewSceneInfo& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
 {
@@ -1820,4 +1868,5 @@
 };
 #endif
+#endif
 
 //! \}
Index: trunk/source/Lib/TLibDecoder/SEIread.h
===================================================================
--- trunk/source/Lib/TLibDecoder/SEIread.h	(revision 1357)
+++ trunk/source/Lib/TLibDecoder/SEIread.h	(revision 1386)
@@ -56,15 +56,13 @@
   SEIReader() {};
   virtual ~SEIReader() {};
-#if NH_MV_LAYERS_NOT_PRESENT_SEI
-  Void parseSEImessage(TComInputBitstream* bs, SEIMessages& seis, const NalUnitType nalUnitType, const TComVPS *vps, const TComSPS *sps, std::ostream *pDecodedMessageOutputStream);
+#if NH_MV
+  Void setLayerId( Int   layerId ) { m_layerId = layerId; };
+  Void setDecOrder( Int64 decOrder ) { m_decOrder = decOrder; };
+  Void parseSEImessage( TComInputBitstream* bs, SEIMessages& seis, const NalUnitType nalUnitType, const TComVPS *vps, const TComSPS *sps, std::ostream *pDecodedMessageOutputStream );
 #else
   Void parseSEImessage(TComInputBitstream* bs, SEIMessages& seis, const NalUnitType nalUnitType, const TComSPS *sps, std::ostream *pDecodedMessageOutputStream);
 #endif
-#if NH_MV_SEI
-  Void setLayerId                            ( Int   layerId )   { m_layerId  = layerId; }; 
-  Void setDecOrder                           ( Int64 decOrder )  { m_decOrder = decOrder; }; 
-#endif
 protected:
-#if NH_MV_LAYERS_NOT_PRESENT_SEI
+#if NH_MV
   Void xReadSEImessage                        (SEIMessages& seis, const NalUnitType nalUnitType, const TComVPS *vps, const TComSPS *sps, std::ostream *pDecodedMessageOutputStream);
 #else
@@ -86,5 +84,5 @@
   Void xParseSEIToneMappingInfo               (SEIToneMappingInfo& sei,               UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
   Void xParseSEISOPDescription                (SEISOPDescription &sei,                UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
-#if NH_MV_LAYERS_NOT_PRESENT_SEI
+#if NH_MV
   Void xParseSEIScalableNesting               (SEIScalableNesting& sei, const NalUnitType nalUnitType, UInt payloadSize, const TComVPS *vps, const TComSPS *sps, std::ostream *pDecodedMessageOutputStream);
 #else
@@ -93,16 +91,10 @@
   Void xParseSEITempMotionConstraintsTileSets (SEITempMotionConstrainedTileSets& sei, UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
   Void xParseSEITimeCode                      (SEITimeCode& sei,                      UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
-  Void xParseSEIChromaSamplingFilterHint      (SEIChromaSamplingFilterHint& sei,      UInt payloadSize/*,TComSPS* */,       std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIChromaResamplingFilterHint    (SEIChromaResamplingFilterHint& sei,    UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
   Void xParseSEIKneeFunctionInfo              (SEIKneeFunctionInfo& sei,              UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
   Void xParseSEIMasteringDisplayColourVolume  (SEIMasteringDisplayColourVolume& sei,  UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIColourRemappingInfo           (SEIColourRemappingInfo& sei,           UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
 #if NH_MV
-#if !NH_MV_SEI
-  Void  xParseSEISubBitstreamProperty         (SEISubBitstreamProperty &sei        ,  UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
-  Void  xResizeSubBitstreamPropertySeiArrays  (SEISubBitstreamProperty &sei);
-#endif
-#endif
-#if NH_MV_LAYERS_NOT_PRESENT_SEI
   Void xParseSEILayersNotPresent              (SEILayersNotPresent &sei, UInt payloadSize, const TComVPS *vps ,std::ostream *pDecodedMessageOutputStream);
-#endif
   Void xParseSEIInterLayerConstrainedTileSets (SEIInterLayerConstrainedTileSets& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream);
 #if NH_MV_SEI_TBD
@@ -118,25 +110,19 @@
 #endif
   Void xParseSEIThreeDimensionalReferenceDisplaysInfo (SEIThreeDimensionalReferenceDisplaysInfo& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream);
-#if SEI_DRI_F0169
   Void xParseSEIDepthRepInfoElement           (double &f,std::ostream *pDecodedMessageOutputStream);
   Void xParseSEIDepthRepresentationInfo       (SEIDepthRepresentationInfo& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream);
-#endif
   Void xParseSEIMultiviewSceneInfo            (SEIMultiviewSceneInfo& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream);
-
   Void xParseSEIMultiviewAcquisitionInfo      (SEIMultiviewAcquisitionInfo& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream);
-
-#if NH_MV_SEI
   Void xParseSEIMultiviewViewPosition         (SEIMultiviewViewPosition& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream);
-#endif
 #if NH_3D
   Void xParseSEIAlternativeDepthInfo          (SEIAlternativeDepthInfo& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream);
 #endif
-
-  Void sei_read_code(std::ostream *pOS, UInt uiLength, UInt& ruiCode, const Char *pSymbolName);
-  Void sei_read_uvlc(std::ostream *pOS,                UInt& ruiCode, const Char *pSymbolName);
-  Void sei_read_svlc(std::ostream *pOS,                Int&  ruiCode, const Char *pSymbolName);
-  Void sei_read_flag(std::ostream *pOS,                UInt& ruiCode, const Char *pSymbolName);
-  Void sei_read_string(std::ostream *pOS, UInt uiBufSize, UChar* pucCode, UInt& ruiLength, const Char *pSymbolName);
-#if NH_MV_SEI
+#endif
+  Void sei_read_code(std::ostream *pOS, UInt uiLength, UInt& ruiCode, const TChar *pSymbolName);
+  Void sei_read_uvlc(std::ostream *pOS,                UInt& ruiCode, const TChar *pSymbolName);
+  Void sei_read_svlc(std::ostream *pOS,                Int&  ruiCode, const TChar *pSymbolName);
+  Void sei_read_flag(std::ostream *pOS,                UInt& ruiCode, const TChar *pSymbolName);
+#if NH_MV
+  Void sei_read_string(std::ostream *pOS, UInt uiBufSize, UChar* pucCode, UInt& ruiLength, const TChar *pSymbolName);
   inline Void output_sei_message_header(SEI &sei, std::ostream *pDecodedMessageOutputStream, UInt payloadSize);
 private: 
Index: trunk/source/Lib/TLibDecoder/SyntaxElementParser.cpp
===================================================================
--- trunk/source/Lib/TLibDecoder/SyntaxElementParser.cpp	(revision 1357)
+++ trunk/source/Lib/TLibDecoder/SyntaxElementParser.cpp	(revision 1386)
@@ -49,5 +49,5 @@
 #if ENC_DEC_TRACE
 
-Void  SyntaxElementParser::xReadCodeTr           (UInt length, UInt& rValue, const Char *pSymbolName)
+Void  SyntaxElementParser::xReadCodeTr           (UInt length, UInt& rValue, const TChar *pSymbolName)
 {
 #if RExt__DECODER_DEBUG_BIT_STATISTICS
@@ -56,5 +56,5 @@
   xReadCode (length, rValue);
 #endif
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
   if ( g_disableHLSTrace || !g_HLSTraceEnable )
   {
@@ -80,5 +80,5 @@
 }
 
-Void  SyntaxElementParser::xReadUvlcTr           (UInt& rValue, const Char *pSymbolName)
+Void  SyntaxElementParser::xReadUvlcTr           (UInt& rValue, const TChar *pSymbolName)
 {
 #if RExt__DECODER_DEBUG_BIT_STATISTICS
@@ -87,5 +87,5 @@
   xReadUvlc (rValue);
 #endif
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
   if ( g_disableHLSTrace || !g_HLSTraceEnable )
   {
@@ -104,5 +104,5 @@
 }
 
-Void  SyntaxElementParser::xReadSvlcTr           (Int& rValue, const Char *pSymbolName)
+Void  SyntaxElementParser::xReadSvlcTr           (Int& rValue, const TChar *pSymbolName)
 {
 #if RExt__DECODER_DEBUG_BIT_STATISTICS
@@ -111,5 +111,5 @@
   xReadSvlc (rValue);
 #endif
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
   if ( g_disableHLSTrace || !g_HLSTraceEnable )
   {
@@ -128,5 +128,5 @@
 }
 
-Void  SyntaxElementParser::xReadFlagTr           (UInt& rValue, const Char *pSymbolName)
+Void  SyntaxElementParser::xReadFlagTr           (UInt& rValue, const TChar *pSymbolName)
 {
 #if RExt__DECODER_DEBUG_BIT_STATISTICS
@@ -135,5 +135,5 @@
   xReadFlag (rValue);
 #endif
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
   if ( g_disableHLSTrace || !g_HLSTraceEnable )
   {
@@ -152,5 +152,6 @@
 }
 
-Void  SyntaxElementParser::xReadStringTr        (UInt buSize, UChar *pValue, UInt& rLength, const Char *pSymbolName)
+#if NH_MV
+Void  SyntaxElementParser::xReadStringTr        (UInt buSize, UChar *pValue, UInt& rLength, const TChar *pSymbolName)
 {
 #if RExt__DECODER_DEBUG_BIT_STATISTICS
@@ -163,5 +164,5 @@
   fflush ( g_hTrace );
 }
-
+#endif
 Void  xTraceAccessUnitDelimiter ()
 {
@@ -181,5 +182,5 @@
 // ====================================================================================================================
 #if RExt__DECODER_DEBUG_BIT_STATISTICS
-Void SyntaxElementParser::xReadCode (UInt uiLength, UInt& ruiCode, const Char *pSymbolName)
+Void SyntaxElementParser::xReadCode (UInt uiLength, UInt& ruiCode, const TChar *pSymbolName)
 #else
 Void SyntaxElementParser::xReadCode (UInt uiLength, UInt& ruiCode)
@@ -194,5 +195,5 @@
 
 #if RExt__DECODER_DEBUG_BIT_STATISTICS
-Void SyntaxElementParser::xReadUvlc( UInt& ruiVal, const Char *pSymbolName)
+Void SyntaxElementParser::xReadUvlc( UInt& ruiVal, const TChar *pSymbolName)
 #else
 Void SyntaxElementParser::xReadUvlc( UInt& ruiVal)
@@ -232,5 +233,5 @@
 
 #if RExt__DECODER_DEBUG_BIT_STATISTICS
-Void SyntaxElementParser::xReadSvlc( Int& riVal, const Char *pSymbolName)
+Void SyntaxElementParser::xReadSvlc( Int& riVal, const TChar *pSymbolName)
 #else
 Void SyntaxElementParser::xReadSvlc( Int& riVal)
@@ -270,5 +271,5 @@
 
 #if RExt__DECODER_DEBUG_BIT_STATISTICS
-Void SyntaxElementParser::xReadFlag (UInt& ruiCode, const Char *pSymbolName)
+Void SyntaxElementParser::xReadFlag (UInt& ruiCode, const TChar *pSymbolName)
 #else
 Void SyntaxElementParser::xReadFlag (UInt& ruiCode)
@@ -281,6 +282,7 @@
 }
 
-#if RExt__DECODER_DEBUG_BIT_STATISTICS
-Void  SyntaxElementParser::xReadString  (UInt bufSize, UChar *pVal, UInt& rLength, const Char *pSymbolName)
+#if NH_MV
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+Void  SyntaxElementParser::xReadString  (UInt bufSize, UChar *pVal, UInt& rLength, const TChar *pSymbolName)
 #else
 Void  SyntaxElementParser::xReadString  (UInt bufSize, UChar *pVal, UInt& rLength)
@@ -302,4 +304,5 @@
   assert( pVal[rLength] == 0 );  
 }
+#endif
 
 Void SyntaxElementParser::xReadRbspTrailingBits()
Index: trunk/source/Lib/TLibDecoder/SyntaxElementParser.h
===================================================================
--- trunk/source/Lib/TLibDecoder/SyntaxElementParser.h	(revision 1357)
+++ trunk/source/Lib/TLibDecoder/SyntaxElementParser.h	(revision 1386)
@@ -49,6 +49,7 @@
 #define READ_SVLC(        code, name)     xReadSvlcTr (         code, name )
 #define READ_FLAG(        code, name)     xReadFlagTr (         code, name )
+#if NH_MV
 #define READ_STRING(bufSize, code, length, name)   xReadStringTr ( bufSize, code, length, name )
-
+#endif
 #else
 
@@ -59,6 +60,7 @@
 #define READ_SVLC(        code, name)     xReadSvlc (         code, name )
 #define READ_FLAG(        code, name)     xReadFlag (         code, name )
+#if NH_MV
 #define READ_STRING(bufSize, code, length, name)   xReadString ( bufSize, code, length, name )
-
+#endif
 #else
 
@@ -67,5 +69,7 @@
 #define READ_SVLC(        code, name)     xReadSvlc (         code )
 #define READ_FLAG(        code, name)     xReadFlag (         code )
+#if NH_MV
 #define READ_STRING(bufSize, code, length, name)   xReadString ( bufSize, code, length )
+#endif
 
 #endif
@@ -91,9 +95,11 @@
 
 #if RExt__DECODER_DEBUG_BIT_STATISTICS
-  Void  xReadCode    ( UInt   length, UInt& val, const Char *pSymbolName );
-  Void  xReadUvlc    ( UInt&  val, const Char *pSymbolName );
-  Void  xReadSvlc    ( Int&   val, const Char *pSymbolName );
-  Void  xReadFlag    ( UInt&  val, const Char *pSymbolName );
-  Void  xReadString  ( UInt bufSize, UChar *val, UInt& length, const Char *pSymbolName);
+  Void  xReadCode    ( UInt   length, UInt& val, const TChar *pSymbolName );
+  Void  xReadUvlc    ( UInt&  val, const TChar *pSymbolName );
+  Void  xReadSvlc    ( Int&   val, const TChar *pSymbolName );
+  Void  xReadFlag    ( UInt&  val, const TChar *pSymbolName );
+#if NH_MV
+  Void  xReadString  ( UInt bufSize, UChar *val, UInt& length, const TChar *pSymbolName);
+#endif
 #else
   Void  xReadCode    ( UInt   length, UInt& val );
@@ -101,12 +107,16 @@
   Void  xReadSvlc    ( Int&   val );
   Void  xReadFlag    ( UInt&  val );
+#if NH_MV
   Void  xReadString  ( UInt bufSize, UChar *val, UInt& length);
 #endif
+#endif
 #if ENC_DEC_TRACE
-  Void  xReadCodeTr  (UInt  length, UInt& rValue, const Char *pSymbolName);
-  Void  xReadUvlcTr  (              UInt& rValue, const Char *pSymbolName);
-  Void  xReadSvlcTr  (               Int& rValue, const Char *pSymbolName);
-  Void  xReadFlagTr  (              UInt& rValue, const Char *pSymbolName);
-  Void  xReadStringTr(UInt bufSize, UChar *pValue, UInt& rLength, const Char *pSymbolName);
+  Void  xReadCodeTr  (UInt  length, UInt& rValue, const TChar *pSymbolName);
+  Void  xReadUvlcTr  (              UInt& rValue, const TChar *pSymbolName);
+  Void  xReadSvlcTr  (               Int& rValue, const TChar *pSymbolName);
+  Void  xReadFlagTr  (              UInt& rValue, const TChar *pSymbolName);
+#if NH_MV
+  Void  xReadStringTr(UInt bufSize, UChar *pValue, UInt& rLength, const TChar *pSymbolName);
+#endif
 #endif
 public:
Index: trunk/source/Lib/TLibDecoder/TDecBinCoderCABAC.cpp
===================================================================
--- trunk/source/Lib/TLibDecoder/TDecBinCoderCABAC.cpp	(revision 1357)
+++ trunk/source/Lib/TLibDecoder/TDecBinCoderCABAC.cpp	(revision 1386)
@@ -169,5 +169,5 @@
   if (g_debugCounter >= debugCabacBinTargetLine)
   {
-    Char breakPointThis;
+    UChar breakPointThis;
     breakPointThis = 7;
   }
Index: trunk/source/Lib/TLibDecoder/TDecCAVLC.cpp
===================================================================
--- trunk/source/Lib/TLibDecoder/TDecCAVLC.cpp	(revision 1357)
+++ trunk/source/Lib/TLibDecoder/TDecCAVLC.cpp	(revision 1386)
@@ -51,5 +51,5 @@
 
 #if ENC_DEC_TRACE
-#if !H_MV_ENC_DEC_TRAC
+#if !NH_MV_ENC_DEC_TRAC
 Void  xTraceVPSHeader ()
 {
@@ -234,5 +234,5 @@
 {
 #if ENC_DEC_TRACE
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
   tracePSHeader( "PPS", pcPPS->getLayerId() ); 
 #else
@@ -454,5 +454,5 @@
 #else
 #if ENC_DEC_TRACE || RExt__DECODER_DEBUG_BIT_STATISTICS
-    static const char *syntaxStrings[]={ "pps_range_extension_flag",
+    static const TChar *syntaxStrings[]={ "pps_range_extension_flag",
                                          "pps_multilayer_extension_flag",
                                          "pps_extension_6bits[0]",
@@ -871,5 +871,5 @@
 {
 #if ENC_DEC_TRACE
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
   tracePSHeader( "SPS", pcSPS->getLayerId() ); 
 #else
@@ -1017,5 +1017,5 @@
     pcSPS->setSpsMaxLatencyIncreasePlus1( uiCode, i );
 #else
-    pcSPS->setMaxLatencyIncrease( uiCode, i );
+    pcSPS->setMaxLatencyIncreasePlus1( uiCode, i );
 #endif
 
@@ -1029,5 +1029,5 @@
         pcSPS->setSpsMaxLatencyIncreasePlus1(pcSPS->getSpsMaxLatencyIncreasePlus1(0), i);
 #else
-        pcSPS->setMaxLatencyIncrease(pcSPS->getMaxLatencyIncrease(0), i);
+        pcSPS->setMaxLatencyIncreasePlus1(pcSPS->getMaxLatencyIncreasePlus1(0), i);
 #endif
       }
@@ -1165,14 +1165,14 @@
     if ( pcSPS->getSpsRangeExtensionsFlag() )
     {
-              TComSPSRExt &spsRangeExtension = pcSPS->getSpsRangeExtension();
-              READ_FLAG( uiCode, "transform_skip_rotation_enabled_flag");     spsRangeExtension.setTransformSkipRotationEnabledFlag(uiCode != 0);
-              READ_FLAG( uiCode, "transform_skip_context_enabled_flag");      spsRangeExtension.setTransformSkipContextEnabledFlag (uiCode != 0);
-              READ_FLAG( uiCode, "implicit_rdpcm_enabled_flag");              spsRangeExtension.setRdpcmEnabledFlag(RDPCM_SIGNAL_IMPLICIT, (uiCode != 0));
-              READ_FLAG( uiCode, "explicit_rdpcm_enabled_flag");              spsRangeExtension.setRdpcmEnabledFlag(RDPCM_SIGNAL_EXPLICIT, (uiCode != 0));
-              READ_FLAG( uiCode, "extended_precision_processing_flag");       spsRangeExtension.setExtendedPrecisionProcessingFlag (uiCode != 0);
-              READ_FLAG( uiCode, "intra_smoothing_disabled_flag");            spsRangeExtension.setIntraSmoothingDisabledFlag      (uiCode != 0);
-              READ_FLAG( uiCode, "high_precision_offsets_enabled_flag");      spsRangeExtension.setHighPrecisionOffsetsEnabledFlag (uiCode != 0);
-              READ_FLAG( uiCode, "persistent_rice_adaptation_enabled_flag");  spsRangeExtension.setPersistentRiceAdaptationEnabledFlag (uiCode != 0);
-              READ_FLAG( uiCode, "cabac_bypass_alignment_enabled_flag");      spsRangeExtension.setCabacBypassAlignmentEnabledFlag  (uiCode != 0);
+      TComSPSRExt &spsRangeExtension = pcSPS->getSpsRangeExtension();
+      READ_FLAG( uiCode, "transform_skip_rotation_enabled_flag");     spsRangeExtension.setTransformSkipRotationEnabledFlag(uiCode != 0);
+      READ_FLAG( uiCode, "transform_skip_context_enabled_flag");      spsRangeExtension.setTransformSkipContextEnabledFlag (uiCode != 0);
+      READ_FLAG( uiCode, "implicit_rdpcm_enabled_flag");              spsRangeExtension.setRdpcmEnabledFlag(RDPCM_SIGNAL_IMPLICIT, (uiCode != 0));
+      READ_FLAG( uiCode, "explicit_rdpcm_enabled_flag");              spsRangeExtension.setRdpcmEnabledFlag(RDPCM_SIGNAL_EXPLICIT, (uiCode != 0));
+      READ_FLAG( uiCode, "extended_precision_processing_flag");       spsRangeExtension.setExtendedPrecisionProcessingFlag (uiCode != 0);
+      READ_FLAG( uiCode, "intra_smoothing_disabled_flag");            spsRangeExtension.setIntraSmoothingDisabledFlag      (uiCode != 0);
+      READ_FLAG( uiCode, "high_precision_offsets_enabled_flag");      spsRangeExtension.setHighPrecisionOffsetsEnabledFlag (uiCode != 0);
+      READ_FLAG( uiCode, "persistent_rice_adaptation_enabled_flag");  spsRangeExtension.setPersistentRiceAdaptationEnabledFlag (uiCode != 0);
+      READ_FLAG( uiCode, "cabac_bypass_alignment_enabled_flag");      spsRangeExtension.setCabacBypassAlignmentEnabledFlag  (uiCode != 0);
     }
 
@@ -1206,5 +1206,5 @@
 
 #if ENC_DEC_TRACE || RExt__DECODER_DEBUG_BIT_STATISTICS
-    static const char *syntaxStrings[]={ "sps_range_extension_flag",
+    static const TChar *syntaxStrings[]={ "sps_range_extension_flag",
                                          "sps_multilayer_extension_flag",
                                          "sps_extension_6bits[0]",
@@ -1277,23 +1277,23 @@
   for( Int d = 0; d  <=  1; d++ )
   {
-    READ_FLAG( uiCode, "iv_mv_pred_flag" ); sps3dExt.setIvMvPredFlag( d, uiCode == 1 );
-    READ_FLAG( uiCode, "iv_mv_scaling_flag" ); sps3dExt.setIvMvScalingFlag( d, uiCode == 1 );
+    READ_FLAG( uiCode, "iv_di_mc_enabled_flag" );              sps3dExt.setIvDiMcEnabledFlag( d, uiCode == 1 );
+    READ_FLAG( uiCode, "iv_mv_scal_enabled_flag" );            sps3dExt.setIvMvScalEnabledFlag( d, uiCode == 1 );
     if( d  ==  0 )
     {
-      READ_UVLC( uiCode, "log2_sub_pb_size_minus3" ); sps3dExt.setLog2SubPbSizeMinus3( d, uiCode );
-      READ_FLAG( uiCode, "iv_res_pred_flag" ); sps3dExt.setIvResPredFlag( d, uiCode == 1 );
-      READ_FLAG( uiCode, "depth_refinement_flag" ); sps3dExt.setDepthRefinementFlag( d, uiCode == 1 );
-      READ_FLAG( uiCode, "view_synthesis_pred_flag" ); sps3dExt.setViewSynthesisPredFlag( d, uiCode == 1 );
-      READ_FLAG( uiCode, "depth_based_blk_part_flag" ); sps3dExt.setDepthBasedBlkPartFlag( d, uiCode == 1 );
+      READ_UVLC( uiCode, "log2_sub_pb_size_minus3" );          sps3dExt.setLog2IvmcSubPbSizeMinus3( d, uiCode );
+      READ_FLAG( uiCode, "iv_res_pred_enabled_flag" );         sps3dExt.setIvResPredEnabledFlag( d, uiCode == 1 );
+      READ_FLAG( uiCode, "depth_ref_enabled_flag" );           sps3dExt.setDepthRefEnabledFlag( d, uiCode == 1 );
+      READ_FLAG( uiCode, "vsp_mc_enabled_flag" );              sps3dExt.setVspMcEnabledFlag( d, uiCode == 1 );
+      READ_FLAG( uiCode, "dbbp_enabled_flag" );                sps3dExt.setDbbpEnabledFlag( d, uiCode == 1 );
     }
     else 
     {
-      READ_FLAG( uiCode, "mpi_flag" ); sps3dExt.setMpiFlag( d, uiCode == 1 );
-      READ_UVLC( uiCode, "log2_mpi_sub_pb_size_minus3" ); sps3dExt.setLog2MpiSubPbSizeMinus3( d, uiCode );
-      READ_FLAG( uiCode, "intra_contour_flag" ); sps3dExt.setIntraContourFlag( d, uiCode == 1 );
-      READ_FLAG( uiCode, "intra_sdc_wedge_flag" ); sps3dExt.setIntraSdcWedgeFlag( d, uiCode == 1 );
-      READ_FLAG( uiCode, "qt_pred_flag" ); sps3dExt.setQtPredFlag( d, uiCode == 1 );
-      READ_FLAG( uiCode, "inter_sdc_flag" ); sps3dExt.setInterSdcFlag( d, uiCode == 1 );
-      READ_FLAG( uiCode, "intra_skip_flag" ); sps3dExt.setDepthIntraSkipFlag( d, uiCode == 1 );
+      READ_FLAG( uiCode, "tex_mc_enabled_flag" );              sps3dExt.setTexMcEnabledFlag( d, uiCode == 1 );
+      READ_UVLC( uiCode, "log2_texmc_sub_pb_size_minus3" );    sps3dExt.setLog2TexmcSubPbSizeMinus3( d, uiCode );
+      READ_FLAG( uiCode, "intra_contour_enabled_flag" );       sps3dExt.setIntraContourEnabledFlag( d, uiCode == 1 );
+      READ_FLAG( uiCode, "intra_dc_only_wedge_enabled_flag" ); sps3dExt.setIntraDcOnlyWedgeEnabledFlag( d, uiCode == 1 );
+      READ_FLAG( uiCode, "cqt_cu_part_pred_enabled_flag" );    sps3dExt.setCqtCuPartPredEnabledFlag( d, uiCode == 1 );
+      READ_FLAG( uiCode, "inter_dc_only_enabled_flag" );       sps3dExt.setInterDcOnlyEnabledFlag( d, uiCode == 1 );
+      READ_FLAG( uiCode, "skip_intra_enabled_flag" );          sps3dExt.setSkipIntraEnabledFlag( d, uiCode == 1 );
     }
   }
@@ -1358,5 +1358,5 @@
 {
 #if ENC_DEC_TRACE
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
   tracePSHeader( "VPS", getDecTop()->getLayerId() ); 
 #else
Index: trunk/source/Lib/TLibDecoder/TDecCu.cpp
===================================================================
--- trunk/source/Lib/TLibDecoder/TDecCu.cpp	(revision 1357)
+++ trunk/source/Lib/TLibDecoder/TDecCu.cpp	(revision 1386)
@@ -213,5 +213,5 @@
   UInt uiTPelY   = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
   UInt uiBPelY   = uiTPelY + (maxCuHeight>>uiDepth) - 1;
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
   DTRACE_CU_S("=========== coding_quadtree ===========\n")
   DTRACE_CU("x0", uiLPelX)
@@ -270,7 +270,7 @@
   }
 
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
   DTRACE_CU_S("=========== coding_unit ===========\n")
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
 #if ENC_DEC_TRACE
     stopAtPos  ( pcCU->getSlice()->getPOC(), 
@@ -359,5 +359,5 @@
       }
 #endif
-#if ENC_DEC_TRACE && H_MV_ENC_DEC_TRAC   
+#if ENC_DEC_TRACE && NH_MV_ENC_DEC_TRAC   
       if ( g_decTraceDispDer )
       {
@@ -396,5 +396,5 @@
   if( pcCU->isSkipped(uiAbsPartIdx) )
   {
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
     DTRACE_PU_S("=========== prediction_unit ===========\n")
     DTRACE_PU("x0", uiLPelX)
@@ -493,5 +493,5 @@
         }
 #endif
-#if ENC_DEC_TRACE && H_MV_ENC_DEC_TRAC   
+#if ENC_DEC_TRACE && NH_MV_ENC_DEC_TRAC   
         if ( g_decTraceMvFromMerge )
         {        
@@ -531,5 +531,5 @@
         pcCU->getCUMvField( REF_PIC_LIST_1 )->setMvFieldSP(pcCU, uiSPAddr, pcMvFieldSP[2*iPartitionIdx + 1], iSPWidth, iSPHeight);
       }
-#if ENC_DEC_TRACE && H_MV_ENC_DEC_TRAC
+#if ENC_DEC_TRACE && NH_MV_ENC_DEC_TRAC
       if ( g_traceSubPBMotion )
       {
Index: trunk/source/Lib/TLibDecoder/TDecEntropy.cpp
===================================================================
--- trunk/source/Lib/TLibDecoder/TDecEntropy.cpp	(revision 1357)
+++ trunk/source/Lib/TLibDecoder/TDecEntropy.cpp	(revision 1386)
@@ -267,5 +267,5 @@
   for ( UInt uiPartIdx = 0, uiSubPartIdx = uiAbsPartIdx; uiPartIdx < uiNumPU; uiPartIdx++, uiSubPartIdx += uiPUOffset )
   {
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
     DTRACE_PU_S("=========== prediction_unit ===========\n")
     // ToDo: 
@@ -484,5 +484,5 @@
   for ( UInt uiPartIdx = 0, uiSubPartIdx = uiAbsPartIdx; uiPartIdx < uiNumPU; uiPartIdx++, uiSubPartIdx += uiPUOffset )
   {
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
     DTRACE_PU_S("=========== prediction_unit ===========\n")
     // ToDo: 
@@ -505,5 +505,5 @@
 #endif
 
-      UInt uiMergeIndex = pcCU->getMergeIndex(uiSubPartIdx);
+      const UInt uiMergeIndex = pcCU->getMergeIndex(uiSubPartIdx);
       if ( pcCU->getSlice()->getPPS()->getLog2ParallelMergeLevelMinus2() && ePartSize != SIZE_2Nx2N && pcSubCU->getWidth( 0 ) <= 8 )
       {
@@ -547,5 +547,4 @@
       else
       {
-        uiMergeIndex = pcCU->getMergeIndex(uiSubPartIdx);
 
 #if NH_3D_MLC
@@ -742,5 +741,5 @@
   {
     m_pcEntropyDecoderIf->parseMVPIdx( iMVPIdx );
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
 #if ENC_DEC_TRACE
     if ( eRefList == REF_PIC_LIST_0 )
@@ -799,5 +798,5 @@
   {
     m_pcEntropyDecoderIf->parseMVPIdx( iMVPIdx );
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
 #if ENC_DEC_TRACE
     if ( eRefList == REF_PIC_LIST_0 )
@@ -834,5 +833,5 @@
   const UInt uiTrDepth = rTu.GetTransformDepthRel();
 
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
 #if ENC_DEC_TRACE
   UInt uiLPelX   = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
@@ -941,5 +940,5 @@
     pcCU->setTrIdxSubParts( uiTrDepth, uiAbsPartIdx, uiDepth );
 
-#if !H_MV_ENC_DEC_TRAC
+#if !NH_MV_ENC_DEC_TRAC
     {
       DTRACE_CABAC_VL( g_nSymbolCounter++ );
Index: trunk/source/Lib/TLibDecoder/TDecGop.cpp
===================================================================
--- trunk/source/Lib/TLibDecoder/TDecGop.cpp	(revision 1357)
+++ trunk/source/Lib/TLibDecoder/TDecGop.cpp	(revision 1386)
@@ -177,5 +177,5 @@
   pcPic->compressMotion();
 #endif
-  Char c = (pcSlice->isIntra() ? 'I' : pcSlice->isInterP() ? 'P' : 'B');
+  TChar c = (pcSlice->isIntra() ? 'I' : pcSlice->isInterP() ? 'P' : 'B');
   if (!pcSlice->isReferenced())
   {
@@ -255,5 +255,5 @@
   TComPictureHash recon_digest;
   Int numChar=0;
-  const Char* hashType = "\0";
+  const TChar* hashType = "\0";
 
   if (pictureHashSEI)
@@ -261,5 +261,5 @@
     switch (pictureHashSEI->method)
     {
-      case SEIDecodedPictureHash::MD5:
+      case HASHTYPE_MD5:
         {
           hashType = "MD5";
@@ -267,5 +267,5 @@
           break;
         }
-      case SEIDecodedPictureHash::CRC:
+      case HASHTYPE_CRC:
         {
           hashType = "CRC";
@@ -273,5 +273,5 @@
           break;
         }
-      case SEIDecodedPictureHash::CHECKSUM:
+      case HASHTYPE_CHECKSUM:
         {
           hashType = "Checksum";
@@ -288,5 +288,5 @@
 
   /* compare digest against received version */
-  const Char* ok = "(unk)";
+  const TChar* ok = "(unk)";
   Bool mismatch = false;
 
Index: trunk/source/Lib/TLibDecoder/TDecSbac.cpp
===================================================================
--- trunk/source/Lib/TLibDecoder/TDecSbac.cpp	(revision 1357)
+++ trunk/source/Lib/TLibDecoder/TDecSbac.cpp	(revision 1386)
@@ -423,5 +423,5 @@
   m_pcTDecBinIf->decodeBinTrm(uiSymbol);
 
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
   DTRACE_CU("pcm_flag", uiSymbol)
 #endif
@@ -467,5 +467,5 @@
   UInt uiSymbol;
   m_pcTDecBinIf->decodeBin( uiSymbol, m_CUTransquantBypassFlagSCModel.get( 0, 0, 0 ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__TQ_BYPASS_FLAG) );
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
   DTRACE_CU("cu_transquant_bypass_flag", uiSymbol); 
 #endif
@@ -490,5 +490,5 @@
   UInt uiCtxSkip = pcCU->getCtxSkipFlag( uiAbsPartIdx );
   m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUSkipFlagSCModel.get( 0, 0, uiCtxSkip ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__SKIP_FLAG) );
-#if !H_MV_ENC_DEC_TRAC
+#if !NH_MV_ENC_DEC_TRAC
   DTRACE_CABAC_VL( g_nSymbolCounter++ );
   DTRACE_CABAC_T( "\tSkipFlag" );
@@ -507,5 +507,5 @@
     pcCU->setMergeFlagSubParts( true , uiAbsPartIdx, 0, uiDepth );
   }
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
   DTRACE_CU("cu_skip_flag", uiSymbol); 
 #endif
@@ -570,9 +570,9 @@
   UInt uiSymbol;
   m_pcTDecBinIf->decodeBin( uiSymbol, *m_cCUMergeFlagExtSCModel.get( 0 ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__MERGE_FLAG) );
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
   DTRACE_PU("merge_flag", uiSymbol)
 #endif
   pcCU->setMergeFlagSubParts( uiSymbol ? true : false, uiAbsPartIdx, uiPUIdx, uiDepth );
-#if !H_MV_ENC_DEC_TRAC
+#if !NH_MV_ENC_DEC_TRAC
   DTRACE_CABAC_VL( g_nSymbolCounter++ );
   DTRACE_CABAC_T( "\tMergeFlag: " );
@@ -608,5 +608,5 @@
       }
     }
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
     DTRACE_PU("merge_idx", uiUnaryIdx)
 #endif
@@ -614,5 +614,5 @@
   ruiMergeIndex = uiUnaryIdx;
 
-#if !H_MV_ENC_DEC_TRAC
+#if !NH_MV_ENC_DEC_TRAC
   DTRACE_CABAC_VL( g_nSymbolCounter++ )
   DTRACE_CABAC_T( "\tparseMergeIndex()" )
@@ -666,5 +666,5 @@
 #endif
   m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUSplitFlagSCModel.get( 0, 0, pcCU->getCtxSplitFlag( uiAbsPartIdx, uiDepth ) ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
     DTRACE_CU("split_cu_flag", uiSymbol); 
 #else
@@ -748,5 +748,5 @@
     {
       m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUPartSizeSCModel.get( 0, 0, 0) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
-#if H_MV_ENC_DEC_TRAC          
+#if NH_MV_ENC_DEC_TRAC          
         DTRACE_CU("part_mode", uiSymbol)
 #endif        
@@ -884,5 +884,5 @@
       }
 #endif
-#if H_MV_ENC_DEC_TRAC          
+#if NH_MV_ENC_DEC_TRAC          
       DTRACE_CU("part_mode", eMode )
 #endif
@@ -914,5 +914,5 @@
   m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUPredModeSCModel.get( 0, 0, 0 ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__PRED_MODE) );
   iPredMode += uiSymbol;
-#if H_MV_ENC_DEC_TRAC          
+#if NH_MV_ENC_DEC_TRAC          
   DTRACE_CU("pred_mode_flag", uiSymbol)
 #endif        
@@ -948,5 +948,5 @@
     m_pcTDecBinIf->decodeBin( symbol, m_cCUIntraPredSCModel.get( 0, 0, 0) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
     mpmPred[j] = symbol;
-#if H_MV_ENC_DEC_TRAC          
+#if NH_MV_ENC_DEC_TRAC          
       DTRACE_CU("prev_intra_luma_pred_flag", symbol)
 #endif
@@ -971,5 +971,5 @@
         symbol++;
       }
-#if H_MV_ENC_DEC_TRAC          
+#if NH_MV_ENC_DEC_TRAC          
         DTRACE_CU("mpm_idx", symbol)
 #endif
@@ -980,5 +980,5 @@
       m_pcTDecBinIf->decodeBinsEP( symbol, 5 RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
       intraPredMode = symbol;
-#if H_MV_ENC_DEC_TRAC          
+#if NH_MV_ENC_DEC_TRAC          
         DTRACE_CU("rem_intra_luma_pred_mode", symbol)
 #endif        
@@ -1020,5 +1020,5 @@
   if( uiSymbol == 0 )
   {
-#if H_MV_ENC_DEC_TRAC          
+#if NH_MV_ENC_DEC_TRAC          
     DTRACE_CU("intra_chroma_pred_mode", uiSymbol )
 #endif        
@@ -1029,5 +1029,5 @@
     UInt uiIPredMode;
     m_pcTDecBinIf->decodeBinsEP( uiIPredMode, 2 RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
-#if H_MV_ENC_DEC_TRAC          
+#if NH_MV_ENC_DEC_TRAC          
       DTRACE_CU("intra_chroma_pred_mode", uiIPredMode )
 #endif        
@@ -1064,5 +1064,5 @@
   uiSymbol++;
   ruiInterDir = uiSymbol;
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
     DTRACE_PU("inter_pred_idc", ruiInterDir - 1 )    
 #endif
@@ -1101,5 +1101,5 @@
   }
   riRefFrmIdx = uiSymbol;
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
 #if ENC_DEC_TRACE
   if ( eRefList == REF_PIC_LIST_0 )
@@ -1194,5 +1194,5 @@
   if (!pcCU->isIntra(uiAbsPartIdx) || (pcCU->getIntraDir( CHANNEL_TYPE_CHROMA, uiAbsPartIdx ) == DM_CHROMA_IDX))
   {
-    Char alpha  = 0;
+    SChar alpha = 0;
     UInt symbol = 0;
 
@@ -1239,5 +1239,5 @@
       RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(TComCodingStatisticsClassType(STATS__CABAC_BITS__TRANSFORM_SUBDIV_FLAG, 5-uiLog2TransformBlockSize))
                           );
-#if !H_MV_ENC_DEC_TRAC
+#if !NH_MV_ENC_DEC_TRAC
   DTRACE_CABAC_VL( g_nSymbolCounter++ )
   DTRACE_CABAC_T( "\tparseTransformSubdivFlag()" )
@@ -1258,5 +1258,5 @@
   const UInt uiCtx = 0;
   m_pcTDecBinIf->decodeBin( uiSymbol , m_cCUQtRootCbfSCModel.get( 0, 0, uiCtx ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__QT_ROOT_CBF) );
-#if !H_MV_ENC_DEC_TRAC
+#if !NH_MV_ENC_DEC_TRAC
   DTRACE_CABAC_VL( g_nSymbolCounter++ )
   DTRACE_CABAC_T( "\tparseQtRootCbf()" )
@@ -1386,5 +1386,5 @@
       pcCU->setCbfPartRange((uiCbf << subTUDepth), compID, subTUAbsPartIdx, partIdxesPerSubTU);
       combinedSubTUCBF |= uiCbf;
-#if !H_MV_ENC_DEC_TRAC  
+#if !NH_MV_ENC_DEC_TRAC  
       DTRACE_CABAC_VL( g_nSymbolCounter++ )
       DTRACE_CABAC_T( "\tparseQtCbf()" )
@@ -1430,5 +1430,5 @@
 
     pcCU->setCbfSubParts((uiCbf << lowestTUDepth), compID, absPartIdx, rTu.GetTransformDepthTotalAdj(compID));
-#if !H_MV_ENC_DEC_TRAC
+#if !NH_MV_ENC_DEC_TRAC
     DTRACE_CABAC_VL( g_nSymbolCounter++ )
     DTRACE_CABAC_T( "\tparseQtCbf()" )
@@ -1491,5 +1491,5 @@
                           );
 
-#if !H_MV_ENC_DEC_TRAC
+#if !NH_MV_ENC_DEC_TRAC
   DTRACE_CABAC_VL( g_nSymbolCounter++ )
   DTRACE_CABAC_T("\tparseTransformSkip()");
@@ -1605,5 +1605,5 @@
   TCoeff* pcCoef=(pcCU->getCoeff(compID)+rTu.getCoefficientOffset(compID));
   const TComSPS &sps=*(pcCU->getSlice()->getSPS());
-#if !H_MV_ENC_DEC_TRAC
+#if !NH_MV_ENC_DEC_TRAC
   DTRACE_CABAC_VL( g_nSymbolCounter++ )
   DTRACE_CABAC_T( "\tparseCoeffNxN()\teType=" )
@@ -2284,5 +2284,5 @@
     uiW += ( 1 == uiCode ? 1 : 0 );
   }
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
   DTRACE_CU("iv_res_pred_weight_idx", uiW )
 #endif
@@ -2303,5 +2303,5 @@
   m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUICFlagSCModel.get( 0, 0, 0 ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__3D_IC) );
 
-#if !H_MV_ENC_DEC_TRAC 
+#if !NH_MV_ENC_DEC_TRAC 
   DTRACE_CABAC_VL( g_nSymbolCounter++ );
   DTRACE_CABAC_T( "\tICFlag" );
@@ -2394,5 +2394,5 @@
     }
   }
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
   DTRACE_CU("delta_dc", rValDeltaDC);
 #endif
@@ -2495,5 +2495,5 @@
 
   m_pcTDecBinIf->decodeBin( uiSymbol, m_cSDCFlagSCModel.get( 0, 0, 0 ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__SDC_INTRA_FLAG) );
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
   DTRACE_CU("dc_only_flag", uiSymbol)
 #endif
Index: trunk/source/Lib/TLibDecoder/TDecSlice.cpp
===================================================================
--- trunk/source/Lib/TLibDecoder/TDecSlice.cpp	(revision 1357)
+++ trunk/source/Lib/TLibDecoder/TDecSlice.cpp	(revision 1386)
@@ -90,5 +90,5 @@
   g_bJustDoIt = g_bEncDecTraceEnable;
 #endif
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
 #if ENC_DEC_TRACE
   incSymbolCounter(); 
@@ -100,5 +100,5 @@
   DTRACE_CABAC_T( "\tPOC: " );
   DTRACE_CABAC_V( pcPic->getPOC() );
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
   DTRACE_CABAC_T( " Layer: " );
   DTRACE_CABAC_V( pcPic->getLayerId() );
Index: trunk/source/Lib/TLibDecoder/TDecTop.cpp
===================================================================
--- trunk/source/Lib/TLibDecoder/TDecTop.cpp	(revision 1357)
+++ trunk/source/Lib/TLibDecoder/TDecTop.cpp	(revision 1386)
@@ -687,8 +687,6 @@
       }
     }
-#if NH_MV_SEI
     m_seiReader.setLayerId ( newPic->getLayerId      ( ) );
     m_seiReader.setDecOrder( newPic->getDecodingOrder( ) );
-#endif
 #endif
 
@@ -839,9 +837,5 @@
     InputNALUnit &nalu=*m_prefixSEINALUs.front();
 #if NH_MV
-#if NH_MV_LAYERS_NOT_PRESENT_SEI
     m_seiReader.parseSEImessage(&(nalu.getBitstream()), m_SEIs, nalu.m_nalUnitType, m_parameterSetManager.getActiveVPS(), m_parameterSetManager.getActiveSPS(getLayerId()), m_pDecodedSEIOutputStream);
-#else
-    m_seiReader.parseSEImessage( &(nalu.getBitstream()), m_SEIs, nalu.m_nalUnitType, m_parameterSetManager.getActiveSPS( getLayerId() ), m_pDecodedSEIOutputStream );
-#endif
 #else
     m_seiReader.parseSEImessage( &(nalu.getBitstream()), m_SEIs, nalu.m_nalUnitType, m_parameterSetManager.getActiveSPS(), m_pDecodedSEIOutputStream );
@@ -1315,9 +1309,5 @@
       {
 #if NH_MV
-#if NH_MV_LAYERS_NOT_PRESENT_SEI
       m_seiReader.parseSEImessage( &(nalu.getBitstream()), m_pcPic->getSEIs(), nalu.m_nalUnitType, m_parameterSetManager.getActiveVPS(), m_parameterSetManager.getActiveSPS(getLayerId()), m_pDecodedSEIOutputStream);
-#else
-      m_seiReader.parseSEImessage( &(nalu.getBitstream()), m_pcPic->getSEIs(), nalu.m_nalUnitType, m_parameterSetManager.getActiveSPS( getLayerId() ), m_pDecodedSEIOutputStream );
-#endif
 #else
         m_seiReader.parseSEImessage( &(nalu.getBitstream()), m_pcPic->getSEIs(), nalu.m_nalUnitType, m_parameterSetManager.getActiveSPS(), m_pDecodedSEIOutputStream );
@@ -1771,4 +1761,12 @@
         xG813DecProcForInterLayerRefPicSet();
       }
+      else
+      {
+#if NH_MV_FIX_INIT_NUM_ACTIVE_REF_LAYER_PICS
+        TComDecodedRps* decRps = m_pcPic->getDecodedRps(); 
+        decRps->m_numActiveRefLayerPics0 = 0;
+        decRps->m_numActiveRefLayerPics1 = 0;      
+#endif
+      }
     }
   }
Index: trunk/source/Lib/TLibEncoder/AnnexBwrite.h
===================================================================
--- trunk/source/Lib/TLibEncoder/AnnexBwrite.h	(revision 1357)
+++ trunk/source/Lib/TLibEncoder/AnnexBwrite.h	(revision 1386)
@@ -60,5 +60,5 @@
     UInt size = 0; /* size of annexB unit in bytes */
 
-    static const Char start_code_prefix[] = {0,0,0,1};
+    static const UChar start_code_prefix[] = {0,0,0,1};
     if (it == au.begin() || nalu.m_nalUnitType == NAL_UNIT_VPS || nalu.m_nalUnitType == NAL_UNIT_SPS || nalu.m_nalUnitType == NAL_UNIT_PPS)
     {
@@ -71,10 +71,10 @@
        *    7.4.1.2.3.
        */
-      out.write(start_code_prefix, 4);
+      out.write(reinterpret_cast<const TChar*>(start_code_prefix), 4);
       size += 4;
     }
     else
     {
-      out.write(start_code_prefix+1, 3);
+      out.write(reinterpret_cast<const TChar*>(start_code_prefix+1), 3);
       size += 3;
     }
Index: trunk/source/Lib/TLibEncoder/NALwrite.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/NALwrite.cpp	(revision 1357)
+++ trunk/source/Lib/TLibEncoder/NALwrite.cpp	(revision 1386)
@@ -45,5 +45,5 @@
 //! \{
 
-static const Char emulation_prevention_three_byte[] = {3};
+static const UChar emulation_prevention_three_byte[] = {3};
 
 Void writeNalUnitHeader(ostream& out, OutputNALUnit& nalu)       // nal_unit_header()
@@ -60,5 +60,5 @@
   bsNALUHeader.write(nalu.m_temporalId+1, 3); // nuh_temporal_id_plus1
 
-  out.write(bsNALUHeader.getByteStream(), bsNALUHeader.getByteStreamLength());
+  out.write(reinterpret_cast<const TChar*>(bsNALUHeader.getByteStream()), bsNALUHeader.getByteStreamLength());
 }
 /**
@@ -124,5 +124,5 @@
     outputBuffer[outputAmount++]=emulation_prevention_three_byte[0];
   }
-  out.write((Char*)&(*outputBuffer.begin()), outputAmount);
+  out.write(reinterpret_cast<const TChar*>(&(*outputBuffer.begin())), outputAmount);
 }
 
Index: trunk/source/Lib/TLibEncoder/SEIEncoder.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/SEIEncoder.cpp	(revision 1357)
+++ trunk/source/Lib/TLibEncoder/SEIEncoder.cpp	(revision 1386)
@@ -294,21 +294,26 @@
   assert (pcPic!=NULL);
 
-  if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 1)
-  {
-    decodedPictureHashSEI->method = SEIDecodedPictureHash::MD5;
+  decodedPictureHashSEI->method = m_pcCfg->getDecodedPictureHashSEIType();
+  switch (m_pcCfg->getDecodedPictureHashSEIType())
+  {
+    case HASHTYPE_MD5:
+  {
     UInt numChar=calcMD5(*pcPic->getPicYuvRec(), decodedPictureHashSEI->m_pictureHash, bitDepths);
     rHashString = hashToString(decodedPictureHashSEI->m_pictureHash, numChar);
   }
-  else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 2)
-  {
-    decodedPictureHashSEI->method = SEIDecodedPictureHash::CRC;
+      break;
+    case HASHTYPE_CRC:
+  {
     UInt numChar=calcCRC(*pcPic->getPicYuvRec(), decodedPictureHashSEI->m_pictureHash, bitDepths);
     rHashString = hashToString(decodedPictureHashSEI->m_pictureHash, numChar);
   }
-  else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 3)
-  {
-    decodedPictureHashSEI->method = SEIDecodedPictureHash::CHECKSUM;
+      break;
+    case HASHTYPE_CHECKSUM:
+    default:
+  {
     UInt numChar=calcChecksum(*pcPic->getPicYuvRec(), decodedPictureHashSEI->m_pictureHash, bitDepths);
     rHashString = hashToString(decodedPictureHashSEI->m_pictureHash, numChar);
+  }
+      break;
   }
 }
@@ -397,56 +402,239 @@
   }
 }
-
-Void SEIEncoder::initSEIChromaSamplingFilterHint(SEIChromaSamplingFilterHint *seiChromaSamplingFilterHint, Int iHorFilterIndex, Int iVerFilterIndex)
-{
-  assert (m_isInitialized);
-  assert (seiChromaSamplingFilterHint!=NULL);
-
-  seiChromaSamplingFilterHint->m_verChromaFilterIdc = iVerFilterIndex;
-  seiChromaSamplingFilterHint->m_horChromaFilterIdc = iHorFilterIndex;
-  seiChromaSamplingFilterHint->m_verFilteringProcessFlag = 1;
-  seiChromaSamplingFilterHint->m_targetFormatIdc = 3;
-  seiChromaSamplingFilterHint->m_perfectReconstructionFlag = false;
-  if(seiChromaSamplingFilterHint->m_verChromaFilterIdc == 1)
-  {
-    seiChromaSamplingFilterHint->m_numVerticalFilters = 1;
-    seiChromaSamplingFilterHint->m_verTapLengthMinus1 = (Int*)malloc(seiChromaSamplingFilterHint->m_numVerticalFilters * sizeof(Int));
-    seiChromaSamplingFilterHint->m_verFilterCoeff =    (Int**)malloc(seiChromaSamplingFilterHint->m_numVerticalFilters * sizeof(Int*));
-    for(Int i = 0; i < seiChromaSamplingFilterHint->m_numVerticalFilters; i ++)
-    {
-      seiChromaSamplingFilterHint->m_verTapLengthMinus1[i] = 0;
-      seiChromaSamplingFilterHint->m_verFilterCoeff[i] = (Int*)malloc(seiChromaSamplingFilterHint->m_verTapLengthMinus1[i] * sizeof(Int));
-      for(Int j = 0; j < seiChromaSamplingFilterHint->m_verTapLengthMinus1[i]; j ++)
-      {
-        seiChromaSamplingFilterHint->m_verFilterCoeff[i][j] = 0;
-      }
-    }
+template <typename T>
+static Void readTokenValue(T            &returnedValue, /// value returned
+                           Bool         &failed,        /// used and updated
+                           std::istream &is,            /// stream to read token from
+                           const TChar  *pToken)        /// token string
+{
+  returnedValue=T();
+  if (failed)
+  {
+    return;
+  }
+
+  Int c;
+  // Ignore any whitespace
+  while ((c=is.get())!=EOF && isspace(c));
+  // test for comment mark
+  while (c=='#')
+  {
+    // Ignore to the end of the line
+    while ((c=is.get())!=EOF && (c!=10 && c!=13));
+    // Ignore any white space at the start of the next line
+    while ((c=is.get())!=EOF && isspace(c));
+  }
+  // test first character of token
+  failed=(c!=pToken[0]);
+  // test remaining characters of token
+  Int pos;
+  for(pos=1;!failed && pToken[pos]!=0 && is.get()==pToken[pos]; pos++);
+  failed|=(pToken[pos]!=0);
+  // Ignore any whitespace before the ':'
+  while (!failed && (c=is.get())!=EOF && isspace(c));
+  failed|=(c!=':');
+  // Now read the value associated with the token:
+  if (!failed)
+  {
+    is >> returnedValue;
+    failed=!is.good();
+    if (!failed)
+    {
+      c=is.get();
+      failed=(c!=EOF && !isspace(c));
+    }
+  }
+  if (failed)
+  {
+    std::cerr << "Unable to read token '" << pToken << "'\n";
+  }
+}
+
+template <typename T>
+static Void readTokenValueAndValidate(T            &returnedValue, /// value returned
+                                      Bool         &failed,        /// used and updated
+                                      std::istream &is,            /// stream to read token from
+                                      const TChar  *pToken,        /// token string
+                                      const T      &minInclusive,  /// minimum value allowed, inclusive
+                                      const T      &maxInclusive)  /// maximum value allowed, inclusive
+{
+  readTokenValue(returnedValue, failed, is, pToken);
+  if (!failed)
+  {
+    if (returnedValue<minInclusive || returnedValue>maxInclusive)
+    {
+      failed=true;
+      std::cerr << "Value for token " << pToken << " must be in the range " << minInclusive << " to " << maxInclusive << " (inclusive); value read: " << returnedValue << std::endl;
+    }
+  }
+}
+
+// Bool version does not have maximum and minimum values.
+static Void readTokenValueAndValidate(Bool         &returnedValue, /// value returned
+                                      Bool         &failed,        /// used and updated
+                                      std::istream &is,            /// stream to read token from
+                                      const TChar  *pToken)        /// token string
+{
+  readTokenValue(returnedValue, failed, is, pToken);
+}
+
+Bool SEIEncoder::initSEIColourRemappingInfo(SEIColourRemappingInfo* seiColourRemappingInfo, Int currPOC) // returns true on success, false on failure.
+{
+  assert (m_isInitialized);
+  assert (seiColourRemappingInfo!=NULL);
+
+  // reading external Colour Remapping Information SEI message parameters from file
+  if( !m_pcCfg->getColourRemapInfoSEIFileRoot().empty())
+  {
+    Bool failed=false;
+
+    // building the CRI file name with poc num in prefix "_poc.txt"
+    std::string colourRemapSEIFileWithPoc(m_pcCfg->getColourRemapInfoSEIFileRoot());
+    {
+      std::stringstream suffix;
+      suffix << "_" << currPOC << ".txt";
+      colourRemapSEIFileWithPoc+=suffix.str();
+    }
+
+    std::ifstream fic(colourRemapSEIFileWithPoc.c_str());
+    if (!fic.good() || !fic.is_open())
+    {
+      std::cerr <<  "No Colour Remapping Information SEI parameters file " << colourRemapSEIFileWithPoc << " for POC " << currPOC << std::endl;
+      return false;
+    }
+
+    // TODO: identify and remove duplication with decoder parsing through abstraction.
+
+    readTokenValueAndValidate(seiColourRemappingInfo->m_colourRemapId,         failed, fic, "colour_remap_id",        UInt(0), UInt(0x7fffffff) );
+    readTokenValueAndValidate(seiColourRemappingInfo->m_colourRemapCancelFlag, failed, fic, "colour_remap_cancel_flag" );
+    if( !seiColourRemappingInfo->m_colourRemapCancelFlag )
+    {
+      readTokenValueAndValidate(seiColourRemappingInfo->m_colourRemapPersistenceFlag,            failed, fic, "colour_remap_persistence_flag" );
+      readTokenValueAndValidate(seiColourRemappingInfo->m_colourRemapVideoSignalInfoPresentFlag, failed, fic, "colour_remap_video_signal_info_present_flag");
+      if( seiColourRemappingInfo->m_colourRemapVideoSignalInfoPresentFlag )
+      {
+        readTokenValueAndValidate(seiColourRemappingInfo->m_colourRemapFullRangeFlag,      failed, fic, "colour_remap_full_range_flag" );
+        readTokenValueAndValidate(seiColourRemappingInfo->m_colourRemapPrimaries,          failed, fic, "colour_remap_primaries",           Int(0), Int(255) );
+        readTokenValueAndValidate(seiColourRemappingInfo->m_colourRemapTransferFunction,   failed, fic, "colour_remap_transfer_function",   Int(0), Int(255) );
+        readTokenValueAndValidate(seiColourRemappingInfo->m_colourRemapMatrixCoefficients, failed, fic, "colour_remap_matrix_coefficients", Int(0), Int(255) );
+      }
+      readTokenValueAndValidate(seiColourRemappingInfo->m_colourRemapInputBitDepth, failed, fic, "colour_remap_input_bit_depth",            Int(8), Int(16) );
+      readTokenValueAndValidate(seiColourRemappingInfo->m_colourRemapBitDepth,      failed, fic, "colour_remap_bit_depth",                  Int(8), Int(16) );
+
+      const Int maximumInputValue    = (1 << (((seiColourRemappingInfo->m_colourRemapInputBitDepth + 7) >> 3) << 3)) - 1;
+      const Int maximumRemappedValue = (1 << (((seiColourRemappingInfo->m_colourRemapBitDepth      + 7) >> 3) << 3)) - 1;
+
+      for( Int c=0 ; c<3 ; c++ )
+      {
+        readTokenValueAndValidate(seiColourRemappingInfo->m_preLutNumValMinus1[c],         failed, fic, "pre_lut_num_val_minus1[c]",        Int(0), Int(32) );
+        if( seiColourRemappingInfo->m_preLutNumValMinus1[c]>0 )
+        {
+          seiColourRemappingInfo->m_preLut[c].resize(seiColourRemappingInfo->m_preLutNumValMinus1[c]+1);
+          for( Int i=0 ; i<=seiColourRemappingInfo->m_preLutNumValMinus1[c] ; i++ )
+          {
+            readTokenValueAndValidate(seiColourRemappingInfo->m_preLut[c][i].codedValue,   failed, fic, "pre_lut_coded_value[c][i]",  Int(0), maximumInputValue    );
+            readTokenValueAndValidate(seiColourRemappingInfo->m_preLut[c][i].targetValue,  failed, fic, "pre_lut_target_value[c][i]", Int(0), maximumRemappedValue );
+          }
+        }
+      }
+      readTokenValueAndValidate(seiColourRemappingInfo->m_colourRemapMatrixPresentFlag, failed, fic, "colour_remap_matrix_present_flag" );
+      if( seiColourRemappingInfo->m_colourRemapMatrixPresentFlag )
+      {
+        readTokenValueAndValidate(seiColourRemappingInfo->m_log2MatrixDenom, failed, fic, "log2_matrix_denom", Int(0), Int(15) );
+        for( Int c=0 ; c<3 ; c++ )
+        {
+          for( Int i=0 ; i<3 ; i++ )
+          {
+            readTokenValueAndValidate(seiColourRemappingInfo->m_colourRemapCoeffs[c][i], failed, fic, "colour_remap_coeffs[c][i]", -32768, 32767 );
+          }
+        }
+      }
+      for( Int c=0 ; c<3 ; c++ )
+      {
+        readTokenValueAndValidate(seiColourRemappingInfo->m_postLutNumValMinus1[c], failed, fic, "post_lut_num_val_minus1[c]", Int(0), Int(32) );
+        if( seiColourRemappingInfo->m_postLutNumValMinus1[c]>0 )
+        {
+          seiColourRemappingInfo->m_postLut[c].resize(seiColourRemappingInfo->m_postLutNumValMinus1[c]+1);
+          for( Int i=0 ; i<=seiColourRemappingInfo->m_postLutNumValMinus1[c] ; i++ )
+          {
+            readTokenValueAndValidate(seiColourRemappingInfo->m_postLut[c][i].codedValue,  failed, fic, "post_lut_coded_value[c][i]",  Int(0), maximumRemappedValue );
+            readTokenValueAndValidate(seiColourRemappingInfo->m_postLut[c][i].targetValue, failed, fic, "post_lut_target_value[c][i]", Int(0), maximumRemappedValue );
+          }
+        }
+      }
+    }
+
+    if( failed )
+    {
+      std::cerr << "Error while reading Colour Remapping Information SEI parameters file '" << colourRemapSEIFileWithPoc << "'" << std::endl;
+      exit(EXIT_FAILURE);
+    }
+  }
+  return true;
+}
+
+
+Void SEIEncoder::initSEIChromaResamplingFilterHint(SEIChromaResamplingFilterHint *seiChromaResamplingFilterHint, Int iHorFilterIndex, Int iVerFilterIndex)
+{
+  assert (m_isInitialized);
+  assert (seiChromaResamplingFilterHint!=NULL);
+
+  seiChromaResamplingFilterHint->m_verChromaFilterIdc = iVerFilterIndex;
+  seiChromaResamplingFilterHint->m_horChromaFilterIdc = iHorFilterIndex;
+  seiChromaResamplingFilterHint->m_verFilteringFieldProcessingFlag = 1;
+  seiChromaResamplingFilterHint->m_targetFormatIdc = 3;
+  seiChromaResamplingFilterHint->m_perfectReconstructionFlag = false;
+
+  // this creates some example filter values, if explicit filter definition is selected
+  if (seiChromaResamplingFilterHint->m_verChromaFilterIdc == 1)
+    {
+    const Int numVerticalFilters = 3;
+    const Int verTapLengthMinus1[] = {5,3,3};
+
+    seiChromaResamplingFilterHint->m_verFilterCoeff.resize(numVerticalFilters);
+    for(Int i = 0; i < numVerticalFilters; i ++)
+      {
+      seiChromaResamplingFilterHint->m_verFilterCoeff[i].resize(verTapLengthMinus1[i]+1);
+    }
+    // Note: C++11 -> seiChromaResamplingFilterHint->m_verFilterCoeff[0] = {-3,13,31,23,3,-3};
+    seiChromaResamplingFilterHint->m_verFilterCoeff[0][0] = -3;
+    seiChromaResamplingFilterHint->m_verFilterCoeff[0][1] = 13;
+    seiChromaResamplingFilterHint->m_verFilterCoeff[0][2] = 31;
+    seiChromaResamplingFilterHint->m_verFilterCoeff[0][3] = 23;
+    seiChromaResamplingFilterHint->m_verFilterCoeff[0][4] = 3;
+    seiChromaResamplingFilterHint->m_verFilterCoeff[0][5] = -3;
+
+    seiChromaResamplingFilterHint->m_verFilterCoeff[1][0] = -1;
+    seiChromaResamplingFilterHint->m_verFilterCoeff[1][1] = 25;
+    seiChromaResamplingFilterHint->m_verFilterCoeff[1][2] = 247;
+    seiChromaResamplingFilterHint->m_verFilterCoeff[1][3] = -15;
+
+    seiChromaResamplingFilterHint->m_verFilterCoeff[2][0] = -20;
+    seiChromaResamplingFilterHint->m_verFilterCoeff[2][1] = 186;
+    seiChromaResamplingFilterHint->m_verFilterCoeff[2][2] = 100;
+    seiChromaResamplingFilterHint->m_verFilterCoeff[2][3] = -10;
   }
   else
   {
-    seiChromaSamplingFilterHint->m_numVerticalFilters = 0;
-    seiChromaSamplingFilterHint->m_verTapLengthMinus1 = NULL;
-    seiChromaSamplingFilterHint->m_verFilterCoeff = NULL;
-  }
-  if(seiChromaSamplingFilterHint->m_horChromaFilterIdc == 1)
-  {
-    seiChromaSamplingFilterHint->m_numHorizontalFilters = 1;
-    seiChromaSamplingFilterHint->m_horTapLengthMinus1 = (Int*)malloc(seiChromaSamplingFilterHint->m_numHorizontalFilters * sizeof(Int));
-    seiChromaSamplingFilterHint->m_horFilterCoeff = (Int**)malloc(seiChromaSamplingFilterHint->m_numHorizontalFilters * sizeof(Int*));
-    for(Int i = 0; i < seiChromaSamplingFilterHint->m_numHorizontalFilters; i ++)
-    {
-      seiChromaSamplingFilterHint->m_horTapLengthMinus1[i] = 0;
-      seiChromaSamplingFilterHint->m_horFilterCoeff[i] = (Int*)malloc(seiChromaSamplingFilterHint->m_horTapLengthMinus1[i] * sizeof(Int));
-      for(Int j = 0; j < seiChromaSamplingFilterHint->m_horTapLengthMinus1[i]; j ++)
-      {
-        seiChromaSamplingFilterHint->m_horFilterCoeff[i][j] = 0;
-      }
-    }
+    seiChromaResamplingFilterHint->m_verFilterCoeff.resize(0);
+  }
+
+  if (seiChromaResamplingFilterHint->m_horChromaFilterIdc == 1)
+    {
+    Int const numHorizontalFilters = 1;
+    const Int horTapLengthMinus1[] = {3};
+
+    seiChromaResamplingFilterHint->m_horFilterCoeff.resize(numHorizontalFilters);
+    for(Int i = 0; i < numHorizontalFilters; i ++)
+      {
+      seiChromaResamplingFilterHint->m_horFilterCoeff[i].resize(horTapLengthMinus1[i]+1);
+    }
+    seiChromaResamplingFilterHint->m_horFilterCoeff[0][0] = 1;
+    seiChromaResamplingFilterHint->m_horFilterCoeff[0][1] = 6;
+    seiChromaResamplingFilterHint->m_horFilterCoeff[0][2] = 1;
   }
   else
   {
-    seiChromaSamplingFilterHint->m_numHorizontalFilters = 0;
-    seiChromaSamplingFilterHint->m_horTapLengthMinus1 = NULL;
-    seiChromaSamplingFilterHint->m_horFilterCoeff = NULL;
+    seiChromaResamplingFilterHint->m_horFilterCoeff.resize(0);
   }
 }
@@ -465,17 +653,4 @@
 
 #if NH_MV
-#if !NH_MV_SEI
-Void SEIEncoder::initSEISubBitstreamProperty(SEISubBitstreamProperty *seiSubBitstreamProperty, const TComSPS *sps)
-{
-  seiSubBitstreamProperty->m_activeVpsId = sps->getVPSId();
-  /* These values can be determined by the encoder; for now we will use the input parameter */  
-  seiSubBitstreamProperty->m_numAdditionalSubStreams = m_pcCfg->getNumAdditionalSubStreams();
-  seiSubBitstreamProperty->m_subBitstreamMode        = m_pcCfg->getSubBitstreamMode();
-  seiSubBitstreamProperty->m_outputLayerSetIdxToVps  = m_pcCfg->getOutputLayerSetIdxToVps();
-  seiSubBitstreamProperty->m_highestSublayerId       = m_pcCfg->getHighestSublayerId();
-  seiSubBitstreamProperty->m_avgBitRate              = m_pcCfg->getAvgBitRate();
-  seiSubBitstreamProperty->m_maxBitRate              = m_pcCfg->getMaxBitRate();  
-}
-#else
 Void SEIEncoder::createAnnexFGISeiMessages( SEIMessages& seiMessage, const TComSlice* slice )
 {
@@ -509,5 +684,4 @@
 }
 #endif
-#endif
 
 //! \}
Index: trunk/source/Lib/TLibEncoder/SEIEncoder.h
===================================================================
--- trunk/source/Lib/TLibEncoder/SEIEncoder.h	(revision 1357)
+++ trunk/source/Lib/TLibEncoder/SEIEncoder.h	(revision 1386)
@@ -79,6 +79,7 @@
   Void initSEITempMotionConstrainedTileSets (SEITempMotionConstrainedTileSets *sei, const TComPPS *pps);
   Void initSEIKneeFunctionInfo(SEIKneeFunctionInfo *sei);
-  Void initSEIChromaSamplingFilterHint(SEIChromaSamplingFilterHint *sei, Int iHorFilterIndex, Int iVerFilterIndex);
+  Void initSEIChromaResamplingFilterHint(SEIChromaResamplingFilterHint *sei, Int iHorFilterIndex, Int iVerFilterIndex);
   Void initSEITimeCode(SEITimeCode *sei);
+  Bool initSEIColourRemappingInfo(SEIColourRemappingInfo *sei, Int currPOC); // returns true on success, false on failure.
 
   // trailing SEIs
@@ -86,9 +87,5 @@
   Void initTemporalLevel0IndexSEI(SEITemporalLevel0Index *sei, TComSlice *slice);
 #if NH_MV
-#if !NH_MV_SEI
-  Void initSEISubBitstreamProperty(SEISubBitstreamProperty *seiSubBitstreamProperty, const TComSPS *sps);
-#else
   Void createAnnexFGISeiMessages( SEIMessages& seiMessage, const TComSlice* slice );;
-#endif
 #endif
 private:
Index: trunk/source/Lib/TLibEncoder/SEIwrite.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/SEIwrite.cpp	(revision 1357)
+++ trunk/source/Lib/TLibEncoder/SEIwrite.cpp	(revision 1386)
@@ -106,6 +106,6 @@
     xWriteSEIScalableNesting(bs, *static_cast<const SEIScalableNesting*>(&sei), sps);
     break;
-  case SEI::CHROMA_SAMPLING_FILTER_HINT:
-    xWriteSEIChromaSamplingFilterHint(*static_cast<const SEIChromaSamplingFilterHint*>(&sei)/*, sps*/);
+  case SEI::CHROMA_RESAMPLING_FILTER_HINT:
+    xWriteSEIChromaResamplingFilterHint(*static_cast<const SEIChromaResamplingFilterHint*>(&sei));
     break;
   case SEI::TEMP_MOTION_CONSTRAINED_TILE_SETS:
@@ -118,20 +118,14 @@
     xWriteSEIKneeFunctionInfo(*static_cast<const SEIKneeFunctionInfo*>(&sei));
     break;
+  case SEI::COLOUR_REMAPPING_INFO:
+    xWriteSEIColourRemappingInfo(*static_cast<const SEIColourRemappingInfo*>(&sei));
+    break;
   case SEI::MASTERING_DISPLAY_COLOUR_VOLUME:
     xWriteSEIMasteringDisplayColourVolume(*static_cast<const SEIMasteringDisplayColourVolume*>(&sei));
     break;
 #if NH_MV
-#if !NH_MV_SEI
-   case SEI::SUB_BITSTREAM_PROPERTY:
-   xWriteSEISubBitstreamProperty(*static_cast<const SEISubBitstreamProperty*>(&sei));
-   break;
-#endif
-#endif
-#if NH_MV_SEI
-#if NH_MV_LAYERS_NOT_PRESENT_SEI
    case SEI::LAYERS_NOT_PRESENT:
        xWriteSEILayersNotPresent(*static_cast<const SEILayersNotPresent*>(&sei));
      break;
-#endif
    case SEI::INTER_LAYER_CONSTRAINED_TILE_SETS:
      xWriteSEIInterLayerConstrainedTileSets(*static_cast<const SEIInterLayerConstrainedTileSets*>(&sei));
@@ -165,9 +159,7 @@
      xWriteSEIThreeDimensionalReferenceDisplaysInfo(*static_cast<const SEIThreeDimensionalReferenceDisplaysInfo*>(&sei));
      break;
-#if SEI_DRI_F0169
    case SEI::DEPTH_REPRESENTATION_INFO:
        xWriteSEIDepthRepresentationInfo(*static_cast<const SEIDepthRepresentationInfo*>(&sei));
        break;
-#endif
    case SEI::MULTIVIEW_SCENE_INFO:
      xWriteSEIMultiviewSceneInfo(*static_cast<const SEIMultiviewSceneInfo*>(&sei));
@@ -189,5 +181,5 @@
 
   default:
-    assert(!"Unhandled SEI message");
+    assert(!"Trying to write unhandled SEI message");
     break;
   }
@@ -277,10 +269,10 @@
 Void SEIWriter::xWriteSEIDecodedPictureHash(const SEIDecodedPictureHash& sei)
 {
-  const Char *traceString="\0";
+  const TChar *traceString="\0";
   switch (sei.method)
   {
-    case SEIDecodedPictureHash::MD5: traceString="picture_md5"; break;
-    case SEIDecodedPictureHash::CRC: traceString="picture_crc"; break;
-    case SEIDecodedPictureHash::CHECKSUM: traceString="picture_checksum"; break;
+    case HASHTYPE_MD5: traceString="picture_md5"; break;
+    case HASHTYPE_CRC: traceString="picture_crc"; break;
+    case HASHTYPE_CHECKSUM: traceString="picture_checksum"; break;
     default: assert(false); break;
   }
@@ -726,106 +718,48 @@
 }
 
-Void SEIWriter::xWriteSEIChromaSamplingFilterHint(const SEIChromaSamplingFilterHint &sei/*, TComSPS* sps*/)
+Void SEIWriter::xWriteSEIChromaResamplingFilterHint(const SEIChromaResamplingFilterHint &sei)
 {
   WRITE_CODE(sei.m_verChromaFilterIdc, 8, "ver_chroma_filter_idc");
   WRITE_CODE(sei.m_horChromaFilterIdc, 8, "hor_chroma_filter_idc");
-  WRITE_FLAG(sei.m_verFilteringProcessFlag, "ver_filtering_process_flag");
+  WRITE_FLAG(sei.m_verFilteringFieldProcessingFlag, "ver_filtering_field_processing_flag");
   if(sei.m_verChromaFilterIdc == 1 || sei.m_horChromaFilterIdc == 1)
   {
-    writeUserDefinedCoefficients(sei);
-  }
-}
-
-// write hardcoded chroma filter coefficients in the SEI messages
-Void SEIWriter::writeUserDefinedCoefficients(const SEIChromaSamplingFilterHint &sei)
-{
-  Int const iNumVerticalFilters = 3;
-  Int verticalTapLength_minus1[iNumVerticalFilters] = {5,3,3};
-  Int* userVerticalCoefficients[iNumVerticalFilters];
-  for(Int i = 0; i < iNumVerticalFilters; i ++)
-  {
-    userVerticalCoefficients[i] = (Int*)malloc( (verticalTapLength_minus1[i]+1) * sizeof(Int));
-  }
-  userVerticalCoefficients[0][0] = -3;
-  userVerticalCoefficients[0][1] = 13;
-  userVerticalCoefficients[0][2] = 31;
-  userVerticalCoefficients[0][3] = 23;
-  userVerticalCoefficients[0][4] = 3;
-  userVerticalCoefficients[0][5] = -3;
-
-  userVerticalCoefficients[1][0] = -1;
-  userVerticalCoefficients[1][1] = 25;
-  userVerticalCoefficients[1][2] = 247;
-  userVerticalCoefficients[1][3] = -15;
-
-  userVerticalCoefficients[2][0] = -20;
-  userVerticalCoefficients[2][1] = 186;
-  userVerticalCoefficients[2][2] = 100;
-  userVerticalCoefficients[2][3] = -10;
-
-  Int const iNumHorizontalFilters = 1;
-  Int horizontalTapLength_minus1[iNumHorizontalFilters] = {3};
-  Int* userHorizontalCoefficients[iNumHorizontalFilters];
-  for(Int i = 0; i < iNumHorizontalFilters; i ++)
-  {
-    userHorizontalCoefficients[i] = (Int*)malloc( (horizontalTapLength_minus1[i]+1) * sizeof(Int));
-  }
-  userHorizontalCoefficients[0][0] = 1;
-  userHorizontalCoefficients[0][1] = 6;
-  userHorizontalCoefficients[0][2] = 1;
-
-  WRITE_UVLC(3, "target_format_idc");
-  if(sei.m_verChromaFilterIdc == 1)
-  {
-    WRITE_UVLC(iNumVerticalFilters, "num_vertical_filters");
-    if(iNumVerticalFilters > 0)
-    {
-      for(Int i = 0; i < iNumVerticalFilters; i ++)
-      {
-        WRITE_UVLC(verticalTapLength_minus1[i], "ver_tap_length_minus_1");
-        for(Int j = 0; j < verticalTapLength_minus1[i]; j ++)
-        {
-          WRITE_SVLC(userVerticalCoefficients[i][j], "ver_filter_coeff");
-        }
-      }
-    }
-  }
-  if(sei.m_horChromaFilterIdc == 1)
-  {
-    WRITE_UVLC(iNumHorizontalFilters, "num_horizontal_filters");
-    if(iNumHorizontalFilters > 0)
-    {
-      for(Int i = 0; i < iNumHorizontalFilters; i ++)
-      {
-        WRITE_UVLC(horizontalTapLength_minus1[i], "hor_tap_length_minus_1");
-        for(Int j = 0; j < horizontalTapLength_minus1[i]; j ++)
-        {
-          WRITE_SVLC(userHorizontalCoefficients[i][j], "hor_filter_coeff");
-        }
-      }
-    }
-  }
-}
-
-#if NH_MV
-#if !NH_MV_SEI
-Void SEIWriter::xWriteSEISubBitstreamProperty(const SEISubBitstreamProperty &sei)
-{
-  WRITE_CODE( sei.m_activeVpsId, 4, "active_vps_id" );
-  assert( sei.m_numAdditionalSubStreams >= 1 );
-  WRITE_UVLC( sei.m_numAdditionalSubStreams - 1, "num_additional_sub_streams_minus1" );
-
-  for( Int i = 0; i < sei.m_numAdditionalSubStreams; i++ )
-  {
-    WRITE_CODE( sei.m_subBitstreamMode[i],       2, "sub_bitstream_mode[i]"           );
-    WRITE_UVLC( sei.m_outputLayerSetIdxToVps[i],    "output_layer_set_idx_to_vps[i]"  );
-    WRITE_CODE( sei.m_highestSublayerId[i],      3, "highest_sub_layer_id[i]"         );
-    WRITE_CODE( sei.m_avgBitRate[i],            16, "avg_bit_rate[i]"                 );
-    WRITE_CODE( sei.m_maxBitRate[i],            16, "max_bit_rate[i]"                 );
-  }
-  xWriteByteAlign();
-}
-#endif
-#endif
+    WRITE_UVLC(sei.m_targetFormatIdc, "target_format_idc");
+    if(sei.m_verChromaFilterIdc == 1)
+    {
+      const Int numVerticalFilter = (Int)sei.m_verFilterCoeff.size();
+      WRITE_UVLC(numVerticalFilter, "num_vertical_filters");
+      if(numVerticalFilter > 0)
+      {
+        for(Int i = 0; i < numVerticalFilter; i ++)
+        {
+          const Int verTapLengthMinus1 = (Int) sei.m_verFilterCoeff[i].size() - 1;
+          WRITE_UVLC(verTapLengthMinus1, "ver_tap_length_minus_1");
+          for(Int j = 0; j < (verTapLengthMinus1 + 1); j ++)
+          {
+            WRITE_SVLC(sei.m_verFilterCoeff[i][j], "ver_filter_coeff");
+          }
+        }
+      }
+    }
+    if(sei.m_horChromaFilterIdc == 1)
+    {
+      const Int numHorizontalFilter = (Int) sei.m_horFilterCoeff.size();
+      WRITE_UVLC(numHorizontalFilter, "num_horizontal_filters");
+      if(numHorizontalFilter > 0)
+      {
+        for(Int i = 0; i < numHorizontalFilter; i ++)
+        {
+          const Int horTapLengthMinus1 = (Int) sei.m_horFilterCoeff[i].size() - 1;
+          WRITE_UVLC(horTapLengthMinus1, "hor_tap_length_minus_1");
+          for(Int j = 0; j < (horTapLengthMinus1 + 1); j ++)
+          {
+            WRITE_SVLC(sei.m_horFilterCoeff[i][j], "hor_filter_coeff");
+          }
+        }
+      }
+    }
+  }
+}
 
 Void SEIWriter::xWriteSEIKneeFunctionInfo(const SEIKneeFunctionInfo &sei)
@@ -849,4 +783,60 @@
 }
 
+Void SEIWriter::xWriteSEIColourRemappingInfo(const SEIColourRemappingInfo& sei)
+{
+  WRITE_UVLC( sei.m_colourRemapId,                             "colour_remap_id" );
+  WRITE_FLAG( sei.m_colourRemapCancelFlag,                     "colour_remap_cancel_flag" );
+  if( !sei.m_colourRemapCancelFlag ) 
+  {
+    WRITE_FLAG( sei.m_colourRemapPersistenceFlag,              "colour_remap_persistence_flag" );
+    WRITE_FLAG( sei.m_colourRemapVideoSignalInfoPresentFlag,   "colour_remap_video_signal_info_present_flag" );
+    if ( sei.m_colourRemapVideoSignalInfoPresentFlag )
+    {
+      WRITE_FLAG( sei.m_colourRemapFullRangeFlag,              "colour_remap_full_range_flag" );
+      WRITE_CODE( sei.m_colourRemapPrimaries,               8, "colour_remap_primaries" );
+      WRITE_CODE( sei.m_colourRemapTransferFunction,        8, "colour_remap_transfer_function" );
+      WRITE_CODE( sei.m_colourRemapMatrixCoefficients,      8, "colour_remap_matrix_coefficients" );
+    }
+    WRITE_CODE( sei.m_colourRemapInputBitDepth,             8, "colour_remap_input_bit_depth" );
+    WRITE_CODE( sei.m_colourRemapBitDepth,                  8, "colour_remap_bit_depth" );
+    for( Int c=0 ; c<3 ; c++ )
+    {
+      WRITE_CODE( sei.m_preLutNumValMinus1[c],              8, "pre_lut_num_val_minus1[c]" );
+      if( sei.m_preLutNumValMinus1[c]>0 )
+      {
+        for( Int i=0 ; i<=sei.m_preLutNumValMinus1[c] ; i++ )
+        {
+          WRITE_CODE( sei.m_preLut[c][i].codedValue,  (( sei.m_colourRemapInputBitDepth + 7 ) >> 3 ) << 3, "pre_lut_coded_value[c][i]" );
+          WRITE_CODE( sei.m_preLut[c][i].targetValue, (( sei.m_colourRemapBitDepth      + 7 ) >> 3 ) << 3, "pre_lut_target_value[c][i]" );
+        }
+      }
+    }
+    WRITE_FLAG( sei.m_colourRemapMatrixPresentFlag,            "colour_remap_matrix_present_flag" );
+    if( sei.m_colourRemapMatrixPresentFlag )
+    {
+      WRITE_CODE( sei.m_log2MatrixDenom,                    4, "log2_matrix_denom" );
+      for( Int c=0 ; c<3 ; c++ )
+      {
+        for( Int i=0 ; i<3 ; i++ )
+        {
+          WRITE_SVLC( sei.m_colourRemapCoeffs[c][i],           "colour_remap_coeffs[c][i]" );
+        }
+      }
+    }
+
+    for( Int c=0 ; c<3 ; c++ )
+    {
+      WRITE_CODE( sei.m_postLutNumValMinus1[c],             8, "m_postLutNumValMinus1[c]" );
+      if( sei.m_postLutNumValMinus1[c]>0 )
+      {
+        for( Int i=0 ; i<=sei.m_postLutNumValMinus1[c] ; i++ )
+        {
+          WRITE_CODE( sei.m_postLut[c][i].codedValue, (( sei.m_colourRemapBitDepth + 7 ) >> 3 ) << 3, "post_lut_coded_value[c][i]" );
+          WRITE_CODE( sei.m_postLut[c][i].targetValue, (( sei.m_colourRemapBitDepth + 7 ) >> 3 ) << 3, "post_lut_target_value[c][i]" );
+        }
+      }
+    }
+  }
+}
 
 Void SEIWriter::xWriteSEIMasteringDisplayColourVolume(const SEIMasteringDisplayColourVolume& sei)
@@ -863,5 +853,5 @@
   WRITE_CODE( sei.values.whitePoint[0],    16,  "white_point_x" );
   WRITE_CODE( sei.values.whitePoint[1],    16,  "white_point_y" );
-
+    
   WRITE_CODE( sei.values.maxLuminance,     32,  "max_display_mastering_luminance" );
   WRITE_CODE( sei.values.minLuminance,     32,  "min_display_mastering_luminance" );
@@ -881,5 +871,5 @@
 }
 
-#if NH_MV_LAYERS_NOT_PRESENT_SEI
+#if NH_MV
 Void SEIWriter::xWriteSEILayersNotPresent(const SEILayersNotPresent& sei)
 {
@@ -890,7 +880,4 @@
   }
 };
-#endif
-
-
 
 Void SEIWriter::xWriteSEIInterLayerConstrainedTileSets( const SEIInterLayerConstrainedTileSets& sei)
@@ -1068,4 +1055,5 @@
 };
 
+
 Void SEIWriter::xWriteSEITemporalMvPredictionConstraints( const SEITemporalMvPredictionConstraints& sei)
 {
@@ -1112,5 +1100,4 @@
 };
 
-#if SEI_DRI_F0169
 Void SEIWriter::xWriteSEIDepthRepresentationInfo( const SEIDepthRepresentationInfo& sei)
 {
@@ -1239,5 +1226,5 @@
 
 };
-#endif
+
 Void SEIWriter::xWriteSEIMultiviewSceneInfo( const SEIMultiviewSceneInfo& sei)
 {
@@ -1299,6 +1286,4 @@
 };
 
-
-#if NH_MV_SEI
 Void SEIWriter::xWriteSEIMultiviewViewPosition( const SEIMultiviewViewPosition& sei)
 {
@@ -1309,5 +1294,4 @@
   }
 };
-#endif
 
 #if NH_3D
@@ -1434,5 +1418,5 @@
 };
 #endif
-
+#endif
 
 //! \}
Index: trunk/source/Lib/TLibEncoder/SEIwrite.h
===================================================================
--- trunk/source/Lib/TLibEncoder/SEIwrite.h	(revision 1357)
+++ trunk/source/Lib/TLibEncoder/SEIwrite.h	(revision 1386)
@@ -53,5 +53,4 @@
 
 protected:
-  Void xWriteSEIpayloadData(TComBitIf& bs, const SEI& sei, const TComSPS *sps);
   Void xWriteSEIuserDataUnregistered(const SEIuserDataUnregistered &sei);
   Void xWriteSEIActiveParameterSets(const SEIActiveParameterSets& sei);
@@ -60,5 +59,4 @@
   Void xWriteSEIBufferingPeriod(const SEIBufferingPeriod& sei, const TComSPS *sps);
   Void xWriteSEIPictureTiming(const SEIPictureTiming& sei, const TComSPS *sps);
-  TComSPS *m_pSPS;
   Void xWriteSEIRecoveryPoint(const SEIRecoveryPoint& sei);
   Void xWriteSEIFramePacking(const SEIFramePacking& sei);
@@ -71,20 +69,13 @@
   Void xWriteSEISOPDescription(const SEISOPDescription& sei);
   Void xWriteSEIScalableNesting(TComBitIf& bs, const SEIScalableNesting& sei, const TComSPS *sps);
-#if NH_MV
-#if !NH_MV_SEI
-  Void xWriteSEISubBitstreamProperty(const SEISubBitstreamProperty &sei);
-#endif
-#endif
   Void xWriteSEITempMotionConstrainedTileSets(const SEITempMotionConstrainedTileSets& sei);
   Void xWriteSEITimeCode(const SEITimeCode& sei);
-  Void xWriteSEIChromaSamplingFilterHint(const SEIChromaSamplingFilterHint& sei/*, TComSPS *sps*/);
-  Void writeUserDefinedCoefficients(const SEIChromaSamplingFilterHint& sei);
+  Void xWriteSEIChromaResamplingFilterHint(const SEIChromaResamplingFilterHint& sei);
   Void xWriteSEIKneeFunctionInfo(const SEIKneeFunctionInfo &sei);
+  Void xWriteSEIColourRemappingInfo(const SEIColourRemappingInfo& sei);
   Void xWriteSEIMasteringDisplayColourVolume( const SEIMasteringDisplayColourVolume& sei);
 
-#if NH_MV_SEI
-#if NH_MV_LAYERS_NOT_PRESENT_SEI
+#if NH_MV
   Void xWriteSEILayersNotPresent              ( const SEILayersNotPresent& sei);
-#endif
   Void xWriteSEIInterLayerConstrainedTileSets ( const SEIInterLayerConstrainedTileSets& sei);
 #if NH_MV_SEI_TBD
@@ -100,8 +91,6 @@
 #endif
   Void xWriteSEIThreeDimensionalReferenceDisplaysInfo ( const SEIThreeDimensionalReferenceDisplaysInfo& sei);
-#if SEI_DRI_F0169
   Void xWriteSEIDepthRepInfoElement           ( double f);
   Void xWriteSEIDepthRepresentationInfo       ( const SEIDepthRepresentationInfo& sei);
-#endif
   Void xWriteSEIMultiviewSceneInfo            ( const SEIMultiviewSceneInfo& sei);
   Void xWriteSEIMultiviewAcquisitionInfo      ( const SEIMultiviewAcquisitionInfo& sei);
@@ -110,7 +99,9 @@
   Void xWriteSEIAlternativeDepthInfo          ( const SEIAlternativeDepthInfo& sei);
 #endif
+#endif
+
+  Void xWriteSEIpayloadData(TComBitIf& bs, const SEI& sei, const TComSPS *sps);
   Void xWriteByteAlign();
 };
-#endif
 
 //! \}
Index: trunk/source/Lib/TLibEncoder/SyntaxElementWriter.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/SyntaxElementWriter.cpp	(revision 1357)
+++ trunk/source/Lib/TLibEncoder/SyntaxElementWriter.cpp	(revision 1386)
@@ -44,10 +44,10 @@
 #if ENC_DEC_TRACE
 
-Void  SyntaxElementWriter::xWriteCodeTr (UInt value, UInt  length, const Char *pSymbolName)
+Void  SyntaxElementWriter::xWriteCodeTr (UInt value, UInt  length, const TChar *pSymbolName)
 {
   xWriteCode (value,length);
   if( g_HLSTraceEnable )
   {
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
     if ( !g_disableNumbering )
     {
@@ -70,10 +70,10 @@
 }
 
-Void  SyntaxElementWriter::xWriteUvlcTr (UInt value, const Char *pSymbolName)
+Void  SyntaxElementWriter::xWriteUvlcTr (UInt value, const TChar *pSymbolName)
 {
   xWriteUvlc (value);
   if( g_HLSTraceEnable )
   {
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
     if ( !g_disableNumbering )
     {
@@ -89,10 +89,10 @@
 }
 
-Void  SyntaxElementWriter::xWriteSvlcTr (Int value, const Char *pSymbolName)
+Void  SyntaxElementWriter::xWriteSvlcTr (Int value, const TChar *pSymbolName)
 {
   xWriteSvlc(value);
   if( g_HLSTraceEnable )
   {
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
     if ( !g_disableNumbering )
     {
@@ -108,10 +108,10 @@
 }
 
-Void  SyntaxElementWriter::xWriteFlagTr(UInt value, const Char *pSymbolName)
+Void  SyntaxElementWriter::xWriteFlagTr(UInt value, const TChar *pSymbolName)
 {
   xWriteFlag(value);
   if( g_HLSTraceEnable )
   {
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
     if ( !g_disableNumbering )
     {
@@ -127,4 +127,5 @@
 }
 
+#if NH_MV_ENC_DEC_TRAC
 Void  SyntaxElementWriter::xWriteStringTr( UChar* value, UInt length, const Char *pSymbolName)
 {
@@ -136,5 +137,5 @@
   }
 }
-
+#endif
 #endif
 
@@ -176,4 +177,5 @@
 }
 
+#if NH_MV_ENC_DEC_TRAC
 Void  SyntaxElementWriter::xWriteString( UChar* sCode, UInt uiLength)
 {
@@ -185,5 +187,5 @@
   m_pcBitIf->write( 0, 8 ); //zero-termination byte
 }
-
+#endif
 Void SyntaxElementWriter::xWriteRbspTrailingBits()
 {
Index: trunk/source/Lib/TLibEncoder/SyntaxElementWriter.h
===================================================================
--- trunk/source/Lib/TLibEncoder/SyntaxElementWriter.h	(revision 1357)
+++ trunk/source/Lib/TLibEncoder/SyntaxElementWriter.h	(revision 1386)
@@ -56,5 +56,7 @@
 #define WRITE_SVLC( value,         name)    xWriteSvlcTr ( value,         name )
 #define WRITE_FLAG( value,         name)    xWriteFlagTr ( value,         name )
+#if NH_MV
 #define WRITE_STRING( value, length, name)   xWriteStringTr( value, length, name )
+#endif
 
 #else
@@ -64,6 +66,7 @@
 #define WRITE_SVLC( value,         name)     xWriteSvlc ( value )
 #define WRITE_FLAG( value,         name)     xWriteFlag ( value )
+#if NH_MV
 #define WRITE_STRING( value, length, name)   xWriteString( value, length )
-
+#endif
 #endif
 
@@ -84,11 +87,15 @@
   Void  xWriteSvlc            ( Int  iCode   );
   Void  xWriteFlag            ( UInt uiCode );
+#if NH_MV
   Void  xWriteString          ( UChar* sCode, UInt uiLength);
+#endif
 #if ENC_DEC_TRACE
-  Void  xWriteCodeTr          ( UInt value, UInt  length, const Char *pSymbolName);
-  Void  xWriteUvlcTr          ( UInt value,               const Char *pSymbolName);
-  Void  xWriteSvlcTr          ( Int  value,               const Char *pSymbolName);
-  Void  xWriteFlagTr          ( UInt value,               const Char *pSymbolName);
+  Void  xWriteCodeTr          ( UInt value, UInt  length, const TChar *pSymbolName);
+  Void  xWriteUvlcTr          ( UInt value,               const TChar *pSymbolName);
+  Void  xWriteSvlcTr          ( Int  value,               const TChar *pSymbolName);
+  Void  xWriteFlagTr          ( UInt value,               const TChar *pSymbolName);
+#if NH_MV
   Void  xWriteStringTr        ( UChar* value, UInt length, const Char *pSymbolName);
+#endif
 #endif
   Void xWriteRbspTrailingBits();
Index: trunk/source/Lib/TLibEncoder/TEncAnalyze.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncAnalyze.h	(revision 1357)
+++ trunk/source/Lib/TLibEncoder/TEncAnalyze.h	(revision 1386)
@@ -137,5 +137,5 @@
 
 
-  Void    printOut ( Char cDelim, const ChromaFormat chFmt, const Bool printMSEBasedSNR, const Bool printSequenceMSE, const BitDepths &bitDepths )
+  Void    printOut ( TChar cDelim, const ChromaFormat chFmt, const Bool printMSEBasedSNR, const Bool printSequenceMSE, const BitDepths &bitDepths )
   {
     Double dFps     =   m_dFrmRate; //--CFG_KDY
Index: trunk/source/Lib/TLibEncoder/TEncBinCoderCABAC.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncBinCoderCABAC.cpp	(revision 1357)
+++ trunk/source/Lib/TLibEncoder/TEncBinCoderCABAC.cpp	(revision 1386)
@@ -246,5 +246,5 @@
   if (g_debugCounter >= debugCabacBinTargetLine)
   {
-    Char breakPointThis;
+    UChar breakPointThis;
     breakPointThis = 7;
   }
Index: trunk/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.cpp	(revision 1357)
+++ trunk/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.cpp	(revision 1386)
@@ -97,5 +97,5 @@
   if (g_debugCounter >= debugEncoderSearchBinTargetLine)
   {
-    Char breakPointThis;
+    UChar breakPointThis;
     breakPointThis = 7;
   }
Index: trunk/source/Lib/TLibEncoder/TEncCavlc.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 1357)
+++ trunk/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 1386)
@@ -49,5 +49,5 @@
 #if ENC_DEC_TRACE
 
-#if !H_MV_ENC_DEC_TRAC
+#if !NH_MV_ENC_DEC_TRAC
 Void  xTraceVPSHeader ()
 {
@@ -69,6 +69,25 @@
   fprintf( g_hTrace, "=========== Slice ===========\n");
 }
-#endif
-#endif
+
+Void  xTraceAccessUnitDelimiter ()
+{
+  fprintf( g_hTrace, "=========== Access Unit Delimiter ===========\n");
+}
+
+#endif
+#endif
+
+Void AUDWriter::codeAUD(TComBitIf& bs, const Int pictureType)
+{
+#if ENC_DEC_TRACE
+  xTraceAccessUnitDelimiter();
+#endif
+
+  assert (pictureType < 3);
+  setBitstream(&bs);
+  WRITE_CODE(pictureType, 3, "pic_type");
+  xWriteRbspTrailingBits();
+}
+
 // ====================================================================================================================
 // Constructor / destructor / create / destroy
@@ -154,5 +173,5 @@
 {
 #if ENC_DEC_TRACE
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
   tracePSHeader( "PPS", pcPPS->getLayerId() ); 
 #else
@@ -167,5 +186,5 @@
   WRITE_FLAG( pcPPS->getSignHideFlag(), "sign_data_hiding_flag" );
   WRITE_FLAG( pcPPS->getCabacInitPresentFlag() ? 1 : 0,   "cabac_init_present_flag" );
-#if PPS_FIX_DEPTH
+#if H_3D_PPS_FIX_DEPTH
   if( pcPPS->getSPS()->getVPS()->getDepthId(pcPPS->getSPS()->getLayerId()) )
   {
@@ -178,5 +197,5 @@
   WRITE_UVLC( pcPPS->getNumRefIdxL0DefaultActive()-1,     "num_ref_idx_l0_default_active_minus1");
   WRITE_UVLC( pcPPS->getNumRefIdxL1DefaultActive()-1,     "num_ref_idx_l1_default_active_minus1");
-#if PPS_FIX_DEPTH
+#if H_3D_PPS_FIX_DEPTH
   }
 #endif
@@ -238,5 +257,5 @@
     codeScalingList( pcPPS->getScalingList() );
   }
-#if PPS_FIX_DEPTH
+#if H_3D_PPS_FIX_DEPTH
   if( pcPPS->getSPS()->getVPS()->getDepthId(pcPPS->getSPS()->getLayerId()) )
   {
@@ -266,5 +285,5 @@
   {
 #if ENC_DEC_TRACE || RExt__DECODER_DEBUG_BIT_STATISTICS
-    static const char *syntaxStrings[]={ "pps_range_extension_flag",
+    static const TChar *syntaxStrings[]={ "pps_range_extension_flag",
                                          "pps_multilayer_extension_flag",
                                          "pps_extension_6bits[0]",
@@ -330,27 +349,27 @@
     if ( pcPPS->getPpsRangeExtensionsFlag() )
     { 
-              const TComPPSRExt &ppsRangeExtension = pcPPS->getPpsRangeExtension();
-              if (pcPPS->getUseTransformSkip())
-              {
-                WRITE_UVLC( ppsRangeExtension.getLog2MaxTransformSkipBlockSize()-2,            "log2_max_transform_skip_block_size_minus2");
-              }
-
-              WRITE_FLAG((ppsRangeExtension.getCrossComponentPredictionEnabledFlag() ? 1 : 0), "cross_component_prediction_enabled_flag" );
-
-              WRITE_FLAG(UInt(ppsRangeExtension.getChromaQpOffsetListEnabledFlag()),           "chroma_qp_offset_list_enabled_flag" );
-              if (ppsRangeExtension.getChromaQpOffsetListEnabledFlag())
-              {
-                WRITE_UVLC(ppsRangeExtension.getDiffCuChromaQpOffsetDepth(),                   "diff_cu_chroma_qp_offset_depth");
-                WRITE_UVLC(ppsRangeExtension.getChromaQpOffsetListLen() - 1,                   "chroma_qp_offset_list_len_minus1");
-                /* skip zero index */
-                for (Int cuChromaQpOffsetIdx = 0; cuChromaQpOffsetIdx < ppsRangeExtension.getChromaQpOffsetListLen(); cuChromaQpOffsetIdx++)
-                {
-                  WRITE_SVLC(ppsRangeExtension.getChromaQpOffsetListEntry(cuChromaQpOffsetIdx+1).u.comp.CbOffset,     "cb_qp_offset_list[i]");
-                  WRITE_SVLC(ppsRangeExtension.getChromaQpOffsetListEntry(cuChromaQpOffsetIdx+1).u.comp.CrOffset,     "cr_qp_offset_list[i]");
-                }
-              }
-
-              WRITE_UVLC( ppsRangeExtension.getLog2SaoOffsetScale(CHANNEL_TYPE_LUMA),           "log2_sao_offset_scale_luma"   );
-              WRITE_UVLC( ppsRangeExtension.getLog2SaoOffsetScale(CHANNEL_TYPE_CHROMA),         "log2_sao_offset_scale_chroma" );
+      const TComPPSRExt &ppsRangeExtension = pcPPS->getPpsRangeExtension();
+      if (pcPPS->getUseTransformSkip())
+      {
+        WRITE_UVLC( ppsRangeExtension.getLog2MaxTransformSkipBlockSize()-2,            "log2_max_transform_skip_block_size_minus2");
+      }
+
+      WRITE_FLAG((ppsRangeExtension.getCrossComponentPredictionEnabledFlag() ? 1 : 0), "cross_component_prediction_enabled_flag" );
+
+      WRITE_FLAG(UInt(ppsRangeExtension.getChromaQpOffsetListEnabledFlag()),           "chroma_qp_offset_list_enabled_flag" );
+      if (ppsRangeExtension.getChromaQpOffsetListEnabledFlag())
+      {
+        WRITE_UVLC(ppsRangeExtension.getDiffCuChromaQpOffsetDepth(),                   "diff_cu_chroma_qp_offset_depth");
+        WRITE_UVLC(ppsRangeExtension.getChromaQpOffsetListLen() - 1,                   "chroma_qp_offset_list_len_minus1");
+        /* skip zero index */
+        for (Int cuChromaQpOffsetIdx = 0; cuChromaQpOffsetIdx < ppsRangeExtension.getChromaQpOffsetListLen(); cuChromaQpOffsetIdx++)
+        {
+          WRITE_SVLC(ppsRangeExtension.getChromaQpOffsetListEntry(cuChromaQpOffsetIdx+1).u.comp.CbOffset,     "cb_qp_offset_list[i]");
+          WRITE_SVLC(ppsRangeExtension.getChromaQpOffsetListEntry(cuChromaQpOffsetIdx+1).u.comp.CrOffset,     "cr_qp_offset_list[i]");
+        }
+      }
+
+      WRITE_UVLC( ppsRangeExtension.getLog2SaoOffsetScale(CHANNEL_TYPE_LUMA),           "log2_sao_offset_scale_luma"   );
+      WRITE_UVLC( ppsRangeExtension.getLog2SaoOffsetScale(CHANNEL_TYPE_CHROMA),         "log2_sao_offset_scale_chroma" );
     }
 
@@ -662,5 +681,5 @@
 
 #if ENC_DEC_TRACE
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
   tracePSHeader( "SPS", pcSPS->getLayerId() ); 
 #else
@@ -748,5 +767,5 @@
     WRITE_UVLC( pcSPS->getSpsMaxLatencyIncreasePlus1(i),   "sps_max_latency_increase_plus1[i]" );
 #else
-    WRITE_UVLC( pcSPS->getMaxLatencyIncrease(i),           "sps_max_latency_increase_plus1[i]" );
+    WRITE_UVLC( pcSPS->getMaxLatencyIncreasePlus1(i),      "sps_max_latency_increase_plus1[i]" );
 #endif
     if (!subLayerOrderingInfoPresentFlag)
@@ -858,5 +877,5 @@
   {
 #if ENC_DEC_TRACE || RExt__DECODER_DEBUG_BIT_STATISTICS
-    static const char *syntaxStrings[]={ "sps_range_extension_flag",
+    static const TChar *syntaxStrings[]={ "sps_range_extension_flag",
       "sps_multilayer_extension_flag",
       "sps_extension_6bits[0]",
@@ -971,23 +990,23 @@
   for( Int d = 0; d  <=  1; d++ )
   {
-    WRITE_FLAG( sps3dExt->getIvMvPredFlag( d ) ? 1 : 0 , "iv_mv_pred_flag" );
-    WRITE_FLAG( sps3dExt->getIvMvScalingFlag( d ) ? 1 : 0 , "iv_mv_scaling_flag" );
+    WRITE_FLAG( sps3dExt->getIvDiMcEnabledFlag( d ) ? 1 : 0 , "iv_di_mc_enabled_flag" );
+    WRITE_FLAG( sps3dExt->getIvMvScalEnabledFlag( d ) ? 1 : 0 , "iv_mv_scal_enabled_flag" );
     if( d  ==  0 )
     {
-      WRITE_UVLC( sps3dExt->getLog2SubPbSizeMinus3( d ), "log2_sub_pb_size_minus3" );
-      WRITE_FLAG( sps3dExt->getIvResPredFlag( d ) ? 1 : 0 , "iv_res_pred_flag" );
-      WRITE_FLAG( sps3dExt->getDepthRefinementFlag( d ) ? 1 : 0 , "depth_refinement_flag" );
-      WRITE_FLAG( sps3dExt->getViewSynthesisPredFlag( d ) ? 1 : 0 , "view_synthesis_pred_flag" );
-      WRITE_FLAG( sps3dExt->getDepthBasedBlkPartFlag( d ) ? 1 : 0 , "depth_based_blk_part_flag" );
+      WRITE_UVLC( sps3dExt->getLog2IvmcSubPbSizeMinus3( d ), "log2_sub_pb_size_minus3" );
+      WRITE_FLAG( sps3dExt->getIvResPredEnabledFlag( d ) ? 1 : 0 , "iv_res_pred_enabled_flag" );
+      WRITE_FLAG( sps3dExt->getDepthRefEnabledFlag( d ) ? 1 : 0 , "depth_ref_enabled_flag" );
+      WRITE_FLAG( sps3dExt->getVspMcEnabledFlag( d ) ? 1 : 0 , "vsp_mc_enabled_flag" );
+      WRITE_FLAG( sps3dExt->getDbbpEnabledFlag( d ) ? 1 : 0 , "dbbp_enabled_flag" );
     }
     else 
     {
-      WRITE_FLAG( sps3dExt->getMpiFlag( d ) ? 1 : 0 , "mpi_flag" );
-      WRITE_UVLC( sps3dExt->getLog2MpiSubPbSizeMinus3( d ), "log2_mpi_sub_pb_size_minus3" );
-      WRITE_FLAG( sps3dExt->getIntraContourFlag( d ) ? 1 : 0 , "intra_contour_flag" );
-      WRITE_FLAG( sps3dExt->getIntraSdcWedgeFlag( d ) ? 1 : 0 , "intra_sdc_wedge_flag" );
-      WRITE_FLAG( sps3dExt->getQtPredFlag( d ) ? 1 : 0 , "qt_pred_flag" );
-      WRITE_FLAG( sps3dExt->getInterSdcFlag( d ) ? 1 : 0 , "inter_sdc_flag" );
-      WRITE_FLAG( sps3dExt->getDepthIntraSkipFlag( d ) ? 1 : 0 , "intra_skip_flag" );
+      WRITE_FLAG( sps3dExt->getTexMcEnabledFlag( d ) ? 1 : 0 , "tex_mc_enabled_flag" );
+      WRITE_UVLC( sps3dExt->getLog2TexmcSubPbSizeMinus3( d ), "log2_texmc_sub_pb_size_minus3" );
+      WRITE_FLAG( sps3dExt->getIntraContourEnabledFlag( d ) ? 1 : 0 , "intra_contour_enabled_flag" );
+      WRITE_FLAG( sps3dExt->getIntraDcOnlyWedgeEnabledFlag( d ) ? 1 : 0 , "intra_dc_only_wedge_enabled_flag" );
+      WRITE_FLAG( sps3dExt->getCqtCuPartPredEnabledFlag( d ) ? 1 : 0 , "cqt_cu_part_pred_enabled_flag" );
+      WRITE_FLAG( sps3dExt->getInterDcOnlyEnabledFlag( d ) ? 1 : 0 , "inter_dc_only_enabled_flag" );
+      WRITE_FLAG( sps3dExt->getSkipIntraEnabledFlag( d ) ? 1 : 0 , "skip_intra_enabled_flag" );
     }
   }
@@ -999,5 +1018,5 @@
 {
 #if ENC_DEC_TRACE
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
   tracePSHeader( "VPS", getEncTop()->getLayerId() ); 
 #else
@@ -1764,5 +1783,5 @@
     WRITE_FLAG( pcSlice->getNoOutputPriorPicsFlag() ? 1 : 0, "no_output_of_prior_pics_flag" );
   }
-#if PPS_FIX_DEPTH
+#if H_3D_PPS_FIX_DEPTH
   if( pcSlice->getIsDepth() )
   {
@@ -2035,5 +2054,5 @@
     {
       Bool overrideFlag = (pcSlice->getNumRefIdx( REF_PIC_LIST_0 )!=pcSlice->getPPS()->getNumRefIdxL0DefaultActive()||(pcSlice->isInterB()&&pcSlice->getNumRefIdx( REF_PIC_LIST_1 )!=pcSlice->getPPS()->getNumRefIdxL1DefaultActive()));
-#if PPS_FIX_DEPTH
+#if H_3D_PPS_FIX_DEPTH
       overrideFlag |= (pcSlice->getIsDepth() && !pcSlice->getViewIndex());
 #endif
@@ -2057,5 +2076,5 @@
       pcSlice->setNumRefIdx(REF_PIC_LIST_1, 0);
     }
-#if PPS_FIX_DEPTH
+#if H_3D_PPS_FIX_DEPTH
     if( (pcSlice->getPPS()->getListsModificationPresentFlag() || (pcSlice->getIsDepth() && !pcSlice->getViewIndex())) && pcSlice->getNumRpsCurrTempList() > 1)
 #else
Index: trunk/source/Lib/TLibEncoder/TEncCavlc.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncCavlc.h	(revision 1357)
+++ trunk/source/Lib/TLibEncoder/TEncCavlc.h	(revision 1386)
@@ -58,4 +58,13 @@
 // ====================================================================================================================
 
+class AUDWriter : public SyntaxElementWriter
+{
+public:
+  AUDWriter() {};
+  virtual ~AUDWriter() {};
+
+  Void  codeAUD(TComBitIf& bs, const Int pictureType);
+};
+
 /// CAVLC encoder class
 class TEncCavlc : public SyntaxElementWriter, public TEncEntropyIf
Index: trunk/source/Lib/TLibEncoder/TEncCfg.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncCfg.h	(revision 1357)
+++ trunk/source/Lib/TLibEncoder/TEncCfg.h	(revision 1386)
@@ -46,5 +46,5 @@
 #include "TLibCommon/TComSlice.h"
 #include <assert.h>
-#if NH_3D
+#if NH_3D_VSO
 #include "TAppCommon/TAppComCamPara.h"
 #include "TLibRenderer/TRenModSetupStrParser.h"
@@ -65,5 +65,5 @@
   Bool m_refPic;
   Int m_numRefPicsActive;
-  Char m_sliceType;
+  SChar m_sliceType;
   Int m_numRefPics;
   Int m_referencePics[MAX_NUM_REF_PICS];
@@ -137,4 +137,6 @@
   Int       m_framesToBeEncoded;
   Double    m_adLambdaModifier[ MAX_TLAYER ];
+  std::vector<Double> m_adIntraLambdaModifier;
+  Double    m_dIntraQpFactor;                                 ///< Intra Q Factor. If negative, use a default equation: 0.57*(1.0 - Clip3( 0.0, 0.5, 0.05*(Double)(isField ? (GopSize-1)/2 : GopSize-1) ))
 
   Bool      m_printMSEBasedSequencePSNR;
@@ -174,4 +176,5 @@
   Int       m_aiPad[2];
 
+  Bool      m_AccessUnitDelimiter;               ///< add Access Unit Delimiter NAL units
 
   Int       m_iMaxRefPicNum;                     ///< this is used to mimic the sliding mechanism used by the decoder
@@ -206,9 +209,11 @@
   //====== Motion search ========
   Bool      m_bDisableIntraPUsInInterSlices;
-  Int       m_iFastSearch;                      //  0:Full search  1:Diamond  2:PMVFAST
+  MESearchMethod m_motionEstimationSearchMethod;
   Int       m_iSearchRange;                     //  0:Full frame
   Int       m_bipredSearchRange;
   Bool      m_bClipForBiPredMeEnabled;
   Bool      m_bFastMEAssumingSmootherMVEnabled;
+  Int       m_minSearchWindow;
+  Bool      m_bRestrictMESampling;
 
 #if NH_MV
@@ -243,5 +248,5 @@
 #endif
   UInt      m_rdPenalty;
-  Bool      m_bUseFastEnc;
+  FastInterSearchMode m_fastInterSearchMode;
   Bool      m_bUseEarlyCU;
   Bool      m_useFastDecisionForMerge;
@@ -289,10 +294,10 @@
   std::vector<Int> m_tileRowHeight;
 
-  Int       m_iWaveFrontSynchro;
-
-  Int       m_decodedPictureHashSEIEnabled;              ///< Checksum(3)/CRC(2)/MD5(1)/disable(0) acting on decoded picture hash SEI message
-  Int       m_bufferingPeriodSEIEnabled;
-  Int       m_pictureTimingSEIEnabled;
-  Int       m_recoveryPointSEIEnabled;
+  Bool      m_entropyCodingSyncEnabledFlag;
+
+  HashType  m_decodedPictureHashSEIType;
+  Bool      m_bufferingPeriodSEIEnabled;
+  Bool      m_pictureTimingSEIEnabled;
+  Bool      m_recoveryPointSEIEnabled;
   Bool      m_toneMappingInfoSEIEnabled;
   Int       m_toneMapId;
@@ -322,20 +327,20 @@
   Int*      m_codedPivotValue;
   Int*      m_targetPivotValue;
-  Int       m_framePackingSEIEnabled;
+  Bool      m_framePackingSEIEnabled;
   Int       m_framePackingSEIType;
   Int       m_framePackingSEIId;
   Int       m_framePackingSEIQuincunx;
   Int       m_framePackingSEIInterpretation;
-  Int       m_segmentedRectFramePackingSEIEnabled;
+  Bool      m_segmentedRectFramePackingSEIEnabled;
   Bool      m_segmentedRectFramePackingSEICancel;
   Int       m_segmentedRectFramePackingSEIType;
   Bool      m_segmentedRectFramePackingSEIPersistence;
   Int       m_displayOrientationSEIAngle;
-  Int       m_temporalLevel0IndexSEIEnabled;
-  Int       m_gradualDecodingRefreshInfoEnabled;
+  Bool      m_temporalLevel0IndexSEIEnabled;
+  Bool      m_gradualDecodingRefreshInfoEnabled;
   Int       m_noDisplaySEITLayer;
-  Int       m_decodingUnitInfoSEIEnabled;
-  Int       m_SOPDescriptionSEIEnabled;
-  Int       m_scalableNestingSEIEnabled;
+  Bool      m_decodingUnitInfoSEIEnabled;
+  Bool      m_SOPDescriptionSEIEnabled;
+  Bool      m_scalableNestingSEIEnabled;
   Bool      m_tmctsSEIEnabled;
   Bool      m_timeCodeSEIEnabled;
@@ -353,6 +358,7 @@
   Int*      m_kneeSEIInputKneePoint;
   Int*      m_kneeSEIOutputKneePoint;
+  std::string m_colourRemapSEIFileRoot;          ///< SEI Colour Remapping File (initialized from external file)
   TComSEIMasteringDisplay m_masteringDisplay;
-#if NH_MV_SEI
+#if NH_MV
   SEIMessages* m_seiMessages; 
 #endif
@@ -360,8 +366,9 @@
   Bool      m_useWeightedPred;       //< Use of Weighting Prediction (P_SLICE)
   Bool      m_useWeightedBiPred;    //< Use of Bi-directional Weighting Prediction (B_SLICE)
+  WeightedPredictionMethod m_weightedPredictionMethod;
   UInt      m_log2ParallelMergeLevelMinus2;       ///< Parallel merge estimation region
   UInt      m_maxNumMergeCand;                    ///< Maximum number of merge candidates
   ScalingListMode m_useScalingListId;            ///< Using quantization matrix i.e. 0=off, 1=default, 2=file.
-  Char*     m_scalingListFile;          ///< quantization matrix file name
+  std::string m_scalingListFileName;              ///< quantization matrix file name
   Int       m_TMVPModeId;
   Bool      m_signHideFlag;
@@ -373,4 +380,9 @@
   Int       m_RCInitialQP;
   Bool      m_RCForceIntraQP;
+#if U0132_TARGET_BITS_SATURATION
+  Bool      m_RCCpbSaturationEnabled;                   
+  UInt      m_RCCpbSize;
+  Double    m_RCInitialCpbFullness;
+#endif
 
 #if KWU_RC_MADPRED_E0227
@@ -398,7 +410,7 @@
   Bool      m_vuiParametersPresentFlag;                       ///< enable generation of VUI parameters
   Bool      m_aspectRatioInfoPresentFlag;                     ///< Signals whether aspect_ratio_idc is present
-  Bool      m_chromaSamplingFilterHintEnabled;                ///< Signals whether chroma sampling filter hint data is present
-  Int       m_chromaSamplingHorFilterIdc;                     ///< Specifies the Index of filter to use
-  Int       m_chromaSamplingVerFilterIdc;                     ///< Specifies the Index of filter to use
+  Bool      m_chromaResamplingFilterHintEnabled;              ///< Signals whether chroma sampling filter hint data is present
+  Int       m_chromaResamplingHorFilterIdc;                   ///< Specifies the Index of filter to use
+  Int       m_chromaResamplingVerFilterIdc;                   ///< Specifies the Index of filter to use
   Int       m_aspectRatioIdc;                                 ///< aspect_ratio_idc
   Int       m_sarWidth;                                       ///< horizontal size of the sample aspect ratio
@@ -438,15 +450,4 @@
   UInt        m_summaryVerboseness;                           ///< Specifies the level of the verboseness of the text output.
 
-#if NH_MV
-#if !NH_MV_SEI
-  Bool              m_subBistreamPropSEIEnabled;
-  Int               m_numAdditionalSubStreams;
-  std::vector<Int>  m_subBitstreamMode;
-  std::vector<Int>  m_outputLayerSetIdxToVps;
-  std::vector<Int>  m_highestSublayerId;
-  std::vector<Int>  m_avgBitRate;
-  std::vector<Int>  m_maxBitRate;
-#endif
-#endif
 
 #if NH_MV
@@ -457,11 +458,11 @@
 #endif 
 
-#if NH_3D
+#if NH_3D_VSO
   Bool      m_isDepth;
+  Bool      m_isAuxDepth; 
 
   //====== Camera Parameters ======
   TAppComCamPara* m_cameraParameters; 
   
-#if NH_3D_VSO
   //====== View Synthesis Optimization ======
   TRenModSetupStrParser* m_renderModelParameters; 
@@ -480,4 +481,5 @@
   Double    m_dDispCoeff;
 #endif
+#if NH_3D
 
   Bool      m_bUseIC;
@@ -486,7 +488,10 @@
   Bool      m_useSDC;
   Bool      m_useDLT;
+#endif
+#if NH_3D_QTL
   Bool      m_bUseQTL;
+#endif
+#if NH_3D
   Int       m_profileIdc;
-
 #endif
 public:
@@ -499,9 +504,10 @@
   , m_viewId(-1)
   , m_viewIndex(-1)
+#if NH_3D_VSO
+  , m_isDepth(false)
+  , m_isAuxDepth(false)
+  , m_bUseVSO(false)
+#endif
 #if NH_3D
-  , m_isDepth(false)
-#if NH_3D_VSO
-  , m_bUseVSO(false)
-#endif
   , m_profileIdc( -1 )
 #endif
@@ -549,7 +555,11 @@
   Void      setViewIndex                     ( Int viewIndex  )   { m_viewIndex  = viewIndex;  }
   Int       getViewIndex                     ()                   { return m_viewIndex;    }
-#if NH_3D
+#if NH_3D_VSO
   Void      setIsDepth                       ( Bool isDepth )   { m_isDepth = isDepth; }
   Bool      getIsDepth                       ()                 { return m_isDepth; }
+  Void      setIsAuxDepth                    ( Bool isAuxDepth ) { m_isAuxDepth = isAuxDepth; }
+  Bool      getIsAuxDepth                       ()               { return m_isAuxDepth; }
+
+
 #endif
 #endif
@@ -606,9 +616,12 @@
   //====== Motion search ========
   Void      setDisableIntraPUsInInterSlices ( Bool  b )      { m_bDisableIntraPUsInInterSlices = b; }
-  Void      setFastSearch                   ( Int   i )      { m_iFastSearch = i; }
+  Void      setMotionEstimationSearchMethod ( MESearchMethod e ) { m_motionEstimationSearchMethod = e; }
   Void      setSearchRange                  ( Int   i )      { m_iSearchRange = i; }
   Void      setBipredSearchRange            ( Int   i )      { m_bipredSearchRange = i; }
   Void      setClipForBiPredMeEnabled       ( Bool  b )      { m_bClipForBiPredMeEnabled = b; }
   Void      setFastMEAssumingSmootherMVEnabled ( Bool b )    { m_bFastMEAssumingSmootherMVEnabled = b; }
+  Void      setMinSearchWindow              ( Int   i )      { m_minSearchWindow = i; }
+  Void      setRestrictMESampling           ( Bool  b )      { m_bRestrictMESampling = b; }
+
 #if NH_MV
   Void      setUseDisparitySearchRangeRestriction ( Bool   b )      { m_bUseDisparitySearchRangeRestriction = b; }
@@ -649,6 +662,12 @@
   Int       getSourceHeight                 ()      { return  m_iSourceHeight; }
   Int       getFramesToBeEncoded            ()      { return  m_framesToBeEncoded; }
+  
+  //====== Lambda Modifiers ========
   Void setLambdaModifier                    ( UInt uiIndex, Double dValue ) { m_adLambdaModifier[ uiIndex ] = dValue; }
   Double getLambdaModifier                  ( UInt uiIndex ) const { return m_adLambdaModifier[ uiIndex ]; }
+  Void      setIntraLambdaModifier          ( const std::vector<Double> &dValue )               { m_adIntraLambdaModifier = dValue;       }
+  const std::vector<Double>& getIntraLambdaModifier()                        const { return m_adIntraLambdaModifier;         }
+  Void      setIntraQpFactor                ( Double dValue )               { m_dIntraQpFactor = dValue;              }
+  Double    getIntraQpFactor                ()                        const { return m_dIntraQpFactor;                }
 
   //==== Coding Structure ========
@@ -662,4 +681,7 @@
   Int       getPad                          ( Int i )      { assert (i < 2 );                      return  m_aiPad[i]; }
 
+  Bool      getAccessUnitDelimiter() const  { return m_AccessUnitDelimiter; }
+  Void      setAccessUnitDelimiter(Bool val){ m_AccessUnitDelimiter = val; }
+
   //======== Transform =============
   UInt      getQuadtreeTULog2MaxSize        ()      const { return m_uiQuadtreeTULog2MaxSize; }
@@ -677,8 +699,11 @@
   //==== Motion search ========
   Bool      getDisableIntraPUsInInterSlices () const { return m_bDisableIntraPUsInInterSlices; }
-  Int       getFastSearch                   () const { return m_iFastSearch; }
+  MESearchMethod getMotionEstimationSearchMethod ( ) const { return m_motionEstimationSearchMethod; }
   Int       getSearchRange                  () const { return m_iSearchRange; }
   Bool      getClipForBiPredMeEnabled       () const { return m_bClipForBiPredMeEnabled; }
   Bool      getFastMEAssumingSmootherMVEnabled ( ) const { return m_bFastMEAssumingSmootherMVEnabled; }
+  Int       getMinSearchWindow                 () const { return m_minSearchWindow; }
+  Bool      getRestrictMESampling              () const { return m_bRestrictMESampling; }
+
 #if NH_MV
   Bool      getUseDisparitySearchRangeRestriction ()      { return  m_bUseDisparitySearchRangeRestriction; }
@@ -701,6 +726,6 @@
   Void      setUseSelectiveRDOQ             ( Bool b )      { m_useSelectiveRDOQ = b; }
 #endif
-  Void      setRDpenalty                 ( UInt  b )     { m_rdPenalty  = b; }
-  Void      setUseFastEnc                   ( Bool  b )     { m_bUseFastEnc = b; }
+  Void      setRDpenalty                    ( UInt  u )     { m_rdPenalty  = u; }
+  Void      setFastInterSearchMode          ( FastInterSearchMode m ) { m_fastInterSearchMode = m; }
   Void      setUseEarlyCU                   ( Bool  b )     { m_bUseEarlyCU = b; }
   Void      setUseFastDecisionForMerge      ( Bool  b )     { m_useFastDecisionForMerge = b; }
@@ -729,5 +754,5 @@
 #endif
   Int       getRDpenalty                    ()      { return m_rdPenalty;  }
-  Bool      getUseFastEnc                   ()      { return m_bUseFastEnc; }
+  FastInterSearchMode getFastInterSearchMode() const{ return m_fastInterSearchMode;  }
   Bool      getUseEarlyCU                   ()      { return m_bUseEarlyCU; }
   Bool      getUseFastDecisionForMerge      ()      { return m_useFastDecisionForMerge; }
@@ -812,14 +837,14 @@
   UInt  getRowHeight                   ( UInt rowIdx )               { return m_tileRowHeight[rowIdx]; }
   Void  xCheckGSParameters();
-  Void  setWaveFrontSynchro(Int iWaveFrontSynchro)                   { m_iWaveFrontSynchro = iWaveFrontSynchro; }
-  Int   getWaveFrontsynchro()                                        { return m_iWaveFrontSynchro; }
-  Void  setDecodedPictureHashSEIEnabled(Int b)                       { m_decodedPictureHashSEIEnabled = b; }
-  Int   getDecodedPictureHashSEIEnabled()                            { return m_decodedPictureHashSEIEnabled; }
-  Void  setBufferingPeriodSEIEnabled(Int b)                          { m_bufferingPeriodSEIEnabled = b; }
-  Int   getBufferingPeriodSEIEnabled()                               { return m_bufferingPeriodSEIEnabled; }
-  Void  setPictureTimingSEIEnabled(Int b)                            { m_pictureTimingSEIEnabled = b; }
-  Int   getPictureTimingSEIEnabled()                                 { return m_pictureTimingSEIEnabled; }
-  Void  setRecoveryPointSEIEnabled(Int b)                            { m_recoveryPointSEIEnabled = b; }
-  Int   getRecoveryPointSEIEnabled()                                 { return m_recoveryPointSEIEnabled; }
+  Void  setEntropyCodingSyncEnabledFlag(Bool b)                      { m_entropyCodingSyncEnabledFlag = b; }
+  Bool  getEntropyCodingSyncEnabledFlag() const                      { return m_entropyCodingSyncEnabledFlag; }
+  Void  setDecodedPictureHashSEIType(HashType m)                     { m_decodedPictureHashSEIType = m; }
+  HashType getDecodedPictureHashSEIType() const                      { return m_decodedPictureHashSEIType; }
+  Void  setBufferingPeriodSEIEnabled(Bool b)                         { m_bufferingPeriodSEIEnabled = b; }
+  Bool  getBufferingPeriodSEIEnabled() const                         { return m_bufferingPeriodSEIEnabled; }
+  Void  setPictureTimingSEIEnabled(Bool b)                           { m_pictureTimingSEIEnabled = b; }
+  Bool  getPictureTimingSEIEnabled() const                           { return m_pictureTimingSEIEnabled; }
+  Void  setRecoveryPointSEIEnabled(Bool b)                           { m_recoveryPointSEIEnabled = b; }
+  Bool  getRecoveryPointSEIEnabled() const                           { return m_recoveryPointSEIEnabled; }
   Void  setToneMappingInfoSEIEnabled(Bool b)                         { m_toneMappingInfoSEIEnabled = b;  }
   Bool  getToneMappingInfoSEIEnabled()                               { return m_toneMappingInfoSEIEnabled;  }
@@ -876,6 +901,6 @@
   Void  setTMISEIExtendedWhiteLevelLumaCodeValue(Int b)              { m_extendedWhiteLevelLumaCodeValue =b;  }
   Int   getTMISEIExtendedWhiteLevelLumaCodeValue()                   { return m_extendedWhiteLevelLumaCodeValue;  }
-  Void  setFramePackingArrangementSEIEnabled(Int b)                  { m_framePackingSEIEnabled = b; }
-  Int   getFramePackingArrangementSEIEnabled()                       { return m_framePackingSEIEnabled; }
+  Void  setFramePackingArrangementSEIEnabled(Bool b)                 { m_framePackingSEIEnabled = b; }
+  Bool  getFramePackingArrangementSEIEnabled() const                 { return m_framePackingSEIEnabled; }
   Void  setFramePackingArrangementSEIType(Int b)                     { m_framePackingSEIType = b; }
   Int   getFramePackingArrangementSEIType()                          { return m_framePackingSEIType; }
@@ -886,6 +911,6 @@
   Void  setFramePackingArrangementSEIInterpretation(Int b)           { m_framePackingSEIInterpretation = b; }
   Int   getFramePackingArrangementSEIInterpretation()                { return m_framePackingSEIInterpretation; }
-  Void  setSegmentedRectFramePackingArrangementSEIEnabled(Int b)     { m_segmentedRectFramePackingSEIEnabled = b; }
-  Int   getSegmentedRectFramePackingArrangementSEIEnabled()          { return m_segmentedRectFramePackingSEIEnabled; }
+  Void  setSegmentedRectFramePackingArrangementSEIEnabled(Bool b)    { m_segmentedRectFramePackingSEIEnabled = b; }
+  Bool  getSegmentedRectFramePackingArrangementSEIEnabled() const    { return m_segmentedRectFramePackingSEIEnabled; }
   Void  setSegmentedRectFramePackingArrangementSEICancel(Int b)      { m_segmentedRectFramePackingSEICancel = b; }
   Int   getSegmentedRectFramePackingArrangementSEICancel()           { return m_segmentedRectFramePackingSEICancel; }
@@ -896,16 +921,16 @@
   Void  setDisplayOrientationSEIAngle(Int b)                         { m_displayOrientationSEIAngle = b; }
   Int   getDisplayOrientationSEIAngle()                              { return m_displayOrientationSEIAngle; }
-  Void  setTemporalLevel0IndexSEIEnabled(Int b)                      { m_temporalLevel0IndexSEIEnabled = b; }
-  Int   getTemporalLevel0IndexSEIEnabled()                           { return m_temporalLevel0IndexSEIEnabled; }
-  Void  setGradualDecodingRefreshInfoEnabled(Int b)                  { m_gradualDecodingRefreshInfoEnabled = b;    }
-  Int   getGradualDecodingRefreshInfoEnabled()                       { return m_gradualDecodingRefreshInfoEnabled; }
+  Void  setTemporalLevel0IndexSEIEnabled(Bool b)                     { m_temporalLevel0IndexSEIEnabled = b; }
+  Bool  getTemporalLevel0IndexSEIEnabled() const                     { return m_temporalLevel0IndexSEIEnabled; }
+  Void  setGradualDecodingRefreshInfoEnabled(Bool b)                 { m_gradualDecodingRefreshInfoEnabled = b;    }
+  Bool  getGradualDecodingRefreshInfoEnabled() const                 { return m_gradualDecodingRefreshInfoEnabled; }
   Void  setNoDisplaySEITLayer(Int b)                                 { m_noDisplaySEITLayer = b;    }
   Int   getNoDisplaySEITLayer()                                      { return m_noDisplaySEITLayer; }
-  Void  setDecodingUnitInfoSEIEnabled(Int b)                         { m_decodingUnitInfoSEIEnabled = b;    }
-  Int   getDecodingUnitInfoSEIEnabled()                              { return m_decodingUnitInfoSEIEnabled; }
-  Void  setSOPDescriptionSEIEnabled(Int b)                           { m_SOPDescriptionSEIEnabled = b; }
-  Int   getSOPDescriptionSEIEnabled()                                { return m_SOPDescriptionSEIEnabled; }
-  Void  setScalableNestingSEIEnabled(Int b)                          { m_scalableNestingSEIEnabled = b; }
-  Int   getScalableNestingSEIEnabled()                               { return m_scalableNestingSEIEnabled; }
+  Void  setDecodingUnitInfoSEIEnabled(Bool b)                        { m_decodingUnitInfoSEIEnabled = b;    }
+  Bool  getDecodingUnitInfoSEIEnabled() const                        { return m_decodingUnitInfoSEIEnabled; }
+  Void  setSOPDescriptionSEIEnabled(Bool b)                          { m_SOPDescriptionSEIEnabled = b; }
+  Bool  getSOPDescriptionSEIEnabled() const                          { return m_SOPDescriptionSEIEnabled; }
+  Void  setScalableNestingSEIEnabled(Bool b)                         { m_scalableNestingSEIEnabled = b; }
+  Bool  getScalableNestingSEIEnabled() const                         { return m_scalableNestingSEIEnabled; }
   Void  setTMCTSSEIEnabled(Bool b)                                   { m_tmctsSEIEnabled = b; }
   Bool  getTMCTSSEIEnabled()                                         { return m_tmctsSEIEnabled; }
@@ -939,39 +964,13 @@
   Void  setKneeSEIOutputKneePoint(Int *p)                            { m_kneeSEIOutputKneePoint = p; }
   Int*  getKneeSEIOutputKneePoint()                                  { return m_kneeSEIOutputKneePoint; }
+  Void  setColourRemapInfoSEIFileRoot( const std::string &s )        { m_colourRemapSEIFileRoot = s; }
+  const std::string &getColourRemapInfoSEIFileRoot() const           { return m_colourRemapSEIFileRoot; }
+
   Void  setMasteringDisplaySEI(const TComSEIMasteringDisplay &src)   { m_masteringDisplay = src; }
   const TComSEIMasteringDisplay &getMasteringDisplaySEI() const      { return m_masteringDisplay; }
 #if NH_MV
-#if NH_MV_SEI
   Void setSeiMessages(SEIMessages *p)                                { m_seiMessages = p;    }
   const SEIMessages*  getSeiMessages()                               { return m_seiMessages; }
-#else
-  Bool   getSubBitstreamPropSEIEnabled()                             { return m_subBistreamPropSEIEnabled;}
-  Void   setSubBitstreamPropSEIEnabled(Bool x)                       { m_subBistreamPropSEIEnabled = x;}
-                                                                     
-  Int    getNumAdditionalSubStreams()                                { return m_numAdditionalSubStreams;}
-  Void   setNumAdditionalSubStreams(Int x)                           { m_numAdditionalSubStreams = x;}
-
-  std::vector<Int> const &getSubBitstreamMode()                      { return m_subBitstreamMode;}
-  Int   getSubBitstreamMode(Int idx)                                 { return m_subBitstreamMode[idx];}
-  Void  setSubBitstreamMode(std::vector<Int> &x)                     { m_subBitstreamMode = x;}
-
-  std::vector<Int> const &getOutputLayerSetIdxToVps()                { return m_outputLayerSetIdxToVps;}
-  Int   getOutputLayerSetIdxToVps(Int idx)                           { return m_outputLayerSetIdxToVps[idx];}
-  Void  setOutputLayerSetIdxToVps(std::vector<Int> &x)               { m_outputLayerSetIdxToVps = x;}
-                                                                     
-  std::vector<Int> const &getHighestSublayerId()                     { return m_highestSublayerId;}
-  Int   getHighestSublayerId(Int idx)                                { return m_highestSublayerId[idx];}
-  Void  setHighestSublayerId(std::vector<Int> &x)                    { m_highestSublayerId = x;}
-                                                                     
-  std::vector<Int> const &getAvgBitRate()                            { return m_avgBitRate;}
-  Int   getAvgBitRate(Int idx)                                       { return m_avgBitRate[idx];}
-  Void  setAvgBitRate(std::vector<Int> &x)                           { m_avgBitRate = x;}
-                                                                     
-  std::vector<Int> const &getMaxBitRate()                            { return m_maxBitRate;}
-  Int   getMaxBitRate(Int idx)                                       { return m_maxBitRate[idx];}
-  Void  setMaxBitRate(std::vector<Int> &x)                           { m_maxBitRate = x;}
-#endif
-#endif
-
+#endif
   Void         setUseWP               ( Bool b )                     { m_useWeightedPred   = b;    }
   Void         setWPBiPred            ( Bool b )                     { m_useWeightedBiPred = b;    }
@@ -984,8 +983,10 @@
   Void         setUseScalingListId    ( ScalingListMode u )          { m_useScalingListId       = u;   }
   ScalingListMode getUseScalingListId    ()                          { return m_useScalingListId;      }
-  Void         setScalingListFile     ( Char*  pch )                 { m_scalingListFile     = pch; }
-  Char*        getScalingListFile     ()                             { return m_scalingListFile;    }
+  Void         setScalingListFileName       ( const std::string &s ) { m_scalingListFileName = s;      }
+  const std::string& getScalingListFileName () const                 { return m_scalingListFileName;   }
   Void         setTMVPModeId ( Int  u )                              { m_TMVPModeId = u;    }
   Int          getTMVPModeId ()                                      { return m_TMVPModeId; }
+  WeightedPredictionMethod getWeightedPredictionMethod() const       { return m_weightedPredictionMethod; }
+  Void         setWeightedPredictionMethod( WeightedPredictionMethod m ) { m_weightedPredictionMethod = m; }
   Void         setSignHideFlag( Bool signHideFlag )                  { m_signHideFlag = signHideFlag; }
   Bool         getSignHideFlag()                                     { return m_signHideFlag; }
@@ -1004,4 +1005,13 @@
   Bool         getForceIntraQP        ()                             { return m_RCForceIntraQP;        }
   Void         setForceIntraQP        ( Bool b )                     { m_RCForceIntraQP = b;           }
+
+#if U0132_TARGET_BITS_SATURATION
+  Bool         getCpbSaturationEnabled()                             { return m_RCCpbSaturationEnabled;}
+  Void         setCpbSaturationEnabled( Bool b )                     { m_RCCpbSaturationEnabled = b;   }
+  UInt         getCpbSize             ()                             { return m_RCCpbSize;}
+  Void         setCpbSize             ( UInt ui )                    { m_RCCpbSize = ui;   }
+  Double       getInitialCpbFullness  ()                             { return m_RCInitialCpbFullness;  }
+  Void         setInitialCpbFullness  (Double f)                     { m_RCInitialCpbFullness = f;     }
+#endif
 
 #if KWU_RC_MADPRED_E0227
@@ -1132,10 +1142,10 @@
   Bool         getLowerBitRateConstraintFlag() const                 { return m_lowerBitRateConstraintFlag; }
   Void         setLowerBitRateConstraintFlag(Bool b)                 { m_lowerBitRateConstraintFlag=b; }
-  Bool      getChromaSamplingFilterHintEnabled()                     { return m_chromaSamplingFilterHintEnabled;}
-  Void      setChromaSamplingFilterHintEnabled(Bool i)               { m_chromaSamplingFilterHintEnabled = i;}
-  Int       getChromaSamplingHorFilterIdc()                          { return m_chromaSamplingHorFilterIdc;}
-  Void      setChromaSamplingHorFilterIdc(Int i)                     { m_chromaSamplingHorFilterIdc = i;}
-  Int       getChromaSamplingVerFilterIdc()                          { return m_chromaSamplingVerFilterIdc;}
-  Void      setChromaSamplingVerFilterIdc(Int i)                     { m_chromaSamplingVerFilterIdc = i;}
+  Bool         getChromaResamplingFilterHintEnabled()                { return m_chromaResamplingFilterHintEnabled;}
+  Void         setChromaResamplingFilterHintEnabled(Bool i)          { m_chromaResamplingFilterHintEnabled = i;}
+  Int          getChromaResamplingHorFilterIdc()                     { return m_chromaResamplingHorFilterIdc;}
+  Void         setChromaResamplingHorFilterIdc(Int i)                { m_chromaResamplingHorFilterIdc = i;}
+  Int          getChromaResamplingVerFilterIdc()                     { return m_chromaResamplingVerFilterIdc;}
+  Void         setChromaResamplingVerFilterIdc(Int i)                { m_chromaResamplingVerFilterIdc = i;}
 
   Void      setSummaryOutFilename(const std::string &s)              { m_summaryOutFilename = s; }
@@ -1147,5 +1157,5 @@
   UInt      getSummaryVerboseness( ) const                           { return m_summaryVerboseness; }
 
-#if NH_3D
+#if NH_3D_VSO
   // Only flags that are not in the SPS3dExtension should go here. 
   /// 3D Tools 
@@ -1153,6 +1163,4 @@
  //==== CAMERA PARAMETERS  ==========
   Void      setCameraParameters             ( TAppComCamPara* c) { m_cameraParameters   = c; }
-
-#if NH_3D_VSO
  //==== VSO  ==========
   Void      setRenderModelParameters ( TRenModSetupStrParser* c ) { m_renderModelParameters = c; }
@@ -1184,5 +1192,5 @@
   Void      setDispCoeff                    ( Double  d )   { m_dDispCoeff  = d; }
 #endif // NH_3D_VSO
-
+#if NH_3D
   Bool      getUseDMM                       ()        { return m_useDMM; }
   Void      setUseDMM                       ( Bool b) { m_useDMM = b;    }
@@ -1192,7 +1200,11 @@
   Bool      getUseDLT                       ()        { return m_useDLT; }
   Void      setUseDLT                       ( Bool b) { m_useDLT = b;    }
-
+#endif
+
+#if NH_3D_QTL
   Void      setUseQTL                       ( Bool b ) { m_bUseQTL = b;    }
   Bool      getUseQTL                       ()         { return m_bUseQTL; }
+#endif
+#if NH_3D
 
   Void      setProfileIdc( Int a )    { assert( a == 1 || a == 6 || a == 8 ); m_profileIdc = a;  }
Index: trunk/source/Lib/TLibEncoder/TEncCu.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncCu.cpp	(revision 1357)
+++ trunk/source/Lib/TLibEncoder/TEncCu.cpp	(revision 1386)
@@ -420,7 +420,10 @@
   const UInt fastDeltaQPCuMaxSize    = Clip3(sps.getMaxCUHeight()>>sps.getLog2DiffMaxMinCodingBlockSize(), sps.getMaxCUHeight(), 32u);
 
-
+#if NH_3D_QTL
 #if NH_3D_QTLPC
   Bool  bLimQtPredFalg    = pcPic->getSlice(0)->getQtPredFlag(); 
+#else
+  Bool  bLimQtPredFalg    = false;
+#endif
   TComPic *pcTexture      = rpcBestCU->getSlice()->getTexturePic();
 
@@ -437,5 +440,5 @@
   m_ppcOrigYuv[uiDepth]->copyFromPicYuv( pcPic->getPicYuvOrg(), rpcBestCU->getCtuRsAddr(), rpcBestCU->getZorderIdxInCtu() );
 
-#if NH_3D_QTLPC  
+#if NH_3D_QTL  
   Bool    bTrySplit     = true;
   Bool    bTrySplitDQP  = true;
@@ -459,5 +462,5 @@
   const UInt uiWidth   = rpcBestCU->getWidth(0);
 
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
 #if ENC_DEC_TRACE
     stopAtPos  ( rpcBestCU->getSlice()->getPOC(), 
@@ -534,5 +537,5 @@
       }
 
-#if NH_3D_QTLPC
+#if NH_3D_QTL
       bTrySplit    = true;
 #endif
@@ -552,5 +555,5 @@
 
       rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
-#if NH_3D_QTLPC
+#if NH_3D_QTL
       //logic for setting bTrySplit using the partition information that is stored of the texture colocated CU
 #if H_3D_FCO
@@ -734,5 +737,5 @@
 #endif
       }
-#if NH_3D_QTLPC      
+#if NH_3D_QTL
       if(depthMapDetect && !bIntraSliceDetect && !rapPic && ( m_pcEncCfg->getUseQTL() || bLimQtPredFalg ))
       {
@@ -789,5 +792,5 @@
           {
             if( uiDepth == sps.getLog2DiffMaxMinCodingBlockSize() && doNotBlockPu
-#if NH_3D_QTLPC
+#if NH_3D_QTL
                 && bTrySplit
 #endif
@@ -809,5 +812,5 @@
 
           if(doNotBlockPu
-#if NH_3D_QTLPC
+#if NH_3D_QTL
             && bTryNx2N
 #endif
@@ -830,5 +833,5 @@
           }
           if(doNotBlockPu
-#if NH_3D_QTLPC
+#if NH_3D_QTL
             && bTry2NxN
 #endif
@@ -871,5 +874,5 @@
             {
               if(doNotBlockPu
-#if NH_3D_QTLPC
+#if NH_3D_QTL
                 && bTry2NxN
 #endif
@@ -891,5 +894,5 @@
               }
               if(doNotBlockPu
-#if NH_3D_QTLPC
+#if NH_3D_QTL
                 && bTry2NxN
 #endif
@@ -917,5 +920,5 @@
             {
               if(doNotBlockPu
-#if NH_3D_QTLPC
+#if NH_3D_QTL
                 && bTry2NxN
 #endif
@@ -939,5 +942,5 @@
               }
               if(doNotBlockPu
-#if NH_3D_QTLPC
+#if NH_3D_QTL
                 && bTry2NxN
 #endif
@@ -966,5 +969,5 @@
             {
               if(doNotBlockPu
-#if NH_3D_QTLPC
+#if NH_3D_QTL
                 && bTryNx2N
 #endif
@@ -987,5 +990,5 @@
               }
               if(doNotBlockPu
-#if NH_3D_QTLPC
+#if NH_3D_QTL
                 && bTryNx2N
 #endif
@@ -1007,5 +1010,5 @@
             {
               if(doNotBlockPu
-#if NH_3D_QTLPC
+#if NH_3D_QTL
                 && bTryNx2N
 #endif
@@ -1027,5 +1030,5 @@
               }
               if(doNotBlockPu
-#if NH_3D_QTLPC
+#if NH_3D_QTL
                 && bTryNx2N
 #endif
@@ -1048,5 +1051,5 @@
 
 #else
-#if NH_3D_QTLPC
+#if NH_3D_QTL
             if (bTry2NxN)
             {
@@ -1063,5 +1066,5 @@
             rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
 #endif
-#if NH_3D_QTLPC
+#if NH_3D_QTL
             }
             if (bTryNx2N)
@@ -1078,5 +1081,5 @@
             rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
 #endif
-#if NH_3D_QTLPC
+#if NH_3D_QTL
             }
 #endif
@@ -1134,5 +1137,5 @@
           if( uiDepth == sps.getLog2DiffMaxMinCodingBlockSize() )
           {
-#if NH_3D_QTLPC //Try IntraNxN
+#if NH_3D_QTL //Try IntraNxN
               if(bTrySplit)
               {
@@ -1150,5 +1153,5 @@
               rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
             }
-#if NH_3D_QTLPC
+#if NH_3D_QTL
               }
 #endif
@@ -1252,5 +1255,5 @@
   const Bool bSubBranch = bBoundary || !( m_pcEncCfg->getUseEarlyCU() && rpcBestCU->getTotalCost()!=MAX_DOUBLE && rpcBestCU->isSkipped(0) );
 #endif
-#if NH_3D_QTLPC
+#if NH_3D_QTL
   if( bSubBranch && uiDepth < sps.getLog2DiffMaxMinCodingBlockSize() && (!getFastDeltaQp() || uiWidth > fastDeltaQPCuMaxSize || bBoundary) && bTrySplitDQP )
 #else
@@ -1516,5 +1519,5 @@
   const UInt uiBPelY   = uiTPelY + (maxCUHeight>>uiDepth) - 1;
 
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
   DTRACE_CU_S("=========== coding_quadtree ===========\n")
   DTRACE_CU("x0", uiLPelX)
@@ -1558,5 +1561,5 @@
   }
 
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
   DTRACE_CU_S("=========== coding_unit ===========\n")
 #endif
@@ -1585,5 +1588,5 @@
   if( pcCU->isSkipped( uiAbsPartIdx ) )
   {
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
     DTRACE_PU_S("=========== prediction_unit ===========\n")
     DTRACE_PU("x0", uiLPelX)
@@ -2216,5 +2219,5 @@
           *earlyDetectionSkipMode = true;
         }
-        else if(m_pcEncCfg->getFastSearch() != SELECTIVE)
+        else if(m_pcEncCfg->getMotionEstimationSearchMethod() != MESEARCH_SELECTIVE)
         {
           Int absoulte_MV=0;
@@ -2305,5 +2308,5 @@
     for( Int nARPW = 0; nARPW <= nARPWMax; nARPW++ )
     {
-#if DEBUG_STRING && H_MV_ENC_DEC_TRAC
+#if DEBUG_STRING && NH_MV_ENC_DEC_TRAC
       sTest.clear(); 
 #endif
@@ -2741,10 +2744,10 @@
   m_pcPredSearch  ->estIntraPredDIS      ( rpcTempCU, m_ppcOrigYuv[uiDepth], m_ppcPredYuvTemp[uiDepth], m_ppcResiYuvTemp[uiDepth], m_ppcRecoYuvTemp[uiDepth], uiPreCalcDistC, false );
 
-#if ENC_DEC_TRACE && H_MV_ENC_DEC_TRAC
+#if ENC_DEC_TRACE && NH_MV_ENC_DEC_TRAC
   Int oldTraceCopyBack = g_traceCopyBack; 
   g_traceCopyBack = false;  
 #endif
   m_ppcRecoYuvTemp[uiDepth]->copyToPicComponent(COMPONENT_Y, rpcTempCU->getPic()->getPicYuvRec(), rpcTempCU->getCtuRsAddr(), rpcTempCU->getZorderIdxInCtu() );
-#if ENC_DEC_TRACE && H_MV_ENC_DEC_TRAC  
+#if ENC_DEC_TRACE && NH_MV_ENC_DEC_TRAC  
   g_traceCopyBack = oldTraceCopyBack; 
 #endif
@@ -3077,5 +3080,5 @@
   m_ppcRecoYuvBest[uiSrcDepth]->copyToPicYuv( rpcPic->getPicYuvRec (), uiCUAddr, uiAbsPartIdx, uiDepth - uiSrcDepth, uiPartIdx);
 
-#if ENC_DEC_TRACE && H_MV_ENC_DEC_TRAC
+#if ENC_DEC_TRACE && NH_MV_ENC_DEC_TRAC
   Bool oldtraceCopyBack = g_traceCopyBack;
   g_traceCopyBack = false; 
@@ -3083,5 +3086,5 @@
   m_ppcPredYuvBest[uiSrcDepth]->copyToPicYuv( rpcPic->getPicYuvPred (), uiCUAddr, uiAbsPartIdx, uiDepth - uiSrcDepth, uiPartIdx);
 
-#if ENC_DEC_TRACE && H_MV_ENC_DEC_TRAC
+#if ENC_DEC_TRACE && NH_MV_ENC_DEC_TRAC
   g_traceCopyBack = oldtraceCopyBack; 
 #endif
Index: trunk/source/Lib/TLibEncoder/TEncEntropy.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncEntropy.cpp	(revision 1357)
+++ trunk/source/Lib/TLibEncoder/TEncEntropy.cpp	(revision 1386)
@@ -281,5 +281,5 @@
   const UInt uiTrIdx = rTu.GetTransformDepthRel();
   const UInt uiDepth = rTu.GetTransformDepthTotal();
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
 #if ENC_DEC_TRACE
   UInt uiLPelX   = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
@@ -388,5 +388,5 @@
   else
   {
-#if !H_MV_ENC_DEC_TRAC
+#if !NH_MV_ENC_DEC_TRAC
     {
       DTRACE_CABAC_VL( g_nSymbolCounter++ );
@@ -557,5 +557,5 @@
   for ( UInt uiPartIdx = 0, uiSubPartIdx = uiAbsPartIdx; uiPartIdx < uiNumPU; uiPartIdx++, uiSubPartIdx += uiPUOffset )
   {
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
     DTRACE_PU_S("=========== prediction_unit ===========\n")
        //Todo: 
@@ -795,5 +795,5 @@
 Void TEncEntropy::encodeCoeffNxN( TComTU &rTu, TCoeff* pcCoef, const ComponentID compID)
 {
-#if ENC_DEC_TRACE && H_MV_ENC_DEC_TRAC
+#if ENC_DEC_TRACE && NH_MV_ENC_DEC_TRAC
   Bool oldTraceFracBits = g_traceEncFracBits; 
   g_traceEncFracBits = false; 
@@ -827,5 +827,5 @@
     }
   }
-#if ENC_DEC_TRACE && H_MV_ENC_DEC_TRAC
+#if ENC_DEC_TRACE && NH_MV_ENC_DEC_TRAC
   g_traceEncFracBits = oldTraceFracBits; 
 #endif
Index: trunk/source/Lib/TLibEncoder/TEncEntropy.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncEntropy.h	(revision 1357)
+++ trunk/source/Lib/TLibEncoder/TEncEntropy.h	(revision 1386)
@@ -139,9 +139,11 @@
   Void    setBitstream              ( TComBitIf* p )          { m_pcEntropyCoderIf->setBitstream(p);  }
   Void    resetBits                 ()                        { m_pcEntropyCoderIf->resetBits();      }
+#if NH_MV
   UInt    getNumberOfWrittenBits    ()                        {
-#if NH_MV
       D_PRINT_INDENT(g_encNumberOfWrittenBits,  "NumBits: " +  n2s( m_pcEntropyCoderIf->getNumberOfWrittenBits() ))
-#endif
  return m_pcEntropyCoderIf->getNumberOfWrittenBits(); }
+#else
+  UInt    getNumberOfWrittenBits    ()                        { return m_pcEntropyCoderIf->getNumberOfWrittenBits(); }
+#endif
   Void    resetEntropy              (const TComSlice *pSlice) { m_pcEntropyCoderIf->resetEntropy(pSlice);  }
   SliceType determineCabacInitIdx   (const TComSlice *pSlice) { return m_pcEntropyCoderIf->determineCabacInitIdx(pSlice); }
Index: trunk/source/Lib/TLibEncoder/TEncGOP.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 1357)
+++ trunk/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 1386)
@@ -219,4 +219,15 @@
 }
 
+Void TEncGOP::xWriteAccessUnitDelimiter (AccessUnit &accessUnit, TComSlice *slice)
+{
+  AUDWriter audWriter;
+  OutputNALUnit nalu(NAL_UNIT_ACCESS_UNIT_DELIMITER);
+
+  Int picType = slice->isIntra() ? 0 : (slice->isInterP() ? 1 : 2);
+
+  audWriter.codeAUD(nalu.m_Bitstream, picType);
+  accessUnit.push_front(new NALUnitEBSP(nalu));
+}
+
 // write SEI list into one NAL unit and add it to the Access unit at auPos
 Void TEncGOP::xWriteSEI (NalUnitType naluType, SEIMessages& seiMessages, AccessUnit &accessUnit, AccessUnit::iterator &auPos, Int temporalId, const TComSPS *sps)
@@ -329,5 +340,5 @@
   xClearSEIs(currentMessages, !testWrite);
 
-#if NH_MV_LAYERS_NOT_PRESENT_SEI
+#if NH_MV
   // Layers not present SEI message
   currentMessages = extractSeisByType(localMessages, SEI::LAYERS_NOT_PRESENT);
@@ -485,14 +496,10 @@
   }
 
-#if NH_MV
-#if !NH_MV_SEI
-  if( m_pcCfg->getSubBitstreamPropSEIEnabled() && ( getLayerId() == 0 ) )
-  {
-    SEISubBitstreamProperty *sei = new SEISubBitstreamProperty;
-    m_seiEncoder.initSEISubBitstreamProperty( sei, sps );
-    seiMessages.push_back(sei);
-  }
-#endif
-#endif
+  if(m_pcCfg->getChromaResamplingFilterHintEnabled())
+  {
+    SEIChromaResamplingFilterHint *seiChromaResamplingFilterHint = new SEIChromaResamplingFilterHint;
+    m_seiEncoder.initSEIChromaResamplingFilterHint(seiChromaResamplingFilterHint, m_pcCfg->getChromaResamplingHorFilterIdc(), m_pcCfg->getChromaResamplingVerFilterIdc());
+    seiMessages.push_back(seiChromaResamplingFilterHint);
+  }
 }
 
@@ -545,11 +552,4 @@
   }
 
-  if(slice->getSPS()->getVuiParametersPresentFlag() && m_pcCfg->getChromaSamplingFilterHintEnabled() && ( slice->getSliceType() == I_SLICE ))
-  {
-    SEIChromaSamplingFilterHint *seiChromaSamplingFilterHint = new SEIChromaSamplingFilterHint;
-    m_seiEncoder.initSEIChromaSamplingFilterHint(seiChromaSamplingFilterHint, m_pcCfg->getChromaSamplingHorFilterIdc(), m_pcCfg->getChromaSamplingVerFilterIdc());
-    seiMessages.push_back(seiChromaSamplingFilterHint);
-  }
-
   if( m_pcEncTop->getNoDisplaySEITLayer() && ( slice->getTLayer() >= m_pcEncTop->getNoDisplaySEITLayer() ) )
   {
@@ -557,4 +557,20 @@
     seiNoDisplay->m_noDisplay = true;
     seiMessages.push_back(seiNoDisplay);
+  }
+
+  // insert one Colour Remapping Info SEI for the picture (if the file exists)
+  if (!m_pcCfg->getColourRemapInfoSEIFileRoot().empty())
+  {
+    SEIColourRemappingInfo *seiColourRemappingInfo = new SEIColourRemappingInfo();
+    const Bool success = m_seiEncoder.initSEIColourRemappingInfo(seiColourRemappingInfo, slice->getPOC() );
+
+    if(success)
+    {
+      seiMessages.push_back(seiColourRemappingInfo);
+    }
+    else
+    {
+      delete seiColourRemappingInfo;
+    }
   }
 }
@@ -577,8 +593,4 @@
 Void TEncGOP::xCreatePictureTimingSEI  (Int IRAPGOPid, SEIMessages& seiMessages, SEIMessages& nestedSeiMessages, SEIMessages& duInfoSeiMessages, TComSlice *slice, Bool isField, std::deque<DUData> &duData)
 {
-  Int picSptDpbOutputDuDelay = 0;
-#if !NH_MV
-  SEIPictureTiming *pictureTimingSEI = new SEIPictureTiming();
-#endif
 
   const TComVUI *vui = slice->getSPS()->getVuiParameters();
@@ -590,8 +602,6 @@
     (  hrd->getNalHrdParametersPresentFlag() || hrd->getVclHrdParametersPresentFlag() ) )
   {
-#if NH_MV
-    // Preliminary fix to avoid memory leak.
+    Int picSptDpbOutputDuDelay = 0;
     SEIPictureTiming *pictureTimingSEI = new SEIPictureTiming();
-#endif
 
     // DU parameters
@@ -712,4 +722,9 @@
       }
     }
+
+    if( !m_pcCfg->getPictureTimingSEIEnabled() && pictureTimingSEI )
+    {
+      delete pictureTimingSEI;
+    }
   }
 }
@@ -745,5 +760,5 @@
 
   // The last DU may have a trailing SEI
-  if (m_pcCfg->getDecodedPictureHashSEIEnabled())
+  if (m_pcCfg->getDecodedPictureHashSEIType()!=HASHTYPE_NONE)
   {
     duData.back().accumBitsDU += ( 20 << 3 ); // probably around 20 bytes - should be further adjusted, e.g. by type
@@ -867,10 +882,10 @@
       if (cabacZeroWordPaddingEnabled)
       {
-        std::vector<Char> zeroBytesPadding(numberOfAdditionalCabacZeroBytes, Char(0));
+        std::vector<UChar> zeroBytesPadding(numberOfAdditionalCabacZeroBytes, UChar(0));
         for(std::size_t i=0; i<numberOfAdditionalCabacZeroWords; i++)
         {
           zeroBytesPadding[i*3+2]=3;  // 00 00 03
         }
-        nalUnitData.write(&(zeroBytesPadding[0]), numberOfAdditionalCabacZeroBytes);
+        nalUnitData.write(reinterpret_cast<const TChar*>(&(zeroBytesPadding[0])), numberOfAdditionalCabacZeroBytes);
         printf("Adding %d bytes of padding\n", UInt(numberOfAdditionalCabacZeroWords*3));
       }
@@ -1058,4 +1073,37 @@
   {
     return 1;
+  }
+}
+
+
+static Void
+printHash(const HashType hashType, const std::string &digestStr)
+{
+  const TChar *decodedPictureHashModeName;
+  switch (hashType)
+  {
+    case HASHTYPE_MD5:
+      decodedPictureHashModeName = "MD5";
+      break;
+    case HASHTYPE_CRC:
+      decodedPictureHashModeName = "CRC";
+      break;
+    case HASHTYPE_CHECKSUM:
+      decodedPictureHashModeName = "Checksum";
+      break;
+    default:
+      decodedPictureHashModeName = NULL;
+      break;
+  }
+  if (decodedPictureHashModeName != NULL)
+  {
+    if (digestStr.empty())
+    {
+      printf(" [%s:%s]", decodedPictureHashModeName, "?");
+    }
+    else
+    {
+      printf(" [%s:%s]", decodedPictureHashModeName, digestStr.c_str());
+    }
   }
 }
@@ -1374,6 +1422,9 @@
     Int numDirectRefLayers = vps    ->getNumDirectRefLayers( getLayerId() );
 #endif
+#if NH_3D_QTL
+    pcSlice->setIvPicLists( m_ivPicLists );
+#endif
 #if NH_3D
-    pcSlice->setIvPicLists( m_ivPicLists );
+
 
     Int gopNum = (pcSlice->getRapPicFlag() && getLayerId() > 0) ? MAX_GOP : iGOPid;
@@ -1594,9 +1645,11 @@
     pcRdCost->setVideoRecPicYuv( m_pcEncTop->getIvPicLists()->getPicYuv( pcSlice->getViewIndex(), false, pcSlice->getPOC(), flagRec ) );
     pcRdCost->setDepthPicYuv   ( m_pcEncTop->getIvPicLists()->getPicYuv( pcSlice->getViewIndex(), true, pcSlice->getPOC(), false ) );
-#else
-    pcRdCost->setVideoRecPicYuv( m_pcEncTop->getIvPicLists()->getPicYuv( pcSlice->getViewIndex(), false , pcSlice->getPOC(), true ) );
-    pcRdCost->setDepthPicYuv   ( m_pcEncTop->getIvPicLists()->getPicYuv( pcSlice->getViewIndex(), true  , pcSlice->getPOC(), false ) );
-#endif
-
+#else    
+    Int curAuxId     = pcSlice->getVPS()->getAuxId( getLayerId() ); 
+    Int curDepthFlag = pcSlice->getIsDepth(); 
+    assert( curAuxId == 2 || curDepthFlag  ); 
+    pcRdCost->setVideoRecPicYuv( m_pcEncTop->getIvPicLists()->getPicYuv( pcSlice->getViewIndex(), false       , 0       , pcSlice->getPOC(), true ) );
+    pcRdCost->setDepthPicYuv   ( m_pcEncTop->getIvPicLists()->getPicYuv( pcSlice->getViewIndex(), curDepthFlag, curAuxId, pcSlice->getPOC(), false ) );
+#endif
     // LGE_WVSO_A0119
     Bool bUseWVSO  = m_pcEncTop->getUseWVSO();
@@ -1605,8 +1658,6 @@
   }
 #endif
-
-    /////////////////////////////////////////////////////////////////////////////////////////////////// Compress a slice
-    //  Slice compression
-    if (m_pcCfg->getUseASR())
+    // set adaptive search range for non-intra-slices
+    if (m_pcCfg->getUseASR() && pcSlice->getSliceType()!=I_SLICE)
     {
       m_pcSliceEncoder->setSearchRange(pcSlice);
@@ -1654,4 +1705,5 @@
       }
       m_pcRateCtrl->initRCPic( frameLevel );
+      estimatedBits = m_pcRateCtrl->getRCPic()->getTargetBits();
 
 #if KWU_RC_MADPRED_E0227
@@ -1662,5 +1714,25 @@
 #endif
 
-      estimatedBits = m_pcRateCtrl->getRCPic()->getTargetBits();
+#if U0132_TARGET_BITS_SATURATION
+      if (m_pcRateCtrl->getCpbSaturationEnabled() && frameLevel != 0)
+      {
+        Int estimatedCpbFullness = m_pcRateCtrl->getCpbState() + m_pcRateCtrl->getBufferingRate();
+
+        // prevent overflow
+        if (estimatedCpbFullness - estimatedBits > (Int)(m_pcRateCtrl->getCpbSize()*0.9f))
+        {
+          estimatedBits = estimatedCpbFullness - (Int)(m_pcRateCtrl->getCpbSize()*0.9f);
+        }
+
+        estimatedCpbFullness -= m_pcRateCtrl->getBufferingRate();
+        // prevent underflow
+        if (estimatedCpbFullness - estimatedBits < (Int)(m_pcRateCtrl->getCpbSize()*0.1f))
+        {
+          estimatedBits = max(200, estimatedCpbFullness - (Int)(m_pcRateCtrl->getCpbSize()*0.1f));
+        }
+
+        m_pcRateCtrl->getRCPic()->setTargetBits(estimatedBits);
+      }
+#endif
 
       Int sliceQP = m_pcCfg->getInitialQP();
@@ -1683,4 +1755,25 @@
           Int bits = m_pcRateCtrl->getRCSeq()->getLeftAverageBits();
           bits = m_pcRateCtrl->getRCPic()->getRefineBitsForIntra( bits );
+
+#if U0132_TARGET_BITS_SATURATION
+          if (m_pcRateCtrl->getCpbSaturationEnabled() )
+          {
+            Int estimatedCpbFullness = m_pcRateCtrl->getCpbState() + m_pcRateCtrl->getBufferingRate();
+
+            // prevent overflow
+            if (estimatedCpbFullness - bits > (Int)(m_pcRateCtrl->getCpbSize()*0.9f))
+            {
+              bits = estimatedCpbFullness - (Int)(m_pcRateCtrl->getCpbSize()*0.9f);
+            }
+
+            estimatedCpbFullness -= m_pcRateCtrl->getBufferingRate();
+            // prevent underflow
+            if (estimatedCpbFullness - bits < (Int)(m_pcRateCtrl->getCpbSize()*0.1f))
+            {
+              bits = estimatedCpbFullness - (Int)(m_pcRateCtrl->getCpbSize()*0.1f);
+            }
+          }
+#endif
+
           if ( bits < 200 )
           {
@@ -1820,9 +1913,9 @@
       // write various parameter sets
       actualTotalBits += xWriteParameterSets(accessUnit, pcSlice);
-#if PPS_FIX_DEPTH
+#if H_3D_PPS_FIX_DEPTH
       if(!pcSlice->getIsDepth() || !pcSlice->getViewIndex() )
       {
 #endif
-#if PPS_FIX_DEPTH
+#if H_3D_PPS_FIX_DEPTH
       }
 #endif
@@ -1834,4 +1927,8 @@
 
       m_bSeqFirst = false;
+    }
+    if (m_pcCfg->getAccessUnitDelimiter())
+    {
+      xWriteAccessUnitDelimiter(accessUnit, pcSlice);
     }
 
@@ -1841,5 +1938,5 @@
     xCreatePerPictureSEIMessages(iGOPid, leadingSeiMessages, nestedSeiMessages, pcSlice);
 
-#if NH_MV_SEI
+#if NH_MV
     m_seiEncoder.createAnnexFGISeiMessages( leadingSeiMessages, pcSlice );
 #endif
@@ -2002,5 +2099,5 @@
 
     std::string digestStr;
-    if (m_pcCfg->getDecodedPictureHashSEIEnabled())
+    if (m_pcCfg->getDecodedPictureHashSEIType()!=HASHTYPE_NONE)
     {
       SEIDecodedPictureHash *decodedPictureHashSei = new SEIDecodedPictureHash();
@@ -2014,19 +2111,5 @@
     xCalculateAddPSNRs( isField, isTff, iGOPid, pcPic, accessUnit, rcListPic, dEncTime, snr_conversion, printFrameMSE );
 
-    if (!digestStr.empty())
-    {
-      if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 1)
-      {
-        printf(" [MD5:%s]", digestStr.c_str());
-      }
-      else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 2)
-      {
-        printf(" [CRC:%s]", digestStr.c_str());
-      }
-      else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 3)
-      {
-        printf(" [Checksum:%s]", digestStr.c_str());
-      }
-    }
+    printHash(m_pcCfg->getDecodedPictureHashSEIType(), digestStr);
 
     if ( m_pcCfg->getUseRateCtrl() )
@@ -2051,4 +2134,11 @@
         m_pcRateCtrl->getRCGOP()->updateAfterPicture( estimatedBits );
       }
+#if U0132_TARGET_BITS_SATURATION
+      if (m_pcRateCtrl->getCpbSaturationEnabled())
+      {
+        m_pcRateCtrl->updateCpbState(actualTotalBits);
+        printf(" [CPB %6d bits]", m_pcRateCtrl->getCpbState());
+      }
+#endif
     }
 
@@ -2352,5 +2442,5 @@
   if (conversion!=IPCOLOURSPACE_UNCHANGED)
   {
-    cscd.create(pcPicD->getWidth(COMPONENT_Y), pcPicD->getHeight(COMPONENT_Y), pcPicD->getChromaFormat(), pcPicD->getWidth(COMPONENT_Y), pcPicD->getHeight(COMPONENT_Y), 0, false);
+    cscd.createWithoutCUInfo(pcPicD->getWidth(COMPONENT_Y), pcPicD->getHeight(COMPONENT_Y), pcPicD->getChromaFormat() );
     TVideoIOYuv::ColourSpaceConvert(*pcPicD, cscd, conversion, false);
   }
@@ -2452,5 +2542,5 @@
   }
 
-  Char c = (pcSlice->isIntra() ? 'I' : pcSlice->isInterP() ? 'P' : 'B');
+  TChar c = (pcSlice->isIntra() ? 'I' : pcSlice->isInterP() ? 'P' : 'B');
   if (!pcSlice->isReferenced())
   {
@@ -2506,4 +2596,6 @@
   printf(" [ET %5.0f ]", dEncTime );
 
+  // printf(" [WP %d]", pcSlice->getUseWeightedPrediction());
+
   for (Int iRefList = 0; iRefList < 2; iRefList++)
   {
@@ -2555,5 +2647,5 @@
     {
       TComPicYuv &reconField=*(apcPicRecFields[fieldNum]);
-      cscd[fieldNum].create(reconField.getWidth(COMPONENT_Y), reconField.getHeight(COMPONENT_Y), reconField.getChromaFormat(), reconField.getWidth(COMPONENT_Y), reconField.getHeight(COMPONENT_Y), 0, false);
+      cscd[fieldNum].createWithoutCUInfo(reconField.getWidth(COMPONENT_Y), reconField.getHeight(COMPONENT_Y), reconField.getChromaFormat() );
       TVideoIOYuv::ColourSpaceConvert(reconField, cscd[fieldNum], conversion, false);
       apcPicRecFields[fieldNum]=cscd+fieldNum;
Index: trunk/source/Lib/TLibEncoder/TEncGOP.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncGOP.h	(revision 1357)
+++ trunk/source/Lib/TLibEncoder/TEncGOP.h	(revision 1386)
@@ -220,4 +220,6 @@
   Double xCalculateRVM();
 
+  Void xWriteAccessUnitDelimiter (AccessUnit &accessUnit, TComSlice *slice);
+
   Void xCreateIRAPLeadingSEIMessages (SEIMessages& seiMessages, const TComSPS *sps, const TComPPS *pps);
   Void xCreatePerPictureSEIMessages (Int picInGOP, SEIMessages& seiMessages, SEIMessages& nestedSeiMessages, TComSlice *slice);
Index: trunk/source/Lib/TLibEncoder/TEncPreanalyzer.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncPreanalyzer.cpp	(revision 1357)
+++ trunk/source/Lib/TLibEncoder/TEncPreanalyzer.cpp	(revision 1386)
@@ -87,15 +87,14 @@
         UInt64 uiSum[4] = {0, 0, 0, 0};
         UInt64 uiSumSq[4] = {0, 0, 0, 0};
-        UInt uiNumPixInAQPart = 0;
         UInt by = 0;
         for ( ; by < uiCurrAQPartHeight>>1; by++ )
         {
           UInt bx = 0;
-          for ( ; bx < uiCurrAQPartWidth>>1; bx++, uiNumPixInAQPart++ )
+          for ( ; bx < uiCurrAQPartWidth>>1; bx++ )
           {
             uiSum  [0] += pBlkY[bx];
             uiSumSq[0] += pBlkY[bx] * pBlkY[bx];
           }
-          for ( ; bx < uiCurrAQPartWidth; bx++, uiNumPixInAQPart++ )
+          for ( ; bx < uiCurrAQPartWidth; bx++ )
           {
             uiSum  [1] += pBlkY[bx];
@@ -107,10 +106,10 @@
         {
           UInt bx = 0;
-          for ( ; bx < uiCurrAQPartWidth>>1; bx++, uiNumPixInAQPart++ )
+          for ( ; bx < uiCurrAQPartWidth>>1; bx++ )
           {
             uiSum  [2] += pBlkY[bx];
             uiSumSq[2] += pBlkY[bx] * pBlkY[bx];
           }
-          for ( ; bx < uiCurrAQPartWidth; bx++, uiNumPixInAQPart++ )
+          for ( ; bx < uiCurrAQPartWidth; bx++ )
           {
             uiSum  [3] += pBlkY[bx];
@@ -120,10 +119,23 @@
         }
 
+        assert ((uiCurrAQPartWidth&1)==0);
+        assert ((uiCurrAQPartHeight&1)==0);
+        const UInt pixelWidthOfQuadrants  = uiCurrAQPartWidth >>1;
+        const UInt pixelHeightOfQuadrants = uiCurrAQPartHeight>>1;
+        const UInt numPixInAQPart         = pixelWidthOfQuadrants * pixelHeightOfQuadrants;
+
         Double dMinVar = DBL_MAX;
+        if (numPixInAQPart!=0)
+        {
         for ( Int i=0; i<4; i++)
         {
-          const Double dAverage = Double(uiSum[i]) / uiNumPixInAQPart;
-          const Double dVariance = Double(uiSumSq[i]) / uiNumPixInAQPart - dAverage * dAverage;
+            const Double dAverage = Double(uiSum[i]) / numPixInAQPart;
+            const Double dVariance = Double(uiSumSq[i]) / numPixInAQPart - dAverage * dAverage;
           dMinVar = min(dMinVar, dVariance);
+        }
+        }
+        else
+        {
+          dMinVar = 0.0;
         }
         const Double dActivity = 1.0 + dMinVar;
Index: trunk/source/Lib/TLibEncoder/TEncRateCtrl.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncRateCtrl.cpp	(revision 1357)
+++ trunk/source/Lib/TLibEncoder/TEncRateCtrl.cpp	(revision 1386)
@@ -1639,4 +1639,10 @@
     m_encRCSeq->initLCUPara();
   }
+#if U0132_TARGET_BITS_SATURATION
+  m_CpbSaturationEnabled = false;
+  m_cpbSize              = targetBitrate;
+  m_cpbState             = (UInt)(m_cpbSize*0.5f);
+  m_bufferingRate        = (Int)(targetBitrate / frameRate);
+#endif
 
 #if KWU_RC_MADPRED_E0227
@@ -1664,4 +1670,34 @@
 }
 
+#if U0132_TARGET_BITS_SATURATION
+Int  TEncRateCtrl::updateCpbState(Int actualBits)
+{
+  Int cpbState = 1;
+
+  m_cpbState -= actualBits;
+  if (m_cpbState < 0)
+  {
+    cpbState = -1;
+  }
+
+  m_cpbState += m_bufferingRate;
+  if (m_cpbState > m_cpbSize)
+  {
+    cpbState = 0;
+  }
+
+  return cpbState;
+}
+
+Void TEncRateCtrl::initHrdParam(const TComHRD* pcHrd, Int iFrameRate, Double fInitialCpbFullness)
+{
+  m_CpbSaturationEnabled = true;
+  m_cpbSize = (pcHrd->getCpbSizeValueMinus1(0, 0, 0) + 1) << (4 + pcHrd->getCpbSizeScale());
+  m_cpbState = (UInt)(m_cpbSize*fInitialCpbFullness);
+  m_bufferingRate = (UInt)(((pcHrd->getBitRateValueMinus1(0, 0, 0) + 1) << (6 + pcHrd->getBitRateScale())) / iFrameRate);
+  printf("\nHRD - [Initial CPB state %6d] [CPB Size %6d] [Buffering Rate %6d]\n", m_cpbState, m_cpbSize, m_bufferingRate);
+}
+#endif
+
 Void TEncRateCtrl::destroyRCGOP()
 {
Index: trunk/source/Lib/TLibEncoder/TEncRateCtrl.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncRateCtrl.h	(revision 1357)
+++ trunk/source/Lib/TLibEncoder/TEncRateCtrl.h	(revision 1386)
@@ -285,4 +285,7 @@
   TRCLCU& getLCU( Int LCUIdx )                            { return m_LCUs[LCUIdx]; }
   Int  getPicActualHeaderBits()                           { return m_picActualHeaderBits; }
+#if U0132_TARGET_BITS_SATURATION
+  Void setBitLeft(Int bits)                               { m_bitsLeft = bits; }
+#endif
   Void setTargetBits( Int bits )                          { m_targetBits = bits; m_bitsLeft = bits;}
   Void setTotalIntraCost(Double cost)                     { m_totalCostIntra = cost; }
@@ -369,4 +372,13 @@
   Void setLayerID(Int layerid)     { m_LayerID = layerid; }
 #endif
+#if U0132_TARGET_BITS_SATURATION
+  Bool       getCpbSaturationEnabled()  { return m_CpbSaturationEnabled;  }
+  UInt       getCpbState()              { return m_cpbState;       }
+  UInt       getCpbSize()               { return m_cpbSize;        }
+  UInt       getBufferingRate()         { return m_bufferingRate;  }
+  Int        updateCpbState(Int actualBits);
+  Void       initHrdParam(const TComHRD* pcHrd, Int iFrameRate, Double fInitialCpbFullness);
+#endif
+
 private:
   TEncRCSeq* m_encRCSeq;
@@ -375,4 +387,11 @@
   list<TEncRCPic*> m_listRCPictures;
   Int        m_RCQP;
+#if U0132_TARGET_BITS_SATURATION
+  Bool       m_CpbSaturationEnabled;    // Enable target bits saturation to avoid CPB overflow and underflow
+  Int        m_cpbState;                // CPB State 
+  UInt       m_cpbSize;                 // CPB size
+  UInt       m_bufferingRate;           // Buffering rate
+#endif
+
 #if KWU_RC_MADPRED_E0227
   Int m_LayerID;
Index: trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp	(revision 1357)
+++ trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp	(revision 1386)
@@ -908,5 +908,5 @@
       m_signLineBuf1 = NULL;
     }
-    m_signLineBuf1 = new Char[m_lineBufWidth+1];
+    m_signLineBuf1 = new SChar[m_lineBufWidth+1];
 
     if (m_signLineBuf2)
@@ -915,9 +915,9 @@
       m_signLineBuf2 = NULL;
     }
-    m_signLineBuf2 = new Char[m_lineBufWidth+1];
+    m_signLineBuf2 = new SChar[m_lineBufWidth+1];
   }
 
   Int x,y, startX, startY, endX, endY, edgeType, firstLineStartX, firstLineEndX;
-  Char signLeft, signRight, signDown;
+  SChar signLeft, signRight, signDown;
   Int64 *diff, *count;
   Pel *srcLine, *orgLine;
@@ -949,8 +949,8 @@
         for (y=0; y<endY; y++)
         {
-          signLeft = (Char)sgn(srcLine[startX] - srcLine[startX-1]);
+          signLeft = (SChar)sgn(srcLine[startX] - srcLine[startX-1]);
           for (x=startX; x<endX; x++)
           {
-            signRight =  (Char)sgn(srcLine[x] - srcLine[x+1]);
+            signRight =  (SChar)sgn(srcLine[x] - srcLine[x+1]);
             edgeType  =  signRight + signLeft;
             signLeft  = -signRight;
@@ -971,8 +971,8 @@
             for(y=0; y<skipLinesB[typeIdx]; y++)
             {
-              signLeft = (Char)sgn(srcLine[startX] - srcLine[startX-1]);
+              signLeft = (SChar)sgn(srcLine[startX] - srcLine[startX-1]);
               for (x=startX; x<endX; x++)
               {
-                signRight =  (Char)sgn(srcLine[x] - srcLine[x+1]);
+                signRight =  (SChar)sgn(srcLine[x] - srcLine[x+1]);
                 edgeType  =  signRight + signLeft;
                 signLeft  = -signRight;
@@ -992,5 +992,5 @@
         diff +=2;
         count+=2;
-        Char *signUpLine = m_signLineBuf1;
+        SChar *signUpLine = m_signLineBuf1;
 
         startX = (!isCalculatePreDeblockSamples) ? 0
@@ -1011,5 +1011,5 @@
         for (x=startX; x<endX; x++)
         {
-          signUpLine[x] = (Char)sgn(srcLine[x] - srcLineAbove[x]);
+          signUpLine[x] = (SChar)sgn(srcLine[x] - srcLineAbove[x]);
         }
 
@@ -1021,5 +1021,5 @@
           for (x=startX; x<endX; x++)
           {
-            signDown  = (Char)sgn(srcLine[x] - srcLineBelow[x]); 
+            signDown  = (SChar)sgn(srcLine[x] - srcLineBelow[x]);
             edgeType  = signDown + signUpLine[x];
             signUpLine[x]= -signDown;
@@ -1061,5 +1061,5 @@
         diff +=2;
         count+=2;
-        Char *signUpLine, *signDownLine, *signTmpLine;
+        SChar *signUpLine, *signDownLine, *signTmpLine;
 
         signUpLine  = m_signLineBuf1;
@@ -1079,5 +1079,5 @@
         for (x=startX; x<endX+1; x++)
         {
-          signUpLine[x] = (Char)sgn(srcLineBelow[x] - srcLine[x-1]);
+          signUpLine[x] = (SChar)sgn(srcLineBelow[x] - srcLine[x-1]);
         }
 
@@ -1103,5 +1103,5 @@
           for (x=startX; x<endX; x++)
           {
-            signDown = (Char)sgn(srcLine[x] - srcLineBelow[x+1]);
+            signDown = (SChar)sgn(srcLine[x] - srcLineBelow[x+1]);
             edgeType = signDown + signUpLine[x];
             diff [edgeType] += (orgLine[x] - srcLine[x]);
@@ -1110,5 +1110,5 @@
             signDownLine[x+1] = -signDown;
           }
-          signDownLine[startX] = (Char)sgn(srcLineBelow[startX] - srcLine[startX-1]);
+          signDownLine[startX] = (SChar)sgn(srcLineBelow[startX] - srcLine[startX-1]);
 
           signTmpLine  = signUpLine;
@@ -1148,5 +1148,5 @@
         diff +=2;
         count+=2;
-        Char *signUpLine = m_signLineBuf1+1;
+        SChar *signUpLine = m_signLineBuf1+1;
 
         startX = (!isCalculatePreDeblockSamples) ? (isLeftAvail  ? 0 : 1)
@@ -1162,5 +1162,5 @@
         for (x=startX-1; x<endX; x++)
         {
-          signUpLine[x] = (Char)sgn(srcLineBelow[x] - srcLine[x+1]);
+          signUpLine[x] = (SChar)sgn(srcLineBelow[x] - srcLine[x+1]);
         }
 
@@ -1191,5 +1191,5 @@
           for(x=startX; x<endX; x++)
           {
-            signDown = (Char)sgn(srcLine[x] - srcLineBelow[x-1]);
+            signDown = (SChar)sgn(srcLine[x] - srcLineBelow[x-1]);
             edgeType = signDown + signUpLine[x];
 
@@ -1199,5 +1199,5 @@
             signUpLine[x-1] = -signDown;
           }
-          signUpLine[endX-1] = (Char)sgn(srcLineBelow[endX-1] - srcLine[endX]);
+          signUpLine[endX-1] = (SChar)sgn(srcLineBelow[endX-1] - srcLine[endX]);
           srcLine  += srcStride;
           orgLine  += orgStride;
Index: trunk/source/Lib/TLibEncoder/TEncSbac.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSbac.cpp	(revision 1357)
+++ trunk/source/Lib/TLibEncoder/TEncSbac.cpp	(revision 1386)
@@ -550,5 +550,5 @@
 
   xWriteUnaryMaxSymbol(iSymbol, m_cMVPIdxSCModel.get(0), 1, iNum-1);
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
 #if ENC_DEC_TRACE
   if ( eRefList == REF_PIC_LIST_0 )
@@ -606,5 +606,5 @@
     {
       m_pcBinIf->encodeBin( eSize == SIZE_2Nx2N? 1 : 0, m_cCUPartSizeSCModel.get( 0, 0, 0 ) );
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
       DTRACE_CU("part_mode", eSize == SIZE_2Nx2N? 1 : 0)
 #endif        
@@ -613,5 +613,5 @@
     return;
   }
-#if H_MV_ENC_DEC_TRAC          
+#if NH_MV_ENC_DEC_TRAC          
   DTRACE_CU("part_mode", eSize )
 #endif        
@@ -781,5 +781,5 @@
   // get context function is here
   m_pcBinIf->encodeBin( pcCU->isIntra( uiAbsPartIdx ) ? 1 : 0, m_cCUPredModeSCModel.get( 0, 0, 0 ) );
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
   DTRACE_CU("pred_mode_flag", pcCU->isIntra( uiAbsPartIdx ) ? 1 : 0); 
 #endif
@@ -791,5 +791,5 @@
   UInt uiSymbol = pcCU->getCUTransquantBypass(uiAbsPartIdx);
   m_pcBinIf->encodeBin( uiSymbol, m_CUTransquantBypassFlagSCModel.get( 0, 0, 0 ) );
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
   DTRACE_CU("cu_transquant_bypass_flag", uiSymbol); 
 #endif
@@ -808,5 +808,5 @@
   UInt uiCtxSkip = pcCU->getCtxSkipFlag( uiAbsPartIdx ) ;
   m_pcBinIf->encodeBin( uiSymbol, m_cCUSkipFlagSCModel.get( 0, 0, uiCtxSkip ) );
-#if !H_MV_ENC_DEC_TRAC
+#if !NH_MV_ENC_DEC_TRAC
   DTRACE_CABAC_VL( g_nSymbolCounter++ );
   DTRACE_CABAC_T( "\tSkipFlag" );
@@ -831,5 +831,5 @@
   m_pcBinIf->encodeBin( uiSymbol, *m_cCUMergeFlagExtSCModel.get( 0 ) );
 
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
   DTRACE_PU("merge_flag", uiSymbol); 
 #else
@@ -872,9 +872,9 @@
       }
     }
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
     DTRACE_PU("merge_idx", uiUnaryIdx); 
 #endif
   }
-#if !H_MV_ENC_DEC_TRAC
+#if !NH_MV_ENC_DEC_TRAC
   DTRACE_CABAC_VL( g_nSymbolCounter++ );
   DTRACE_CABAC_T( "\tparseMergeIndex()" );
@@ -899,5 +899,5 @@
      m_pcBinIf->encodeBin( ( iW == iMaxW ) ? 1 : 0, m_cCUPUARPWSCModel.get( 0, 0, 2 ) );
   }
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
   DTRACE_CU("iv_res_pred_weight_idx", iW); 
 #endif
@@ -916,5 +916,5 @@
   UInt uiSymbol = pcCU->getICFlag( uiAbsPartIdx ) ? 1 : 0;
   m_pcBinIf->encodeBin( uiSymbol, m_cCUICFlagSCModel.get( 0, 0, 0 ) );
-#if !H_MV_ENC_DEC_TRAC
+#if !NH_MV_ENC_DEC_TRAC
   DTRACE_CABAC_VL( g_nSymbolCounter++ );
   DTRACE_CABAC_T( "\tICFlag" );
@@ -971,5 +971,5 @@
 
   m_pcBinIf->encodeBin( uiCurrSplitFlag, m_cCUSplitFlagSCModel.get( 0, 0, uiCtx ) );
-#if !H_MV_ENC_DEC_TRAC
+#if !NH_MV_ENC_DEC_TRAC
   DTRACE_CABAC_VL( g_nSymbolCounter++ )
   DTRACE_CABAC_T( "\tSplitFlag\n" )
@@ -983,5 +983,5 @@
 {
   m_pcBinIf->encodeBin( uiSymbol, m_cCUTransSubdivFlagSCModel.get( 0, 0, uiCtx ) );
-#if !H_MV_ENC_DEC_TRAC
+#if !NH_MV_ENC_DEC_TRAC
   DTRACE_CABAC_VL( g_nSymbolCounter++ )
   DTRACE_CABAC_T( "\tparseTransformSubdivFlag()" )
@@ -1027,5 +1027,5 @@
     }
     m_pcBinIf->encodeBin((predIdx[j] != -1)? 1 : 0, m_cCUIntraPredSCModel.get( 0, 0, 0 ) );
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
       DTRACE_CU("prev_intra_luma_pred_flag", (predIdx[j] != -1)? 1 : 0); 
 #endif
@@ -1048,5 +1048,5 @@
         m_pcBinIf->encodeBinEP( predIdx[j]-1 );
       }
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
         DTRACE_CU("mpm_idx", predIdx[j] ); 
 #endif
@@ -1071,5 +1071,5 @@
       }
       m_pcBinIf->encodeBinsEP( dir[j], 5 );
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
         DTRACE_CU("rem_intra_luma_pred_mode", dir[j] ); 
 #endif
@@ -1089,5 +1089,5 @@
   {
     m_pcBinIf->encodeBin( 0, m_cCUChromaPredSCModel.get( 0, 0, 0 ) );
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
     DTRACE_CU("intra_chroma_pred_mode", 0 ); 
 #endif
@@ -1110,5 +1110,5 @@
 
     m_pcBinIf->encodeBinsEP( uiIntraDirChroma, 2 );
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
     DTRACE_CU("intra_chroma_pred_mode", uiIntraDirChroma ); 
 #endif
@@ -1134,5 +1134,5 @@
     m_pcBinIf->encodeBin( uiInterDir, *( pCtx + 4 ) );
   }
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
   DTRACE_PU("inter_pred_idc", uiInterDir ); 
 #endif
@@ -1169,5 +1169,5 @@
     }
   }
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
 #if ENC_DEC_TRACE
     iRefFrame = pcCU->getCUMvField( eRefList )->getRefIdx( uiAbsPartIdx ); 
@@ -1366,5 +1366,5 @@
 
       m_pcBinIf->encodeBin(uiCbf, m_cCUQtCbfSCModel.get(0, contextSet, uiCtx));
-#if !H_MV_ENC_DEC_TRAC
+#if !NH_MV_ENC_DEC_TRAC
       DTRACE_CABAC_VL( g_nSymbolCounter++ )
       DTRACE_CABAC_T( "\tparseQtCbf()" )
@@ -1400,5 +1400,5 @@
     const UInt uiCbf = pcCU->getCbf( absPartIdx, compID, lowestTUDepth );
     m_pcBinIf->encodeBin( uiCbf , m_cCUQtCbfSCModel.get( 0, contextSet, uiCtx ) );
-#if !H_MV_ENC_DEC_TRAC
+#if !NH_MV_ENC_DEC_TRAC
     DTRACE_CABAC_VL( g_nSymbolCounter++ )
     DTRACE_CABAC_T( "\tparseQtCbf()" )
@@ -1448,5 +1448,5 @@
   UInt useTransformSkip = pcCU->getTransformSkip( uiAbsPartIdx,component);
   m_pcBinIf->encodeBin( useTransformSkip, m_cTransformSkipSCModel.get( 0, toChannelType(component), 0 ) );
-#if !H_MV_ENC_DEC_TRAC
+#if !NH_MV_ENC_DEC_TRAC
   DTRACE_CABAC_VL( g_nSymbolCounter++ )
   DTRACE_CABAC_T("\tparseTransformSkip()");
@@ -1476,5 +1476,5 @@
 
   m_pcBinIf->encodeBinTrm (uiIPCM);
-#if H_MV_ENC_DEC_TRAC          
+#if NH_MV_ENC_DEC_TRAC          
   DTRACE_CU("pcm_flag", uiIPCM)
 #endif
@@ -1512,5 +1512,5 @@
   UInt uiCtx = 0;
   m_pcBinIf->encodeBin( uiCbf , m_cCUQtRootCbfSCModel.get( 0, 0, uiCtx ) );
-#if !H_MV_ENC_DEC_TRAC
+#if !NH_MV_ENC_DEC_TRAC
   DTRACE_CABAC_VL( g_nSymbolCounter++ )
   DTRACE_CABAC_T( "\tparseQtRootCbf()" )
@@ -1629,5 +1629,5 @@
   const UInt uiHeight=tuRect.height;
   const TComSPS &sps=*(pcCU->getSlice()->getSPS());
-#if !H_MV_ENC_DEC_TRAC
+#if !NH_MV_ENC_DEC_TRAC
 
   DTRACE_CABAC_VL( g_nSymbolCounter++ )
@@ -2526,5 +2526,5 @@
 Void TEncSbac::xCodeDeltaDC( Pel valDeltaDC, UInt uiNumSeg )
 {
-#if ENC_DEC_TRACE && H_MV_ENC_DEC_TRAC
+#if ENC_DEC_TRACE && NH_MV_ENC_DEC_TRAC
   DTRACE_CU("delta_dc", valDeltaDC);
 #endif
@@ -2618,5 +2618,5 @@
 {
   UInt uiSymbol = pcCU->getSDCFlag( uiAbsPartIdx ) ? 1 : 0;
-#if ENC_DEC_TRACE && H_MV_ENC_DEC_TRAC
+#if ENC_DEC_TRACE && NH_MV_ENC_DEC_TRAC
   DTRACE_CU("dc_only_flag", uiSymbol)
 #endif
Index: trunk/source/Lib/TLibEncoder/TEncSearch.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSearch.cpp	(revision 1357)
+++ trunk/source/Lib/TLibEncoder/TEncSearch.cpp	(revision 1386)
@@ -74,11 +74,4 @@
 };
 
-static const UInt s_auiDFilter[9] =
-{
-  0, 1, 0,
-  2, 3, 2,
-  0, 1, 0
-};
-
 static Void offsetSubTUCBFs(TComTU &rTu, const ComponentID compID)
 {
@@ -120,9 +113,8 @@
 , m_iSearchRange (0)
 , m_bipredSearchRange (0)
-, m_iFastSearch (0)
+, m_motionEstimationSearchMethod (MESEARCH_FULL)
 , m_pppcRDSbacCoder (NULL)
 , m_pcRDGoOnSbacCoder (NULL)
 , m_pTempPel (NULL)
-, m_puiDFilter (NULL)
 , m_isInitialized (false)
 {
@@ -130,8 +122,6 @@
   {
     m_ppcQTTempCoeff[ch]                           = NULL;
-    m_pcQTTempCoeff[ch]                            = NULL;
 #if ADAPTIVE_QP_SELECTION
     m_ppcQTTempArlCoeff[ch]                        = NULL;
-    m_pcQTTempArlCoeff[ch]                         = NULL;
 #endif
     m_puhQTTempCbf[ch]                             = NULL;
@@ -181,9 +171,7 @@
       }
       delete[] m_ppcQTTempCoeff[ch];
-      delete[] m_pcQTTempCoeff[ch];
       delete[] m_puhQTTempCbf[ch];
 #if ADAPTIVE_QP_SELECTION
       delete[] m_ppcQTTempArlCoeff[ch];
-      delete[] m_pcQTTempArlCoeff[ch];
 #endif
     }
@@ -229,5 +217,5 @@
                       Int           iSearchRange,
                       Int           bipredSearchRange,
-                      Int           iFastSearch,
+                      MESearchMethod motionEstimationSearchMethod,
                       const UInt    maxCUWidth,
                       const UInt    maxCUHeight,
@@ -244,5 +232,5 @@
   m_iSearchRange         = iSearchRange;
   m_bipredSearchRange    = bipredSearchRange;
-  m_iFastSearch          = iFastSearch;
+  m_motionEstimationSearchMethod = motionEstimationSearchMethod;
   m_pcEntropyCoder       = pcEntropyCoder;
   m_pcRdCost             = pcRdCost;
@@ -258,6 +246,4 @@
     }
   }
-
-  m_puiDFilter = s_auiDFilter + 4;
 
   // initialize motion cost
@@ -289,8 +275,6 @@
     const UInt csy=::getComponentScaleY(ComponentID(ch), cform);
     m_ppcQTTempCoeff[ch] = new TCoeff* [uiNumLayersToAllocate];
-    m_pcQTTempCoeff[ch]   = new TCoeff [(maxCUWidth*maxCUHeight)>>(csx+csy)   ];
 #if ADAPTIVE_QP_SELECTION
     m_ppcQTTempArlCoeff[ch]  = new TCoeff*[uiNumLayersToAllocate];
-    m_pcQTTempArlCoeff[ch]   = new TCoeff [(maxCUWidth*maxCUHeight)>>(csx+csy)   ];
 #endif
     m_puhQTTempCbf[ch] = new UChar  [uiNumPartitions];
@@ -304,5 +288,5 @@
     }
 
-    m_phQTTempCrossComponentPredictionAlpha[ch]    = new Char  [uiNumPartitions];
+    m_phQTTempCrossComponentPredictionAlpha[ch]    = new SChar  [uiNumPartitions];
     m_pSharedPredTransformSkip[ch]                 = new Pel   [MAX_CU_SIZE*MAX_CU_SIZE];
     m_pcQTTempTUCoeff[ch]                          = new TCoeff[MAX_CU_SIZE*MAX_CU_SIZE];
@@ -323,46 +307,13 @@
 }
 
-#define TZ_SEARCH_CONFIGURATION                                                                                 \
-const Int  iRaster                  = 5;  /* TZ soll von aussen ?ergeben werden */                            \
-const Bool bTestOtherPredictedMV    = 0;                                                                      \
-const Bool bTestZeroVector          = 1;                                                                      \
-const Bool bTestZeroVectorStart     = 0;                                                                      \
-const Bool bTestZeroVectorStop      = 0;                                                                      \
-const Bool bFirstSearchDiamond      = 1;  /* 1 = xTZ8PointDiamondSearch   0 = xTZ8PointSquareSearch */        \
-const Bool bFirstSearchStop         = m_pcEncCfg->getFastMEAssumingSmootherMVEnabled();                       \
-const UInt uiFirstSearchRounds      = 3;  /* first search stop X rounds after best match (must be >=1) */     \
-const Bool bEnableRasterSearch      = 1;                                                                      \
-const Bool bAlwaysRasterSearch      = 0;  /* ===== 1: BETTER but factor 2 slower ===== */                     \
-const Bool bRasterRefinementEnable  = 0;  /* enable either raster refinement or star refinement */            \
-const Bool bRasterRefinementDiamond = 0;  /* 1 = xTZ8PointDiamondSearch   0 = xTZ8PointSquareSearch */        \
-const Bool bStarRefinementEnable    = 1;  /* enable either star refinement or raster refinement */            \
-const Bool bStarRefinementDiamond   = 1;  /* 1 = xTZ8PointDiamondSearch   0 = xTZ8PointSquareSearch */        \
-const Bool bStarRefinementStop      = 0;                                                                      \
-const UInt uiStarRefinementRounds   = 2;  /* star refinement stop X rounds after best match (must be >=1) */  \
-
-
-#define SEL_SEARCH_CONFIGURATION                                                                                 \
-  const Bool bTestOtherPredictedMV    = 1;                                                                       \
-  const Bool bTestZeroVector          = 1;                                                                       \
-  const Bool bEnableRasterSearch      = 1;                                                                       \
-  const Bool bAlwaysRasterSearch      = 0;  /* ===== 1: BETTER but factor 15x slower ===== */                    \
-  const Bool bStarRefinementEnable    = 1;  /* enable either star refinement or raster refinement */             \
-  const Bool bStarRefinementDiamond   = 1;  /* 1 = xTZ8PointDiamondSearch   0 = xTZ8PointSquareSearch */         \
-  const Bool bStarRefinementStop      = 0;                                                                       \
-  const UInt uiStarRefinementRounds   = 2;  /* star refinement stop X rounds after best match (must be >=1) */   \
-  const UInt uiSearchRange            = m_iSearchRange;                                                          \
-  const Int  uiSearchRangeInitial     = m_iSearchRange >> 2;                                                     \
-  const Int  uiSearchStep             = 4;                                                                       \
-  const Int  iMVDistThresh            = 8;                                                                       \
-
-
-
-__inline Void TEncSearch::xTZSearchHelp( TComPattern* pcPatternKey, IntTZSearchStruct& rcStruct, const Int iSearchX, const Int iSearchY, const UChar ucPointNr, const UInt uiDistance )
+
+
+
+__inline Void TEncSearch::xTZSearchHelp( const TComPattern* const pcPatternKey, IntTZSearchStruct& rcStruct, const Int iSearchX, const Int iSearchY, const UChar ucPointNr, const UInt uiDistance )
 {
   Distortion  uiSad = 0;
 
-  Pel*  piRefSrch;
-
-  piRefSrch = rcStruct.piRefY + iSearchY * rcStruct.iYStride + iSearchX;
+  const Pel* const  piRefSrch = rcStruct.piRefY + iSearchY * rcStruct.iYStride + iSearchX;
+
 #if NH_3D_IC
   m_cDistParam.bUseIC = pcPatternKey->getICFlag();
@@ -374,26 +325,19 @@
   m_pcRdCost->setDistParam( pcPatternKey, piRefSrch, rcStruct.iYStride,  m_cDistParam );
 
-  if(m_pcEncCfg->getFastSearch() != SELECTIVE)
-  {
-    // fast encoder decision: use subsampled SAD when rows > 8 for integer ME
-    if ( m_pcEncCfg->getUseFastEnc() )
-    {
-      if ( m_cDistParam.iRows > 8 )
-      {
-        m_cDistParam.iSubShift = 1;
-      }
-    }
-  }
-
   setDistParamComp(COMPONENT_Y);
 
   // distortion
   m_cDistParam.bitDepth = pcPatternKey->getBitDepthY();
-  if(m_pcEncCfg->getFastSearch() == SELECTIVE)
+  m_cDistParam.m_maximumDistortionForEarlyExit = rcStruct.uiBestSad;
+
+  if((m_pcEncCfg->getRestrictMESampling() == false) && m_pcEncCfg->getMotionEstimationSearchMethod() == MESEARCH_SELECTIVE)
   {
     Int isubShift = 0;
     // motion cost
-    Distortion uiBitCost = m_pcRdCost->getCost( iSearchX, iSearchY );
-
+    Distortion uiBitCost = m_pcRdCost->getCostOfVectorWithPredictor( iSearchX, iSearchY );
+
+    // Skip search if bit cost is already larger than best SAD
+    if (uiBitCost < rcStruct.uiBestSad)
+    {
     if ( m_cDistParam.iRows > 32 )
     {
@@ -443,4 +387,6 @@
           rcStruct.uiBestRound    = 0;
           rcStruct.ucPointNr      = ucPointNr;
+            m_cDistParam.m_maximumDistortionForEarlyExit = uiSad;
+          }
         }
       }
@@ -449,8 +395,21 @@
   else
   {
+    // fast encoder decision: use subsampled SAD when rows > 8 for integer ME
+    if ( m_pcEncCfg->getFastInterSearchMode()==FASTINTERSEARCH_MODE1 || m_pcEncCfg->getFastInterSearchMode()==FASTINTERSEARCH_MODE3 )
+    {
+      if ( m_cDistParam.iRows > 8 )
+      {
+        m_cDistParam.iSubShift = 1;
+      }
+    }
+
     uiSad = m_cDistParam.DistFunc( &m_cDistParam );
 
+    // only add motion cost if uiSad is smaller than best. Otherwise pointless
+    // to add motion cost.
+    if( uiSad < rcStruct.uiBestSad )
+    {
     // motion cost
-    uiSad += m_pcRdCost->getCost( iSearchX, iSearchY );
+      uiSad += m_pcRdCost->getCostOfVectorWithPredictor( iSearchX, iSearchY );
 
     if( uiSad < rcStruct.uiBestSad )
@@ -462,4 +421,6 @@
       rcStruct.uiBestRound    = 0;
       rcStruct.ucPointNr      = ucPointNr;
+        m_cDistParam.m_maximumDistortionForEarlyExit = uiSad;
+      }
     }
   }
@@ -469,5 +430,5 @@
 
 
-__inline Void TEncSearch::xTZ2PointSearch( TComPattern* pcPatternKey, IntTZSearchStruct& rcStruct, TComMv* pcMvSrchRngLT, TComMv* pcMvSrchRngRB )
+__inline Void TEncSearch::xTZ2PointSearch( const TComPattern* const pcPatternKey, IntTZSearchStruct& rcStruct, const TComMv* const pcMvSrchRngLT, const TComMv* const pcMvSrchRngRB )
 {
   Int   iSrchRngHorLeft   = pcMvSrchRngLT->getHor();
@@ -602,10 +563,10 @@
 
 
-__inline Void TEncSearch::xTZ8PointSquareSearch( TComPattern* pcPatternKey, IntTZSearchStruct& rcStruct, TComMv* pcMvSrchRngLT, TComMv* pcMvSrchRngRB, const Int iStartX, const Int iStartY, const Int iDist )
+__inline Void TEncSearch::xTZ8PointSquareSearch( const TComPattern* const pcPatternKey, IntTZSearchStruct& rcStruct, const TComMv* const pcMvSrchRngLT, const TComMv* const pcMvSrchRngRB, const Int iStartX, const Int iStartY, const Int iDist )
 {
-  Int   iSrchRngHorLeft   = pcMvSrchRngLT->getHor();
-  Int   iSrchRngHorRight  = pcMvSrchRngRB->getHor();
-  Int   iSrchRngVerTop    = pcMvSrchRngLT->getVer();
-  Int   iSrchRngVerBottom = pcMvSrchRngRB->getVer();
+  const Int   iSrchRngHorLeft   = pcMvSrchRngLT->getHor();
+  const Int   iSrchRngHorRight  = pcMvSrchRngRB->getHor();
+  const Int   iSrchRngVerTop    = pcMvSrchRngLT->getVer();
+  const Int   iSrchRngVerBottom = pcMvSrchRngRB->getVer();
 
   // 8 point search,                   //   1 2 3
@@ -660,10 +621,17 @@
 
 
-__inline Void TEncSearch::xTZ8PointDiamondSearch( TComPattern* pcPatternKey, IntTZSearchStruct& rcStruct, TComMv* pcMvSrchRngLT, TComMv* pcMvSrchRngRB, const Int iStartX, const Int iStartY, const Int iDist )
+__inline Void TEncSearch::xTZ8PointDiamondSearch( const TComPattern*const  pcPatternKey,
+                                                  IntTZSearchStruct& rcStruct,
+                                                  const TComMv*const  pcMvSrchRngLT,
+                                                  const TComMv*const  pcMvSrchRngRB,
+                                                  const Int iStartX,
+                                                  const Int iStartY,
+                                                  const Int iDist,
+                                                  const Bool bCheckCornersAtDist1 )
 {
-  Int   iSrchRngHorLeft   = pcMvSrchRngLT->getHor();
-  Int   iSrchRngHorRight  = pcMvSrchRngRB->getHor();
-  Int   iSrchRngVerTop    = pcMvSrchRngLT->getVer();
-  Int   iSrchRngVerBottom = pcMvSrchRngRB->getVer();
+  const Int   iSrchRngHorLeft   = pcMvSrchRngLT->getHor();
+  const Int   iSrchRngHorRight  = pcMvSrchRngRB->getHor();
+  const Int   iSrchRngVerTop    = pcMvSrchRngLT->getVer();
+  const Int   iSrchRngVerBottom = pcMvSrchRngRB->getVer();
 
   // 8 point search,                   //   1 2 3
@@ -677,10 +645,25 @@
   rcStruct.uiBestRound += 1;
 
-  if ( iDist == 1 ) // iDist == 1
+  if ( iDist == 1 )
   {
     if ( iTop >= iSrchRngVerTop ) // check top
     {
+      if (bCheckCornersAtDist1)
+      {
+        if ( iLeft >= iSrchRngHorLeft) // check top-left
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iLeft, iTop, 1, iDist );
+        }
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iTop, 2, iDist );
+        if ( iRight <= iSrchRngHorRight ) // check middle right
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iRight, iTop, 3, iDist );
+        }
+      }
+      else
+      {
       xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iTop, 2, iDist );
     }
+    }
     if ( iLeft >= iSrchRngHorLeft ) // check middle left
     {
@@ -693,8 +676,23 @@
     if ( iBottom <= iSrchRngVerBottom ) // check bottom
     {
+      if (bCheckCornersAtDist1)
+      {
+        if ( iLeft >= iSrchRngHorLeft) // check top-left
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iLeft, iBottom, 6, iDist );
+        }
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iBottom, 7, iDist );
+        if ( iRight <= iSrchRngHorRight ) // check middle right
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iRight, iBottom, 8, iDist );
+        }
+      }
+      else
+      {
       xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iBottom, 7, iDist );
     }
   }
-  else // if (iDist != 1)
+  }
+  else
   {
     if ( iDist <= 8 )
@@ -770,8 +768,8 @@
         for ( Int index = 1; index < 4; index++ )
         {
-          Int iPosYT = iTop    + ((iDist>>2) * index);
-          Int iPosYB = iBottom - ((iDist>>2) * index);
-          Int iPosXL = iStartX - ((iDist>>2) * index);
-          Int iPosXR = iStartX + ((iDist>>2) * index);
+          const Int iPosYT = iTop    + ((iDist>>2) * index);
+          const Int iPosYB = iBottom - ((iDist>>2) * index);
+          const Int iPosXL = iStartX - ((iDist>>2) * index);
+          const Int iPosXR = iStartX + ((iDist>>2) * index);
           xTZSearchHelp( pcPatternKey, rcStruct, iPosXL, iPosYT, 0, iDist );
           xTZSearchHelp( pcPatternKey, rcStruct, iPosXR, iPosYT, 0, iDist );
@@ -800,8 +798,8 @@
         for ( Int index = 1; index < 4; index++ )
         {
-          Int iPosYT = iTop    + ((iDist>>2) * index);
-          Int iPosYB = iBottom - ((iDist>>2) * index);
-          Int iPosXL = iStartX - ((iDist>>2) * index);
-          Int iPosXR = iStartX + ((iDist>>2) * index);
+          const Int iPosYT = iTop    + ((iDist>>2) * index);
+          const Int iPosYB = iBottom - ((iDist>>2) * index);
+          const Int iPosXL = iStartX - ((iDist>>2) * index);
+          const Int iPosXR = iStartX + ((iDist>>2) * index);
 
           if ( iPosYT >= iSrchRngVerTop ) // check top
@@ -833,10 +831,4 @@
 }
 
-
-
-
-
-//<--
-
 Distortion TEncSearch::xPatternRefinement( TComPattern* pcPatternKey,
                                            TComMv baseRefMv,
@@ -886,5 +878,5 @@
     m_cDistParam.bitDepth = pcPatternKey->getBitDepthY();
     uiDist = m_cDistParam.DistFunc( &m_cDistParam );
-    uiDist += m_pcRdCost->getCost( cMvTest.getHor(), cMvTest.getVer() );
+    uiDist += m_pcRdCost->getCostOfVectorWithPredictor( cMvTest.getHor(), cMvTest.getVer() );
 
     if ( uiDist < uiDistBest )
@@ -892,4 +884,5 @@
       uiDistBest  = uiDist;
       uiDirecBest = i;
+      m_cDistParam.m_maximumDistortionForEarlyExit = uiDist;
     }
   }
@@ -2410,5 +2403,5 @@
 }
 
-Char
+SChar
 TEncSearch::xCalcCrossComponentPredictionAlpha(       TComTU &rTu,
                                                 const ComponentID compID,
@@ -2427,5 +2420,5 @@
   const Int diffBitDepth = pCU->getSlice()->getSPS()->getDifferentialLumaChromaBitDepth();
 
-  Char alpha = 0;
+  SChar alpha = 0;
   Int SSxy  = 0;
   Int SSxx  = 0;
@@ -2447,7 +2440,7 @@
   {
     Double dAlpha = SSxy / Double( SSxx );
-    alpha = Char(Clip3<Int>(-16, 16, (Int)(dAlpha * 16)));
-
-    static const Char alphaQuant[17] = {0, 1, 1, 2, 2, 2, 4, 4, 4, 4, 4, 4, 8, 8, 8, 8, 8};
+    alpha = SChar(Clip3<Int>(-16, 16, (Int)(dAlpha * 16)));
+
+    static const SChar alphaQuant[17] = {0, 1, 1, 2, 2, 2, 4, 4, 4, 4, 4, 4, 8, 8, 8, 8, 8};
 
     alpha = (alpha < 0) ? -alphaQuant[Int(-alpha)] : alphaQuant[Int(alpha)];
@@ -2540,5 +2533,5 @@
         Double     singleCostTmp             = 0;
         UInt       singleCbfCTmp             = 0;
-        Char       bestCrossCPredictionAlpha = 0;
+        SChar      bestCrossCPredictionAlpha = 0;
         Int        bestTransformSkipMode     = 0;
 
@@ -3689,5 +3682,5 @@
               ::memcpy( m_puhQTTempCbf[compID], pcCU->getCbf( compID )+uiPartOffset, uiQPartNum * sizeof( UChar ) );
               ::memcpy( m_puhQTTempTransformSkipFlag[compID], pcCU->getTransformSkip( compID )+uiPartOffset, uiQPartNum * sizeof( UChar ) );
-              ::memcpy( m_phQTTempCrossComponentPredictionAlpha[compID], pcCU->getCrossComponentPredictionAlpha(compID)+uiPartOffset, uiQPartNum * sizeof( Char ) );
+              ::memcpy( m_phQTTempCrossComponentPredictionAlpha[compID], pcCU->getCrossComponentPredictionAlpha(compID)+uiPartOffset, uiQPartNum * sizeof( SChar ) );
             }
           }
@@ -3702,5 +3695,5 @@
           ::memcpy( pcCU->getCbf( compID )+uiPartOffset, m_puhQTTempCbf[compID], uiQPartNum * sizeof( UChar ) );
           ::memcpy( pcCU->getTransformSkip( compID )+uiPartOffset, m_puhQTTempTransformSkipFlag[compID], uiQPartNum * sizeof( UChar ) );
-          ::memcpy( pcCU->getCrossComponentPredictionAlpha(compID)+uiPartOffset, m_phQTTempCrossComponentPredictionAlpha[compID], uiQPartNum * sizeof( Char ) );
+          ::memcpy( pcCU->getCrossComponentPredictionAlpha(compID)+uiPartOffset, m_phQTTempCrossComponentPredictionAlpha[compID], uiQPartNum * sizeof( SChar ) );
         }
       }
@@ -3812,5 +3805,5 @@
 {
   UInt        uiDepth      = pcCU->getDepth(0);
-  const UInt  uiDistortion = 0;
+  const Distortion  uiDistortion = 0;
   UInt        uiBits;
 
@@ -4325,5 +4318,5 @@
             /*correct the bit-rate part of the current ref*/
             m_pcRdCost->setPredictor  ( cMvPred[iRefList][iRefIdxTemp] );
-            uiBitsTemp += m_pcRdCost->getBits( cMvTemp[1][iRefIdxTemp].getHor(), cMvTemp[1][iRefIdxTemp].getVer() );
+            uiBitsTemp += m_pcRdCost->getBitsOfVectorWithPredictor( cMvTemp[1][iRefIdxTemp].getHor(), cMvTemp[1][iRefIdxTemp].getVer() );
             /*calculate the correct cost*/
             uiCostTemp += m_pcRdCost->getCost( uiBitsTemp );
@@ -4374,5 +4367,5 @@
     }
 
-    //  Bi-directional prediction
+    //  Bi-predictive Motion estimation
     if ( (pcCU->getSlice()->isInterB()) && (pcCU->isBipredRestriction(iPartIdx) == false) )
     {
@@ -4429,5 +4422,5 @@
 
       // fast encoder setting: only one iteration
-      if ( m_pcEncCfg->getUseFastEnc() || pcCU->getSlice()->getMvdL1ZeroFlag())
+      if ( m_pcEncCfg->getFastInterSearchMode()==FASTINTERSEARCH_MODE1 || m_pcEncCfg->getFastInterSearchMode()==FASTINTERSEARCH_MODE2 || pcCU->getSlice()->getMvdL1ZeroFlag() )
       {
         iNumIter = 1;
@@ -4438,5 +4431,5 @@
         Int         iRefList    = iIter % 2;
 
-        if ( m_pcEncCfg->getUseFastEnc() )
+        if ( m_pcEncCfg->getFastInterSearchMode()==FASTINTERSEARCH_MODE1 || m_pcEncCfg->getFastInterSearchMode()==FASTINTERSEARCH_MODE2 )
         {
           if( uiCost[0] <= uiCost[1] )
@@ -4629,5 +4622,5 @@
       TComMvField cMEMvField[2];
 
-      m_pcRdCost->getMotionCost( true, 0, pcCU->getCUTransquantBypass(uiPartAddr) );
+      m_pcRdCost->selectMotionLambda( true, 0, pcCU->getCUTransquantBypass(uiPartAddr) );
 
 #if AMP_MRG
@@ -4652,6 +4645,6 @@
       // save ME result.
       uiMEInterDir = pcCU->getInterDir( uiPartAddr );
-      pcCU->getMvField( pcCU, uiPartAddr, REF_PIC_LIST_0, cMEMvField[0] );
-      pcCU->getMvField( pcCU, uiPartAddr, REF_PIC_LIST_1, cMEMvField[1] );
+      TComDataCU::getMvField( pcCU, uiPartAddr, REF_PIC_LIST_0, cMEMvField[0] );
+      TComDataCU::getMvField( pcCU, uiPartAddr, REF_PIC_LIST_1, cMEMvField[1] );
 
       // find Merge result
@@ -5040,5 +5033,5 @@
   }
 
-  m_pcRdCost->getMotionCost( true, 0, pcCU->getCUTransquantBypass(0) );
+  m_pcRdCost->selectMotionLambda( true, 0, pcCU->getCUTransquantBypass(0) );
   m_pcRdCost->setCostScale ( 0    );
 
@@ -5046,5 +5039,5 @@
 
   m_pcRdCost->setPredictor( rcMvPred );
-  Int iOrgMvBits  = m_pcRdCost->getBits(cMv.getHor(), cMv.getVer());
+  Int iOrgMvBits  = m_pcRdCost->getBitsOfVectorWithPredictor(cMv.getHor(), cMv.getVer());
   iOrgMvBits += m_auiMVPIdxCost[riMVPIdx][AMVP_MAX_NUM_CANDS];
   Int iBestMvBits = iOrgMvBits;
@@ -5059,5 +5052,5 @@
     m_pcRdCost->setPredictor( pcAMVPInfo->m_acMvCand[iMVPIdx] );
 
-    Int iMvBits = m_pcRdCost->getBits(cMv.getHor(), cMv.getVer());
+    Int iMvBits = m_pcRdCost->getBitsOfVectorWithPredictor(cMv.getHor(), cMv.getVer());
     iMvBits += m_auiMVPIdxCost[iMVPIdx][AMVP_MAX_NUM_CANDS];
 
@@ -5134,5 +5127,5 @@
 
   uiCost = m_pcRdCost->getDistPart( pcCU->getSlice()->getSPS()->getBitDepth(CHANNEL_TYPE_LUMA), pcTemplateCand->getAddr(COMPONENT_Y, uiPartAddr), pcTemplateCand->getStride(COMPONENT_Y), pcOrgYuv->getAddr(COMPONENT_Y, uiPartAddr), pcOrgYuv->getStride(COMPONENT_Y), iSizeX, iSizeY, COMPONENT_Y, DF_SAD );
-  uiCost = (UInt) m_pcRdCost->calcRdCost( m_auiMVPIdxCost[iMVPIdx][iMVPNum], uiCost, false, DF_SAD );
+  uiCost = (UInt) m_pcRdCost->calcRdCost( m_auiMVPIdxCost[iMVPIdx][iMVPNum], uiCost, DF_SAD );
   return uiCost;
 }
@@ -5176,5 +5169,5 @@
 #endif
 
-  if ( bBi )
+  if ( bBi ) // Bipredictive ME
   {
     TComYuv*  pcYuvOther = &m_acYuvPred[1-(Int)eRefPicList];
@@ -5187,4 +5180,5 @@
     fWeight = 0.5;
   }
+  m_cDistParam.bIsBiPred = bBi;
 
   //  Search key pattern initialization
@@ -5212,5 +5206,5 @@
   }
 
-  m_pcRdCost->getMotionCost( true, 0, pcCU->getCUTransquantBypass(uiPartAddr) );
+  m_pcRdCost->selectMotionLambda( true, 0, pcCU->getCUTransquantBypass(uiPartAddr) );
 
   m_pcRdCost->setPredictor  ( *pcMvPred );
@@ -5231,5 +5225,5 @@
   setWpScalingDistParam( pcCU, iRefIdxPred, eRefPicList );
   //  Do integer search
-  if ( !m_iFastSearch || bBi )
+  if ( (m_motionEstimationSearchMethod==MESEARCH_FULL) || bBi )
   {
     xPatternSearch      ( pcPatternKey, piRefY, iRefStride, &cMvSrchRngLT, &cMvSrchRngRB, rcMv, ruiCost );
@@ -5250,5 +5244,5 @@
   }
 
-  m_pcRdCost->getMotionCost( true, 0, pcCU->getCUTransquantBypass(uiPartAddr) );
+  m_pcRdCost->selectMotionLambda( true, 0, pcCU->getCUTransquantBypass(uiPartAddr) );
 #if NH_3D_INTEGER_MV_DEPTH
   if( ! pcCU->getSlice()->getIsDepth() )
@@ -5268,5 +5262,5 @@
 #endif
 
-  UInt uiMvBits = m_pcRdCost->getBits( rcMv.getHor(), rcMv.getVer() );
+  UInt uiMvBits = m_pcRdCost->getBitsOfVectorWithPredictor( rcMv.getHor(), rcMv.getVer() );
 #if NH_3D_INTEGER_MV_DEPTH
   if( pcCU->getSlice()->getIsDepth() )
@@ -5285,5 +5279,6 @@
 
 
-Void TEncSearch::xSetSearchRange ( TComDataCU* pcCU, TComMv& cMvPred, Int iSrchRng, TComMv& rcMvSrchRngLT, TComMv& rcMvSrchRngRB )
+Void TEncSearch::xSetSearchRange ( const TComDataCU* const pcCU, const TComMv& cMvPred, const Int iSrchRng,
+                                   TComMv& rcMvSrchRngLT, TComMv& rcMvSrchRngRB )
 {
   Int  iMvShift = 2;
@@ -5317,12 +5312,21 @@
   pcCU->clipMv        ( rcMvSrchRngRB );
 
+#if ME_ENABLE_ROUNDING_OF_MVS
+  rcMvSrchRngLT.divideByPowerOf2(iMvShift);
+  rcMvSrchRngRB.divideByPowerOf2(iMvShift);
+#else
   rcMvSrchRngLT >>= iMvShift;
   rcMvSrchRngRB >>= iMvShift;
+#endif
 }
 
 
-
-
-Void TEncSearch::xPatternSearch( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, TComMv* pcMvSrchRngLT, TComMv* pcMvSrchRngRB, TComMv& rcMv, Distortion& ruiSAD )
+Void TEncSearch::xPatternSearch( const TComPattern* const pcPatternKey,
+                                 const Pel*               piRefY,
+                                 const Int                iRefStride,
+                                 const TComMv* const      pcMvSrchRngLT,
+                                 const TComMv* const      pcMvSrchRngRB,
+                                 TComMv&      rcMv,
+                                 Distortion&  ruiSAD )
 {
   Int   iSrchRngHorLeft   = pcMvSrchRngLT->getHor();
@@ -5336,11 +5340,9 @@
   Int         iBestY = 0;
 
-  Pel*  piRefSrch;
-
   //-- jclee for using the SAD function pointer
   m_pcRdCost->setDistParam( pcPatternKey, piRefY, iRefStride,  m_cDistParam );
 
   // fast encoder decision: use subsampled SAD for integer ME
-  if ( m_pcEncCfg->getUseFastEnc() )
+  if ( m_pcEncCfg->getFastInterSearchMode()==FASTINTERSEARCH_MODE1 || m_pcEncCfg->getFastInterSearchMode()==FASTINTERSEARCH_MODE3 )
   {
     if ( m_cDistParam.iRows > 8 )
@@ -5356,6 +5358,5 @@
     {
       //  find min. distortion position
-      piRefSrch = piRefY + x;
-      m_cDistParam.pCur = piRefSrch;
+      m_cDistParam.pCur = piRefY + x;
 
       setDistParamComp(COMPONENT_Y);
@@ -5373,5 +5374,5 @@
 
       // motion cost
-      uiSad += m_pcRdCost->getCost( x, y );
+      uiSad += m_pcRdCost->getCostOfVectorWithPredictor( x, y );
 
       if ( uiSad < uiSadBest )
@@ -5380,4 +5381,5 @@
         iBestX    = x;
         iBestY    = y;
+        m_cDistParam.m_maximumDistortionForEarlyExit = uiSad;
       }
     }
@@ -5387,5 +5389,5 @@
   rcMv.set( iBestX, iBestY );
 
-  ruiSAD = uiSadBest - m_pcRdCost->getCost( iBestX, iBestY );
+  ruiSAD = uiSadBest - m_pcRdCost->getCostOfVectorWithPredictor( iBestX, iBestY );
   return;
 }
@@ -5393,13 +5395,13 @@
 
 
-Void TEncSearch::xPatternSearchFast( TComDataCU*   pcCU,
-                                     TComPattern*  pcPatternKey,
-                                     Pel*          piRefY,
-                                     Int           iRefStride,
-                                     TComMv*       pcMvSrchRngLT,
-                                     TComMv*       pcMvSrchRngRB,
+Void TEncSearch::xPatternSearchFast( const TComDataCU* const  pcCU,
+                                     const TComPattern* const pcPatternKey,
+                                     const Pel* const         piRefY,
+                                     const Int                iRefStride,
+                                     const TComMv* const      pcMvSrchRngLT,
+                                     const TComMv* const      pcMvSrchRngRB,
                                      TComMv       &rcMv,
                                      Distortion   &ruiSAD,
-                                     const TComMv* pIntegerMv2Nx2NPred )
+                                     const TComMv* const      pIntegerMv2Nx2NPred )
 {
   assert (MD_LEFT < NUM_MV_PREDICTORS);
@@ -5410,13 +5412,19 @@
   pcCU->getMvPredAboveRight ( m_acMvPredictors[MD_ABOVE_RIGHT] );
 
-  switch ( m_iFastSearch )
-  {
-    case 1:
-      xTZSearch( pcCU, pcPatternKey, piRefY, iRefStride, pcMvSrchRngLT, pcMvSrchRngRB, rcMv, ruiSAD, pIntegerMv2Nx2NPred );
+  switch ( m_motionEstimationSearchMethod )
+  {
+    case MESEARCH_DIAMOND:
+      xTZSearch( pcCU, pcPatternKey, piRefY, iRefStride, pcMvSrchRngLT, pcMvSrchRngRB, rcMv, ruiSAD, pIntegerMv2Nx2NPred, false );
       break;
 
-    case 2:
+    case MESEARCH_SELECTIVE:
       xTZSearchSelective( pcCU, pcPatternKey, piRefY, iRefStride, pcMvSrchRngLT, pcMvSrchRngRB, rcMv, ruiSAD, pIntegerMv2Nx2NPred );
       break;
+
+    case MESEARCH_DIAMOND_ENHANCED:
+      xTZSearch( pcCU, pcPatternKey, piRefY, iRefStride, pcMvSrchRngLT, pcMvSrchRngRB, rcMv, ruiSAD, pIntegerMv2Nx2NPred, true );
+      break;
+
+    case MESEARCH_FULL: // shouldn't get here.
     default:
       break;
@@ -5427,20 +5435,36 @@
 
 
-Void TEncSearch::xTZSearch( TComDataCU*  pcCU,
-                            TComPattern* pcPatternKey,
-                            Pel*         piRefY,
-                            Int          iRefStride,
-                            TComMv*      pcMvSrchRngLT,
-                            TComMv*      pcMvSrchRngRB,
+Void TEncSearch::xTZSearch( const TComDataCU* const pcCU,
+                            const TComPattern* const pcPatternKey,
+                            const Pel* const         piRefY,
+                            const Int                iRefStride,
+                            const TComMv* const      pcMvSrchRngLT,
+                            const TComMv* const      pcMvSrchRngRB,
                             TComMv      &rcMv,
                             Distortion  &ruiSAD,
-                            const TComMv* pIntegerMv2Nx2NPred )
+                            const TComMv* const      pIntegerMv2Nx2NPred,
+                            const Bool               bExtendedSettings)
 {
-  Int   iSrchRngHorLeft   = pcMvSrchRngLT->getHor();
-  Int   iSrchRngHorRight  = pcMvSrchRngRB->getHor();
-  Int   iSrchRngVerTop    = pcMvSrchRngLT->getVer();
-  Int   iSrchRngVerBottom = pcMvSrchRngRB->getVer();
-
-  TZ_SEARCH_CONFIGURATION
+  const Bool bUseAdaptiveRaster                      = bExtendedSettings;
+  const Int  iRaster                                 = 5;
+  const Bool bTestOtherPredictedMV                   = bExtendedSettings;
+  const Bool bTestZeroVector                         = true;
+  const Bool bTestZeroVectorStart                    = bExtendedSettings;
+  const Bool bTestZeroVectorStop                     = false;
+  const Bool bFirstSearchDiamond                     = true;  // 1 = xTZ8PointDiamondSearch   0 = xTZ8PointSquareSearch
+  const Bool bFirstCornersForDiamondDist1            = bExtendedSettings;
+  const Bool bFirstSearchStop                        = m_pcEncCfg->getFastMEAssumingSmootherMVEnabled();
+  const UInt uiFirstSearchRounds                     = 3;     // first search stop X rounds after best match (must be >=1)
+  const Bool bEnableRasterSearch                     = true;
+  const Bool bAlwaysRasterSearch                     = bExtendedSettings;  // true: BETTER but factor 2 slower
+  const Bool bRasterRefinementEnable                 = false; // enable either raster refinement or star refinement
+  const Bool bRasterRefinementDiamond                = false; // 1 = xTZ8PointDiamondSearch   0 = xTZ8PointSquareSearch
+  const Bool bRasterRefinementCornersForDiamondDist1 = bExtendedSettings;
+  const Bool bStarRefinementEnable                   = true;  // enable either star refinement or raster refinement
+  const Bool bStarRefinementDiamond                  = true;  // 1 = xTZ8PointDiamondSearch   0 = xTZ8PointSquareSearch
+  const Bool bStarRefinementCornersForDiamondDist1   = bExtendedSettings;
+  const Bool bStarRefinementStop                     = false;
+  const UInt uiStarRefinementRounds                  = 2;  // star refinement stop X rounds after best match (must be >=1)
+  const Bool bNewZeroNeighbourhoodTest               = bExtendedSettings;
 
   UInt uiSearchRange = m_iSearchRange;
@@ -5449,5 +5473,10 @@
   if( ! pcCU->getSlice()->getIsDepth() )
 #endif
+#if ME_ENABLE_ROUNDING_OF_MVS
+  rcMv.divideByPowerOf2(2);
+#else
   rcMv >>= 2;
+#endif
+
   // init TZSearchStruct
   IntTZSearchStruct cStruct;
@@ -5470,11 +5499,19 @@
       {      
 #endif
-        cMv >>= 2;
+#if ME_ENABLE_ROUNDING_OF_MVS
+      cMv.divideByPowerOf2(2);
+#else
+      cMv >>= 2;
+#endif
+
 #if NH_3D_INTEGER_MV_DEPTH
       }
 #endif
-
+      if (cMv != rcMv && (cMv.getHor() != cStruct.iBestX && cMv.getVer() != cStruct.iBestY))
+      {
+        // only test cMV if not obviously previously tested.
       xTZSearchHelp( pcPatternKey, cStruct, cMv.getHor(), cMv.getVer(), 0, 0 );
     }
+  }
   }
 
@@ -5482,6 +5519,16 @@
   if ( bTestZeroVector )
   {
+    if ((rcMv.getHor() != 0 || rcMv.getVer() != 0) &&
+        (0 != cStruct.iBestX || 0 != cStruct.iBestY))
+    {
+      // only test 0-vector if not obviously previously tested.
     xTZSearchHelp( pcPatternKey, cStruct, 0, 0, 0, 0 );
   }
+  }
+
+  Int   iSrchRngHorLeft   = pcMvSrchRngLT->getHor();
+  Int   iSrchRngHorRight  = pcMvSrchRngRB->getHor();
+  Int   iSrchRngVerTop    = pcMvSrchRngLT->getVer();
+  Int   iSrchRngVerBottom = pcMvSrchRngRB->getVer();
 
   if (pIntegerMv2Nx2NPred != 0)
@@ -5490,6 +5537,15 @@
     integerMv2Nx2NPred <<= 2;
     pcCU->clipMv( integerMv2Nx2NPred );
+#if ME_ENABLE_ROUNDING_OF_MVS
+    integerMv2Nx2NPred.divideByPowerOf2(2);
+#else
     integerMv2Nx2NPred >>= 2;
+#endif
+    if ((rcMv != integerMv2Nx2NPred) &&
+        (integerMv2Nx2NPred.getHor() != cStruct.iBestX || integerMv2Nx2NPred.getVer() != cStruct.iBestY))
+    {
+      // only test integerMv2Nx2NPred if not obviously previously tested.
     xTZSearchHelp(pcPatternKey, cStruct, integerMv2Nx2NPred.getHor(), integerMv2Nx2NPred.getVer(), 0, 0);
+    }
 
     // reset search range
@@ -5511,10 +5567,13 @@
   Int  iStartY = cStruct.iBestY;
 
-  // first search
+  const Bool bBestCandidateZero = (cStruct.iBestX == 0) && (cStruct.iBestY == 0);
+
+  // first search around best position up to now.
+  // The following works as a "subsampled/log" window search around the best candidate
   for ( iDist = 1; iDist <= (Int)uiSearchRange; iDist*=2 )
   {
     if ( bFirstSearchDiamond == 1 )
     {
-      xTZ8PointDiamondSearch ( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, iStartX, iStartY, iDist );
+      xTZ8PointDiamondSearch ( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, iStartX, iStartY, iDist, bFirstCornersForDiamondDist1 );
     }
     else
@@ -5529,4 +5588,6 @@
   }
 
+  if (!bNewZeroNeighbourhoodTest)
+  {
   // test whether zero Mv is a better start point than Median predictor
   if ( bTestZeroVectorStart && ((cStruct.iBestX != 0) || (cStruct.iBestY != 0)) )
@@ -5538,6 +5599,25 @@
       for ( iDist = 1; iDist <= (Int)uiSearchRange; iDist*=2 )
       {
-        xTZ8PointDiamondSearch( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, 0, 0, iDist );
+          xTZ8PointDiamondSearch( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, 0, 0, iDist, false );
         if ( bTestZeroVectorStop && (cStruct.uiBestRound > 0) ) // stop criterion
+        {
+          break;
+        }
+      }
+    }
+  }
+  }
+  else
+  {
+    // Test also zero neighbourhood but with half the range
+    // It was reported that the original (above) search scheme using bTestZeroVectorStart did not
+    // make sense since one would have already checked the zero candidate earlier
+    // and thus the conditions for that test would have not been satisfied
+    if (bTestZeroVectorStart == true && bBestCandidateZero != true)
+    {
+      for ( iDist = 1; iDist <= ((Int)uiSearchRange >> 1); iDist*=2 )
+      {
+        xTZ8PointDiamondSearch( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, 0, 0, iDist, false );
+        if ( bTestZeroVectorStop && (cStruct.uiBestRound > 2) ) // stop criterion
         {
           break;
@@ -5555,4 +5635,31 @@
 
   // raster search if distance is too big
+  if (bUseAdaptiveRaster)
+  {
+    int iWindowSize = iRaster;
+    Int   iSrchRngRasterLeft   = iSrchRngHorLeft;
+    Int   iSrchRngRasterRight  = iSrchRngHorRight;
+    Int   iSrchRngRasterTop    = iSrchRngVerTop;
+    Int   iSrchRngRasterBottom = iSrchRngVerBottom;
+
+    if (!(bEnableRasterSearch && ( ((Int)(cStruct.uiBestDistance) > iRaster))))
+    {
+      iWindowSize ++;
+      iSrchRngRasterLeft /= 2;
+      iSrchRngRasterRight /= 2;
+      iSrchRngRasterTop /= 2;
+      iSrchRngRasterBottom /= 2;
+    }
+    cStruct.uiBestDistance = iWindowSize;
+    for ( iStartY = iSrchRngRasterTop; iStartY <= iSrchRngRasterBottom; iStartY += iWindowSize )
+    {
+      for ( iStartX = iSrchRngRasterLeft; iStartX <= iSrchRngRasterRight; iStartX += iWindowSize )
+      {
+        xTZSearchHelp( pcPatternKey, cStruct, iStartX, iStartY, 0, iWindowSize );
+      }
+    }
+  }
+  else
+  {
   if ( bEnableRasterSearch && ( ((Int)(cStruct.uiBestDistance) > iRaster) || bAlwaysRasterSearch ) )
   {
@@ -5565,4 +5672,5 @@
       }
     }
+  }
   }
 
@@ -5579,5 +5687,5 @@
         if ( bRasterRefinementDiamond == 1 )
         {
-          xTZ8PointDiamondSearch ( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, iStartX, iStartY, iDist );
+          xTZ8PointDiamondSearch ( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, iStartX, iStartY, iDist, bRasterRefinementCornersForDiamondDist1 );
         }
         else
@@ -5599,5 +5707,5 @@
   }
 
-  // start refinement
+  // star refinement
   if ( bStarRefinementEnable && cStruct.uiBestDistance > 0 )
   {
@@ -5612,5 +5720,5 @@
         if ( bStarRefinementDiamond == 1 )
         {
-          xTZ8PointDiamondSearch ( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, iStartX, iStartY, iDist );
+          xTZ8PointDiamondSearch ( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, iStartX, iStartY, iDist, bStarRefinementCornersForDiamondDist1 );
         }
         else
@@ -5638,19 +5746,30 @@
   // write out best match
   rcMv.set( cStruct.iBestX, cStruct.iBestY );
-  ruiSAD = cStruct.uiBestSad - m_pcRdCost->getCost( cStruct.iBestX, cStruct.iBestY );
+  ruiSAD = cStruct.uiBestSad - m_pcRdCost->getCostOfVectorWithPredictor( cStruct.iBestX, cStruct.iBestY );
 }
 
 
-Void TEncSearch::xTZSearchSelective( TComDataCU*   pcCU,
-                                     TComPattern*  pcPatternKey,
-                                     Pel*          piRefY,
-                                     Int           iRefStride,
-                                     TComMv*       pcMvSrchRngLT,
-                                     TComMv*       pcMvSrchRngRB,
+Void TEncSearch::xTZSearchSelective( const TComDataCU* const   pcCU,
+                                     const TComPattern* const  pcPatternKey,
+                                     const Pel* const          piRefY,
+                                     const Int                 iRefStride,
+                                     const TComMv* const       pcMvSrchRngLT,
+                                     const TComMv* const       pcMvSrchRngRB,
                                      TComMv       &rcMv,
                                      Distortion   &ruiSAD,
-                                     const TComMv* pIntegerMv2Nx2NPred )
+                                     const TComMv* const       pIntegerMv2Nx2NPred )
 {
-  SEL_SEARCH_CONFIGURATION
+  const Bool bTestOtherPredictedMV    = true;
+  const Bool bTestZeroVector          = true;
+  const Bool bEnableRasterSearch      = true;
+  const Bool bAlwaysRasterSearch      = false;  // 1: BETTER but factor 15x slower
+  const Bool bStarRefinementEnable    = true;   // enable either star refinement or raster refinement
+  const Bool bStarRefinementDiamond   = true;   // 1 = xTZ8PointDiamondSearch   0 = xTZ8PointSquareSearch
+  const Bool bStarRefinementStop      = false;
+  const UInt uiStarRefinementRounds   = 2;  // star refinement stop X rounds after best match (must be >=1)
+  const UInt uiSearchRange            = m_iSearchRange;
+  const Int  uiSearchRangeInitial     = m_iSearchRange >> 2;
+  const Int  uiSearchStep             = 4;
+  const Int  iMVDistThresh            = 8;
 
   Int   iSrchRngHorLeft         = pcMvSrchRngLT->getHor();
@@ -5669,5 +5788,9 @@
 
   pcCU->clipMv( rcMv );
+#if ME_ENABLE_ROUNDING_OF_MVS
+  rcMv.divideByPowerOf2(2);
+#else
   rcMv >>= 2;
+#endif
   // init TZSearchStruct
   IntTZSearchStruct cStruct;
@@ -5689,5 +5812,9 @@
       TComMv cMv = m_acMvPredictors[index];
       pcCU->clipMv( cMv );
+#if ME_ENABLE_ROUNDING_OF_MVS
+      cMv.divideByPowerOf2(2);
+#else
       cMv >>= 2;
+#endif
       xTZSearchHelp( pcPatternKey, cStruct, cMv.getHor(), cMv.getVer(), 0, 0 );
     }
@@ -5705,5 +5832,9 @@
     integerMv2Nx2NPred <<= 2;
     pcCU->clipMv( integerMv2Nx2NPred );
+#if ME_ENABLE_ROUNDING_OF_MVS
+    integerMv2Nx2NPred.divideByPowerOf2(2);
+#else
     integerMv2Nx2NPred >>= 2;
+#endif
     xTZSearchHelp(pcPatternKey, cStruct, integerMv2Nx2NPred.getHor(), integerMv2Nx2NPred.getVer(), 0, 0);
 
@@ -5734,6 +5865,6 @@
     {
       xTZSearchHelp( pcPatternKey, cStruct, iStartX, iStartY, 0, 0 );
-      xTZ8PointDiamondSearch ( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, iStartX, iStartY, 1 );
-      xTZ8PointDiamondSearch ( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, iStartX, iStartY, 2 );
+      xTZ8PointDiamondSearch ( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, iStartX, iStartY, 1, false );
+      xTZ8PointDiamondSearch ( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, iStartX, iStartY, 2, false );
     }
   }
@@ -5766,5 +5897,5 @@
         if ( bStarRefinementDiamond == 1 )
         {
-          xTZ8PointDiamondSearch ( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, iStartX, iStartY, iDist );
+          xTZ8PointDiamondSearch ( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, iStartX, iStartY, iDist, false );
         }
         else
@@ -5792,5 +5923,5 @@
   // write out best match
   rcMv.set( cStruct.iBestX, cStruct.iBestY );
-  ruiSAD = cStruct.uiBestSad - m_pcRdCost->getCost( cStruct.iBestX, cStruct.iBestY );
+  ruiSAD = cStruct.uiBestSad - m_pcRdCost->getCostOfVectorWithPredictor( cStruct.iBestX, cStruct.iBestY );
 
 }
@@ -5968,5 +6099,5 @@
   }
 
-#if ENC_DEC_TRACE && H_MV_ENC_DEC_TRAC
+#if ENC_DEC_TRACE && NH_MV_ENC_DEC_TRAC
   Bool oldTraceRDCost = g_traceRDCost;     
   g_traceRDCost = false; 
@@ -5981,5 +6112,5 @@
   xEstimateInterResidualQT( pcYuvResi,  pcYuvOrg, pcYuvPred, nonZeroCost, nonZeroBits, nonZeroDistortion, &zeroDistortion, tuLevel0 DEBUG_STRING_PASS_INTO(sDebug) );    
 
-#if ENC_DEC_TRACE && H_MV_ENC_DEC_TRAC
+#if ENC_DEC_TRACE && NH_MV_ENC_DEC_TRAC
   g_traceRDCost = oldTraceRDCost;
   g_traceEncFracBits = oldTraceFracBits; 
@@ -6027,5 +6158,5 @@
       const ComponentID component = ComponentID(comp);
       ::memset( pcCU->getCbf( component ) , 0, uiQPartNum * sizeof(UChar) );
-      ::memset( pcCU->getCrossComponentPredictionAlpha(component), 0, ( uiQPartNum * sizeof(Char) ) );
+      ::memset( pcCU->getCrossComponentPredictionAlpha(component), 0, ( uiQPartNum * sizeof(SChar) ) );
     }
     static const UInt useTS[MAX_NUM_COMPONENT]={0,0,0};
@@ -6315,5 +6446,5 @@
   //  Stores the best explicit RDPCM mode for a TU encoded without split
   UInt       bestExplicitRdpcmModeUnSplit[MAX_NUM_COMPONENT][2/*0 = top (or whole TU for non-4:2:2) sub-TU, 1 = bottom sub-TU*/] = {{3,3}, {3,3}, {3,3}};
-  Char       bestCrossCPredictionAlpha   [MAX_NUM_COMPONENT][2/*0 = top (or whole TU for non-4:2:2) sub-TU, 1 = bottom sub-TU*/] = {{0,0},{0,0},{0,0}};
+  SChar      bestCrossCPredictionAlpha   [MAX_NUM_COMPONENT][2/*0 = top (or whole TU for non-4:2:2) sub-TU, 1 = bottom sub-TU*/] = {{0,0},{0,0},{0,0}};
 
   m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
@@ -6386,5 +6517,5 @@
                                                          && (pcCU->getCbf(subTUAbsPartIdx, COMPONENT_Y, uiTrMode) != 0);
 
-          Char preCalcAlpha = 0;
+          SChar preCalcAlpha = 0;
           const Pel *pLumaResi = m_pcQTTempTComYuv[uiQTTempAccessLayer].getAddrPix( COMPONENT_Y, rTu.getRect( COMPONENT_Y ).x0, rTu.getRect( COMPONENT_Y ).y0 );
 
@@ -6578,5 +6709,4 @@
               }
 
-
               DEBUG_STRING_NEW(sSingleStringTest)
 #if NH_MV
@@ -6588,5 +6718,4 @@
                 D_PRINT_INC_INDENT(g_traceModeCheck, "NonZero");
 #endif
-
                 if (isFirstMode)
                 {
Index: trunk/source/Lib/TLibEncoder/TEncSearch.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSearch.h	(revision 1357)
+++ trunk/source/Lib/TLibEncoder/TEncSearch.h	(revision 1386)
@@ -68,8 +68,6 @@
 private:
   TCoeff**        m_ppcQTTempCoeff[MAX_NUM_COMPONENT /* 0->Y, 1->Cb, 2->Cr*/];
-  TCoeff*         m_pcQTTempCoeff[MAX_NUM_COMPONENT];
 #if ADAPTIVE_QP_SELECTION
   TCoeff**        m_ppcQTTempArlCoeff[MAX_NUM_COMPONENT];
-  TCoeff*         m_pcQTTempArlCoeff[MAX_NUM_COMPONENT];
 #endif
   UChar*          m_puhQTTempTrIdx;
@@ -79,5 +77,5 @@
   TComYuv         m_tmpYuvPred; // To be used in xGetInterPredictionError() to avoid constant memory allocation/deallocation
 
-  Char*           m_phQTTempCrossComponentPredictionAlpha[MAX_NUM_COMPONENT];
+  SChar*          m_phQTTempCrossComponentPredictionAlpha[MAX_NUM_COMPONENT];
   Pel*            m_pSharedPredTransformSkip[MAX_NUM_COMPONENT];
   TCoeff*         m_pcQTTempTUCoeff[MAX_NUM_COMPONENT];
@@ -100,11 +98,9 @@
   Int             m_iSearchRange;
   Int             m_bipredSearchRange; // Search range for bi-prediction
-  Int             m_iFastSearch;
+  MESearchMethod  m_motionEstimationSearchMethod;
 #if NH_MV
   Bool            m_vertRestriction; 
 #endif 
   Int             m_aaiAdaptSR[MAX_NUM_REF_LIST_ADAPT_SR][MAX_IDX_ADAPT_SR];
-  TComMv          m_cSrchRngLT;
-  TComMv          m_cSrchRngRB;
   TComMv          m_acMvPredictors[NUM_MV_PREDICTORS]; // Left, Above, AboveRight. enum MVP_DIR first NUM_MV_PREDICTORS entries are suitable for accessing.
 
@@ -116,5 +112,4 @@
   // Misc.
   Pel*            m_pTempPel;
-  const UInt*     m_puiDFilter;
 
 #if NH_3D_VSO // M17
@@ -136,5 +131,5 @@
             Int           iSearchRange,
             Int           bipredSearchRange,
-            Int           iFastSearch,
+            MESearchMethod motionEstimationSearchMethod,
             const UInt    maxCUWidth,
             const UInt    maxCUHeight,
@@ -157,5 +152,5 @@
   typedef struct
   {
-    Pel*        piRefY;
+    const Pel*  piRefY;
     Int         iYStride;
     Int         iBestX;
@@ -168,8 +163,8 @@
 
   // sub-functions for ME
-  __inline Void xTZSearchHelp         ( TComPattern* pcPatternKey, IntTZSearchStruct& rcStruct, const Int iSearchX, const Int iSearchY, const UChar ucPointNr, const UInt uiDistance );
-  __inline Void xTZ2PointSearch       ( TComPattern* pcPatternKey, IntTZSearchStruct& rcStrukt, TComMv* pcMvSrchRngLT, TComMv* pcMvSrchRngRB );
-  __inline Void xTZ8PointSquareSearch ( TComPattern* pcPatternKey, IntTZSearchStruct& rcStrukt, TComMv* pcMvSrchRngLT, TComMv* pcMvSrchRngRB, const Int iStartX, const Int iStartY, const Int iDist );
-  __inline Void xTZ8PointDiamondSearch( TComPattern* pcPatternKey, IntTZSearchStruct& rcStrukt, TComMv* pcMvSrchRngLT, TComMv* pcMvSrchRngRB, const Int iStartX, const Int iStartY, const Int iDist );
+  __inline Void xTZSearchHelp         ( const TComPattern* const pcPatternKey, IntTZSearchStruct& rcStruct, const Int iSearchX, const Int iSearchY, const UChar ucPointNr, const UInt uiDistance );
+  __inline Void xTZ2PointSearch       ( const TComPattern* const pcPatternKey, IntTZSearchStruct& rcStruct, const TComMv* const pcMvSrchRngLT, const TComMv* const pcMvSrchRngRB );
+  __inline Void xTZ8PointSquareSearch ( const TComPattern* const pcPatternKey, IntTZSearchStruct& rcStruct, const TComMv* const pcMvSrchRngLT, const TComMv* const pcMvSrchRngRB, const Int iStartX, const Int iStartY, const Int iDist );
+  __inline Void xTZ8PointDiamondSearch( const TComPattern* const pcPatternKey, IntTZSearchStruct& rcStruct, const TComMv* const pcMvSrchRngLT, const TComMv* const pcMvSrchRngRB, const Int iStartX, const Int iStartY, const Int iDist, const Bool bCheckCornersAtDist1 );
 
   Void xGetInterPredictionError( TComDataCU* pcCU, TComYuv* pcYuvOrg, Int iPartIdx, Distortion& ruiSAD, Bool Hadamard );
@@ -322,5 +317,5 @@
                                                const Int     strideBest );
 
-  Char xCalcCrossComponentPredictionAlpha    (       TComTU &rTu,
+  SChar xCalcCrossComponentPredictionAlpha   (       TComTU &rTu,
                                                const ComponentID compID,
                                                const Pel*        piResiL,
@@ -446,48 +441,49 @@
                                     Bool         bBi = false  );
 
-  Void xTZSearch                  ( TComDataCU*  pcCU,
-                                    TComPattern* pcPatternKey,
-                                    Pel*         piRefY,
-                                    Int          iRefStride,
-                                    TComMv*      pcMvSrchRngLT,
-                                    TComMv*      pcMvSrchRngRB,
+  Void xTZSearch                  ( const TComDataCU* const  pcCU,
+                                    const TComPattern* const pcPatternKey,
+                                    const Pel* const         piRefY,
+                                    const Int                iRefStride,
+                                    const TComMv* const      pcMvSrchRngLT,
+                                    const TComMv* const      pcMvSrchRngRB,
                                     TComMv&      rcMv,
                                     Distortion&  ruiSAD,
-                                    const TComMv *pIntegerMv2Nx2NPred
+                                    const TComMv* const      pIntegerMv2Nx2NPred,
+                                    const Bool               bExtendedSettings
                                     );
 
-  Void xTZSearchSelective         ( TComDataCU*  pcCU,
-                                    TComPattern* pcPatternKey,
-                                    Pel*         piRefY,
-                                    Int          iRefStride,
-                                    TComMv*      pcMvSrchRngLT,
-                                    TComMv*      pcMvSrchRngRB,
+  Void xTZSearchSelective         ( const TComDataCU* const  pcCU,
+                                    const TComPattern* const pcPatternKey,
+                                    const Pel* const         piRefY,
+                                    const Int                iRefStride,
+                                    const TComMv* const      pcMvSrchRngLT,
+                                    const TComMv* const      pcMvSrchRngRB,
                                     TComMv&      rcMv,
                                     Distortion&  ruiSAD,
-                                    const TComMv *pIntegerMv2Nx2NPred
+                                    const TComMv* const      pIntegerMv2Nx2NPred
                                     );
 
-  Void xSetSearchRange            ( TComDataCU*  pcCU,
-                                    TComMv&      cMvPred,
-                                    Int          iSrchRng,
+  Void xSetSearchRange            ( const TComDataCU* const pcCU,
+                                    const TComMv&      cMvPred,
+                                    const Int          iSrchRng,
                                     TComMv&      rcMvSrchRngLT,
                                     TComMv&      rcMvSrchRngRB );
 
-  Void xPatternSearchFast         ( TComDataCU*  pcCU,
-                                    TComPattern* pcPatternKey,
-                                    Pel*         piRefY,
-                                    Int          iRefStride,
-                                    TComMv*      pcMvSrchRngLT,
-                                    TComMv*      pcMvSrchRngRB,
+  Void xPatternSearchFast         ( const TComDataCU* const  pcCU,
+                                    const TComPattern* const pcPatternKey,
+                                    const Pel* const         piRefY,
+                                    const Int                iRefStride,
+                                    const TComMv* const      pcMvSrchRngLT,
+                                    const TComMv* const      pcMvSrchRngRB,
                                     TComMv&      rcMv,
                                     Distortion&  ruiSAD,
-                                    const TComMv* pIntegerMv2Nx2NPred
+                                    const TComMv* const      pIntegerMv2Nx2NPred
                                   );
 
-  Void xPatternSearch             ( TComPattern* pcPatternKey,
-                                    Pel*         piRefY,
-                                    Int          iRefStride,
-                                    TComMv*      pcMvSrchRngLT,
-                                    TComMv*      pcMvSrchRngRB,
+  Void xPatternSearch             ( const TComPattern* const pcPatternKey,
+                                    const Pel*               piRefY,
+                                    const Int                iRefStride,
+                                    const TComMv* const      pcMvSrchRngLT,
+                                    const TComMv* const      pcMvSrchRngRB,
                                     TComMv&      rcMv,
                                     Distortion&  ruiSAD );
Index: trunk/source/Lib/TLibEncoder/TEncSlice.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 1357)
+++ trunk/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 1386)
@@ -203,5 +203,5 @@
 Void TEncSlice::initEncSlice( TComPic* pcPic, Int pocLast, Int pocCurr, Int iGOPid, TComSlice*& rpcSlice, TComVPS* pVPS, Int layerId, bool isField )
 #else
-Void TEncSlice::initEncSlice( TComPic* pcPic, Int pocLast, Int pocCurr, Int iGOPid, TComSlice*& rpcSlice, Bool isField )
+Void TEncSlice::initEncSlice( TComPic* pcPic, const Int pocLast, const Int pocCurr, const Int iGOPid, TComSlice*& rpcSlice, const Bool isField )
 #endif
 {
@@ -318,6 +318,10 @@
   else
   {
+#if NH_MV
 #if 0 // Check this! NH_MV
     rpcSlice->setTemporalLayerNonReferenceFlag(!m_pcCfg->getGOPEntry( (eSliceTypeBaseView == I_SLICE) ? MAX_GOP : iGOPid ).m_refPic);
+#else
+    rpcSlice->setTemporalLayerNonReferenceFlag(!m_pcCfg->getGOPEntry(iGOPid).m_refPic);
+#endif
 #else
     rpcSlice->setTemporalLayerNonReferenceFlag(!m_pcCfg->getGOPEntry(iGOPid).m_refPic);
@@ -372,6 +376,4 @@
     Int    NumberBFrames = ( m_pcCfg->getGOPSize() - 1 );
     Int    SHIFT_QP = 12;
-
-    Double dLambda_scale = 1.0 - Clip3( 0.0, 0.5, 0.05*(Double)(isField ? NumberBFrames/2 : NumberBFrames) );
 
 #if FULL_NBIT
@@ -397,5 +399,14 @@
 #endif
     {
-      dQPFactor=0.57*dLambda_scale;
+      if (m_pcCfg->getIntraQpFactor()>=0.0 && m_pcCfg->getGOPEntry(iGOPid).m_sliceType != I_SLICE)
+      {
+        dQPFactor=m_pcCfg->getIntraQpFactor();
+      }
+      else
+      {
+        Double dLambda_scale = 1.0 - Clip3( 0.0, 0.5, 0.05*(Double)(isField ? NumberBFrames/2 : NumberBFrames) );
+        
+        dQPFactor=0.57*dLambda_scale;
+      }
     }
     dLambda = dQPFactor*pow( 2.0, qp_temp/3.0 );
@@ -428,17 +439,27 @@
   iQP     = m_piRdPicQp    [0];
 
-  if( rpcSlice->getSliceType( ) != I_SLICE )
-  {
+
 #if NH_MV
-    dLambda *= m_pcCfg->getLambdaModifier( m_pcCfg->getGOPEntry((eSliceTypeBaseView == I_SLICE) ? MAX_GOP : iGOPid).m_temporalId );
-#else
-    dLambda *= m_pcCfg->getLambdaModifier( m_pcCfg->getGOPEntry(iGOPid).m_temporalId );
-#endif
-  }
-
+  const Int temporalId=m_pcCfg->getGOPEntry((eSliceTypeBaseView == I_SLICE) ? MAX_GOP : iGOPid).m_temporalId;
+#else
+  const Int temporalId=m_pcCfg->getGOPEntry(iGOPid).m_temporalId;
+#endif
+  const std::vector<Double> &intraLambdaModifiers=m_pcCfg->getIntraLambdaModifier();
+
+  Double lambdaModifier;
+  if( rpcSlice->getSliceType( ) != I_SLICE || intraLambdaModifiers.empty())
+  {
+    lambdaModifier = m_pcCfg->getLambdaModifier( temporalId );
+  }
+  else
+  {
+    lambdaModifier = intraLambdaModifiers[ (temporalId < intraLambdaModifiers.size()) ? temporalId : (intraLambdaModifiers.size()-1) ];
+  }
+
+  dLambda *= lambdaModifier;
   setUpLambda(rpcSlice, dLambda, iQP);
 
 #if NH_3D_VSO
-  m_pcRdCost->setUseLambdaScaleVSO  ( (m_pcCfg->getUseVSO() ||  m_pcCfg->getForceLambdaScaleVSO()) && m_pcCfg->getIsDepth() );
+  m_pcRdCost->setUseLambdaScaleVSO  ( (m_pcCfg->getUseVSO() ||  m_pcCfg->getForceLambdaScaleVSO()) && ( m_pcCfg->getIsDepth()  | m_pcCfg->getIsAuxDepth() ) );
   m_pcRdCost->setLambdaVSO          ( dLambda * m_pcCfg->getLambdaScaleVSO() );
 
@@ -449,5 +470,5 @@
 
   // LGE_WVSO_A0119
-  if( m_pcCfg->getUseWVSO() && m_pcCfg->getIsDepth() )
+  if( m_pcCfg->getUseWVSO() && ( m_pcCfg->getIsDepth() || m_pcCfg->getIsAuxDepth() ) )
   {
     m_pcRdCost->setDWeight  ( m_pcCfg->getDWeight()   );
@@ -547,9 +568,5 @@
   rpcSlice->setDepth            ( depth );
 
-#if NH_MV
-  pcPic->setTLayer( m_pcCfg->getGOPEntry( (eSliceTypeBaseView == I_SLICE) ? MAX_GOP : iGOPid ).m_temporalId );
-#else
-  pcPic->setTLayer( m_pcCfg->getGOPEntry(iGOPid).m_temporalId );
-#endif
+  pcPic->setTLayer( temporalId );
   if(eSliceType==I_SLICE)
   {
@@ -589,4 +606,5 @@
 // ====================================================================================================================
 
+//! set adaptive search range based on poc difference
 Void TEncSlice::setSearchRange( TComSlice* pcSlice )
 {
@@ -598,13 +616,12 @@
   Int iNumPredDir = pcSlice->isInterP() ? 1 : 2;
 
-  for (Int iDir = 0; iDir <= iNumPredDir; iDir++)
-  {
-    //RefPicList e = (RefPicList)iDir;
+  for (Int iDir = 0; iDir < iNumPredDir; iDir++)
+  {
     RefPicList  e = ( iDir ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
     for (Int iRefIdx = 0; iRefIdx < pcSlice->getNumRefIdx(e); iRefIdx++)
     {
       iRefPOC = pcSlice->getRefPic(e, iRefIdx)->getPOC();
-      Int iNewSR = Clip3(8, iMaxSR, (iMaxSR*ADAPT_SR_SCALE*abs(iCurrPOC - iRefPOC)+iOffset)/iGOPSize);
-      m_pcPredSearch->setAdaptiveSearchRange(iDir, iRefIdx, iNewSR);
+      Int newSearchRange = Clip3(m_pcCfg->getMinSearchWindow(), iMaxSR, (iMaxSR*ADAPT_SR_SCALE*abs(iCurrPOC - iRefPOC)+iOffset)/iGOPSize);
+      m_pcPredSearch->setAdaptiveSearchRange(iDir, iRefIdx, newSearchRange);
     }
   }
@@ -696,5 +713,9 @@
 
     // compute RD cost and choose the best
-    Double dPicRdCost = m_pcRdCost->calcRdCost64( m_uiPicTotalBits, uiPicDist, true, DF_SSE_FRAME); // NOTE: Is the 'true' parameter really necessary?
+#if NH_3D_VSO
+    Double dPicRdCost = m_pcRdCost->calcRdCost( (Double)m_uiPicTotalBits, uiPicDist, DF_SSE_FRAME);
+#else
+    Double dPicRdCost = m_pcRdCost->calcRdCost( (Double)m_uiPicTotalBits, (Double)uiPicDist, DF_SSE_FRAME);
+#endif
 #if H_3D
     // Above calculation need to be fixed for VSO, including frameLambda value. 
@@ -805,5 +826,5 @@
     }
 
-    xEstimateWPParamSlice( pcSlice );
+    xEstimateWPParamSlice( pcSlice, m_pcCfg->getWeightedPredictionMethod() );
     pcSlice->initWpScaling(pcSlice->getSPS());
 
@@ -849,5 +870,5 @@
     {
       // This will only occur if dependent slice-segments (m_entropyCodingSyncContextState=true) are being used.
-      if( pCurrentTile->getTileWidthInCtus() >= 2 || !m_pcCfg->getWaveFrontsynchro() )
+      if( pCurrentTile->getTileWidthInCtus() >= 2 || !m_pcCfg->getEntropyCodingSyncEnabledFlag() )
       {
         m_pppcRDSbacCoder[0][CI_CURR_BEST]->loadContexts( &m_lastSliceSegmentEndContextState );
@@ -878,5 +899,5 @@
         iLastPosY = iCurPosY;         
         TEncTop* pcEncTop = (TEncTop*) m_pcCfg; // Fix this later.
-        pcEncTop->setupRenModel( pcSlice->getPOC() , pcSlice->getViewIndex(), pcSlice->getIsDepth() ? 1 : 0, iCurPosY, pcSlice->getSPS()->getMaxCUHeight() );
+        pcEncTop->setupRenModel( pcSlice->getPOC() , pcSlice->getViewIndex(), pcSlice->getIsDepth() || pcSlice->getVPS()->getAuxId( pcSlice->getLayerId()  ) ? 1 : 0, iCurPosY, pcSlice->getSPS()->getMaxCUHeight() );
       }
     }
@@ -892,5 +913,5 @@
       m_pppcRDSbacCoder[0][CI_CURR_BEST]->resetEntropy(pcSlice);
     }
-    else if ( ctuXPosInCtus == tileXPosInCtus && m_pcCfg->getWaveFrontsynchro())
+    else if ( ctuXPosInCtus == tileXPosInCtus && m_pcCfg->getEntropyCodingSyncEnabledFlag())
     {
       // reset and then update contexts to the state at the end of the top-right CTU (if within current slice and tile).
@@ -1031,5 +1052,5 @@
 
     // Store probabilities of second CTU in line into buffer - used only if wavefront-parallel-processing is enabled.
-    if ( ctuXPosInCtus == tileXPosInCtus+1 && m_pcCfg->getWaveFrontsynchro())
+    if ( ctuXPosInCtus == tileXPosInCtus+1 && m_pcCfg->getEntropyCodingSyncEnabledFlag())
     {
       m_entropyCodingSyncContextState.loadContexts(m_pppcRDSbacCoder[0][CI_CURR_BEST]);
@@ -1123,5 +1144,5 @@
   g_bJustDoIt = g_bEncDecTraceEnable;
 #endif
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
 #if ENC_DEC_TRACE
   incSymbolCounter();
@@ -1133,5 +1154,5 @@
   DTRACE_CABAC_T( "\tPOC: " );
   DTRACE_CABAC_V( pcPic->getPOC() );
-#if H_MV_ENC_DEC_TRAC
+#if NH_MV_ENC_DEC_TRAC
   DTRACE_CABAC_T( " Layer: " );
   DTRACE_CABAC_V( pcPic->getLayerId() );
Index: trunk/source/Lib/TLibEncoder/TEncSlice.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSlice.h	(revision 1357)
+++ trunk/source/Lib/TLibEncoder/TEncSlice.h	(revision 1386)
@@ -120,6 +120,6 @@
                                 Int iGOPid, TComSlice*& rpcSlice, TComVPS* pVPS, Int layerId, bool isField  ); 
 #else
-  Void    initEncSlice        ( TComPic*  pcPic, Int pocLast, Int pocCurr, 
-                                Int iGOPid,   TComSlice*& rpcSlice, Bool isField );
+  Void    initEncSlice        ( TComPic*  pcPic, const Int pocLast, const Int pocCurr,
+                                const Int iGOPid,   TComSlice*& rpcSlice, const Bool isField );
 #endif
   Void    resetQP             ( TComPic* pic, Int sliceQP, Double lambda );
Index: trunk/source/Lib/TLibEncoder/TEncTop.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncTop.cpp	(revision 1357)
+++ trunk/source/Lib/TLibEncoder/TEncTop.cpp	(revision 1386)
@@ -44,5 +44,5 @@
 #endif
 #if NH_MV
-#include "../../App/TAppEncoder/TAppEncTop.h"
+//#include "../../App/TAppEncoder/TAppEncTop.h"
 #endif
 
@@ -216,4 +216,10 @@
   xInitVPS();
 
+#if U0132_TARGET_BITS_SATURATION
+  if (m_RCCpbSaturationEnabled)
+  {
+    m_cRateCtrl.initHrdParam(m_cSPS.getVuiParameters()->getHrdParameters(), m_iFrameRate, m_RCInitialCpbFullness);
+  }
+#endif
   m_cRdCost.setCostMode(m_costMode);
 
@@ -264,5 +270,5 @@
 
   // initialize encoder search class
-  m_cSearch.init( this, &m_cTrQuant, m_iSearchRange, m_bipredSearchRange, m_iFastSearch, m_maxCUWidth, m_maxCUHeight, m_maxTotalCUDepth, &m_cEntropyCoder, &m_cRdCost, getRDSbacCoder(), getRDGoOnSbacCoder() );
+  m_cSearch.init( this, &m_cTrQuant, m_iSearchRange, m_bipredSearchRange, m_motionEstimationSearchMethod, m_maxCUWidth, m_maxCUHeight, m_maxTotalCUDepth, &m_cEntropyCoder, &m_cRdCost, getRDSbacCoder(), getRDGoOnSbacCoder() );
 
   m_iMaxRefPicNum = 0;
@@ -299,5 +305,5 @@
   {
     m_cSPS.getScalingList().setDefaultScalingList ();
-    if(m_cSPS.getScalingList().xParseScalingList(getScalingListFile()))
+    if(m_cSPS.getScalingList().xParseScalingList(getScalingListFileName()))
     {
       Bool bParsedScalingList=false; // Use of boolean so that assertion outputs useful string
@@ -842,5 +848,10 @@
     m_cSPS.setUsedByCurrPicLtSPSFlag(k, 0);
   }
+
+#if U0132_TARGET_BITS_SATURATION
+  if( getPictureTimingSEIEnabled() || getDecodingUnitInfoSEIEnabled() || getCpbSaturationEnabled() )
+#else
   if( getPictureTimingSEIEnabled() || getDecodingUnitInfoSEIEnabled() )
+#endif
   {
     xInitHrdParameters();
@@ -866,7 +877,21 @@
   m_cSPS.setSpsRangeExtensionsFlag( m_cSPS.getSpsRangeExtension().settingsDifferFromDefaults() );
 #endif
-
-}
-
+}
+#if U0132_TARGET_BITS_SATURATION
+// calculate scale value of bitrate and initial delay
+Int calcScale(Int x)
+{
+  UInt iMask = 0xffffffff;
+  Int ScaleValue = 32;
+
+  while ((x&iMask) != 0)
+  {
+    ScaleValue--;
+    iMask = (iMask >> 1);
+}
+
+  return ScaleValue;
+}
+#endif
 Void TEncTop::xInitHrdParameters()
 {
@@ -874,6 +899,11 @@
   Int  bitRate         = getTargetBitrate();
   Bool isRandomAccess  = getIntraPeriod() > 0;
-
+# if U0132_TARGET_BITS_SATURATION
+  Int cpbSize          = getCpbSize();
+
+  if( !getVuiParametersPresentFlag() && !getCpbSaturationEnabled() )
+#else
   if( !getVuiParametersPresentFlag() )
+#endif
   {
     return;
@@ -925,6 +955,27 @@
   }
 
+#if U0132_TARGET_BITS_SATURATION
+  if (calcScale(bitRate) <= 6)
+  {
+    hrd->setBitRateScale(0);
+  }
+  else
+  {
+    hrd->setBitRateScale(calcScale(bitRate) - 6);
+  }
+
+  if (calcScale(cpbSize) <= 4)
+  {
+    hrd->setCpbSizeScale(0);
+  }
+  else
+  {
+    hrd->setCpbSizeScale(calcScale(cpbSize) - 4);
+  }
+#else
   hrd->setBitRateScale( 4 );                                       // in units of 2^( 6 + 4 ) = 1,024 bps
   hrd->setCpbSizeScale( 6 );                                       // in units of 2^( 4 + 6 ) = 1,024 bit
+#endif
+
   hrd->setDuCpbSizeScale( 6 );                                     // in units of 2^( 4 + 6 ) = 1,024 bit
 
@@ -958,5 +1009,10 @@
     bitrateValue = bitRate / (1 << (6 + hrd->getBitRateScale()) );      // bitRate is in bits, so it needs to be scaled down
     // CpbSize[ i ] = ( cpb_size_value_minus1[ i ] + 1 ) * 2^( 4 + cpb_size_scale )
+#if U0132_TARGET_BITS_SATURATION
+    cpbSizeValue = cpbSize / (1 << (4 + hrd->getCpbSizeScale()) );      // using bitRate results in 1 second CPB size
+#else
     cpbSizeValue = bitRate / (1 << (4 + hrd->getCpbSizeScale()) );      // using bitRate results in 1 second CPB size
+#endif
+
 
     // DU CPB size could be smaller (i.e. bitrateValue / number of DUs), but we don't know 
@@ -1066,5 +1122,5 @@
   m_cPPS.setQpOffset(COMPONENT_Cr, m_chromaCrQpOffset );
 
-  m_cPPS.setEntropyCodingSyncEnabledFlag( m_iWaveFrontSynchro > 0 );
+  m_cPPS.setEntropyCodingSyncEnabledFlag( m_entropyCodingSyncEnabledFlag );
   m_cPPS.setTilesEnabledFlag( (m_iNumColumnsMinus1 > 0 || m_iNumRowsMinus1 > 0) );
   m_cPPS.setUseWP( m_useWeightedPred );
@@ -1509,8 +1565,23 @@
     Int iBaseViewIdx = m_cameraParameters->getBaseSortedId2Id()[ iBaseViewSIdx ];
 
-    TComPicYuv* pcPicYuvVideoRec  = m_ivPicLists->getPicYuv( iBaseViewIdx, false, iPoc, true  );
-    TComPicYuv* pcPicYuvDepthRec  = m_ivPicLists->getPicYuv( iBaseViewIdx, true , iPoc, true  );
-    TComPicYuv* pcPicYuvVideoOrg  = m_ivPicLists->getPicYuv( iBaseViewIdx, false, iPoc, false );
-    TComPicYuv* pcPicYuvDepthOrg  = m_ivPicLists->getPicYuv( iBaseViewIdx, true , iPoc, false );    
+    Int  auxId     =   getVPS()->getAuxId  ( getLayerId() );     
+    Bool depthFlag = ( getVPS()->getDepthId( getLayerId() ) == 1 ); 
+
+    if( auxId == 0 && !depthFlag  )
+    {
+      // Defaults for texture layers
+#if NH_3D
+      depthFlag = true; 
+      auxId     = 0; 
+#else
+      depthFlag = false; 
+      auxId     = 2; 
+#endif
+    }
+
+    TComPicYuv* pcPicYuvVideoRec  = m_ivPicLists->getPicYuv( iBaseViewIdx, false    , 0    , iPoc, true  );
+    TComPicYuv* pcPicYuvDepthRec  = m_ivPicLists->getPicYuv( iBaseViewIdx, depthFlag, auxId, iPoc, true  );
+    TComPicYuv* pcPicYuvVideoOrg  = m_ivPicLists->getPicYuv( iBaseViewIdx, false,     0    , iPoc, false );
+    TComPicYuv* pcPicYuvDepthOrg  = m_ivPicLists->getPicYuv( iBaseViewIdx, depthFlag, auxId, iPoc, false );    
 
     TComPicYuv* pcPicYuvVideoRef  = ( iVideoDistMode == 2 ) ? pcPicYuvVideoOrg  : NULL;
@@ -1577,5 +1648,5 @@
     if ( iOrgRefBaseViewSIdx != -1 )
     {
-      pcPicYuvOrgRef = m_ivPicLists->getPicYuv(  m_cameraParameters->getBaseSortedId2Id()[ iOrgRefBaseViewSIdx ] , false, iPoc, false );
+      pcPicYuvOrgRef = m_ivPicLists->getPicYuv(  m_cameraParameters->getBaseSortedId2Id()[ iOrgRefBaseViewSIdx ] , false, 0, iPoc, false );
       AOF ( pcPicYuvOrgRef );
     }
Index: trunk/source/Lib/TLibEncoder/WeightPredAnalysis.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/WeightPredAnalysis.cpp	(revision 1357)
+++ trunk/source/Lib/TLibEncoder/WeightPredAnalysis.cpp	(revision 1386)
@@ -41,7 +41,186 @@
 #include "../TLibCommon/TComPicYuv.h"
 #include "WeightPredAnalysis.h"
-
-#define ABS(a)    ((a) < 0 ? - (a) : (a))
-#define DTHRESH (0.99)
+#include <limits>
+
+static const Double WEIGHT_PRED_SAD_RELATIVE_TO_NON_WEIGHT_PRED_SAD=0.99; // NOTE: U0040 used 0.95
+
+//! calculate SAD values for both WP version and non-WP version.
+static
+Int64 xCalcSADvalueWP(const Int   bitDepth,
+                      const Pel  *pOrgPel,
+                      const Pel  *pRefPel,
+                      const Int   width,
+                      const Int   height,
+                      const Int   orgStride,
+                      const Int   refStride,
+                      const Int   log2Denom,
+                      const Int   weight,
+                      const Int   offset,
+                      const Bool  useHighPrecision);
+
+//! calculate SAD values for both WP version and non-WP version.
+static
+Int64 xCalcSADvalueWPOptionalClip(const Int   bitDepth,
+                                  const Pel  *pOrgPel,
+                                  const Pel  *pRefPel,
+                                  const Int   width,
+                                  const Int   height,
+                                  const Int   orgStride,
+                                  const Int   refStride,
+                                  const Int   log2Denom,
+                                  const Int   weight,
+                                  const Int   offset,
+                                  const Bool  useHighPrecision,
+                                  const Bool  clipped);
+
+// -----------------------------------------------------------------------------
+// Helper functions
+
+
+//! calculate Histogram for array of pixels
+static
+Void xCalcHistogram(const Pel  *pPel,
+                    std::vector<Int> &histogram,
+                    const Int   width,
+                    const Int   height,
+                    const Int   stride,
+                    const Int   maxPel)
+{
+  histogram.clear();
+  histogram.resize(maxPel);
+  for( Int y = 0; y < height; y++ )
+  {
+    for( Int x = 0; x < width; x++ )
+    {
+      const Pel v=pPel[x];
+      histogram[v<0?0:(v>=maxPel)?maxPel-1:v]++;
+    }
+    pPel += stride;
+  }
+}
+
+static
+Distortion xCalcHistDistortion (const std::vector<Int> &histogram0,
+                                const std::vector<Int> &histogram1)
+{
+  Distortion distortion = 0;
+  assert(histogram0.size()==histogram1.size());
+  const Int numElements=Int(histogram0.size());
+
+  // Scan histograms to compute histogram distortion
+  for (Int i = 0; i <= numElements; i++)
+  {
+    distortion += (Distortion)(abs(histogram0[i] - histogram1[i]));
+  }
+
+  return distortion;
+}
+
+static
+void xScaleHistogram(const std::vector<Int> &histogramInput,
+                           std::vector<Int> &histogramOutput, // cannot be the same as the input
+                     const Int               bitDepth,
+                     const Int               log2Denom,
+                     const Int               weight,
+                     const Int               offset,
+                     const Bool              bHighPrecision)
+{
+  assert(&histogramInput != &histogramOutput);
+  const Int numElements=Int(histogramInput.size());
+  histogramOutput.clear();
+  histogramOutput.resize(numElements);
+
+  const Int64 iRealLog2Denom = bHighPrecision ? 0 : (bitDepth - 8);
+  const Int64 iRealOffset    = ((Int64)offset)<<iRealLog2Denom;
+
+  const Int divOffset = log2Denom == 0 ? 0 : 1 << (log2Denom - 1);
+  // Scan histogram and apply illumination parameters appropriately
+  // Then compute updated histogram.
+  // Note that this technique only works with single list weights/offsets.
+
+  for (Int i = 0; i < numElements; i++)
+  {
+    const Int j = Clip3(0, numElements - 1, (Int)(((weight * i + divOffset) >> log2Denom) + iRealOffset));
+    histogramOutput[j] += histogramInput[i];
+  }
+}
+
+static
+Distortion xSearchHistogram(const std::vector<Int> &histogramSource,
+                            const std::vector<Int> &histogramRef,
+                                  std::vector<Int> &outputHistogram,
+                            const Int               bitDepth,
+                            const Int               log2Denom,
+                                  Int              &weightToUpdate,
+                                  Int              &offsetToUpdate,
+                            const Bool              bHighPrecision,
+                            const ComponentID       compID)
+{
+  const Int initialWeight   = weightToUpdate;
+  const Int initialOffset   = offsetToUpdate;
+  const Int weightRange     = 10;
+  const Int offsetRange     = 10;
+  const Int maxOffset       = 1 << ((bHighPrecision == true) ? (bitDepth - 1) : 7);
+  const Int range           = bHighPrecision ? (1<<bitDepth) / 2 : 128;
+  const Int defaultWeight   = (1<<log2Denom);
+  const Int minSearchWeight = std::max<Int>(initialWeight - weightRange, defaultWeight - range);
+  const Int maxSearchWeight = std::min<Int>(initialWeight + weightRange+1, defaultWeight + range);
+
+  Distortion minDistortion   = std::numeric_limits<Distortion>::max();
+  Int        bestWeight      = initialWeight;
+  Int        bestOffset      = initialOffset;
+
+  for (Int searchWeight = minSearchWeight; searchWeight < maxSearchWeight; searchWeight++)
+  {
+    if (compID == COMPONENT_Y)
+    {
+      for (Int searchOffset = std::max<Int>(initialOffset - offsetRange, -maxOffset);
+               searchOffset <= initialOffset + offsetRange && searchOffset<=(maxOffset-1);
+               searchOffset++)
+      {
+        xScaleHistogram(histogramRef, outputHistogram, bitDepth, log2Denom, searchWeight, searchOffset, bHighPrecision);
+        const Distortion distortion = xCalcHistDistortion(histogramSource, outputHistogram);
+
+        if (distortion < minDistortion)
+        {
+          minDistortion = distortion;
+          bestWeight    = searchWeight;
+          bestOffset    = searchOffset;
+        }
+      }
+    }
+    else
+    {
+      const Int pred        = ( maxOffset - ( ( maxOffset*searchWeight)>>(log2Denom) ) );
+
+      for (Int searchOffset = initialOffset - offsetRange; searchOffset <= initialOffset + offsetRange; searchOffset++)
+      {
+        const Int deltaOffset   = Clip3( -4*maxOffset, 4*maxOffset-1, (searchOffset - pred) ); // signed 10bit (if !bHighPrecision)
+        const Int clippedOffset = Clip3( -1*maxOffset, 1*maxOffset-1, (deltaOffset  + pred) ); // signed 8bit  (if !bHighPrecision)
+        xScaleHistogram(histogramRef, outputHistogram, bitDepth, log2Denom, searchWeight, clippedOffset, bHighPrecision);
+        const Distortion distortion = xCalcHistDistortion(histogramSource, outputHistogram);
+
+        if (distortion < minDistortion)
+        {
+          minDistortion = distortion;
+          bestWeight    = searchWeight;
+          bestOffset    = clippedOffset;
+        }
+      }
+    }
+  }
+
+  weightToUpdate = bestWeight;
+  offsetToUpdate = bestOffset;
+
+  // regenerate best histogram
+  xScaleHistogram(histogramRef, outputHistogram, bitDepth, log2Denom, bestWeight, bestOffset, bHighPrecision);
+
+  return minDistortion;
+}
+
+
+// -----------------------------------------------------------------------------
+// Member functions
 
 WeightPredAnalysis::WeightPredAnalysis()
@@ -49,9 +228,9 @@
   for ( UInt lst =0 ; lst<NUM_REF_PIC_LIST_01 ; lst++ )
   {
-    for ( Int iRefIdx=0 ; iRefIdx<MAX_NUM_REF ; iRefIdx++ )
+    for ( Int refIdx=0 ; refIdx<MAX_NUM_REF ; refIdx++ )
     {
       for ( Int comp=0 ; comp<MAX_NUM_COMPONENT ;comp++ )
       {
-        WPScalingParam  *pwp   = &(m_wp[lst][iRefIdx][comp]);
+        WPScalingParam  *pwp   = &(m_wp[lst][refIdx][comp]);
         pwp->bPresentFlag      = false;
         pwp->uiLog2WeightDenom = 0;
@@ -78,34 +257,34 @@
     // calculate DC/AC value for channel
 
-    const Int iStride = pPic->getStride(compID);
-    const Int iWidth  = pPic->getWidth(compID);
-    const Int iHeight = pPic->getHeight(compID);
-
-    const Int iSample = iWidth*iHeight;
-
-    Int64 iOrgDC = 0;
+    const Int stride = pPic->getStride(compID);
+    const Int width  = pPic->getWidth(compID);
+    const Int height = pPic->getHeight(compID);
+
+    const Int sample = width*height;
+
+    Int64 orgDC = 0;
     {
       const Pel *pPel = pPic->getAddr(compID);
 
-      for(Int y = 0; y < iHeight; y++, pPel+=iStride )
-      {
-        for(Int x = 0; x < iWidth; x++ )
-        {
-          iOrgDC += (Int)( pPel[x] );
-        }
-      }
-    }
-
-    const Int64 iOrgNormDC = ((iOrgDC+(iSample>>1)) / iSample);
-
-    Int64 iOrgAC = 0;
+      for(Int y = 0; y < height; y++, pPel+=stride )
+      {
+        for(Int x = 0; x < width; x++ )
+        {
+          orgDC += (Int)( pPel[x] );
+        }
+      }
+    }
+
+    const Int64 orgNormDC = ((orgDC+(sample>>1)) / sample);
+
+    Int64 orgAC = 0;
     {
       const Pel *pPel = pPic->getAddr(compID);
 
-      for(Int y = 0; y < iHeight; y++, pPel += iStride )
-      {
-        for(Int x = 0; x < iWidth; x++ )
-        {
-          iOrgAC += abs( (Int)pPel[x] - (Int)iOrgNormDC );
+      for(Int y = 0; y < height; y++, pPel += stride )
+      {
+        for(Int x = 0; x < width; x++ )
+        {
+          orgAC += abs( (Int)pPel[x] - (Int)orgNormDC );
         }
       }
@@ -113,6 +292,6 @@
 
     const Int fixedBitShift = (slice->getSPS()->getSpsRangeExtension().getHighPrecisionOffsetsEnabledFlag())?RExt__PREDICTION_WEIGHTING_ANALYSIS_DC_PRECISION:0;
-    weightACDCParam[compID].iDC = (((iOrgDC<<fixedBitShift)+(iSample>>1)) / iSample);
-    weightACDCParam[compID].iAC = iOrgAC;
+    weightACDCParam[compID].iDC = (((orgDC<<fixedBitShift)+(sample>>1)) / sample);
+    weightACDCParam[compID].iAC = orgAC;
   }
 
@@ -126,18 +305,18 @@
   const TComPicYuv *pPic = slice->getPic()->getPicYuvOrg();
 
-  Int iPresentCnt = 0;
+  Int presentCnt = 0;
   for ( UInt lst=0 ; lst<NUM_REF_PIC_LIST_01 ; lst++ )
   {
-    for ( Int iRefIdx=0 ; iRefIdx<MAX_NUM_REF ; iRefIdx++ )
+    for ( Int refIdx=0 ; refIdx<MAX_NUM_REF ; refIdx++ )
     {
       for(Int componentIndex = 0; componentIndex < pPic->getNumberValidComponents(); componentIndex++)
       {
-        WPScalingParam  *pwp = &(m_wp[lst][iRefIdx][componentIndex]);
-        iPresentCnt += (Int)pwp->bPresentFlag;
-      }
-    }
-  }
-
-  if(iPresentCnt==0)
+        WPScalingParam  *pwp = &(m_wp[lst][refIdx][componentIndex]);
+        presentCnt += (Int)pwp->bPresentFlag;
+      }
+    }
+  }
+
+  if(presentCnt==0)
   {
     slice->setTestWeightPred(false);
@@ -146,9 +325,9 @@
     for ( UInt lst=0 ; lst<NUM_REF_PIC_LIST_01 ; lst++ )
     {
-      for ( Int iRefIdx=0 ; iRefIdx<MAX_NUM_REF ; iRefIdx++ )
+      for ( Int refIdx=0 ; refIdx<MAX_NUM_REF ; refIdx++ )
       {
         for(Int componentIndex = 0; componentIndex < pPic->getNumberValidComponents(); componentIndex++)
         {
-          WPScalingParam  *pwp = &(m_wp[lst][iRefIdx][componentIndex]);
+          WPScalingParam  *pwp = &(m_wp[lst][refIdx][componentIndex]);
 
           pwp->bPresentFlag      = false;
@@ -163,5 +342,5 @@
   else
   {
-    slice->setTestWeightPred(slice->getPPS()->getUseWP());
+    slice->setTestWeightPred  (slice->getPPS()->getUseWP());
     slice->setTestWeightBiPred(slice->getPPS()->getWPBiPred());
   }
@@ -170,5 +349,5 @@
 
 //! estimate wp tables for explicit wp
-Void WeightPredAnalysis::xEstimateWPParamSlice(TComSlice *const slice)
+Void WeightPredAnalysis::xEstimateWPParamSlice(TComSlice *const slice, const WeightedPredictionMethod method)
 {
   Int  iDenom         = 6;
@@ -191,5 +370,25 @@
   // selecting whether WP is used, or not (fast search)
   // NOTE: This is not operating on a slice, but the entire picture.
-  xSelectWP(slice, iDenom);
+  switch (method)
+  {
+    case WP_PER_PICTURE_WITH_SIMPLE_DC_COMBINED_COMPONENT:
+      xSelectWP(slice, iDenom);
+      break;
+    case WP_PER_PICTURE_WITH_SIMPLE_DC_PER_COMPONENT:
+      xSelectWPHistExtClip(slice, iDenom, false, false, false);
+      break;
+    case WP_PER_PICTURE_WITH_HISTOGRAM_AND_PER_COMPONENT:
+      xSelectWPHistExtClip(slice, iDenom, false, false, true);
+      break;
+    case WP_PER_PICTURE_WITH_HISTOGRAM_AND_PER_COMPONENT_AND_CLIPPING:
+      xSelectWPHistExtClip(slice, iDenom, false, true, true);
+      break;
+    case WP_PER_PICTURE_WITH_HISTOGRAM_AND_PER_COMPONENT_AND_CLIPPING_AND_EXTENSION:
+      xSelectWPHistExtClip(slice, iDenom, true, true, true);
+      break;
+    default:
+      assert(0);
+      exit(1);
+  }
 
   slice->setWpScaling( m_wp );
@@ -251,5 +450,5 @@
         // Weighting factor limitation
         const Int defaultWeight = (1<<log2Denom);
-        const Int deltaWeight   = (defaultWeight - weight);
+        const Int deltaWeight   = (weight - defaultWeight);
 
         if(deltaWeight >= range || deltaWeight < -range)
@@ -269,21 +468,143 @@
 
 
+/** select whether weighted pred enables or not.
+ * \param TComSlice *slice
+ * \param log2Denom
+ * \returns Bool
+ */
+Bool WeightPredAnalysis::xSelectWPHistExtClip(TComSlice *const slice, const Int log2Denom, const Bool bDoEnhancement, const Bool bClipInitialSADWP, const Bool bUseHistogram)
+{
+  const TComPicYuv *const pPic             = slice->getPic()->getPicYuvOrg();
+  const Int               defaultWeight    = 1<<log2Denom;
+  const Int               numPredDir       = slice->isInterP() ? 1 : 2;
+  const Bool              useHighPrecision = slice->getSPS()->getSpsRangeExtension().getHighPrecisionOffsetsEnabledFlag();
+
+  assert (numPredDir <= Int(NUM_REF_PIC_LIST_01));
+
+  for ( Int refList = 0; refList < numPredDir; refList++ )
+  {
+    const RefPicList eRefPicList = ( refList ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
+
+    for ( Int refIdxTemp = 0; refIdxTemp < slice->getNumRefIdx(eRefPicList); refIdxTemp++ )
+    {
+      Bool  useChromaWeight = false;
+
+      for(Int comp=0; comp<pPic->getNumberValidComponents(); comp++)
+      {
+        const ComponentID  compID     = ComponentID(comp);
+        const Pel         *pOrg       = pPic->getAddr(compID);
+        const Pel         *pRef       = slice->getRefPic(eRefPicList, refIdxTemp)->getPicYuvRec()->getAddr(compID);
+        const Int          orgStride  = pPic->getStride(compID);
+        const Int          refStride  = slice->getRefPic(eRefPicList, refIdxTemp)->getPicYuvRec()->getStride(compID);
+        const Int          width      = pPic->getWidth(compID);
+        const Int          height     = pPic->getHeight(compID);
+        const Int          bitDepth   = slice->getSPS()->getBitDepth(toChannelType(compID));
+              WPScalingParam &wp      = m_wp[refList][refIdxTemp][compID];
+              Int          weight     = wp.iWeight;
+              Int          offset     = wp.iOffset;
+              Int          weightDef  = defaultWeight;
+              Int          offsetDef  = 0;
+
+        // calculate SAD costs with/without wp for luma
+        const Int64 SADnoWP = xCalcSADvalueWPOptionalClip(bitDepth, pOrg, pRef, width, height, orgStride, refStride, log2Denom, defaultWeight, 0, useHighPrecision, bClipInitialSADWP);
+        if (SADnoWP > 0)
+        {
+          const Int64 SADWP   = xCalcSADvalueWPOptionalClip(bitDepth, pOrg, pRef, width, height, orgStride, refStride, log2Denom, weight,   offset, useHighPrecision, bClipInitialSADWP);
+          const Double dRatioSAD = (Double)SADWP / (Double)SADnoWP;
+          Double dRatioSr0SAD = std::numeric_limits<Double>::max();
+          Double dRatioSrSAD  = std::numeric_limits<Double>::max();
+
+          if (bUseHistogram)
+          {
+            std::vector<Int> histogramOrg;// = pPic->getHistogram(compID);
+            std::vector<Int> histogramRef;// = slice->getRefPic(eRefPicList, refIdxTemp)->getPicYuvRec()->getHistogram(compID);
+            std::vector<Int> searchedHistogram;
+
+            // Compute histograms
+            xCalcHistogram(pOrg, histogramOrg, width, height, orgStride, 1 << bitDepth);
+            xCalcHistogram(pRef, histogramRef, width, height, refStride, 1 << bitDepth);
+
+            // Do a histogram search around DC WP parameters; resulting distortion and 'searchedHistogram' is discarded
+            xSearchHistogram(histogramOrg, histogramRef, searchedHistogram, bitDepth, log2Denom, weight, offset, useHighPrecision, compID);
+            // calculate updated WP SAD
+            const Int64 SADSrWP = xCalcSADvalueWP(bitDepth, pOrg, pRef, width, height, orgStride, refStride, log2Denom, weight, offset, useHighPrecision);
+            dRatioSrSAD  = (Double)SADSrWP  / (Double)SADnoWP;
+
+            if (bDoEnhancement)
+            {
+              // Do the same around the default ones; resulting distortion and 'searchedHistogram' is discarded
+              xSearchHistogram(histogramOrg, histogramRef, searchedHistogram, bitDepth, log2Denom, weightDef, offsetDef, useHighPrecision, compID);
+              // calculate updated WP SAD
+              const Int64 SADSr0WP = xCalcSADvalueWP(bitDepth, pOrg, pRef, width, height, orgStride, refStride, log2Denom, weightDef, offsetDef, useHighPrecision);
+              dRatioSr0SAD = (Double)SADSr0WP / (Double)SADnoWP;
+            }
+          }
+
+          if(min(dRatioSr0SAD, min(dRatioSAD, dRatioSrSAD)) >= WEIGHT_PRED_SAD_RELATIVE_TO_NON_WEIGHT_PRED_SAD)
+          {
+            wp.bPresentFlag      = false;
+            wp.iOffset           = 0;
+            wp.iWeight           = defaultWeight;
+            wp.uiLog2WeightDenom = log2Denom;
+          }
+          else
+          {
+            if (compID != COMPONENT_Y)
+            {
+              useChromaWeight = true;
+            }
+
+            if (dRatioSr0SAD < dRatioSrSAD && dRatioSr0SAD < dRatioSAD)
+            {
+              wp.bPresentFlag      = true;
+              wp.iOffset           = offsetDef;
+              wp.iWeight           = weightDef;
+              wp.uiLog2WeightDenom = log2Denom;
+            }
+            else if (dRatioSrSAD < dRatioSAD)
+            {
+              wp.bPresentFlag      = true;
+              wp.iOffset           = offset;
+              wp.iWeight           = weight;
+              wp.uiLog2WeightDenom = log2Denom;
+            }
+          }
+        }
+        else // (SADnoWP <= 0)
+        {
+          wp.bPresentFlag      = false;
+          wp.iOffset           = 0;
+          wp.iWeight           = defaultWeight;
+          wp.uiLog2WeightDenom = log2Denom;
+        }
+      }
+
+      for(Int comp=1; comp<pPic->getNumberValidComponents(); comp++)
+      {
+        m_wp[refList][refIdxTemp][comp].bPresentFlag = useChromaWeight;
+      }
+    }
+  }
+
+  return true;
+}
+
 //! select whether weighted pred enables or not.
 Bool WeightPredAnalysis::xSelectWP(TComSlice *const slice, const Int log2Denom)
 {
         TComPicYuv *const pPic                                = slice->getPic()->getPicYuvOrg();
-  const Int               iDefaultWeight                      = ((Int)1<<log2Denom);
-  const Int               iNumPredDir                         = slice->isInterP() ? 1 : 2;
+  const Int               defaultWeight                       = 1<<log2Denom;
+  const Int               numPredDir                          = slice->isInterP() ? 1 : 2;
   const Bool              useHighPrecisionPredictionWeighting = slice->getSPS()->getSpsRangeExtension().getHighPrecisionOffsetsEnabledFlag();
 
-  assert (iNumPredDir <= Int(NUM_REF_PIC_LIST_01));
-
-  for ( Int iRefList = 0; iRefList < iNumPredDir; iRefList++ )
-  {
-    const RefPicList eRefPicList = ( iRefList ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
-
-    for ( Int iRefIdxTemp = 0; iRefIdxTemp < slice->getNumRefIdx(eRefPicList); iRefIdxTemp++ )
-    {
-      Int64 iSADWP = 0, iSADnoWP = 0;
+  assert (numPredDir <= Int(NUM_REF_PIC_LIST_01));
+
+  for ( Int refList = 0; refList < numPredDir; refList++ )
+  {
+    const RefPicList eRefPicList = ( refList ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
+
+    for ( Int refIdxTemp = 0; refIdxTemp < slice->getNumRefIdx(eRefPicList); refIdxTemp++ )
+    {
+      Int64 SADWP = 0, SADnoWP = 0;
 
       for(Int comp=0; comp<pPic->getNumberValidComponents(); comp++)
@@ -291,25 +612,26 @@
         const ComponentID  compID     = ComponentID(comp);
               Pel         *pOrg       = pPic->getAddr(compID);
-              Pel         *pRef       = slice->getRefPic(eRefPicList, iRefIdxTemp)->getPicYuvRec()->getAddr(compID);
-        const Int          iOrgStride = pPic->getStride(compID);
-        const Int          iRefStride = slice->getRefPic(eRefPicList, iRefIdxTemp)->getPicYuvRec()->getStride(compID);
-        const Int          iWidth     = pPic->getWidth(compID);
-        const Int          iHeight    = pPic->getHeight(compID);
+              Pel         *pRef       = slice->getRefPic(eRefPicList, refIdxTemp)->getPicYuvRec()->getAddr(compID);
+        const Int          orgStride = pPic->getStride(compID);
+        const Int          refStride = slice->getRefPic(eRefPicList, refIdxTemp)->getPicYuvRec()->getStride(compID);
+        const Int          width     = pPic->getWidth(compID);
+        const Int          height    = pPic->getHeight(compID);
         const Int          bitDepth   = slice->getSPS()->getBitDepth(toChannelType(compID));
 
         // calculate SAD costs with/without wp for luma
-        iSADWP   += xCalcSADvalueWP(bitDepth, pOrg, pRef, iWidth, iHeight, iOrgStride, iRefStride, log2Denom, m_wp[iRefList][iRefIdxTemp][compID].iWeight, m_wp[iRefList][iRefIdxTemp][compID].iOffset, useHighPrecisionPredictionWeighting);
-        iSADnoWP += xCalcSADvalueWP(bitDepth, pOrg, pRef, iWidth, iHeight, iOrgStride, iRefStride, log2Denom, iDefaultWeight, 0, useHighPrecisionPredictionWeighting);
-      }
-
-      const Double dRatio = ((Double)iSADWP / (Double)iSADnoWP);
-      if(dRatio >= (Double)DTHRESH)
+        SADWP   += xCalcSADvalueWP(bitDepth, pOrg, pRef, width, height, orgStride, refStride, log2Denom, m_wp[refList][refIdxTemp][compID].iWeight, m_wp[refList][refIdxTemp][compID].iOffset, useHighPrecisionPredictionWeighting);
+        SADnoWP += xCalcSADvalueWP(bitDepth, pOrg, pRef, width, height, orgStride, refStride, log2Denom, defaultWeight, 0, useHighPrecisionPredictionWeighting);
+      }
+
+      const Double dRatio = SADnoWP > 0 ? (((Double)SADWP / (Double)SADnoWP)) : std::numeric_limits<Double>::max();
+      if(dRatio >= WEIGHT_PRED_SAD_RELATIVE_TO_NON_WEIGHT_PRED_SAD)
       {
         for(Int comp=0; comp<pPic->getNumberValidComponents(); comp++)
         {
-          m_wp[iRefList][iRefIdxTemp][comp].bPresentFlag      = false;
-          m_wp[iRefList][iRefIdxTemp][comp].iOffset           = 0;
-          m_wp[iRefList][iRefIdxTemp][comp].iWeight           = iDefaultWeight;
-          m_wp[iRefList][iRefIdxTemp][comp].uiLog2WeightDenom = log2Denom;
+          WPScalingParam &wp=m_wp[refList][refIdxTemp][comp];
+          wp.bPresentFlag      = false;
+          wp.iOffset           = 0;
+          wp.iWeight           = defaultWeight;
+          wp.uiLog2WeightDenom = log2Denom;
         }
       }
@@ -320,32 +642,88 @@
 }
 
-
-//! calculate SAD values for both WP version and non-WP version.
-Int64 WeightPredAnalysis::xCalcSADvalueWP(const Int   bitDepth,
-                                          const Pel  *pOrgPel,
-                                          const Pel  *pRefPel,
-                                          const Int   iWidth,
-                                          const Int   iHeight,
-                                          const Int   iOrgStride,
-                                          const Int   iRefStride,
-                                          const Int   iLog2Denom,
-                                          const Int   iWeight,
-                                          const Int   iOffset,
-                                          const Bool  useHighPrecisionPredictionWeighting)
-{
-  const Int64 iSize          = iWidth*iHeight;
-  const Int64 iRealLog2Denom = useHighPrecisionPredictionWeighting ? iLog2Denom : (iLog2Denom + (bitDepth - 8));
-
-  Int64 iSAD = 0;
-  for( Int y = 0; y < iHeight; y++ )
-  {
-    for( Int x = 0; x < iWidth; x++ )
-    {
-      iSAD += ABS(( ((Int64)pOrgPel[x]<<(Int64)iLog2Denom) - ( (Int64)pRefPel[x] * (Int64)iWeight + ((Int64)iOffset<<iRealLog2Denom) ) ) );
-    }
-    pOrgPel += iOrgStride;
-    pRefPel += iRefStride;
-  }
-
-  return (iSAD/iSize);
-}
+// Alternatively, a SSE-based measure could be used instead.
+// The respective function has been removed as it currently redundant.
+static
+Int64 xCalcSADvalueWP(const Int   bitDepth,
+                      const Pel  *pOrgPel,
+                      const Pel  *pRefPel,
+                      const Int   width,
+                      const Int   height,
+                      const Int   orgStride,
+                      const Int   refStride,
+                      const Int   log2Denom,
+                      const Int   weight,
+                      const Int   offset,
+                      const Bool  useHighPrecision)
+{
+  //const Int64 iSize          = iWidth*iHeight;
+  const Int64 realLog2Denom = useHighPrecision ? log2Denom : (log2Denom + (bitDepth - 8));
+  const Int64 realOffset    = ((Int64)offset)<<realLog2Denom;
+
+  Int64 SAD = 0;
+  for( Int y = 0; y < height; y++ )
+  {
+    for( Int x = 0; x < width; x++ )
+    {
+      SAD += abs(( ((Int64)pOrgPel[x] << (Int64) log2Denom) - ( (Int64) pRefPel[x] * (Int64) weight + (realOffset) ) ) );
+    }
+    pOrgPel += orgStride;
+    pRefPel += refStride;
+  }
+
+  //return (iSAD/iSize);
+  return SAD;
+}
+
+static
+Int64 xCalcSADvalueWPOptionalClip(const Int   bitDepth,
+                                  const Pel  *pOrgPel,
+                                  const Pel  *pRefPel,
+                                  const Int   width,
+                                  const Int   height,
+                                  const Int   orgStride,
+                                  const Int   refStride,
+                                  const Int   log2Denom,
+                                  const Int   weight,
+                                  const Int   offset,
+                                  const Bool  useHighPrecision,
+                                  const Bool  clipped)
+{
+  Int64 SAD = 0;
+  if (clipped)
+  {
+    const Int64 realLog2Denom = useHighPrecision ? 0 : (bitDepth - 8);
+    const Int64 realOffset    = (Int64)offset<<realLog2Denom;
+    const Int64 roundOffset = (log2Denom == 0) ? 0 : 1 << (log2Denom - 1);
+    const Int64 minValue = 0;
+    const Int64 maxValue = (1 << bitDepth) - 1;
+
+    for( Int y = 0; y < height; y++ )
+    {
+      for( Int x = 0; x < width; x++ )
+      {
+        Int64 scaledValue = Clip3(minValue, maxValue,  ((((Int64) pRefPel[x] * (Int64) weight + roundOffset) ) >>  (Int64) log2Denom) + realOffset);
+        SAD += abs((Int64)pOrgPel[x] -  scaledValue);
+      }
+      pOrgPel += orgStride;
+      pRefPel += refStride;
+    }
+  }
+  else
+  {
+    //const Int64 iSize          = iWidth*iHeight;
+    const Int64 realLog2Denom = useHighPrecision ? log2Denom : (log2Denom + (bitDepth - 8));
+    const Int64 realOffset    = ((Int64)offset)<<realLog2Denom;
+
+    for( Int y = 0; y < height; y++ )
+    {
+      for( Int x = 0; x < width; x++ )
+      {
+        SAD += abs(( ((Int64)pOrgPel[x] << (Int64) log2Denom) - ( (Int64) pRefPel[x] * (Int64) weight + (realOffset) ) ) );
+      }
+      pOrgPel += orgStride;
+      pRefPel += refStride;
+    }
+  }
+  return SAD;
+}
Index: trunk/source/Lib/TLibEncoder/WeightPredAnalysis.h
===================================================================
--- trunk/source/Lib/TLibEncoder/WeightPredAnalysis.h	(revision 1357)
+++ trunk/source/Lib/TLibEncoder/WeightPredAnalysis.h	(revision 1386)
@@ -52,17 +52,6 @@
 
   Bool  xSelectWP            (TComSlice *const slice, const Int log2Denom);
+  Bool  xSelectWPHistExtClip (TComSlice *const slice, const Int log2Denom, const Bool bDoEnhancement, const Bool bClipInitialSADWP, const Bool bUseHistogram);
   Bool  xUpdatingWPParameters(TComSlice *const slice, const Int log2Denom);
-
-  Int64 xCalcSADvalueWP      (const Int   bitDepth,
-                              const Pel  *pOrgPel,
-                              const Pel  *pRefPel,
-                              const Int   iWidth,
-                              const Int   iHeight,
-                              const Int   iOrgStride,
-                              const Int   iRefStride,
-                              const Int   iLog2Denom,
-                              const Int   iWeight,
-                              const Int   iOffset,
-                              const Bool  useHighPrecisionPredictionWeighting);
 
 public:
@@ -72,5 +61,5 @@
   // WP analysis :
   Void  xCalcACDCParamSlice  (TComSlice *const slice);
-  Void  xEstimateWPParamSlice(TComSlice *const slice);
+  Void  xEstimateWPParamSlice(TComSlice *const slice, const WeightedPredictionMethod method);
   Void  xCheckWPEnable       (TComSlice *const slice);
 };
Index: trunk/source/Lib/TLibRenderer/TRenFilter.cpp
===================================================================
--- trunk/source/Lib/TLibRenderer/TRenFilter.cpp	(revision 1357)
+++ trunk/source/Lib/TLibRenderer/TRenFilter.cpp	(revision 1386)
@@ -36,5 +36,5 @@
 #include "TRenFilter.h"
 #include "TRenInterpFilter.h"
-#if NH_3D
+#if NH_3D_VSO
 
 ///// COMMON /////
Index: trunk/source/Lib/TLibRenderer/TRenFilter.h
===================================================================
--- trunk/source/Lib/TLibRenderer/TRenFilter.h	(revision 1357)
+++ trunk/source/Lib/TLibRenderer/TRenFilter.h	(revision 1386)
@@ -39,5 +39,5 @@
 #include "TRenImage.h"
 #include "TRenInterpFilter.h"
-#if NH_3D
+#if NH_3D_VSO
 
 typedef Int (TRenInterpFilter<REN_BIT_DEPTH>::*FpChromaIntFilt) ( Pel*, Int );
Index: trunk/source/Lib/TLibRenderer/TRenImage.cpp
===================================================================
--- trunk/source/Lib/TLibRenderer/TRenImage.cpp	(revision 1357)
+++ trunk/source/Lib/TLibRenderer/TRenImage.cpp	(revision 1386)
@@ -37,5 +37,5 @@
 #include "TRenFilter.h"
 #include "assert.h"
-#if NH_3D
+#if NH_3D_VSO
 
 
Index: trunk/source/Lib/TLibRenderer/TRenImage.h
===================================================================
--- trunk/source/Lib/TLibRenderer/TRenImage.h	(revision 1357)
+++ trunk/source/Lib/TLibRenderer/TRenImage.h	(revision 1386)
@@ -39,5 +39,5 @@
 #include "../TLibCommon/TComPicYuv.h"
 #include "TRenImagePlane.h"
-#if NH_3D
+#if NH_3D_VSO
 
 
Index: trunk/source/Lib/TLibRenderer/TRenImagePlane.cpp
===================================================================
--- trunk/source/Lib/TLibRenderer/TRenImagePlane.cpp	(revision 1357)
+++ trunk/source/Lib/TLibRenderer/TRenImagePlane.cpp	(revision 1386)
@@ -36,5 +36,5 @@
 #include "TRenFilter.h"
 #include <string.h>
-#if NH_3D
+#if NH_3D_VSO
 
 /////// TRenImagePlane ///////
Index: trunk/source/Lib/TLibRenderer/TRenImagePlane.h
===================================================================
--- trunk/source/Lib/TLibRenderer/TRenImagePlane.h	(revision 1357)
+++ trunk/source/Lib/TLibRenderer/TRenImagePlane.h	(revision 1386)
@@ -39,5 +39,5 @@
 #include "../TLibCommon/TComPicYuv.h"
 
-#if NH_3D
+#if NH_3D_VSO
 #define PelImagePlane     TRenImagePlane<Pel>
 #define DoubleImagePlane  TRenImagePlane<Double>
Index: trunk/source/Lib/TLibRenderer/TRenInterpFilter.cpp
===================================================================
--- trunk/source/Lib/TLibRenderer/TRenInterpFilter.cpp	(revision 1357)
+++ trunk/source/Lib/TLibRenderer/TRenInterpFilter.cpp	(revision 1386)
@@ -39,5 +39,5 @@
 
 #include "TRenInterpFilter.h"
-#if NH_3D
+#if NH_3D_VSO
 
 // ====================================================================================================================
Index: trunk/source/Lib/TLibRenderer/TRenInterpFilter.h
===================================================================
--- trunk/source/Lib/TLibRenderer/TRenInterpFilter.h	(revision 1357)
+++ trunk/source/Lib/TLibRenderer/TRenInterpFilter.h	(revision 1386)
@@ -44,5 +44,5 @@
 #include "TLibCommon/CommonDef.h"
 #include "assert.h"
-#if NH_3D
+#if NH_3D_VSO
 
 // ====================================================================================================================
Index: trunk/source/Lib/TLibRenderer/TRenModSetupStrParser.cpp
===================================================================
--- trunk/source/Lib/TLibRenderer/TRenModSetupStrParser.cpp	(revision 1357)
+++ trunk/source/Lib/TLibRenderer/TRenModSetupStrParser.cpp	(revision 1386)
@@ -37,5 +37,5 @@
 #include "TRenModSetupStrParser.h"
 
-#if NH_3D
+#if NH_3D_VSO
 Int
 TRenModSetupStrParser::getNumOfModels()
@@ -153,5 +153,5 @@
 
 Void
-TRenModSetupStrParser::setString( Int iNumOfBaseViews, Char* pchSetStr )
+TRenModSetupStrParser::setString( Int iNumOfBaseViews, TChar* pchSetStr )
 {
   for (Int iContent = 0; iContent < 2; iContent++)
@@ -178,5 +178,5 @@
 TRenModSetupStrParser::xParseString()
 {
-  Char cChar;
+  TChar cChar;
   xGetNextChar(cChar);
   while(  cChar != '\0' )
@@ -220,5 +220,5 @@
   m_bCurrentViewSet = false;
 
-  Char cChar;
+  TChar cChar;
   xGetNextCharGoOn( cChar );
   xError( cChar != '[' );
@@ -249,7 +249,7 @@
 
 Void
-TRenModSetupStrParser::xReadViews( Char cType )
-{
-  Char cChar;
+TRenModSetupStrParser::xReadViews( TChar cType )
+{
+  TChar cChar;
   xGetNextCharGoOn( cChar );
   xError( cChar != '(' );
@@ -272,5 +272,5 @@
 
 Void
-TRenModSetupStrParser::xReadViewInfo( Char cType )
+TRenModSetupStrParser::xReadViewInfo( TChar cType )
 {
   std::vector<Int> aiViewNums;
@@ -280,6 +280,6 @@
   {
   case 'B':
-    Char cVideoType;
-    Char cDepthType;
+    TChar cVideoType;
+    TChar cDepthType;
 
     xGetNextCharGoOn   ( cVideoType );
@@ -317,5 +317,5 @@
   case 'L':
   case 'R':
-    Char cRefType;
+    TChar cRefType;
     xGetNextCharGoOn   ( cRefType   );
     xGetViewNumberRange( aiViewNums );
@@ -328,5 +328,5 @@
 
 Void
-TRenModSetupStrParser::xAddBaseView( Int iViewIdx, Char cVideoType, Char cDepthType )
+TRenModSetupStrParser::xAddBaseView( Int iViewIdx, TChar cVideoType, TChar cDepthType )
 {
   AOF( m_bCurrentViewSet );
@@ -334,7 +334,5 @@
   if ( cDepthType == 'x' ) cDepthType = 'o';
   if ( cVideoType == 'x' ) cVideoType = 'o';
-
-
-
+  
   xError( cDepthType != 'o' && cDepthType != 'c' && cVideoType != 'r' );
   xError( cVideoType != 'o' && cVideoType != 'c' && cVideoType != 'r' );
@@ -346,5 +344,5 @@
 
 Void
-TRenModSetupStrParser::xAddSynthView( Int iViewNum, Char cType, Char cRefType )
+TRenModSetupStrParser::xAddSynthView( Int iViewNum, TChar cType, TChar cRefType )
 {
   AOF( m_bCurrentViewSet );
@@ -399,5 +397,5 @@
   size_t iStartPos;
   size_t iEndPos;
-  Char cChar;
+  TChar cChar;
   xGetNextCharGoOn(cChar );
   if (cChar == '{')
@@ -424,5 +422,5 @@
 
   size_t iNumElem = iEndPos - iStartPos + 1;
-  Char* pcTempBuffer = new Char[  iNumElem + 1];
+  TChar* pcTempBuffer = new TChar[  iNumElem + 1];
   strncpy( pcTempBuffer, m_pchSetStr + iStartPos, iNumElem );
   pcTempBuffer[iNumElem] = '\0';
@@ -433,5 +431,5 @@
 
 Void
-TRenModSetupStrParser::xGetNextCharGoOn( Char& rcNextChar )
+TRenModSetupStrParser::xGetNextCharGoOn( TChar& rcNextChar )
 {
   while ( m_pchSetStr[m_iPosInStr] == ' ' || m_pchSetStr[m_iPosInStr] == ',' )
@@ -445,5 +443,5 @@
 
 Void
-TRenModSetupStrParser::xGetNextChar( Char& rcNextChar )
+TRenModSetupStrParser::xGetNextChar( TChar& rcNextChar )
 {
   size_t iPos = m_iPosInStr;
Index: trunk/source/Lib/TLibRenderer/TRenModSetupStrParser.h
===================================================================
--- trunk/source/Lib/TLibRenderer/TRenModSetupStrParser.h	(revision 1357)
+++ trunk/source/Lib/TLibRenderer/TRenModSetupStrParser.h	(revision 1386)
@@ -39,5 +39,5 @@
 #include "../TLibCommon/TypeDef.h"
 #include "../TAppCommon/TAppComCamPara.h"
-#if NH_3D
+#if NH_3D_VSO
 
 
@@ -92,5 +92,5 @@
   TRenModSetupStrParser();
 
-  Void setString( Int iNumOfBaseViews, Char* pchSetStr );
+  Void setString( Int iNumOfBaseViews, TChar* pchSetStr );
 
 private:
@@ -112,5 +112,5 @@
   Int                              m_iNumberOfModels;
 
-  Char*                            m_pchSetStr;
+  TChar*                            m_pchSetStr;
   size_t                           m_iPosInStr;
 
@@ -118,12 +118,12 @@
   Void xParseString();
   Void xParseSourceView();
-  Void xReadViews         ( Char cType );
-  Void xReadViewInfo      ( Char cType );
-  Void xAddBaseView       ( Int iViewIdx, Char cVideoType, Char cDepthType );
-  Void xAddSynthView      ( Int iViewNum, Char cType, Char cRefType );
+  Void xReadViews         ( TChar cType );
+  Void xReadViewInfo      ( TChar cType );
+  Void xAddBaseView       ( Int iViewIdx, TChar cVideoType, TChar cDepthType );
+  Void xAddSynthView      ( Int iViewNum, TChar cType, TChar cRefType );
   Void xError             ( Bool bIsError );
   Void xGetViewNumberRange( std::vector<Int>& raiViewNumbers );
-  Void xGetNextCharGoOn   ( Char& rcNextChar );
-  Void xGetNextChar       ( Char& rcNextChar );
+  Void xGetNextCharGoOn   ( TChar& rcNextChar );
+  Void xGetNextChar       ( TChar& rcNextChar );
 };
 
Index: trunk/source/Lib/TLibRenderer/TRenTop.cpp
===================================================================
--- trunk/source/Lib/TLibRenderer/TRenTop.cpp	(revision 1357)
+++ trunk/source/Lib/TLibRenderer/TRenTop.cpp	(revision 1386)
@@ -40,5 +40,5 @@
 #include <math.h>
 #include "../TLibCommon/CommonDef.h"
-#if NH_3D
+#if NH_3D_VSO
 
 
Index: trunk/source/Lib/TLibRenderer/TRenTop.h
===================================================================
--- trunk/source/Lib/TLibRenderer/TRenTop.h	(revision 1357)
+++ trunk/source/Lib/TLibRenderer/TRenTop.h	(revision 1386)
@@ -39,5 +39,5 @@
 #include "../TLibCommon/TComPicYuv.h"
 
-#if NH_3D
+#if NH_3D_VSO
 #include <list>
 #include <vector>
Index: trunk/source/Lib/TLibVideoIO/TVideoIOYuv.cpp
===================================================================
--- trunk/source/Lib/TLibVideoIO/TVideoIOYuv.cpp	(revision 1357)
+++ trunk/source/Lib/TLibVideoIO/TVideoIOYuv.cpp	(revision 1386)
@@ -95,4 +95,6 @@
 }
 
+static Void
+copyPlane(const TComPicYuv &src, const ComponentID srcPlane, TComPicYuv &dest, const ComponentID destPlane);
 
 // ====================================================================================================================
@@ -116,5 +118,5 @@
  * \param internalBitDepth bit-depth array to scale image data to/from when reading/writing.
  */
-Void TVideoIOYuv::open( Char* pchFile, Bool bWriteMode, const Int fileBitDepth[MAX_NUM_CHANNEL_TYPE], const Int MSBExtendedBitDepth[MAX_NUM_CHANNEL_TYPE], const Int internalBitDepth[MAX_NUM_CHANNEL_TYPE] )
+Void TVideoIOYuv::open( const std::string &fileName, Bool bWriteMode, const Int fileBitDepth[MAX_NUM_CHANNEL_TYPE], const Int MSBExtendedBitDepth[MAX_NUM_CHANNEL_TYPE], const Int internalBitDepth[MAX_NUM_CHANNEL_TYPE] )
 {
   //NOTE: files cannot have bit depth greater than 16
@@ -141,5 +143,5 @@
   if ( bWriteMode )
   {
-    m_cHandle.open( pchFile, ios::binary | ios::out );
+    m_cHandle.open( fileName.c_str(), ios::binary | ios::out );
 
     if( m_cHandle.fail() )
@@ -151,5 +153,5 @@
   else
   {
-    m_cHandle.open( pchFile, ios::binary | ios::in );
+    m_cHandle.open( fileName.c_str(), ios::binary | ios::in );
 
     if( m_cHandle.fail() )
@@ -217,5 +219,5 @@
 
   /* fall back to consuming the input */
-  Char buf[512];
+  TChar buf[512];
   const streamoff offset_mod_bufsize = offset % sizeof(buf);
   for (streamoff i = 0; i < offset - offset_mod_bufsize; i += sizeof(buf))
@@ -274,5 +276,6 @@
   const UInt stride_file      = (width444 * (is16bit ? 2 : 1)) >> csx_file;
 
-  UChar  *buf   = new UChar[stride_file];
+  std::vector<UChar> bufVec(stride_file);
+  UChar *buf=&(bufVec[0]);
 
   if (compID!=COMPONENT_Y && (fileFormat==CHROMA_400 || destFormat==CHROMA_400))
@@ -297,5 +300,4 @@
       if (fd.eof() || fd.fail() )
       {
-        delete[] buf;
         return false;
       }
@@ -311,8 +313,7 @@
       {
         // read a new line
-        fd.read(reinterpret_cast<Char*>(buf), stride_file);
+        fd.read(reinterpret_cast<TChar*>(buf), stride_file);
         if (fd.eof() || fd.fail() )
         {
-          delete[] buf;
           return false;
         }
@@ -381,5 +382,4 @@
     }
   }
-  delete[] buf;
   return true;
 }
@@ -419,5 +419,6 @@
   const UInt height_file      = height444>>csy_file;
 
-  UChar  *buf   = new UChar[stride_file];
+  std::vector<UChar> bufVec(stride_file);
+  UChar *buf=&(bufVec[0]);
 
   if (compID!=COMPONENT_Y && (fileFormat==CHROMA_400 || srcFormat==CHROMA_400))
@@ -447,8 +448,7 @@
         }
 
-        fd.write(reinterpret_cast<Char*>(buf), stride_file);
+        fd.write(reinterpret_cast<const TChar*>(buf), stride_file);
         if (fd.eof() || fd.fail() )
         {
-          delete[] buf;
           return false;
         }
@@ -506,8 +506,7 @@
         }
 
-        fd.write(reinterpret_cast<Char*>(buf), stride_file);
+        fd.write(reinterpret_cast<const TChar*>(buf), stride_file);
         if (fd.eof() || fd.fail() )
         {
-          delete[] buf;
           return false;
         }
@@ -521,5 +520,4 @@
     }
   }
-  delete[] buf;
   return true;
 }
@@ -544,5 +542,6 @@
   const UInt height_file      = height444>>csy_file;
 
-  UChar  *buf   = new UChar[stride_file * 2];
+  std::vector<UChar> bufVec(stride_file * 2);
+  UChar *buf=&(bufVec[0]);
 
   if (compID!=COMPONENT_Y && (fileFormat==CHROMA_400 || srcFormat==CHROMA_400))
@@ -577,8 +576,7 @@
         }
 
-        fd.write(reinterpret_cast<Char*>(buf), (stride_file * 2));
+        fd.write(reinterpret_cast<const TChar*>(buf), (stride_file * 2));
         if (fd.eof() || fd.fail() )
         {
-          delete[] buf;
           return false;
         }
@@ -642,8 +640,7 @@
         }
 
-        fd.write(reinterpret_cast<Char*>(buf), (stride_file * 2));
+        fd.write(reinterpret_cast<const TChar*>(buf), (stride_file * 2));
         if (fd.eof() || fd.fail() )
         {
-          delete[] buf;
           return false;
         }
@@ -658,5 +655,4 @@
     }
   }
-  delete[] buf;
   return true;
 }
@@ -760,5 +756,5 @@
   if (ipCSC!=IPCOLOURSPACE_UNCHANGED)
   {
-    cPicYuvCSCd.create(pPicYuvUser->getWidth(COMPONENT_Y), pPicYuvUser->getHeight(COMPONENT_Y), pPicYuvUser->getChromaFormat(), pPicYuvUser->getWidth(COMPONENT_Y), pPicYuvUser->getHeight(COMPONENT_Y), 0, false);
+    cPicYuvCSCd.createWithoutCUInfo(pPicYuvUser->getWidth(COMPONENT_Y), pPicYuvUser->getHeight(COMPONENT_Y), pPicYuvUser->getChromaFormat() );
     ColourSpaceConvert(*pPicYuvUser, cPicYuvCSCd, ipCSC, false);
   }
@@ -766,14 +762,6 @@
 
   // compute actual YUV frame size excluding padding size
-  const Int   iStride444 = pPicYuv->getStride(COMPONENT_Y);
-  const UInt width444  = pPicYuv->getWidth(COMPONENT_Y) - confLeft - confRight;
-  const UInt height444 = pPicYuv->getHeight(COMPONENT_Y) -  confTop  - confBottom;
   Bool is16bit = false;
   Bool nonZeroBitDepthShift=false;
-
-  if ((width444 == 0) || (height444 == 0))
-  {
-    printf ("\nWarning: writing %d x %d luma sample output picture!", width444, height444);
-  }
 
   for(UInt ch=0; ch<MAX_NUM_CHANNEL_TYPE; ch++)
@@ -799,6 +787,5 @@
   {
     dstPicYuv = new TComPicYuv;
-    dstPicYuv->create( pPicYuv->getWidth(COMPONENT_Y), pPicYuv->getHeight(COMPONENT_Y), pPicYuv->getChromaFormat(), pPicYuv->getWidth(COMPONENT_Y), pPicYuv->getHeight(COMPONENT_Y), 0, false );
-    pPicYuv->copyToPic(dstPicYuv);
+    dstPicYuv->createWithoutCUInfo( pPicYuv->getWidth(COMPONENT_Y), pPicYuv->getHeight(COMPONENT_Y), pPicYuv->getChromaFormat() );
 
     for(UInt comp=0; comp<dstPicYuv->getNumberValidComponents(); comp++)
@@ -810,4 +797,5 @@
       const Pel maxval = b709Compliance? ((0xff << (m_MSBExtendedBitDepth[ch] - 8)) -1) : (1 << m_MSBExtendedBitDepth[ch]) - 1;
 
+      copyPlane(*pPicYuv, compID, *dstPicYuv, compID);
       scalePlane(dstPicYuv->getAddr(compID), dstPicYuv->getStride(compID), dstPicYuv->getWidth(compID), dstPicYuv->getHeight(compID), -m_bitdepthShift[ch], minval, maxval);
     }
@@ -817,4 +805,14 @@
     dstPicYuv = pPicYuv;
   }
+
+  const Int  stride444 = dstPicYuv->getStride(COMPONENT_Y);
+  const UInt width444  = dstPicYuv->getWidth(COMPONENT_Y) - confLeft - confRight;
+  const UInt height444 = dstPicYuv->getHeight(COMPONENT_Y) -  confTop  - confBottom;
+
+  if ((width444 == 0) || (height444 == 0))
+  {
+    printf ("\nWarning: writing %d x %d luma sample output picture!", width444, height444);
+  }
+
 #if NH_3D
   for(UInt comp=0; retval && comp< ::getNumberValidComponents(format); comp++)
@@ -825,8 +823,8 @@
     const ComponentID compID = ComponentID(comp);
     const ChannelType ch=toChannelType(compID);
-    const UInt csx = pPicYuv->getComponentScaleX(compID);
-    const UInt csy = pPicYuv->getComponentScaleY(compID);
-    const Int planeOffset =  (confLeft>>csx) + (confTop>>csy) * pPicYuv->getStride(compID);
-    if (! writePlane(m_cHandle, dstPicYuv->getAddr(compID) + planeOffset, is16bit, iStride444, width444, height444, compID, dstPicYuv->getChromaFormat(), format, m_fileBitdepth[ch]))
+    const UInt csx = dstPicYuv->getComponentScaleX(compID);
+    const UInt csy = dstPicYuv->getComponentScaleY(compID);
+    const Int planeOffset =  (confLeft>>csx) + (confTop>>csy) * dstPicYuv->getStride(compID);
+    if (! writePlane(m_cHandle, dstPicYuv->getAddr(compID) + planeOffset, is16bit, stride444, width444, height444, compID, dstPicYuv->getChromaFormat(), format, m_fileBitdepth[ch]))
     {
       retval=false;
@@ -852,6 +850,6 @@
   if (ipCSC!=IPCOLOURSPACE_UNCHANGED)
   {
-    cPicYuvTopCSCd   .create(pPicYuvUserTop   ->getWidth(COMPONENT_Y), pPicYuvUserTop   ->getHeight(COMPONENT_Y), pPicYuvUserTop   ->getChromaFormat(), pPicYuvUserTop   ->getWidth(COMPONENT_Y), pPicYuvUserTop   ->getHeight(COMPONENT_Y), 0, false);
-    cPicYuvBottomCSCd.create(pPicYuvUserBottom->getWidth(COMPONENT_Y), pPicYuvUserBottom->getHeight(COMPONENT_Y), pPicYuvUserBottom->getChromaFormat(), pPicYuvUserBottom->getWidth(COMPONENT_Y), pPicYuvUserBottom->getHeight(COMPONENT_Y), 0, false);
+    cPicYuvTopCSCd   .createWithoutCUInfo(pPicYuvUserTop   ->getWidth(COMPONENT_Y), pPicYuvUserTop   ->getHeight(COMPONENT_Y), pPicYuvUserTop   ->getChromaFormat() );
+    cPicYuvBottomCSCd.createWithoutCUInfo(pPicYuvUserBottom->getWidth(COMPONENT_Y), pPicYuvUserBottom->getHeight(COMPONENT_Y), pPicYuvUserBottom->getChromaFormat() );
     ColourSpaceConvert(*pPicYuvUserTop,    cPicYuvTopCSCd,    ipCSC, false);
     ColourSpaceConvert(*pPicYuvUserBottom, cPicYuvBottomCSCd, ipCSC, false);
@@ -892,6 +890,5 @@
     {
       dstPicYuv = new TComPicYuv;
-      dstPicYuv->create( pPicYuv->getWidth(COMPONENT_Y), pPicYuv->getHeight(COMPONENT_Y), pPicYuv->getChromaFormat(), pPicYuv->getWidth(COMPONENT_Y), pPicYuv->getHeight(COMPONENT_Y), 0, false );
-      pPicYuv->copyToPic(dstPicYuv);
+      dstPicYuv->createWithoutCUInfo( pPicYuv->getWidth(COMPONENT_Y), pPicYuv->getHeight(COMPONENT_Y), pPicYuv->getChromaFormat() );
 
       for(UInt comp=0; comp<dstPicYuv->getNumberValidComponents(); comp++)
@@ -903,4 +900,5 @@
         const Pel maxval = b709Compliance? ((0xff << (m_MSBExtendedBitDepth[ch] - 8)) -1) : (1 << m_MSBExtendedBitDepth[ch]) - 1;
 
+        copyPlane(*pPicYuv, compID, *dstPicYuv, compID);
         scalePlane(dstPicYuv->getAddr(compID), dstPicYuv->getStride(compID), dstPicYuv->getWidth(compID), dstPicYuv->getHeight(compID), -m_bitdepthShift[ch], minval, maxval);
       }
@@ -916,7 +914,4 @@
   assert(dstPicYuvTop->getNumberValidComponents() == dstPicYuvBottom->getNumberValidComponents());
   assert(dstPicYuvTop->getChromaFormat()          == dstPicYuvBottom->getChromaFormat()         );
-  assert(dstPicYuvTop->getWidth(COMPONENT_Y)      == dstPicYuvBottom->getWidth(COMPONENT_Y)    );
-  assert(dstPicYuvTop->getHeight(COMPONENT_Y)     == dstPicYuvBottom->getHeight(COMPONENT_Y)    );
-  assert(dstPicYuvTop->getStride(COMPONENT_Y)     == dstPicYuvBottom->getStride(COMPONENT_Y)    );
 
   for(UInt comp=0; retval && comp<dstPicYuvTop->getNumberValidComponents(); comp++)
@@ -925,4 +920,6 @@
     const ChannelType ch=toChannelType(compID);
 
+    assert(dstPicYuvTop->getWidth          (compID) == dstPicYuvBottom->getWidth          (compID));
+    assert(dstPicYuvTop->getHeight         (compID) == dstPicYuvBottom->getHeight         (compID));
     assert(dstPicYuvTop->getComponentScaleX(compID) == dstPicYuvBottom->getComponentScaleX(compID));
     assert(dstPicYuvTop->getComponentScaleY(compID) == dstPicYuvBottom->getComponentScaleY(compID));
Index: trunk/source/Lib/TLibVideoIO/TVideoIOYuv.h
===================================================================
--- trunk/source/Lib/TLibVideoIO/TVideoIOYuv.h	(revision 1357)
+++ trunk/source/Lib/TLibVideoIO/TVideoIOYuv.h	(revision 1386)
@@ -64,5 +64,5 @@
   virtual ~TVideoIOYuv()  {}
 
-  Void  open  ( Char* pchFile, Bool bWriteMode, const Int fileBitDepth[MAX_NUM_CHANNEL_TYPE], const Int MSBExtendedBitDepth[MAX_NUM_CHANNEL_TYPE], const Int internalBitDepth[MAX_NUM_CHANNEL_TYPE] ); ///< open or create file
+  Void  open  ( const std::string &fileName, Bool bWriteMode, const Int fileBitDepth[MAX_NUM_CHANNEL_TYPE], const Int MSBExtendedBitDepth[MAX_NUM_CHANNEL_TYPE], const Int internalBitDepth[MAX_NUM_CHANNEL_TYPE] ); ///< open or create file
   Void  close ();                                           ///< close file
 
