Index: /trunk/build/HM_vc10.sln
===================================================================
--- /trunk/build/HM_vc10.sln	(revision 2)
+++ /trunk/build/HM_vc10.sln	(revision 2)
@@ -0,0 +1,86 @@
+﻿
+Microsoft Visual Studio Solution File, Format Version 11.00
+# Visual Studio 2010
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppDecoder", "vc10\TAppDecoder_vc10.vcxproj", "{A7A515D9-E917-4706-BD5B-57DC6C78D612}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppEncoder", "vc10\TAppEncoder_vc10.vcxproj", "{D759E4E1-D33A-4483-B57B-0FD248E022FE}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppCommon", "vc10\TAppCommon_vc10.vcxproj", "{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibCommon", "vc10\TLibCommon_vc10.vcxproj", "{78018D78-F890-47E3-A0B7-09D273F0B11D}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibDecoder", "vc10\TLibDecoder_vc10.vcxproj", "{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibEncoder", "vc10\TLibEncoder_vc10.vcxproj", "{47E90995-1FC5-4EE4-A94D-AD474169F0E1}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibVideoIO", "vc10\TLibVideoIO_vc10.vcxproj", "{5280C25A-D316-4BE7-AE50-29D72108624F}"
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug|Win32 = Debug|Win32
+		Debug|x64 = Debug|x64
+		Release|Win32 = Release|Win32
+		Release|x64 = Release|x64
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Debug|Win32.ActiveCfg = Debug|Win32
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Debug|Win32.Build.0 = Debug|Win32
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Debug|x64.ActiveCfg = Debug|x64
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Debug|x64.Build.0 = Debug|x64
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Release|Win32.ActiveCfg = Release|Win32
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Release|Win32.Build.0 = Release|Win32
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Release|x64.ActiveCfg = Release|x64
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Release|x64.Build.0 = Release|x64
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Debug|Win32.ActiveCfg = Debug|Win32
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Debug|Win32.Build.0 = Debug|Win32
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Debug|x64.ActiveCfg = Debug|x64
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Debug|x64.Build.0 = Debug|x64
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Release|Win32.ActiveCfg = Release|Win32
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Release|Win32.Build.0 = Release|Win32
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Release|x64.ActiveCfg = Release|x64
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Release|x64.Build.0 = Release|x64
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Debug|Win32.ActiveCfg = Debug|Win32
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Debug|Win32.Build.0 = Debug|Win32
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Debug|x64.ActiveCfg = Debug|x64
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Debug|x64.Build.0 = Debug|x64
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Release|Win32.ActiveCfg = Release|Win32
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Release|Win32.Build.0 = Release|Win32
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Release|x64.ActiveCfg = Release|x64
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Release|x64.Build.0 = Release|x64
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Debug|Win32.ActiveCfg = Debug|Win32
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Debug|Win32.Build.0 = Debug|Win32
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Debug|x64.ActiveCfg = Debug|x64
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Debug|x64.Build.0 = Debug|x64
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Release|Win32.ActiveCfg = Release|Win32
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Release|Win32.Build.0 = Release|Win32
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Release|x64.ActiveCfg = Release|x64
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Release|x64.Build.0 = Release|x64
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Debug|Win32.ActiveCfg = Debug|Win32
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Debug|Win32.Build.0 = Debug|Win32
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Debug|x64.ActiveCfg = Debug|x64
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Debug|x64.Build.0 = Debug|x64
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Release|Win32.ActiveCfg = Release|Win32
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Release|Win32.Build.0 = Release|Win32
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Release|x64.ActiveCfg = Release|x64
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Release|x64.Build.0 = Release|x64
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Debug|Win32.ActiveCfg = Debug|Win32
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Debug|Win32.Build.0 = Debug|Win32
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Debug|x64.ActiveCfg = Debug|x64
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Debug|x64.Build.0 = Debug|x64
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Release|Win32.ActiveCfg = Release|Win32
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Release|Win32.Build.0 = Release|Win32
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Release|x64.ActiveCfg = Release|x64
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Release|x64.Build.0 = Release|x64
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Debug|Win32.ActiveCfg = Debug|Win32
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Debug|Win32.Build.0 = Debug|Win32
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Debug|x64.ActiveCfg = Debug|x64
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Debug|x64.Build.0 = Debug|x64
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Release|Win32.ActiveCfg = Release|Win32
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Release|Win32.Build.0 = Release|Win32
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Release|x64.ActiveCfg = Release|x64
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Release|x64.Build.0 = Release|x64
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+EndGlobal
Index: /trunk/build/HM_vc8.sln
===================================================================
--- /trunk/build/HM_vc8.sln	(revision 2)
+++ /trunk/build/HM_vc8.sln	(revision 2)
@@ -0,0 +1,98 @@
+﻿
+Microsoft Visual Studio Solution File, Format Version 10.00
+# Visual Studio 2008
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppDecoder", "vc8\TAppDecoder_vc8.vcproj", "{A7A515D9-E917-4706-BD5B-57DC6C78D612}"
+	ProjectSection(ProjectDependencies) = postProject
+		{8783AD3A-A5CA-42B7-AAC4-A07EB845A684} = {8783AD3A-A5CA-42B7-AAC4-A07EB845A684}
+		{5280C25A-D316-4BE7-AE50-29D72108624F} = {5280C25A-D316-4BE7-AE50-29D72108624F}
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94} = {F8B77A48-AF6C-4746-A89F-B706ABA6AD94}
+		{78018D78-F890-47E3-A0B7-09D273F0B11D} = {78018D78-F890-47E3-A0B7-09D273F0B11D}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppEncoder", "vc8\TAppEncoder_vc8.vcproj", "{D759E4E1-D33A-4483-B57B-0FD248E022FE}"
+	ProjectSection(ProjectDependencies) = postProject
+		{5280C25A-D316-4BE7-AE50-29D72108624F} = {5280C25A-D316-4BE7-AE50-29D72108624F}
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1} = {47E90995-1FC5-4EE4-A94D-AD474169F0E1}
+		{78018D78-F890-47E3-A0B7-09D273F0B11D} = {78018D78-F890-47E3-A0B7-09D273F0B11D}
+		{8783AD3A-A5CA-42B7-AAC4-A07EB845A684} = {8783AD3A-A5CA-42B7-AAC4-A07EB845A684}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppCommon", "vc8\TAppCommon_vc8.vcproj", "{8783AD3A-A5CA-42B7-AAC4-A07EB845A684}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibCommon", "vc8\TLibCommon_vc8.vcproj", "{78018D78-F890-47E3-A0B7-09D273F0B11D}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibDecoder", "vc8\TLibDecoder_vc8.vcproj", "{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibEncoder", "vc8\TLibEncoder_vc8.vcproj", "{47E90995-1FC5-4EE4-A94D-AD474169F0E1}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibVideoIO", "vc8\TLibVideoIO_vc8.vcproj", "{5280C25A-D316-4BE7-AE50-29D72108624F}"
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug|Win32 = Debug|Win32
+		Debug|x64 = Debug|x64
+		Release|Win32 = Release|Win32
+		Release|x64 = Release|x64
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Debug|Win32.ActiveCfg = Debug|Win32
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Debug|Win32.Build.0 = Debug|Win32
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Debug|x64.ActiveCfg = Debug|x64
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Debug|x64.Build.0 = Debug|x64
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Release|Win32.ActiveCfg = Release|Win32
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Release|Win32.Build.0 = Release|Win32
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Release|x64.ActiveCfg = Release|x64
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Release|x64.Build.0 = Release|x64
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Debug|Win32.ActiveCfg = Debug|Win32
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Debug|Win32.Build.0 = Debug|Win32
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Debug|x64.ActiveCfg = Debug|x64
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Debug|x64.Build.0 = Debug|x64
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Release|Win32.ActiveCfg = Release|Win32
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Release|Win32.Build.0 = Release|Win32
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Release|x64.ActiveCfg = Release|x64
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Release|x64.Build.0 = Release|x64
+		{8783AD3A-A5CA-42B7-AAC4-A07EB845A684}.Debug|Win32.ActiveCfg = Debug|Win32
+		{8783AD3A-A5CA-42B7-AAC4-A07EB845A684}.Debug|Win32.Build.0 = Debug|Win32
+		{8783AD3A-A5CA-42B7-AAC4-A07EB845A684}.Debug|x64.ActiveCfg = Debug|x64
+		{8783AD3A-A5CA-42B7-AAC4-A07EB845A684}.Debug|x64.Build.0 = Debug|x64
+		{8783AD3A-A5CA-42B7-AAC4-A07EB845A684}.Release|Win32.ActiveCfg = Release|Win32
+		{8783AD3A-A5CA-42B7-AAC4-A07EB845A684}.Release|Win32.Build.0 = Release|Win32
+		{8783AD3A-A5CA-42B7-AAC4-A07EB845A684}.Release|x64.ActiveCfg = Release|x64
+		{8783AD3A-A5CA-42B7-AAC4-A07EB845A684}.Release|x64.Build.0 = Release|x64
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Debug|Win32.ActiveCfg = Debug|Win32
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Debug|Win32.Build.0 = Debug|Win32
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Debug|x64.ActiveCfg = Debug|x64
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Debug|x64.Build.0 = Debug|x64
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Release|Win32.ActiveCfg = Release|Win32
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Release|Win32.Build.0 = Release|Win32
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Release|x64.ActiveCfg = Release|x64
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Release|x64.Build.0 = Release|x64
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Debug|Win32.ActiveCfg = Debug|Win32
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Debug|Win32.Build.0 = Debug|Win32
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Debug|x64.ActiveCfg = Debug|x64
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Debug|x64.Build.0 = Debug|x64
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Release|Win32.ActiveCfg = Release|Win32
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Release|Win32.Build.0 = Release|Win32
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Release|x64.ActiveCfg = Release|x64
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Release|x64.Build.0 = Release|x64
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Debug|Win32.ActiveCfg = Debug|Win32
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Debug|Win32.Build.0 = Debug|Win32
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Debug|x64.ActiveCfg = Debug|x64
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Debug|x64.Build.0 = Debug|x64
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Release|Win32.ActiveCfg = Release|Win32
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Release|Win32.Build.0 = Release|Win32
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Release|x64.ActiveCfg = Release|x64
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Release|x64.Build.0 = Release|x64
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Debug|Win32.ActiveCfg = Debug|Win32
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Debug|Win32.Build.0 = Debug|Win32
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Debug|x64.ActiveCfg = Debug|x64
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Debug|x64.Build.0 = Debug|x64
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Release|Win32.ActiveCfg = Release|Win32
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Release|Win32.Build.0 = Release|Win32
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Release|x64.ActiveCfg = Release|x64
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Release|x64.Build.0 = Release|x64
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+EndGlobal
Index: /trunk/build/HM_vc9.sln
===================================================================
--- /trunk/build/HM_vc9.sln	(revision 2)
+++ /trunk/build/HM_vc9.sln	(revision 2)
@@ -0,0 +1,98 @@
+﻿
+Microsoft Visual Studio Solution File, Format Version 10.00
+# Visual Studio 2008
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppDecoder", "vc9\TAppDecoder_vc9.vcproj", "{A7A515D9-E917-4706-BD5B-57DC6C78D612}"
+	ProjectSection(ProjectDependencies) = postProject
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94} = {F8B77A48-AF6C-4746-A89F-B706ABA6AD94}
+		{5280C25A-D316-4BE7-AE50-29D72108624F} = {5280C25A-D316-4BE7-AE50-29D72108624F}
+		{78018D78-F890-47E3-A0B7-09D273F0B11D} = {78018D78-F890-47E3-A0B7-09D273F0B11D}
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5} = {D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppEncoder", "vc9\TAppEncoder_vc9.vcproj", "{D759E4E1-D33A-4483-B57B-0FD248E022FE}"
+	ProjectSection(ProjectDependencies) = postProject
+		{5280C25A-D316-4BE7-AE50-29D72108624F} = {5280C25A-D316-4BE7-AE50-29D72108624F}
+		{78018D78-F890-47E3-A0B7-09D273F0B11D} = {78018D78-F890-47E3-A0B7-09D273F0B11D}
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1} = {47E90995-1FC5-4EE4-A94D-AD474169F0E1}
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5} = {D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppCommon", "vc9\TAppCommon_vc9.vcproj", "{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibCommon", "vc9\TLibCommon_vc9.vcproj", "{78018D78-F890-47E3-A0B7-09D273F0B11D}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibDecoder", "vc9\TLibDecoder_vc9.vcproj", "{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibEncoder", "vc9\TLibEncoder_vc9.vcproj", "{47E90995-1FC5-4EE4-A94D-AD474169F0E1}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibVideoIO", "vc9\TLibVideoIO_vc9.vcproj", "{5280C25A-D316-4BE7-AE50-29D72108624F}"
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug|Win32 = Debug|Win32
+		Debug|x64 = Debug|x64
+		Release|Win32 = Release|Win32
+		Release|x64 = Release|x64
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Debug|Win32.ActiveCfg = Debug|Win32
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Debug|Win32.Build.0 = Debug|Win32
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Debug|x64.ActiveCfg = Debug|x64
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Debug|x64.Build.0 = Debug|x64
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Release|Win32.ActiveCfg = Release|Win32
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Release|Win32.Build.0 = Release|Win32
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Release|x64.ActiveCfg = Release|x64
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Release|x64.Build.0 = Release|x64
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Debug|Win32.ActiveCfg = Debug|Win32
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Debug|Win32.Build.0 = Debug|Win32
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Debug|x64.ActiveCfg = Debug|x64
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Debug|x64.Build.0 = Debug|x64
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Release|Win32.ActiveCfg = Release|Win32
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Release|Win32.Build.0 = Release|Win32
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Release|x64.ActiveCfg = Release|x64
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Release|x64.Build.0 = Release|x64
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Debug|Win32.ActiveCfg = Debug|Win32
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Debug|Win32.Build.0 = Debug|Win32
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Debug|x64.ActiveCfg = Debug|x64
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Debug|x64.Build.0 = Debug|x64
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Release|Win32.ActiveCfg = Release|Win32
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Release|Win32.Build.0 = Release|Win32
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Release|x64.ActiveCfg = Release|x64
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Release|x64.Build.0 = Release|x64
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Debug|Win32.ActiveCfg = Debug|Win32
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Debug|Win32.Build.0 = Debug|Win32
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Debug|x64.ActiveCfg = Debug|x64
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Debug|x64.Build.0 = Debug|x64
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Release|Win32.ActiveCfg = Release|Win32
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Release|Win32.Build.0 = Release|Win32
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Release|x64.ActiveCfg = Release|x64
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Release|x64.Build.0 = Release|x64
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Debug|Win32.ActiveCfg = Debug|Win32
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Debug|Win32.Build.0 = Debug|Win32
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Debug|x64.ActiveCfg = Debug|x64
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Debug|x64.Build.0 = Debug|x64
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Release|Win32.ActiveCfg = Release|Win32
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Release|Win32.Build.0 = Release|Win32
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Release|x64.ActiveCfg = Release|x64
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Release|x64.Build.0 = Release|x64
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Debug|Win32.ActiveCfg = Debug|Win32
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Debug|Win32.Build.0 = Debug|Win32
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Debug|x64.ActiveCfg = Debug|x64
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Debug|x64.Build.0 = Debug|x64
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Release|Win32.ActiveCfg = Release|Win32
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Release|Win32.Build.0 = Release|Win32
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Release|x64.ActiveCfg = Release|x64
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Release|x64.Build.0 = Release|x64
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Debug|Win32.ActiveCfg = Debug|Win32
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Debug|Win32.Build.0 = Debug|Win32
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Debug|x64.ActiveCfg = Debug|x64
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Debug|x64.Build.0 = Debug|x64
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Release|Win32.ActiveCfg = Release|Win32
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Release|Win32.Build.0 = Release|Win32
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Release|x64.ActiveCfg = Release|x64
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Release|x64.Build.0 = Release|x64
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+EndGlobal
Index: /trunk/build/linux/app/TAppDecoder/makefile
===================================================================
--- /trunk/build/linux/app/TAppDecoder/makefile	(revision 2)
+++ /trunk/build/linux/app/TAppDecoder/makefile	(revision 2)
@@ -0,0 +1,58 @@
+# the SOURCE definiton lets you move your makefile to another position
+CONFIG 				= CONSOLE
+
+# set directories to your wanted values
+SRC_DIR				= ../../../../source/App/TAppDecoder
+INC_DIR				= ../../../../source/Lib
+LIB_DIR				= ../../../../lib
+BIN_DIR				= ../../../../bin
+
+SRC_DIR1		=
+SRC_DIR2		=
+SRC_DIR3		=
+SRC_DIR4		=
+
+USER_INC_DIRS	= -I$(SRC_DIR) 
+USER_LIB_DIRS	=
+
+# intermediate directory for object files
+OBJ_DIR				= ./objects
+
+# set executable name
+PRJ_NAME			= TAppDecoder
+
+# defines to set
+DEFS				= -DMSYS_LINUX -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64 -DMSYS_UNIX_LARGEFILE
+
+# set objects
+OBJS          		= 	\
+					$(OBJ_DIR)/decmain.o \
+					$(OBJ_DIR)/TAppDecCfg.o \
+					$(OBJ_DIR)/TAppDecTop.o \
+
+# set libs to link with
+LIBS				= -ldl
+
+DEBUG_LIBS			=
+RELEASE_LIBS		=
+
+STAT_LIBS			= -lpthread
+DYN_LIBS			=
+
+
+DYN_DEBUG_LIBS		= -lTLibDecoderd -lTLibCommond -lTLibVideoIOd -lTAppCommond
+DYN_DEBUG_PREREQS		= $(LIB_DIR)/libTLibDecoderd.a $(LIB_DIR)/libTLibCommond.a $(LIB_DIR)/libTLibVideoIOd.a $(LIB_DIR)/libTAppCommond.a
+STAT_DEBUG_LIBS		= -lTLibDecoderStaticd -lTLibCommonStaticd -lTLibVideoIOStaticd -lTAppCommonStaticd
+STAT_DEBUG_PREREQS		= $(LIB_DIR)/libTLibDecoderStaticd.a $(LIB_DIR)/libTLibCommonStaticd.a $(LIB_DIR)/libTLibVideoIOStaticd.a $(LIB_DIR)/libTAppCommonStaticd.a
+
+DYN_RELEASE_LIBS	= -lTLibDecoder -lTLibCommon -lTLibVideoIO -lTAppCommon
+DYN_RELEASE_PREREQS	= $(LIB_DIR)/libTLibDecoder.a $(LIB_DIR)/libTLibCommon.a $(LIB_DIR)/libTLibVideoIO.a $(LIB_DIR)/libTAppCommon.a
+STAT_RELEASE_LIBS	= -lTLibDecoderStatic -lTLibCommonStatic -lTLibVideoIOStatic -lTAppCommonStatic
+STAT_RELEASE_PREREQS	= $(LIB_DIR)/libTLibDecoderStatic.a $(LIB_DIR)/libTLibCommonStatic.a $(LIB_DIR)/libTLibVideoIOStatic.a $(LIB_DIR)/libTAppCommonStatic.a
+
+
+# name of the base makefile
+MAKE_FILE_NAME		= ../../common/makefile.base
+
+# include the base makefile
+include $(MAKE_FILE_NAME)
Index: /trunk/build/linux/app/TAppEncoder/makefile
===================================================================
--- /trunk/build/linux/app/TAppEncoder/makefile	(revision 2)
+++ /trunk/build/linux/app/TAppEncoder/makefile	(revision 2)
@@ -0,0 +1,59 @@
+# the SOURCE definiton lets you move your makefile to another position
+CONFIG 				= CONSOLE
+
+# set directories to your wanted values
+SRC_DIR				= ../../../../source/App/TAppEncoder
+INC_DIR				= ../../../../source/Lib
+LIB_DIR				= ../../../../lib
+BIN_DIR				= ../../../../bin
+
+SRC_DIR1		=
+SRC_DIR2		=
+SRC_DIR3		=
+SRC_DIR4		=
+
+USER_INC_DIRS	= -I$(SRC_DIR)
+USER_LIB_DIRS	=
+
+# intermediate directory for object files
+OBJ_DIR				= ./objects
+
+# set executable name
+PRJ_NAME			= TAppEncoder
+
+# defines to set
+DEFS				= -DMSYS_LINUX -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64 -DMSYS_UNIX_LARGEFILE
+
+# set objects
+OBJS          		= 	\
+					$(OBJ_DIR)/encmain.o \
+					$(OBJ_DIR)/TAppEncCfg.o \
+					$(OBJ_DIR)/TAppEncLayerCfg.o \
+					$(OBJ_DIR)/TAppEncTop.o \
+
+# set libs to link with
+LIBS				= -ldl
+
+DEBUG_LIBS			=
+RELEASE_LIBS		=
+
+STAT_LIBS			= -lpthread
+DYN_LIBS			=
+
+
+DYN_DEBUG_LIBS		= -lTLibEncoderd -lTLibCommond -lTLibVideoIOd -lTAppCommond
+DYN_DEBUG_PREREQS		= $(LIB_DIR)/libTLibEncoderd.a $(LIB_DIR)/libTLibCommond.a $(LIB_DIR)/libTLibVideoIOd.a $(LIB_DIR)/libTAppCommond.a
+STAT_DEBUG_LIBS		= -lTLibEncoderStaticd -lTLibCommonStaticd -lTLibVideoIOStaticd -lTAppCommonStaticd
+STAT_DEBUG_PREREQS		= $(LIB_DIR)/libTLibEncoderStaticd.a $(LIB_DIR)/libTLibCommonStaticd.a $(LIB_DIR)/libTLibVideoIOStaticd.a $(LIB_DIR)/libTAppCommonStaticd.a
+
+DYN_RELEASE_LIBS	= -lTLibEncoder -lTLibCommon -lTLibVideoIO -lTAppCommon
+DYN_RELEASE_PREREQS	= $(LIB_DIR)/libTLibEncoder.a $(LIB_DIR)/libTLibCommon.a $(LIB_DIR)/libTLibVideoIO.a $(LIB_DIR)/libTAppCommon.a
+STAT_RELEASE_LIBS	= -lTLibEncoderStatic -lTLibCommonStatic -lTLibVideoIOStatic -lTAppCommonStatic
+STAT_RELEASE_PREREQS	= $(LIB_DIR)/libTLibEncoderStatic.a $(LIB_DIR)/libTLibCommonStatic.a $(LIB_DIR)/libTLibVideoIOStatic.a $(LIB_DIR)/libTAppCommonStatic.a
+
+
+# name of the base makefile
+MAKE_FILE_NAME		= ../../common/makefile.base
+
+# include the base makefile
+include $(MAKE_FILE_NAME)
Index: /trunk/build/linux/common/makefile.base
===================================================================
--- /trunk/build/linux/common/makefile.base	(revision 2)
+++ /trunk/build/linux/common/makefile.base	(revision 2)
@@ -0,0 +1,471 @@
+#########################################################
+# check CONFIG parameter
+#########################################################
+
+ifneq ($(CONFIG), LIBRARY)
+ifneq ($(CONFIG), CONSOLE)
+CONFIG_ERR = TRUE
+endif
+endif
+
+#########################################################
+# executables used
+#########################################################
+
+CPP   	= g++
+AR    	= ar
+LD    	= $(CPP)
+ASM		= nasm
+
+#########################################################
+# output file names and version information
+#########################################################
+
+ifeq ($(CONFIG), LIBRARY)
+# the libraries that can be created
+STAT_DEBUG_OUT    	= $(LIB_DIR)/lib$(PRJ_NAME)Staticd.a
+STAT_RELEASE_OUT  	= $(LIB_DIR)/lib$(PRJ_NAME)Static.a
+DYN_DEBUG_OUT     	= $(LIB_DIR)/lib$(PRJ_NAME)d.so
+DYN_RELEASE_OUT   	= $(LIB_DIR)/lib$(PRJ_NAME).so
+#
+else 
+ifeq ($(CONFIG), CONSOLE)
+# the executables that can be created
+STAT_DEBUG_OUT    = $(BIN_DIR)/$(PRJ_NAME)Staticd
+STAT_RELEASE_OUT  = $(BIN_DIR)/$(PRJ_NAME)Static
+DYN_DEBUG_OUT     = $(BIN_DIR)/$(PRJ_NAME)d
+DYN_RELEASE_OUT   = $(BIN_DIR)/$(PRJ_NAME)
+#
+endif
+endif
+
+
+#########################################################
+# c compiler flags
+#########################################################
+
+# default cpp flags for all configurations
+#CPPFLAGS          = -Wall -fPIC $(DEFS) -I$(CURDIR)/$(INC_DIR) $(USER_INC_DIRS)
+CPPFLAGS          = -fPIC $(DEFS) -I$(CURDIR)/$(INC_DIR) $(USER_INC_DIRS) -Wall -Wshadow -Wno-sign-compare -Werror
+
+########## 
+# enforce 32-bit build : 1=yes, 0=no
+##########
+M32?= 0
+ifeq ($(M32),1)
+CPPFLAGS+=-m32
+endif
+##########
+
+#
+# debug cpp flags
+DEBUG_CPPFLAGS    = -g  -D_DEBUG
+#
+# release cpp
+RELEASE_CPPFLAGS  =  -O3 -ffloat-store -Wuninitialized
+
+
+#########################################################
+# assembler compiler flags
+#########################################################
+
+# default asm flags for all configurations
+ASMFLAGS          = -f elf $(DEFS)
+#
+# debug asm flags
+DEBUG_ASMFLAGS    = -g
+#
+# release asm flags
+RELEASE_ASMFLAGS  =
+
+
+
+#########################################################
+# linker flags
+#########################################################
+
+# linker flags for all
+ALL_LDFLAGS       = -Wall
+
+########## 
+# enforce 32-bit build : 1=yes, 0=no
+##########
+ifeq ($(M32),1)
+ALL_LDFLAGS+=-m32
+endif
+##########
+
+
+ifeq ($(CONFIG), LIBRARY)
+# linker flags for library
+# LDFLAGS           = $(ALL_LDFLAGS) -shared -Wl,-Bsymbolic
+LDFLAGS           = $(ALL_LDFLAGS) -shared
+#
+# debug linker flags for library
+DEBUG_LDFLAGS     = -Wl,-soname,lib$(PRJ_NAME)d.so.$(VER)
+#
+# release linker flags for library
+RELEASE_LDFLAGS   = -Wl,-soname,lib$(PRJ_NAME).so.$(VER)
+#
+else
+ifeq ($(CONFIG), CONSOLE)
+# linker flags for console
+LDFLAGS           = $(ALL_LDFLAGS)
+#
+# debug linker flags for console
+DEBUG_LDFLAGS     =
+#
+# release linker flags for console
+RELEASE_LDFLAGS   =
+#
+endif
+endif
+
+
+
+#########################################################
+# objects that have to be created
+#########################################################
+
+# the object types that have to be created      
+RELEASE_OBJS  = $(OBJS:.o=.r.o)
+DEBUG_OBJS    = $(OBJS:.o=.d.o)
+
+
+#########################################################
+# rules
+#########################################################
+
+# suffixes
+.SUFFIXES: .cpp .asm .r.o .d.o
+
+#########################################################
+# assembler rules
+#########################################################
+
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR)/%.asm
+	$(ASM) $(ASMFLAGS) $(RELEASE_ASMFLAGS) -o $@ $<
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR)/%.asm
+	$(ASM) $(ASMFLAGS) $(DEBUG_ASMFLAGS) -o $@ $<
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR1)/%.asm
+	$(ASM) $(ASMFLAGS) $(RELEASE_ASMFLAGS) -o $@ $<
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR1)/%.asm
+	$(ASM) $(ASMFLAGS) $(DEBUG_ASMFLAGS) -o $@ $<
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR2)/%.asm
+	$(ASM) $(ASMFLAGS) $(RELEASE_ASMFLAGS) -o $@ $<
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR2)/%.asm
+	$(ASM) $(ASMFLAGS) $(DEBUG_ASMFLAGS) -o $@ $<
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR3)/%.asm
+	$(ASM) $(ASMFLAGS) $(RELEASE_ASMFLAGS) -o $@ $<
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR3)/%.asm
+	$(ASM) $(ASMFLAGS) $(DEBUG_ASMFLAGS) -o $@ $<
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR4)/%.asm
+	$(ASM) $(ASMFLAGS) $(RELEASE_ASMFLAGS) -o $@ $<
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR4)/%.asm
+	$(ASM) $(ASMFLAGS) $(DEBUG_ASMFLAGS) -o $@ $<
+
+
+
+#########################################################
+# c rules
+#########################################################
+
+# Generate dependency files during compilation
+# see also: http://make.paulandlesley.org/autodep.html
+#    2005-01-25 Steffen Kamp (kamp@ient.rwth-aachen.de), RWTH Aachen
+define COMPILE_AND_DEPEND_RELEASE
+        $(CPP) -c -MMD -MF $(OBJ_DIR)/$*.r.d -MT $(OBJ_DIR)/$*.r.o $(CPPFLAGS) $(RELEASE_CPPFLAGS) -o $@ $(CURDIR)/$<
+        @cp $(OBJ_DIR)/$*.r.d $(OBJ_DIR)/$*.r.P; \
+                sed -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\\$$//' \
+                -e '/^$$/ d' -e 's/$$/ :/' < $(OBJ_DIR)/$*.r.d >> $(OBJ_DIR)/$*.r.P; \
+                rm -f $(OBJ_DIR)/$*.r.d
+endef
+define COMPILE_AND_DEPEND_DEBUG
+        $(CPP) -c -MMD -MF $(OBJ_DIR)/$*.d.d -MT $(OBJ_DIR)/$*.d.o $(CPPFLAGS) $(DEBUG_CPPFLAGS) -o $@ $(CURDIR)/$<
+        @cp $(OBJ_DIR)/$*.d.d $(OBJ_DIR)/$*.d.P; \
+                sed -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\\$$//' \
+                -e '/^$$/ d' -e 's/$$/ :/' < $(OBJ_DIR)/$*.d.d >> $(OBJ_DIR)/$*.d.P; \
+                rm -f $(OBJ_DIR)/$*.d.d
+endef
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR)/%.cpp
+	$(COMPILE_AND_DEPEND_RELEASE)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR)/%.cpp
+	$(COMPILE_AND_DEPEND_DEBUG)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR1)/%.cpp
+	$(COMPILE_AND_DEPEND_RELEASE)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR1)/%.cpp
+	$(COMPILE_AND_DEPEND_DEBUG)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR2)/%.cpp
+	$(COMPILE_AND_DEPEND_RELEASE)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR2)/%.cpp
+	$(COMPILE_AND_DEPEND_DEBUG)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR3)/%.cpp
+	$(COMPILE_AND_DEPEND_RELEASE)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR3)/%.cpp
+	$(COMPILE_AND_DEPEND_DEBUG)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR4)/%.cpp
+	$(COMPILE_AND_DEPEND_RELEASE)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR4)/%.cpp
+	$(COMPILE_AND_DEPEND_DEBUG)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR)/%.c
+	$(COMPILE_AND_DEPEND_RELEASE)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR)/%.c
+	$(COMPILE_AND_DEPEND_DEBUG)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR1)/%.c
+	$(COMPILE_AND_DEPEND_RELEASE)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR1)/%.c
+	$(COMPILE_AND_DEPEND_DEBUG)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR2)/%.c
+	$(COMPILE_AND_DEPEND_RELEASE)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR2)/%.c
+	$(COMPILE_AND_DEPEND_DEBUG)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR3)/%.c
+	$(COMPILE_AND_DEPEND_RELEASE)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR3)/%.c
+	$(COMPILE_AND_DEPEND_DEBUG)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR4)/%.c
+	$(COMPILE_AND_DEPEND_RELEASE)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR4)/%.c
+	$(COMPILE_AND_DEPEND_DEBUG)
+
+
+#########################################################
+# directory settings
+#########################################################
+
+ifeq ($(CONFIG), LIBRARY)
+# directories that have to be created for a library
+CHECK_DIRS = $(OBJ_DIR) $(LIB_DIR)
+#
+else
+ifeq ($(CONFIG), CONSOLE)
+# directories that have to be created for console and MFC
+CHECK_DIRS = $(OBJ_DIR) $(BIN_DIR)
+#
+endif
+endif
+
+
+#########################################################
+# targets
+#########################################################
+
+all:              	check_errors debug release
+
+debug:            	check_errors \
+					$(CHECK_DIRS) \
+					$(STAT_DEBUG_OUT)
+
+release:          	check_errors \
+					$(CHECK_DIRS) \
+					$(STAT_RELEASE_OUT)
+
+
+#all:              	check_errors debug release
+#
+#debug:            	check_errors \
+#					$(CHECK_DIRS) \
+#					$(DYN_DEBUG_OUT) \
+#					$(STAT_DEBUG_OUT)
+#
+#release:          	check_errors \
+#					$(CHECK_DIRS) \
+#					$(DYN_RELEASE_OUT) \
+#					$(STAT_RELEASE_OUT)
+#
+#stat_debug:       	check_errors \
+#					$(CHECK_DIRS) \
+#					$(STAT_DEBUG_OUT)
+#          
+#dyn_debug:        	check_errors \
+#					$(CHECK_DIRS) \
+#					$(DYN_DEBUG_OUT)
+#
+#stat_release:     	check_errors \
+#					$(CHECK_DIRS) \
+#					$(STAT_RELEASE_OUT)
+#        
+#dyn_release:      	check_errors \
+#					$(CHECK_DIRS) \
+#					$(DYN_RELEASE_OUT)
+
+##########################################################
+# check for errors
+##########################################################
+check_errors:
+	@if [ "$(CONFIG_ERR)" = "TRUE" ]; then\
+		echo "Wrong CONFIG parameter specified: $(CONFIG)";\
+		false;\
+	fi
+
+
+##########################################################
+# create directories
+##########################################################
+
+$(OBJ_DIR):
+	@if [ ! -d $(OBJ_DIR) ]; then\
+		mkdir $(OBJ_DIR);\
+	fi
+
+$(LIB_DIR):
+	@if [ ! -d $(LIB_DIR) ]; then\
+		mkdir $(LIB_DIR);\
+	fi
+
+$(BIN_DIR):
+	@if [ ! -d $(BIN_DIR) ]; then\
+		mkdir $(BIN_DIR);\
+	fi
+
+
+
+##########################################################
+# create output files
+##########################################################
+
+ifeq ($(CONFIG), LIBRARY)
+#
+# create static debug out
+$(STAT_DEBUG_OUT): $(DEBUG_OBJS)
+	$(AR) -crs $@ $(DEBUG_OBJS)
+#
+#
+# create release debug out
+$(STAT_RELEASE_OUT): $(RELEASE_OBJS)
+	$(AR) -crs $@ $(RELEASE_OBJS)
+#
+#
+# create dynamic debug out
+$(DYN_DEBUG_OUT): $(DYN_DEBUG_OUT).$(VER) 
+	ln -fs lib$(PRJ_NAME)d.so.$(VER) $@
+#
+# create dynamic debug out
+$(DYN_DEBUG_OUT).$(VER): $(DEBUG_OBJS) 
+	$(LD) $(LDFLAGS) $(DEBUG_LDFLAGS) -o $@ $(DEBUG_OBJS) -L$(LIB_DIR) $(USER_LIB_DIRS) $(LIBS) $(DEBUG_LIBS) $(DYN_LIBS) $(DYN_DEBUG_LIBS)
+#
+#
+# create dynamic release out
+$(DYN_RELEASE_OUT): $(DYN_RELEASE_OUT).$(VER)
+	ln -fs lib$(PRJ_NAME).so.$(VER) $@
+#
+# create dynamic release out
+$(DYN_RELEASE_OUT).$(VER): $(RELEASE_OBJS)
+	$(LD) $(LDFLAGS) $(RELEASE_LDFLAGS) -o $@ $(RELEASE_OBJS) -L$(LIB_DIR) $(USER_LIB_DIRS) $(LIBS) $(RELEASE_LIBS) $(DYN_LIBS) $(DYN_RELEASE_LIBS)
+#
+#
+#
+#
+#
+else
+ifeq ($(CONFIG), CONSOLE)
+#
+# added linked libraries to target prerequisites - $(*_PREREQS) variables - to force relinking when libraries have been rebuilt
+#    2005-01-25 Steffen Kamp (kamp@ient.rwth-aachen.de), RWTH Aachen
+#
+# create static debug out
+$(STAT_DEBUG_OUT): $(DEBUG_OBJS) $(STAT_DEBUG_PREREQS)
+	$(LD) -o $@ $(LDFLAGS) $(DEBUG_LDFLAGS) $(DEBUG_OBJS) -L$(LIB_DIR) $(USER_LIB_DIRS) $(LIBS) $(DEBUG_LIBS) $(STAT_LIBS) $(STAT_DEBUG_LIBS)
+#
+#
+# create static release out
+$(STAT_RELEASE_OUT): $(RELEASE_OBJS) $(STAT_RELEASE_PREREQS)
+	$(LD) -o $@ $(LDFLAGS) $(RELEASE_LDFLAGS) $(RELEASE_OBJS) -L$(LIB_DIR) $(USER_LIB_DIRS) $(LIBS) $(RELEASE_LIBS) $(STAT_LIBS) $(STAT_RELEASE_LIBS)
+#
+#
+# create dynamic debug out
+$(DYN_DEBUG_OUT): $(DEBUG_OBJS) $(DYN_DEBUG_PREREQS)
+	$(LD) -o $@ $(LDFLAGS) $(DEBUG_LDFLAGS) $(DEBUG_OBJS) -L$(LIB_DIR) $(USER_LIB_DIRS) $(LIBS) $(DEBUG_LIBS) $(DYN_LIBS) $(DYN_DEBUG_LIBS)
+#
+#
+# create dynamic release out
+$(DYN_RELEASE_OUT): $(RELEASE_OBJS) $(DYN_RELEASE_PREREQS)
+	$(LD) -o $@ $(LDFLAGS) $(RELEASE_LDFLAGS) $(RELEASE_OBJS) -L$(LIB_DIR) $(USER_LIB_DIRS) $(LIBS) $(RELEASE_LIBS) $(DYN_LIBS) $(DYN_RELEASE_LIBS)
+#
+#
+endif
+endif
+
+##########################################################
+# delete all produced files
+##########################################################
+
+clean:
+	/bin/rm -rf $(STAT_DEBUG_OUT)
+	/bin/rm -rf $(STAT_RELEASE_OUT)
+	/bin/rm -rf $(DYN_DEBUG_OUT)
+	/bin/rm -rf $(DYN_RELEASE_OUT)
+	/bin/rm -rf $(OBJ_DIR)
+
+ifeq ($(CONFIG), LIBRARY)
+	/bin/rm -rf $(DYN_DEBUG_OUT).$(VER)
+	/bin/rm -rf $(DYN_RELEASE_OUT).$(VER)
+endif
+
+
+##########################################################
+# include dependency files
+##########################################################
+
+-include $(OBJS:.o=.d.P)
+-include $(OBJS:.o=.r.P)
Index: /trunk/build/linux/lib/TAppCommon/makefile
===================================================================
--- /trunk/build/linux/lib/TAppCommon/makefile	(revision 2)
+++ /trunk/build/linux/lib/TAppCommon/makefile	(revision 2)
@@ -0,0 +1,55 @@
+# the SOURCE definiton lets move your makefile to another position
+CONFIG 			= LIBRARY
+
+# set pathes to the correct directories
+SRC_DIR			= ../../../../source/Lib/TAppCommon
+INC_DIR			= ../../../../source/Lib
+LIB_DIR			= ../../../../lib
+BIN_DIR			= ../../../../bin
+
+SRC_DIR1		=
+SRC_DIR2		=
+SRC_DIR3		=
+SRC_DIR4		=
+
+
+USER_INC_DIRS	= -I$(SRC_DIR)
+USER_LIB_DIRS	=
+
+# intermediate directory for object files
+OBJ_DIR			= ./objects
+
+# the library name
+PRJ_NAME	 	= TAppCommon
+
+# version information
+MAJOR_VER		= 0
+MINOR_VER		= 1
+VER				= $(MAJOR_VER).$(MINOR_VER)
+
+# defines to set
+DEFS			= -DMSYS_LINUX
+
+# set objects
+OBJS          	= \
+			$(OBJ_DIR)/program_options_lite.o \
+
+LIBS				= -lpthread
+
+DEBUG_LIBS			=
+RELEASE_LIBS		=
+
+STAT_LIBS			=
+DYN_LIBS			= -ldl
+
+# the libraries to link with
+STAT_DEBUG_LIBS		=
+STAT_RELEASE_LIBS	=
+DYN_DEBUG_LIBS		=
+DYN_RELEASE_LIBS	=
+
+# name of the base makefile
+MAKE_FILE_NAME		= ../../common/makefile.base
+
+# include the base makefile
+include $(MAKE_FILE_NAME)
Index: /trunk/build/linux/lib/TLibCommon/makefile
===================================================================
--- /trunk/build/linux/lib/TLibCommon/makefile	(revision 2)
+++ /trunk/build/linux/lib/TLibCommon/makefile	(revision 2)
@@ -0,0 +1,79 @@
+# the SOURCE definiton lets move your makefile to another position
+CONFIG 			= LIBRARY
+
+# set pathes to the correct directories
+SRC_DIR			= ../../../../source/Lib/TLibCommon
+INC_DIR			= ../../../../source/Lib
+LIB_DIR			= ../../../../lib
+BIN_DIR			= ../../../../bin
+
+SRC_DIR1		= ../../../../source/Lib/libmd5
+SRC_DIR2		=
+SRC_DIR3		=
+SRC_DIR4		=
+
+
+USER_INC_DIRS	= -I$(SRC_DIR)
+USER_LIB_DIRS	=
+
+# intermediate directory for object files
+OBJ_DIR			= ./objects
+
+# the library name
+PRJ_NAME	 	= TLibCommon
+
+# version information
+MAJOR_VER		= 0
+MINOR_VER		= 1
+VER				= $(MAJOR_VER).$(MINOR_VER)
+
+# defines to set
+DEFS			= -DMSYS_LINUX
+
+# set objects
+OBJS          	= \
+			$(OBJ_DIR)/ContextModel.o \
+			$(OBJ_DIR)/ContextModel3DBuffer.o \
+			$(OBJ_DIR)/TComCABACTables.o \
+			$(OBJ_DIR)/TComAdaptiveLoopFilter.o \
+			$(OBJ_DIR)/TComSampleAdaptiveOffset.o \
+			$(OBJ_DIR)/TComBitStream.o \
+			$(OBJ_DIR)/TComDataCU.o \
+			$(OBJ_DIR)/TComLoopFilter.o \
+			$(OBJ_DIR)/TComMotionInfo.o \
+			$(OBJ_DIR)/TComPattern.o \
+			$(OBJ_DIR)/TComPic.o \
+			$(OBJ_DIR)/TComPicSym.o \
+			$(OBJ_DIR)/TComPicYuv.o \
+			$(OBJ_DIR)/TComPicYuvMD5.o \
+			$(OBJ_DIR)/TComPrediction.o \
+			$(OBJ_DIR)/TComRdCost.o \
+			$(OBJ_DIR)/TComRom.o \
+			$(OBJ_DIR)/TComSlice.o \
+			$(OBJ_DIR)/TComTrQuant.o \
+			$(OBJ_DIR)/TComYuv.o \
+			$(OBJ_DIR)/TComInterpolationFilter.o \
+			$(OBJ_DIR)/libmd5.o \
+			$(OBJ_DIR)/TComWeightPrediction.o \
+			$(OBJ_DIR)/TComRdCostWeightPrediction.o \
+			$(OBJ_DIR)/TComUpsampleFilter.o \
+
+LIBS				= -lpthread
+
+DEBUG_LIBS			=
+RELEASE_LIBS		=
+
+STAT_LIBS			=
+DYN_LIBS			= -ldl
+
+# the libraries to link with
+STAT_DEBUG_LIBS		=
+STAT_RELEASE_LIBS	=
+DYN_DEBUG_LIBS		=
+DYN_RELEASE_LIBS	=
+
+# name of the base makefile
+MAKE_FILE_NAME		= ../../common/makefile.base
+
+# include the base makefile
+include $(MAKE_FILE_NAME)
Index: /trunk/build/linux/lib/TLibDecoder/makefile
===================================================================
--- /trunk/build/linux/lib/TLibDecoder/makefile	(revision 2)
+++ /trunk/build/linux/lib/TLibDecoder/makefile	(revision 2)
@@ -0,0 +1,66 @@
+# the SOURCE definiton lets move your makefile to another position
+CONFIG 			= LIBRARY
+
+# set pathes to the correct directories
+SRC_DIR			= ../../../../source/Lib/TLibDecoder
+INC_DIR			= ../../../../source/Lib
+LIB_DIR			= ../../../../lib
+BIN_DIR			= ../../../../bin
+
+SRC_DIR1		=
+SRC_DIR2		=
+SRC_DIR3		=
+SRC_DIR4		=
+
+
+USER_INC_DIRS	= -I$(SRC_DIR)
+USER_LIB_DIRS	=
+
+# intermediate directory for object files
+OBJ_DIR			= ./objects
+
+# the library name
+PRJ_NAME	 	= TLibDecoder
+
+# version information
+MAJOR_VER		= 0
+MINOR_VER		= 1
+VER				= $(MAJOR_VER).$(MINOR_VER)
+
+# defines to set
+DEFS			= -DMSYS_LINUX
+
+# set objects
+OBJS          	= \
+				$(OBJ_DIR)/AnnexBread.o \
+				$(OBJ_DIR)/NALread.o \
+				$(OBJ_DIR)/SEIread.o \
+				$(OBJ_DIR)/SyntaxElementParser.o \
+				$(OBJ_DIR)/TDecBinCoderCABAC.o \
+				$(OBJ_DIR)/TDecCAVLC.o \
+				$(OBJ_DIR)/TDecCu.o \
+				$(OBJ_DIR)/TDecEntropy.o \
+				$(OBJ_DIR)/TDecGop.o \
+				$(OBJ_DIR)/TDecSbac.o \
+				$(OBJ_DIR)/TDecSlice.o \
+				$(OBJ_DIR)/TDecTop.o \
+
+LIBS				= -lpthread
+
+DEBUG_LIBS			=
+RELEASE_LIBS		=
+
+STAT_LIBS			=
+DYN_LIBS			= -ldl
+
+# the libraries to link with
+STAT_DEBUG_LIBS		=
+STAT_RELEASE_LIBS	=
+DYN_DEBUG_LIBS		=
+DYN_RELEASE_LIBS	=
+
+# name of the base makefile
+MAKE_FILE_NAME		= ../../common/makefile.base
+
+# include the base makefile
+include $(MAKE_FILE_NAME)
Index: /trunk/build/linux/lib/TLibEncoder/makefile
===================================================================
--- /trunk/build/linux/lib/TLibEncoder/makefile	(revision 2)
+++ /trunk/build/linux/lib/TLibEncoder/makefile	(revision 2)
@@ -0,0 +1,74 @@
+# the SOURCE definiton lets move your makefile to another position
+CONFIG 			= LIBRARY
+
+# set pathes to the correct directories
+SRC_DIR			= ../../../../source/Lib/TLibEncoder
+INC_DIR			= ../../../../source/Lib
+LIB_DIR			= ../../../../lib
+BIN_DIR			= ../../../../bin
+
+SRC_DIR1		=
+SRC_DIR2		=
+SRC_DIR3		=
+SRC_DIR4		=
+
+
+USER_INC_DIRS	= -I$(SRC_DIR)
+USER_LIB_DIRS	=
+
+# intermediate directory for object files
+OBJ_DIR			= ./objects
+
+# the library name
+PRJ_NAME	 	= TLibEncoder
+
+# version information
+MAJOR_VER		= 0
+MINOR_VER		= 1
+VER				= $(MAJOR_VER).$(MINOR_VER)
+
+# defines to set
+DEFS			= -DMSYS_LINUX
+
+# set objects
+OBJS          	= \
+			$(OBJ_DIR)/NALwrite.o \
+			$(OBJ_DIR)/SEIwrite.o \
+			$(OBJ_DIR)/SyntaxElementWriter.o \
+			$(OBJ_DIR)/TEncBinCoderCABAC.o \
+			$(OBJ_DIR)/TEncBinCoderCABACCounter.o \
+			$(OBJ_DIR)/TEncAdaptiveLoopFilter.o \
+			$(OBJ_DIR)/TEncSampleAdaptiveOffset.o \
+			$(OBJ_DIR)/TEncAnalyze.o \
+			$(OBJ_DIR)/TEncCavlc.o \
+			$(OBJ_DIR)/TEncCu.o \
+			$(OBJ_DIR)/TEncEntropy.o \
+			$(OBJ_DIR)/TEncGOP.o \
+			$(OBJ_DIR)/TEncSbac.o \
+			$(OBJ_DIR)/TEncSearch.o \
+			$(OBJ_DIR)/TEncSlice.o \
+			$(OBJ_DIR)/TEncTop.o \
+			$(OBJ_DIR)/TEncPic.o \
+			$(OBJ_DIR)/TEncPreanalyzer.o \
+			$(OBJ_DIR)/WeightPredAnalysis.o \
+			$(OBJ_DIR)/TEncRateCtrl.o \
+
+LIBS				= -lpthread
+
+DEBUG_LIBS			=
+RELEASE_LIBS		=
+
+STAT_LIBS			=
+DYN_LIBS			= -ldl
+
+# the libraries to link with
+STAT_DEBUG_LIBS		=
+STAT_RELEASE_LIBS	=
+DYN_DEBUG_LIBS		=
+DYN_RELEASE_LIBS	=
+
+# name of the base makefile
+MAKE_FILE_NAME		= ../../common/makefile.base
+
+# include the base makefile
+include $(MAKE_FILE_NAME)
Index: /trunk/build/linux/lib/TLibVideoIO/makefile
===================================================================
--- /trunk/build/linux/lib/TLibVideoIO/makefile	(revision 2)
+++ /trunk/build/linux/lib/TLibVideoIO/makefile	(revision 2)
@@ -0,0 +1,56 @@
+# the SOURCE definiton lets move your makefile to another position
+CONFIG 			= LIBRARY
+
+# set pathes to the correct directories
+SRC_DIR			= ../../../../source/Lib/TLibVideoIO
+INC_DIR			= ../../../../source/Lib
+LIB_DIR			= ../../../../lib
+BIN_DIR			= ../../../../bin
+
+SRC_DIR1		=
+SRC_DIR2		=
+SRC_DIR3		=
+SRC_DIR4		=
+
+
+USER_INC_DIRS	= -I$(SRC_DIR)
+USER_LIB_DIRS	=
+
+# intermediate directory for object files
+OBJ_DIR			= ./objects
+
+# the library name
+PRJ_NAME	 	= TLibVideoIO
+
+# version information
+MAJOR_VER		= 0
+MINOR_VER		= 28
+VER				= $(MAJOR_VER).$(MINOR_VER)
+
+# defines to set
+DEFS			= -DMSYS_LINUX -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64 -DMSYS_UNIX_LARGEFILE
+
+# set objects
+OBJS          	= \
+			$(OBJ_DIR)/TVideoIOYuv.o \
+						
+
+LIBS				= -lpthread 
+
+DEBUG_LIBS			=
+RELEASE_LIBS		=
+
+STAT_LIBS			=
+DYN_LIBS			=
+
+# the libraries to link with
+STAT_DEBUG_LIBS		= 
+STAT_RELEASE_LIBS	= 
+DYN_DEBUG_LIBS		=
+DYN_RELEASE_LIBS	=
+
+# name of the base makefile
+MAKE_FILE_NAME		= ../../common/makefile.base
+
+# include the base makefile
+include $(MAKE_FILE_NAME)
Index: /trunk/build/linux/makefile
===================================================================
--- /trunk/build/linux/makefile	(revision 2)
+++ /trunk/build/linux/makefile	(revision 2)
@@ -0,0 +1,48 @@
+### enforce 32-bit build : 1=yes, 0=no
+M32?= 0
+ 
+export M32
+
+all:
+	$(MAKE) -C lib/TLibVideoIO 	MM32=$(M32)
+	$(MAKE) -C lib/TLibCommon 	MM32=$(M32)
+	$(MAKE) -C lib/TLibDecoder 	MM32=$(M32)
+	$(MAKE) -C lib/TLibEncoder 	MM32=$(M32)
+	$(MAKE) -C lib/TAppCommon       MM32=$(M32)
+	$(MAKE) -C app/TAppDecoder      MM32=$(M32)
+	$(MAKE) -C app/TAppEncoder      MM32=$(M32)
+	$(MAKE) -C utils/annexBbytecount       MM32=$(M32)
+	$(MAKE) -C utils/convert_NtoMbit_YCbCr MM32=$(M32)
+
+debug:
+	$(MAKE) -C lib/TLibVideoIO 	debug MM32=$(M32)
+	$(MAKE) -C lib/TLibCommon 	debug MM32=$(M32)
+	$(MAKE) -C lib/TLibDecoder 	debug MM32=$(M32)
+	$(MAKE) -C lib/TLibEncoder 	debug MM32=$(M32)
+	$(MAKE) -C lib/TAppCommon       debug MM32=$(M32)
+	$(MAKE) -C app/TAppDecoder      debug MM32=$(M32)
+	$(MAKE) -C app/TAppEncoder      debug MM32=$(M32)
+	$(MAKE) -C utils/annexBbytecount       debug MM32=$(M32)
+	$(MAKE) -C utils/convert_NtoMbit_YCbCr debug MM32=$(M32)
+
+release:
+	$(MAKE) -C lib/TLibVideoIO 	release MM32=$(M32)
+	$(MAKE) -C lib/TLibCommon 	release MM32=$(M32)
+	$(MAKE) -C lib/TLibDecoder 	release MM32=$(M32)
+	$(MAKE) -C lib/TLibEncoder 	release MM32=$(M32)
+	$(MAKE) -C lib/TAppCommon       release MM32=$(M32)
+	$(MAKE) -C app/TAppDecoder      release MM32=$(M32)
+	$(MAKE) -C app/TAppEncoder      release MM32=$(M32)
+	$(MAKE) -C utils/annexBbytecount       release MM32=$(M32)
+	$(MAKE) -C utils/convert_NtoMbit_YCbCr release MM32=$(M32)
+
+clean:
+	$(MAKE) -C lib/TLibVideoIO 	clean MM32=$(M32)
+	$(MAKE) -C lib/TLibCommon 	clean MM32=$(M32)
+	$(MAKE) -C lib/TLibDecoder 	clean MM32=$(M32)
+	$(MAKE) -C lib/TLibEncoder 	clean MM32=$(M32)
+	$(MAKE) -C lib/TAppCommon       clean MM32=$(M32)
+	$(MAKE) -C app/TAppDecoder      clean MM32=$(M32)
+	$(MAKE) -C app/TAppEncoder      clean MM32=$(M32)
+	$(MAKE) -C utils/annexBbytecount       clean MM32=$(M32)
+	$(MAKE) -C utils/convert_NtoMbit_YCbCr clean MM32=$(M32)
Index: /trunk/build/linux/utils/annexBbytecount/makefile
===================================================================
--- /trunk/build/linux/utils/annexBbytecount/makefile	(revision 2)
+++ /trunk/build/linux/utils/annexBbytecount/makefile	(revision 2)
@@ -0,0 +1,56 @@
+# the SOURCE definiton lets you move your makefile to another position
+CONFIG 				= CONSOLE
+
+# set directories to your wanted values
+SRC_DIR				= ../../../../source/App/utils
+INC_DIR				= ../../../../source/Lib
+LIB_DIR				= ../../../../lib
+BIN_DIR				= ../../../../bin
+
+SRC_DIR1		=
+SRC_DIR2		=
+SRC_DIR3		=
+SRC_DIR4		=
+
+USER_INC_DIRS	= -I$(SRC_DIR) 
+USER_LIB_DIRS	=
+
+# intermediate directory for object files
+OBJ_DIR				= ./objects
+
+# set executable name
+PRJ_NAME			= annexBbytecount
+
+# defines to set
+DEFS				= -DMSYS_LINUX -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64 -DMSYS_UNIX_LARGEFILE
+
+# set objects
+OBJS          		= 	\
+					$(OBJ_DIR)/annexBbytecount.o \
+
+# set libs to link with
+LIBS				= -ldl
+
+DEBUG_LIBS			=
+RELEASE_LIBS		=
+
+STAT_LIBS			= -lpthread
+DYN_LIBS			=
+
+
+DYN_DEBUG_LIBS		= -lTLibDecoderd -lTLibCommond -lTLibVideoIOd -lTAppCommond
+DYN_DEBUG_PREREQS		= $(LIB_DIR)/libTLibDecoderd.a $(LIB_DIR)/libTLibCommond.a $(LIB_DIR)/libTLibVideoIOd.a $(LIB_DIR)/libTAppCommond.a
+STAT_DEBUG_LIBS		= -lTLibDecoderStaticd -lTLibCommonStaticd -lTLibVideoIOStaticd -lTAppCommonStaticd
+STAT_DEBUG_PREREQS		= $(LIB_DIR)/libTLibDecoderStaticd.a $(LIB_DIR)/libTLibCommonStaticd.a $(LIB_DIR)/libTLibVideoIOStaticd.a $(LIB_DIR)/libTAppCommonStaticd.a
+
+DYN_RELEASE_LIBS	= -lTLibDecoder -lTLibCommon -lTLibVideoIO -lTAppCommon
+DYN_RELEASE_PREREQS	= $(LIB_DIR)/libTLibDecoder.a $(LIB_DIR)/libTLibCommon.a $(LIB_DIR)/libTLibVideoIO.a $(LIB_DIR)/libTAppCommon.a
+STAT_RELEASE_LIBS	= -lTLibDecoderStatic -lTLibCommonStatic -lTLibVideoIOStatic -lTAppCommonStatic
+STAT_RELEASE_PREREQS	= $(LIB_DIR)/libTLibDecoderStatic.a $(LIB_DIR)/libTLibCommonStatic.a $(LIB_DIR)/libTLibVideoIOStatic.a $(LIB_DIR)/libTAppCommonStatic.a
+
+
+# name of the base makefile
+MAKE_FILE_NAME		= ../../common/makefile.base
+
+# include the base makefile
+include $(MAKE_FILE_NAME)
Index: /trunk/build/linux/utils/convert_NtoMbit_YCbCr/makefile
===================================================================
--- /trunk/build/linux/utils/convert_NtoMbit_YCbCr/makefile	(revision 2)
+++ /trunk/build/linux/utils/convert_NtoMbit_YCbCr/makefile	(revision 2)
@@ -0,0 +1,56 @@
+# the SOURCE definiton lets you move your makefile to another position
+CONFIG 				= CONSOLE
+
+# set directories to your wanted values
+SRC_DIR				= ../../../../source/App/utils
+INC_DIR				= ../../../../source/Lib
+LIB_DIR				= ../../../../lib
+BIN_DIR				= ../../../../bin
+
+SRC_DIR1		=
+SRC_DIR2		=
+SRC_DIR3		=
+SRC_DIR4		=
+
+USER_INC_DIRS	= -I$(SRC_DIR) 
+USER_LIB_DIRS	=
+
+# intermediate directory for object files
+OBJ_DIR				= ./objects
+
+# set executable name
+PRJ_NAME			= convert_NtoMbit_YCbCr
+
+# defines to set
+DEFS				= -DMSYS_LINUX -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64 -DMSYS_UNIX_LARGEFILE
+
+# set objects
+OBJS          		= 	\
+					$(OBJ_DIR)/convert_NtoMbit_YCbCr.o \
+
+# set libs to link with
+LIBS				= -ldl
+
+DEBUG_LIBS			=
+RELEASE_LIBS		=
+
+STAT_LIBS			= -lpthread
+DYN_LIBS			=
+
+
+DYN_DEBUG_LIBS		= -lTLibDecoderd -lTLibCommond -lTLibVideoIOd -lTAppCommond
+DYN_DEBUG_PREREQS		= $(LIB_DIR)/libTLibDecoderd.a $(LIB_DIR)/libTLibCommond.a $(LIB_DIR)/libTLibVideoIOd.a $(LIB_DIR)/libTAppCommond.a
+STAT_DEBUG_LIBS		= -lTLibDecoderStaticd -lTLibCommonStaticd -lTLibVideoIOStaticd -lTAppCommonStaticd
+STAT_DEBUG_PREREQS		= $(LIB_DIR)/libTLibDecoderStaticd.a $(LIB_DIR)/libTLibCommonStaticd.a $(LIB_DIR)/libTLibVideoIOStaticd.a $(LIB_DIR)/libTAppCommonStaticd.a
+
+DYN_RELEASE_LIBS	= -lTLibDecoder -lTLibCommon -lTLibVideoIO -lTAppCommon
+DYN_RELEASE_PREREQS	= $(LIB_DIR)/libTLibDecoder.a $(LIB_DIR)/libTLibCommon.a $(LIB_DIR)/libTLibVideoIO.a $(LIB_DIR)/libTAppCommon.a
+STAT_RELEASE_LIBS	= -lTLibDecoderStatic -lTLibCommonStatic -lTLibVideoIOStatic -lTAppCommonStatic
+STAT_RELEASE_PREREQS	= $(LIB_DIR)/libTLibDecoderStatic.a $(LIB_DIR)/libTLibCommonStatic.a $(LIB_DIR)/libTLibVideoIOStatic.a $(LIB_DIR)/libTAppCommonStatic.a
+
+
+# name of the base makefile
+MAKE_FILE_NAME		= ../../common/makefile.base
+
+# include the base makefile
+include $(MAKE_FILE_NAME)
Index: /trunk/build/vc10/TAppCommon_vc10.vcproj
===================================================================
--- /trunk/build/vc10/TAppCommon_vc10.vcproj	(revision 2)
+++ /trunk/build/vc10/TAppCommon_vc10.vcproj	(revision 2)
@@ -0,0 +1,301 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9,00"
+	Name="TAppCommon"
+	ProjectGUID="{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}"
+	RootNamespace="TAppCommon"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TAppCommon\program_options_lite.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TAppCommon\program_options_lite.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /trunk/build/vc10/TAppCommon_vc10.vcxproj
===================================================================
--- /trunk/build/vc10/TAppCommon_vc10.vcxproj	(revision 2)
+++ /trunk/build/vc10/TAppCommon_vc10.vcxproj	(revision 2)
@@ -0,0 +1,142 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug|x64">
+      <Configuration>Debug</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|x64">
+      <Configuration>Release</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectName>TAppCommon</ProjectName>
+    <ProjectGuid>{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}</ProjectGuid>
+    <RootNamespace>TAppCommon</RootNamespace>
+    <Keyword>Win32Proj</Keyword>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup>
+    <_ProjectFileVersion>10.0.40219.1</_ProjectFileVersion>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TAppCommon\program_options_lite.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TAppCommon\program_options_lite.h" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: /trunk/build/vc10/TAppCommon_vc10.vcxproj.filters
===================================================================
--- /trunk/build/vc10/TAppCommon_vc10.vcxproj.filters	(revision 2)
+++ /trunk/build/vc10/TAppCommon_vc10.vcxproj.filters	(revision 2)
@@ -0,0 +1,23 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{61c3b510-d4b2-46da-9a25-be492f2fc243}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{94c90dc5-7f7b-4776-ba53-bf464ac89d29}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TAppCommon\program_options_lite.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TAppCommon\program_options_lite.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: /trunk/build/vc10/TAppCommon_vc10.vcxproj.user
===================================================================
--- /trunk/build/vc10/TAppCommon_vc10.vcxproj.user	(revision 2)
+++ /trunk/build/vc10/TAppCommon_vc10.vcxproj.user	(revision 2)
@@ -0,0 +1,3 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+</Project>
Index: /trunk/build/vc10/TAppDecoder_vc10.vcproj
===================================================================
--- /trunk/build/vc10/TAppDecoder_vc10.vcproj	(revision 2)
+++ /trunk/build/vc10/TAppDecoder_vc10.vcproj	(revision 2)
@@ -0,0 +1,358 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9.00"
+	Name="TAppDecoder"
+	ProjectGUID="{A7A515D9-E917-4706-BD5B-57DC6C78D612}"
+	RootNamespace="TAppDecoder"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc10\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc10\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc10\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc10\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppDecoder\decmain.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppDecoder\TAppDecCfg.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppDecoder\TAppDecTop.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppDecoder\TAppDecCfg.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppDecoder\TAppDecTop.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /trunk/build/vc10/TAppDecoder_vc10.vcxproj
===================================================================
--- /trunk/build/vc10/TAppDecoder_vc10.vcxproj	(revision 2)
+++ /trunk/build/vc10/TAppDecoder_vc10.vcxproj	(revision 2)
@@ -0,0 +1,187 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug|x64">
+      <Configuration>Debug</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|x64">
+      <Configuration>Release</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectName>TAppDecoder</ProjectName>
+    <ProjectGuid>{A7A515D9-E917-4706-BD5B-57DC6C78D612}</ProjectGuid>
+    <RootNamespace>TAppDecoder</RootNamespace>
+    <Keyword>Win32Proj</Keyword>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup>
+    <_ProjectFileVersion>10.0.40219.1</_ProjectFileVersion>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</LinkIncremental>
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX86</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX64</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX86</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX64</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\App\TAppDecoder\decmain.cpp" />
+    <ClCompile Include="..\..\source\App\TAppDecoder\TAppDecCfg.cpp" />
+    <ClCompile Include="..\..\source\App\TAppDecoder\TAppDecTop.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\App\TAppDecoder\TAppDecCfg.h" />
+    <ClInclude Include="..\..\source\App\TAppDecoder\TAppDecTop.h" />
+  </ItemGroup>
+  <ItemGroup>
+    <ProjectReference Include="TAppCommon_vc10.vcxproj">
+      <Project>{d1e8a1c2-15db-4c94-80e8-4f70cf0a2dc5}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+    <ProjectReference Include="TLibCommon_vc10.vcxproj">
+      <Project>{78018d78-f890-47e3-a0b7-09d273f0b11d}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+    <ProjectReference Include="TLibDecoder_vc10.vcxproj">
+      <Project>{f8b77a48-af6c-4746-a89f-b706aba6ad94}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+    <ProjectReference Include="TLibVideoIO_vc10.vcxproj">
+      <Project>{5280c25a-d316-4be7-ae50-29d72108624f}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: /trunk/build/vc10/TAppDecoder_vc10.vcxproj.filters
===================================================================
--- /trunk/build/vc10/TAppDecoder_vc10.vcxproj.filters	(revision 2)
+++ /trunk/build/vc10/TAppDecoder_vc10.vcxproj.filters	(revision 2)
@@ -0,0 +1,36 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{f91faffd-ddc1-46ee-bf46-c9f336a04889}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{53724405-0877-4412-a713-0153d444b64f}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+    <Filter Include="Resource Files">
+      <UniqueIdentifier>{f426d7ef-18cf-4428-8729-17e3d457a2d8}</UniqueIdentifier>
+      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\App\TAppDecoder\decmain.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\App\TAppDecoder\TAppDecCfg.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\App\TAppDecoder\TAppDecTop.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\App\TAppDecoder\TAppDecCfg.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\App\TAppDecoder\TAppDecTop.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: /trunk/build/vc10/TAppDecoder_vc10.vcxproj.user
===================================================================
--- /trunk/build/vc10/TAppDecoder_vc10.vcxproj.user	(revision 2)
+++ /trunk/build/vc10/TAppDecoder_vc10.vcxproj.user	(revision 2)
@@ -0,0 +1,8 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <LocalDebuggerCommandArguments>-b str/BasketballPass.bin -ls 2 -ibl O:/BasketballPassBL_rec.yuv -ibs O:/BasketballPassBL_syntax.bin -wdt 416 -hgt 240</LocalDebuggerCommandArguments>
+    <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
+    <LocalDebuggerWorkingDirectory>$(ProjectDir)/../../../</LocalDebuggerWorkingDirectory>
+  </PropertyGroup>
+</Project>
Index: /trunk/build/vc10/TAppEncoder_vc10.vcproj
===================================================================
--- /trunk/build/vc10/TAppEncoder_vc10.vcproj	(revision 2)
+++ /trunk/build/vc10/TAppEncoder_vc10.vcproj	(revision 2)
@@ -0,0 +1,366 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9.00"
+	Name="TAppEncoder"
+	ProjectGUID="{D759E4E1-D33A-4483-B57B-0FD248E022FE}"
+	RootNamespace="TAppEncoder"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc10\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc10\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc10\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc10\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\encmain.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\TAppEncCfg.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\TAppEncLayerCfg.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\TAppEncTop.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\TAppEncCfg.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\TAppEncLayerCfg.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\TAppEncTop.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /trunk/build/vc10/TAppEncoder_vc10.vcxproj
===================================================================
--- /trunk/build/vc10/TAppEncoder_vc10.vcxproj	(revision 2)
+++ /trunk/build/vc10/TAppEncoder_vc10.vcxproj	(revision 2)
@@ -0,0 +1,189 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug|x64">
+      <Configuration>Debug</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|x64">
+      <Configuration>Release</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectName>TAppEncoder</ProjectName>
+    <ProjectGuid>{D759E4E1-D33A-4483-B57B-0FD248E022FE}</ProjectGuid>
+    <RootNamespace>TAppEncoder</RootNamespace>
+    <Keyword>Win32Proj</Keyword>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup>
+    <_ProjectFileVersion>10.0.40219.1</_ProjectFileVersion>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</LinkIncremental>
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX86</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX64</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX86</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX64</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\App\TAppEncoder\encmain.cpp" />
+    <ClCompile Include="..\..\source\App\TAppEncoder\TAppEncCfg.cpp" />
+    <ClCompile Include="..\..\source\App\TAppEncoder\TAppEncLayerCfg.cpp" />
+    <ClCompile Include="..\..\source\App\TAppEncoder\TAppEncTop.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\App\TAppEncoder\TAppEncCfg.h" />
+    <ClInclude Include="..\..\source\App\TAppEncoder\TAppEncLayerCfg.h" />
+    <ClInclude Include="..\..\source\App\TAppEncoder\TAppEncTop.h" />
+  </ItemGroup>
+  <ItemGroup>
+    <ProjectReference Include="TAppCommon_vc10.vcxproj">
+      <Project>{d1e8a1c2-15db-4c94-80e8-4f70cf0a2dc5}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+    <ProjectReference Include="TLibCommon_vc10.vcxproj">
+      <Project>{78018d78-f890-47e3-a0b7-09d273f0b11d}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+    <ProjectReference Include="TLibEncoder_vc10.vcxproj">
+      <Project>{47e90995-1fc5-4ee4-a94d-ad474169f0e1}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+    <ProjectReference Include="TLibVideoIO_vc10.vcxproj">
+      <Project>{5280c25a-d316-4be7-ae50-29d72108624f}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: /trunk/build/vc10/TAppEncoder_vc10.vcxproj.filters
===================================================================
--- /trunk/build/vc10/TAppEncoder_vc10.vcxproj.filters	(revision 2)
+++ /trunk/build/vc10/TAppEncoder_vc10.vcxproj.filters	(revision 2)
@@ -0,0 +1,42 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{5a91399d-a287-4a11-b533-6094f5650005}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{829a2cbb-01c0-489f-b342-3eb74b2dcb35}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+    <Filter Include="Resource Files">
+      <UniqueIdentifier>{2a3d6658-bcc6-4553-8ece-38846d0d457c}</UniqueIdentifier>
+      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\App\TAppEncoder\encmain.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\App\TAppEncoder\TAppEncCfg.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\App\TAppEncoder\TAppEncTop.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\App\TAppEncoder\TAppEncLayerCfg.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\App\TAppEncoder\TAppEncCfg.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\App\TAppEncoder\TAppEncTop.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\App\TAppEncoder\TAppEncLayerCfg.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: /trunk/build/vc10/TAppEncoder_vc10.vcxproj.user
===================================================================
--- /trunk/build/vc10/TAppEncoder_vc10.vcxproj.user	(revision 2)
+++ /trunk/build/vc10/TAppEncoder_vc10.vcxproj.user	(revision 2)
@@ -0,0 +1,10 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <LocalDebuggerCommandArguments>-c cfg/svc/BasketballPass_layers10.cfg -c cfg/encoder_lowdelay_main.cfg -q0 22 -q1 20 -g 4 -f 5 -b str/BasketballPass.bin -c option.cfg -ibl O:/BasketballPassBL_rec.yuv -ibs O:/BasketballPassBL_syntax.bin</LocalDebuggerCommandArguments>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <LocalDebuggerWorkingDirectory>$(ProjectDir)/../../../</LocalDebuggerWorkingDirectory>
+    <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
+  </PropertyGroup>
+</Project>
Index: /trunk/build/vc10/TLibCommon_vc10.vcproj
===================================================================
--- /trunk/build/vc10/TLibCommon_vc10.vcproj	(revision 2)
+++ /trunk/build/vc10/TLibCommon_vc10.vcproj	(revision 2)
@@ -0,0 +1,531 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9.00"
+	Name="TLibCommon"
+	ProjectGUID="{78018D78-F890-47E3-A0B7-09D273F0B11D}"
+	RootNamespace="TLibCommon"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\ContextModel.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\ContextModel3DBuffer.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\libmd5\libmd5.c"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComAdaptiveLoopFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComBitStream.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComCABACTables.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComDataCU.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComInterpolationFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComLoopFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComMotionInfo.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPattern.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPic.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPicSym.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPicYuv.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPicYuvMD5.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPrediction.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRdCost.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRdCostWeightPrediction.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRom.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComSampleAdaptiveOffset.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComSlice.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComTrQuant.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComUpsampleFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComWeightPrediction.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComYuv.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\AccessUnit.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\CommonDef.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\ContextModel.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\ContextModel3DBuffer.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\ContextTables.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\libmd5\libmd5.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\libmd5\MD5.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\NAL.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\SEI.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComAdaptiveLoopFilter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComBitCounter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComBitStream.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComCABACTables.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComDataCU.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComInterpolationFilter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComList.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComLoopFilter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComMotionInfo.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComMv.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPattern.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPic.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPicSym.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPicYuv.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPrediction.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRdCost.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRdCostWeightPrediction.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRom.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComSampleAdaptiveOffset.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComSlice.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComTrQuant.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComUpsampleFilter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComWeightPrediction.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComYuv.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TypeDef.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /trunk/build/vc10/TLibCommon_vc10.vcxproj
===================================================================
--- /trunk/build/vc10/TLibCommon_vc10.vcxproj	(revision 2)
+++ /trunk/build/vc10/TLibCommon_vc10.vcxproj	(revision 2)
@@ -0,0 +1,199 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug|x64">
+      <Configuration>Debug</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|x64">
+      <Configuration>Release</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectName>TLibCommon</ProjectName>
+    <ProjectGuid>{78018D78-F890-47E3-A0B7-09D273F0B11D}</ProjectGuid>
+    <RootNamespace>TLibCommon</RootNamespace>
+    <Keyword>Win32Proj</Keyword>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup>
+    <_ProjectFileVersion>10.0.40219.1</_ProjectFileVersion>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\ContextModel.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\ContextModel3DBuffer.cpp" />
+    <ClCompile Include="..\..\source\Lib\libmd5\libmd5.c" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComAdaptiveLoopFilter.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComBitStream.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComCABACTables.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComDataCU.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComInterpolationFilter.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComLoopFilter.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComMotionInfo.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPattern.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPic.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPicSym.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPicYuv.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPicYuvMD5.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPrediction.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComRdCost.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComRdCostWeightPrediction.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComRom.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComSampleAdaptiveOffset.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComSlice.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComTrQuant.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComUpsampleFilter.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComWeightPrediction.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComYuv.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\AccessUnit.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\CommonDef.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\ContextModel.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\ContextModel3DBuffer.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\ContextTables.h" />
+    <ClInclude Include="..\..\source\Lib\libmd5\libmd5.h" />
+    <ClInclude Include="..\..\source\Lib\libmd5\MD5.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\NAL.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\SEI.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComAdaptiveLoopFilter.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComBitCounter.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComBitStream.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComCABACTables.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComDataCU.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComInterpolationFilter.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComList.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComLoopFilter.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComMotionInfo.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComMv.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPattern.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPic.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPicSym.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPicYuv.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPrediction.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComRdCost.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComRdCostWeightPrediction.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComRom.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComSampleAdaptiveOffset.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComSlice.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComTrQuant.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComUpsampleFilter.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComWeightPrediction.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComYuv.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TypeDef.h" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: /trunk/build/vc10/TLibCommon_vc10.vcxproj.filters
===================================================================
--- /trunk/build/vc10/TLibCommon_vc10.vcxproj.filters	(revision 2)
+++ /trunk/build/vc10/TLibCommon_vc10.vcxproj.filters	(revision 2)
@@ -0,0 +1,194 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\ContextModel.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\ContextModel3DBuffer.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\libmd5\libmd5.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComAdaptiveLoopFilter.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComBitStream.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComCABACTables.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComDataCU.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComInterpolationFilter.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComLoopFilter.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComMotionInfo.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPattern.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPic.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPicSym.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPicYuv.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPicYuvMD5.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPrediction.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComRdCost.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComRdCostWeightPrediction.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComRom.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComSampleAdaptiveOffset.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComSlice.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComTrQuant.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComWeightPrediction.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComYuv.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComUpsampleFilter.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\AccessUnit.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\CommonDef.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\ContextModel.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\ContextModel3DBuffer.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\ContextTables.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\libmd5\libmd5.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\libmd5\MD5.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\NAL.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\SEI.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComAdaptiveLoopFilter.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComBitCounter.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComBitStream.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComCABACTables.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComDataCU.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComInterpolationFilter.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComList.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComLoopFilter.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComMotionInfo.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComMv.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPattern.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPic.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPicSym.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPicYuv.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPrediction.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComRdCost.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComRdCostWeightPrediction.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComRom.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComSampleAdaptiveOffset.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComSlice.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComTrQuant.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComWeightPrediction.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComYuv.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TypeDef.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComUpsampleFilter.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: /trunk/build/vc10/TLibCommon_vc10.vcxproj.user
===================================================================
--- /trunk/build/vc10/TLibCommon_vc10.vcxproj.user	(revision 2)
+++ /trunk/build/vc10/TLibCommon_vc10.vcxproj.user	(revision 2)
@@ -0,0 +1,3 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+</Project>
Index: /trunk/build/vc10/TLibDecoder_vc10.vcproj
===================================================================
--- /trunk/build/vc10/TLibDecoder_vc10.vcproj	(revision 2)
+++ /trunk/build/vc10/TLibDecoder_vc10.vcproj	(revision 2)
@@ -0,0 +1,393 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9.00"
+	Name="TLibDecoder"
+	ProjectGUID="{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}"
+	RootNamespace="TLibDecoder"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\AnnexBread.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\NALread.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\SEIread.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\SyntaxElementParser.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecCAVLC.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecCu.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecEntropy.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecGop.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecSbac.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecSlice.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecTop.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\AnnexBread.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\NALread.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\SEIread.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\SyntaxElementParser.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecBinCoder.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecCAVLC.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecCu.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecEntropy.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecGop.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecSbac.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecSlice.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecTop.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /trunk/build/vc10/TLibDecoder_vc10.vcxproj
===================================================================
--- /trunk/build/vc10/TLibDecoder_vc10.vcxproj	(revision 2)
+++ /trunk/build/vc10/TLibDecoder_vc10.vcxproj	(revision 2)
@@ -0,0 +1,165 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug|x64">
+      <Configuration>Debug</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|x64">
+      <Configuration>Release</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectName>TLibDecoder</ProjectName>
+    <ProjectGuid>{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}</ProjectGuid>
+    <RootNamespace>TLibDecoder</RootNamespace>
+    <Keyword>Win32Proj</Keyword>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup>
+    <_ProjectFileVersion>10.0.40219.1</_ProjectFileVersion>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\AnnexBread.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\NALread.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\SEIread.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\SyntaxElementParser.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecCAVLC.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecCu.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecEntropy.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecGop.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecSbac.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecSlice.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecTop.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\AnnexBread.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\NALread.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\SEIread.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\SyntaxElementParser.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecBinCoder.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecCAVLC.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecCu.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecEntropy.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecGop.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecSbac.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecSlice.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecTop.h" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: /trunk/build/vc10/TLibDecoder_vc10.vcxproj.filters
===================================================================
--- /trunk/build/vc10/TLibDecoder_vc10.vcxproj.filters	(revision 2)
+++ /trunk/build/vc10/TLibDecoder_vc10.vcxproj.filters	(revision 2)
@@ -0,0 +1,92 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{57c32785-e8b2-4ab2-82f6-091ce0690afe}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{8351b640-31d1-405d-a45f-7e5469df1a8c}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\AnnexBread.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\NALread.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\SEIread.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\SyntaxElementParser.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecCAVLC.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecCu.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecEntropy.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecGop.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecSbac.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecSlice.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecTop.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\AnnexBread.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\NALread.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\SEIread.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\SyntaxElementParser.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecBinCoder.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecCAVLC.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecCu.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecEntropy.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecGop.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecSbac.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecSlice.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecTop.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: /trunk/build/vc10/TLibDecoder_vc10.vcxproj.user
===================================================================
--- /trunk/build/vc10/TLibDecoder_vc10.vcxproj.user	(revision 2)
+++ /trunk/build/vc10/TLibDecoder_vc10.vcxproj.user	(revision 2)
@@ -0,0 +1,3 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+</Project>
Index: /trunk/build/vc10/TLibEncoder_vc10.vcproj
===================================================================
--- /trunk/build/vc10/TLibEncoder_vc10.vcproj	(revision 2)
+++ /trunk/build/vc10/TLibEncoder_vc10.vcproj	(revision 2)
@@ -0,0 +1,465 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9.00"
+	Name="TLibEncoder"
+	ProjectGUID="{47E90995-1FC5-4EE4-A94D-AD474169F0E1}"
+	RootNamespace="TLibEncoder"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\NALwrite.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\SEIwrite.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\SyntaxElementWriter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncAdaptiveLoopFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncAnalyze.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncBinCoderCABAC.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncBinCoderCABACCounter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncCavlc.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncCu.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncEntropy.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncGOP.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncPic.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncPreanalyzer.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncRateCtrl.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSampleAdaptiveOffset.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSbac.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSearch.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSlice.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncTop.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\WeightPredAnalysis.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\AnnexBwrite.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\NALwrite.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\SEIwrite.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\SyntaxElementWriter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncAdaptiveLoopFilter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncAnalyze.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncBinCoder.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncBinCoderCABAC.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncBinCoderCABACCounter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncCavlc.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncCfg.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncCu.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncEntropy.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncGOP.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncPic.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncPreanalyzer.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncRateCtrl.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSampleAdaptiveOffset.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSbac.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSearch.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSlice.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncTop.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\WeightPredAnalysis.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /trunk/build/vc10/TLibEncoder_vc10.vcxproj
===================================================================
--- /trunk/build/vc10/TLibEncoder_vc10.vcxproj	(revision 2)
+++ /trunk/build/vc10/TLibEncoder_vc10.vcxproj	(revision 2)
@@ -0,0 +1,183 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug|x64">
+      <Configuration>Debug</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|x64">
+      <Configuration>Release</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectName>TLibEncoder</ProjectName>
+    <ProjectGuid>{47E90995-1FC5-4EE4-A94D-AD474169F0E1}</ProjectGuid>
+    <RootNamespace>TLibEncoder</RootNamespace>
+    <Keyword>Win32Proj</Keyword>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup>
+    <_ProjectFileVersion>10.0.40219.1</_ProjectFileVersion>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\NALwrite.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\SEIwrite.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\SyntaxElementWriter.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncAdaptiveLoopFilter.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncAnalyze.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncBinCoderCABAC.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncBinCoderCABACCounter.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncCavlc.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncCu.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncEntropy.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncGOP.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncPic.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncPreanalyzer.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncRateCtrl.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSampleAdaptiveOffset.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSbac.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSearch.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSlice.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncTop.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\WeightPredAnalysis.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\AnnexBwrite.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\NALwrite.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\SEIwrite.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\SyntaxElementWriter.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncAdaptiveLoopFilter.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncAnalyze.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncBinCoder.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncBinCoderCABAC.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncBinCoderCABACCounter.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncCavlc.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncCfg.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncCu.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncEntropy.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncGOP.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncPic.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncPreanalyzer.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncRateCtrl.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSampleAdaptiveOffset.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSbac.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSearch.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSlice.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncTop.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\WeightPredAnalysis.h" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: /trunk/build/vc10/TLibEncoder_vc10.vcxproj.filters
===================================================================
--- /trunk/build/vc10/TLibEncoder_vc10.vcxproj.filters	(revision 2)
+++ /trunk/build/vc10/TLibEncoder_vc10.vcxproj.filters	(revision 2)
@@ -0,0 +1,146 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{65968186-a1e6-40bc-bda8-f69881ce59b4}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{cb19f901-43b3-4f82-9502-f2c1d70ac336}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\NALwrite.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\SEIwrite.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\SyntaxElementWriter.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncAdaptiveLoopFilter.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncAnalyze.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncBinCoderCABAC.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncBinCoderCABACCounter.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncCavlc.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncCu.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncEntropy.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncGOP.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncPic.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncPreanalyzer.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncRateCtrl.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSampleAdaptiveOffset.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSbac.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSearch.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSlice.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncTop.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\WeightPredAnalysis.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\AnnexBwrite.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\NALwrite.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\SEIwrite.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\SyntaxElementWriter.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncAdaptiveLoopFilter.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncAnalyze.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncBinCoder.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncBinCoderCABAC.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncBinCoderCABACCounter.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncCavlc.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncCfg.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncCu.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncEntropy.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncGOP.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncPic.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncPreanalyzer.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncRateCtrl.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSampleAdaptiveOffset.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSbac.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSearch.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSlice.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncTop.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\WeightPredAnalysis.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: /trunk/build/vc10/TLibEncoder_vc10.vcxproj.user
===================================================================
--- /trunk/build/vc10/TLibEncoder_vc10.vcxproj.user	(revision 2)
+++ /trunk/build/vc10/TLibEncoder_vc10.vcxproj.user	(revision 2)
@@ -0,0 +1,3 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+</Project>
Index: /trunk/build/vc10/TLibVideoIO_vc10.vcproj
===================================================================
--- /trunk/build/vc10/TLibVideoIO_vc10.vcproj	(revision 2)
+++ /trunk/build/vc10/TLibVideoIO_vc10.vcproj	(revision 2)
@@ -0,0 +1,301 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9,00"
+	Name="TLibVideoIO"
+	ProjectGUID="{5280C25A-D316-4BE7-AE50-29D72108624F}"
+	RootNamespace="TLibVideoIo"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibVideoIO\TVideoIOYuv.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibVideoIO\TVideoIOYuv.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /trunk/build/vc10/TLibVideoIO_vc10.vcxproj
===================================================================
--- /trunk/build/vc10/TLibVideoIO_vc10.vcxproj	(revision 2)
+++ /trunk/build/vc10/TLibVideoIO_vc10.vcxproj	(revision 2)
@@ -0,0 +1,142 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug|x64">
+      <Configuration>Debug</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|x64">
+      <Configuration>Release</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectName>TLibVideoIO</ProjectName>
+    <ProjectGuid>{5280C25A-D316-4BE7-AE50-29D72108624F}</ProjectGuid>
+    <RootNamespace>TLibVideoIo</RootNamespace>
+    <Keyword>Win32Proj</Keyword>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup>
+    <_ProjectFileVersion>10.0.40219.1</_ProjectFileVersion>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibVideoIO\TVideoIOYuv.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibVideoIO\TVideoIOYuv.h" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: /trunk/build/vc10/TLibVideoIO_vc10.vcxproj.filters
===================================================================
--- /trunk/build/vc10/TLibVideoIO_vc10.vcxproj.filters	(revision 2)
+++ /trunk/build/vc10/TLibVideoIO_vc10.vcxproj.filters	(revision 2)
@@ -0,0 +1,23 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{911df9cd-3c73-4c8c-b5f0-0e479fc64370}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{77db35f6-2e38-4135-84fc-4ceda8d818f7}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibVideoIO\TVideoIOYuv.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibVideoIO\TVideoIOYuv.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: /trunk/build/vc10/TLibVideoIO_vc10.vcxproj.user
===================================================================
--- /trunk/build/vc10/TLibVideoIO_vc10.vcxproj.user	(revision 2)
+++ /trunk/build/vc10/TLibVideoIO_vc10.vcxproj.user	(revision 2)
@@ -0,0 +1,3 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+</Project>
Index: /trunk/build/vc8/TAppCommon_vc8.vcproj
===================================================================
--- /trunk/build/vc8/TAppCommon_vc8.vcproj	(revision 2)
+++ /trunk/build/vc8/TAppCommon_vc8.vcproj	(revision 2)
@@ -0,0 +1,298 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="TAppCommon"
+	ProjectGUID="{8783AD3A-A5CA-42B7-AAC4-A07EB845A684}"
+	RootNamespace="TAppCommon"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TAppCommon\program_options_lite.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TAppCommon\program_options_lite.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /trunk/build/vc8/TAppDecoder_vc8.vcproj
===================================================================
--- /trunk/build/vc8/TAppDecoder_vc8.vcproj	(revision 2)
+++ /trunk/build/vc8/TAppDecoder_vc8.vcproj	(revision 2)
@@ -0,0 +1,367 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="TAppDecoder"
+	ProjectGUID="{A7A515D9-E917-4706-BD5B-57DC6C78D612}"
+	RootNamespace="TAppDecoder"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppDecoder\decmain.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppDecoder\TAppDecCfg.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppDecoder\TAppDecTop.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppDecoder\TAppDecCfg.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppDecoder\TAppDecTop.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /trunk/build/vc8/TAppEncoder_vc8.vcproj
===================================================================
--- /trunk/build/vc8/TAppEncoder_vc8.vcproj	(revision 2)
+++ /trunk/build/vc8/TAppEncoder_vc8.vcproj	(revision 2)
@@ -0,0 +1,375 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="TAppEncoder"
+	ProjectGUID="{D759E4E1-D33A-4483-B57B-0FD248E022FE}"
+	RootNamespace="TAppEncoder"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\encmain.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\TAppEncCfg.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\TAppEncLayerCfg.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\TAppEncTop.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\TAppEncCfg.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\TAppEncLayerCfg.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\TAppEncTop.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /trunk/build/vc8/TLibCommon_vc8.vcproj
===================================================================
--- /trunk/build/vc8/TLibCommon_vc8.vcproj	(revision 2)
+++ /trunk/build/vc8/TLibCommon_vc8.vcproj	(revision 2)
@@ -0,0 +1,528 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="TLibCommon"
+	ProjectGUID="{78018D78-F890-47E3-A0B7-09D273F0B11D}"
+	RootNamespace="TLibCommon"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\ContextModel.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\ContextModel3DBuffer.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\libmd5\libmd5.c"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComAdaptiveLoopFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComBitStream.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComCABACTables.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComDataCU.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComInterpolationFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComLoopFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComMotionInfo.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPattern.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPic.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPicSym.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPicYuv.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPicYuvMD5.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPrediction.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRdCost.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRdCostWeightPrediction.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRom.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComSampleAdaptiveOffset.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComSlice.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComTrQuant.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComUpsampleFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComWeightPrediction.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComYuv.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\AccessUnit.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\CommonDef.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\ContextModel.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\ContextModel3DBuffer.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\ContextTables.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\libmd5\libmd5.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\libmd5\MD5.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\NAL.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\SEI.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComAdaptiveLoopFilter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComBitCounter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComBitStream.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComCABACTables.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComDataCU.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComInterpolationFilter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComList.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComLoopFilter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComMotionInfo.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComMv.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPattern.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPic.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPicSym.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPicYuv.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPrediction.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRdCost.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRdCostWeightPrediction.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRom.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComSampleAdaptiveOffset.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComSlice.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComTrQuant.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComUpsampleFilter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComWeightPrediction.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComYuv.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TypeDef.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /trunk/build/vc8/TLibDecoder_vc8.vcproj
===================================================================
--- /trunk/build/vc8/TLibDecoder_vc8.vcproj	(revision 2)
+++ /trunk/build/vc8/TLibDecoder_vc8.vcproj	(revision 2)
@@ -0,0 +1,390 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="TLibDecoder"
+	ProjectGUID="{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}"
+	RootNamespace="TLibDecoder"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\AnnexBread.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\NALread.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\SEIread.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\SyntaxElementParser.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecCAVLC.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecCu.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecEntropy.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecGop.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecSbac.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecSlice.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecTop.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\AnnexBread.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\NALread.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\SEIread.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\SyntaxElementParser.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecBinCoder.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecCAVLC.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecCu.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecEntropy.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecGop.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecSbac.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecSlice.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecTop.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /trunk/build/vc8/TLibEncoder_vc8.vcproj
===================================================================
--- /trunk/build/vc8/TLibEncoder_vc8.vcproj	(revision 2)
+++ /trunk/build/vc8/TLibEncoder_vc8.vcproj	(revision 2)
@@ -0,0 +1,462 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="TLibEncoder"
+	ProjectGUID="{47E90995-1FC5-4EE4-A94D-AD474169F0E1}"
+	RootNamespace="TLibEncoder"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\NALwrite.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\SEIwrite.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\SyntaxElementWriter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncAdaptiveLoopFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncAnalyze.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncBinCoderCABAC.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncBinCoderCABACCounter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncCavlc.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncCu.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncEntropy.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncGOP.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncPic.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncPreanalyzer.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncRateCtrl.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSampleAdaptiveOffset.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSbac.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSearch.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSlice.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncTop.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\WeightPredAnalysis.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\AnnexBwrite.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\NALwrite.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\SEIwrite.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\SyntaxElementWriter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncAdaptiveLoopFilter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncAnalyze.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncBinCoder.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncBinCoderCABAC.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncBinCoderCABACCounter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncCavlc.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncCfg.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncCu.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncEntropy.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncGOP.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncPic.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncPreanalyzer.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncRateCtrl.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSampleAdaptiveOffset.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSbac.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSearch.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSlice.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncTop.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\WeightPredAnalysis.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /trunk/build/vc8/TLibVideoIO_vc8.vcproj
===================================================================
--- /trunk/build/vc8/TLibVideoIO_vc8.vcproj	(revision 2)
+++ /trunk/build/vc8/TLibVideoIO_vc8.vcproj	(revision 2)
@@ -0,0 +1,298 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="TLibVideoIO"
+	ProjectGUID="{5280C25A-D316-4BE7-AE50-29D72108624F}"
+	RootNamespace="TLibVideoIo"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibVideoIO\TVideoIOYuv.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibVideoIO\TVideoIOYuv.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /trunk/build/vc9/TAppCommon_vc9.vcproj
===================================================================
--- /trunk/build/vc9/TAppCommon_vc9.vcproj	(revision 2)
+++ /trunk/build/vc9/TAppCommon_vc9.vcproj	(revision 2)
@@ -0,0 +1,301 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9,00"
+	Name="TAppCommon"
+	ProjectGUID="{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}"
+	RootNamespace="TAppCommon"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TAppCommon\program_options_lite.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TAppCommon\program_options_lite.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /trunk/build/vc9/TAppCommon_vc9.vcxproj
===================================================================
--- /trunk/build/vc9/TAppCommon_vc9.vcxproj	(revision 2)
+++ /trunk/build/vc9/TAppCommon_vc9.vcxproj	(revision 2)
@@ -0,0 +1,142 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug|x64">
+      <Configuration>Debug</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|x64">
+      <Configuration>Release</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectName>TAppCommon</ProjectName>
+    <ProjectGuid>{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}</ProjectGuid>
+    <RootNamespace>TAppCommon</RootNamespace>
+    <Keyword>Win32Proj</Keyword>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup>
+    <_ProjectFileVersion>10.0.40219.1</_ProjectFileVersion>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TAppCommon\program_options_lite.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TAppCommon\program_options_lite.h" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: /trunk/build/vc9/TAppCommon_vc9.vcxproj.filters
===================================================================
--- /trunk/build/vc9/TAppCommon_vc9.vcxproj.filters	(revision 2)
+++ /trunk/build/vc9/TAppCommon_vc9.vcxproj.filters	(revision 2)
@@ -0,0 +1,23 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{61c3b510-d4b2-46da-9a25-be492f2fc243}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{94c90dc5-7f7b-4776-ba53-bf464ac89d29}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TAppCommon\program_options_lite.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TAppCommon\program_options_lite.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: /trunk/build/vc9/TAppCommon_vc9.vcxproj.user
===================================================================
--- /trunk/build/vc9/TAppCommon_vc9.vcxproj.user	(revision 2)
+++ /trunk/build/vc9/TAppCommon_vc9.vcxproj.user	(revision 2)
@@ -0,0 +1,3 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+</Project>
Index: /trunk/build/vc9/TAppDecoder_vc9.vcproj
===================================================================
--- /trunk/build/vc9/TAppDecoder_vc9.vcproj	(revision 2)
+++ /trunk/build/vc9/TAppDecoder_vc9.vcproj	(revision 2)
@@ -0,0 +1,358 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9.00"
+	Name="TAppDecoder"
+	ProjectGUID="{A7A515D9-E917-4706-BD5B-57DC6C78D612}"
+	RootNamespace="TAppDecoder"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppDecoder\decmain.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppDecoder\TAppDecCfg.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppDecoder\TAppDecTop.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppDecoder\TAppDecCfg.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppDecoder\TAppDecTop.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /trunk/build/vc9/TAppDecoder_vc9.vcxproj
===================================================================
--- /trunk/build/vc9/TAppDecoder_vc9.vcxproj	(revision 2)
+++ /trunk/build/vc9/TAppDecoder_vc9.vcxproj	(revision 2)
@@ -0,0 +1,187 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug|x64">
+      <Configuration>Debug</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|x64">
+      <Configuration>Release</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectName>TAppDecoder</ProjectName>
+    <ProjectGuid>{A7A515D9-E917-4706-BD5B-57DC6C78D612}</ProjectGuid>
+    <RootNamespace>TAppDecoder</RootNamespace>
+    <Keyword>Win32Proj</Keyword>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup>
+    <_ProjectFileVersion>10.0.40219.1</_ProjectFileVersion>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\..\bin\vc9\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\..\bin\vc9\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\..\bin\vc9\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\..\bin\vc9\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</LinkIncremental>
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX86</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX64</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX86</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX64</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\App\TAppDecoder\decmain.cpp" />
+    <ClCompile Include="..\..\source\App\TAppDecoder\TAppDecCfg.cpp" />
+    <ClCompile Include="..\..\source\App\TAppDecoder\TAppDecTop.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\App\TAppDecoder\TAppDecCfg.h" />
+    <ClInclude Include="..\..\source\App\TAppDecoder\TAppDecTop.h" />
+  </ItemGroup>
+  <ItemGroup>
+    <ProjectReference Include="TAppCommon_vc9.vcxproj">
+      <Project>{d1e8a1c2-15db-4c94-80e8-4f70cf0a2dc5}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+    <ProjectReference Include="TLibCommon_vc9.vcxproj">
+      <Project>{78018d78-f890-47e3-a0b7-09d273f0b11d}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+    <ProjectReference Include="TLibDecoder_vc9.vcxproj">
+      <Project>{f8b77a48-af6c-4746-a89f-b706aba6ad94}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+    <ProjectReference Include="TLibVideoIO_vc9.vcxproj">
+      <Project>{5280c25a-d316-4be7-ae50-29d72108624f}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: /trunk/build/vc9/TAppDecoder_vc9.vcxproj.filters
===================================================================
--- /trunk/build/vc9/TAppDecoder_vc9.vcxproj.filters	(revision 2)
+++ /trunk/build/vc9/TAppDecoder_vc9.vcxproj.filters	(revision 2)
@@ -0,0 +1,36 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{f91faffd-ddc1-46ee-bf46-c9f336a04889}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{53724405-0877-4412-a713-0153d444b64f}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+    <Filter Include="Resource Files">
+      <UniqueIdentifier>{f426d7ef-18cf-4428-8729-17e3d457a2d8}</UniqueIdentifier>
+      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\App\TAppDecoder\decmain.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\App\TAppDecoder\TAppDecCfg.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\App\TAppDecoder\TAppDecTop.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\App\TAppDecoder\TAppDecCfg.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\App\TAppDecoder\TAppDecTop.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: /trunk/build/vc9/TAppDecoder_vc9.vcxproj.user
===================================================================
--- /trunk/build/vc9/TAppDecoder_vc9.vcxproj.user	(revision 2)
+++ /trunk/build/vc9/TAppDecoder_vc9.vcxproj.user	(revision 2)
@@ -0,0 +1,8 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <LocalDebuggerCommandArguments>-b str/BasketballPass.bin -ls 2 -o0 rec/BasketballPass_l0_drec.yuv -o1 rec/BasketballPass_l1_drec.yuv</LocalDebuggerCommandArguments>
+    <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
+    <LocalDebuggerWorkingDirectory>$(ProjectDir)/../../../</LocalDebuggerWorkingDirectory>
+  </PropertyGroup>
+</Project>
Index: /trunk/build/vc9/TAppEncoder_vc9.vcproj
===================================================================
--- /trunk/build/vc9/TAppEncoder_vc9.vcproj	(revision 2)
+++ /trunk/build/vc9/TAppEncoder_vc9.vcproj	(revision 2)
@@ -0,0 +1,366 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9.00"
+	Name="TAppEncoder"
+	ProjectGUID="{D759E4E1-D33A-4483-B57B-0FD248E022FE}"
+	RootNamespace="TAppEncoder"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\encmain.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\TAppEncCfg.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\TAppEncLayerCfg.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\TAppEncTop.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\TAppEncCfg.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\TAppEncLayerCfg.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\TAppEncTop.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /trunk/build/vc9/TAppEncoder_vc9.vcxproj
===================================================================
--- /trunk/build/vc9/TAppEncoder_vc9.vcxproj	(revision 2)
+++ /trunk/build/vc9/TAppEncoder_vc9.vcxproj	(revision 2)
@@ -0,0 +1,189 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug|x64">
+      <Configuration>Debug</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|x64">
+      <Configuration>Release</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectName>TAppEncoder</ProjectName>
+    <ProjectGuid>{D759E4E1-D33A-4483-B57B-0FD248E022FE}</ProjectGuid>
+    <RootNamespace>TAppEncoder</RootNamespace>
+    <Keyword>Win32Proj</Keyword>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup>
+    <_ProjectFileVersion>10.0.40219.1</_ProjectFileVersion>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\..\bin\vc9\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\..\bin\vc9\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\..\bin\vc9\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\..\bin\vc9\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</LinkIncremental>
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX86</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX64</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX86</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX64</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\App\TAppEncoder\encmain.cpp" />
+    <ClCompile Include="..\..\source\App\TAppEncoder\TAppEncCfg.cpp" />
+    <ClCompile Include="..\..\source\App\TAppEncoder\TAppEncLayerCfg.cpp" />
+    <ClCompile Include="..\..\source\App\TAppEncoder\TAppEncTop.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\App\TAppEncoder\TAppEncCfg.h" />
+    <ClInclude Include="..\..\source\App\TAppEncoder\TAppEncLayerCfg.h" />
+    <ClInclude Include="..\..\source\App\TAppEncoder\TAppEncTop.h" />
+  </ItemGroup>
+  <ItemGroup>
+    <ProjectReference Include="TAppCommon_vc9.vcxproj">
+      <Project>{d1e8a1c2-15db-4c94-80e8-4f70cf0a2dc5}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+    <ProjectReference Include="TLibCommon_vc9.vcxproj">
+      <Project>{78018d78-f890-47e3-a0b7-09d273f0b11d}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+    <ProjectReference Include="TLibEncoder_vc9.vcxproj">
+      <Project>{47e90995-1fc5-4ee4-a94d-ad474169f0e1}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+    <ProjectReference Include="TLibVideoIO_vc9.vcxproj">
+      <Project>{5280c25a-d316-4be7-ae50-29d72108624f}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: /trunk/build/vc9/TAppEncoder_vc9.vcxproj.filters
===================================================================
--- /trunk/build/vc9/TAppEncoder_vc9.vcxproj.filters	(revision 2)
+++ /trunk/build/vc9/TAppEncoder_vc9.vcxproj.filters	(revision 2)
@@ -0,0 +1,42 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{5a91399d-a287-4a11-b533-6094f5650005}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{829a2cbb-01c0-489f-b342-3eb74b2dcb35}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+    <Filter Include="Resource Files">
+      <UniqueIdentifier>{2a3d6658-bcc6-4553-8ece-38846d0d457c}</UniqueIdentifier>
+      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\App\TAppEncoder\encmain.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\App\TAppEncoder\TAppEncCfg.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\App\TAppEncoder\TAppEncTop.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\App\TAppEncoder\TAppEncLayerCfg.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\App\TAppEncoder\TAppEncCfg.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\App\TAppEncoder\TAppEncTop.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\App\TAppEncoder\TAppEncLayerCfg.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: /trunk/build/vc9/TAppEncoder_vc9.vcxproj.user
===================================================================
--- /trunk/build/vc9/TAppEncoder_vc9.vcxproj.user	(revision 2)
+++ /trunk/build/vc9/TAppEncoder_vc9.vcxproj.user	(revision 2)
@@ -0,0 +1,10 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <LocalDebuggerCommandArguments>-c cfg/svc/BasketballPass_layers10.cfg -c cfg/encoder_main_lb.cfg -q0 22 -q1 22 -g 4 -f 5 -b str/BasketballPass.bin -c option.cfg</LocalDebuggerCommandArguments>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <LocalDebuggerWorkingDirectory>$(ProjectDir)/../../../</LocalDebuggerWorkingDirectory>
+    <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
+  </PropertyGroup>
+</Project>
Index: /trunk/build/vc9/TLibCommon_vc9.vcproj
===================================================================
--- /trunk/build/vc9/TLibCommon_vc9.vcproj	(revision 2)
+++ /trunk/build/vc9/TLibCommon_vc9.vcproj	(revision 2)
@@ -0,0 +1,531 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9.00"
+	Name="TLibCommon"
+	ProjectGUID="{78018D78-F890-47E3-A0B7-09D273F0B11D}"
+	RootNamespace="TLibCommon"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\ContextModel.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\ContextModel3DBuffer.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\libmd5\libmd5.c"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComAdaptiveLoopFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComBitStream.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComCABACTables.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComDataCU.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComInterpolationFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComLoopFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComMotionInfo.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPattern.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPic.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPicSym.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPicYuv.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPicYuvMD5.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPrediction.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRdCost.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRdCostWeightPrediction.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRom.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComSampleAdaptiveOffset.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComSlice.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComTrQuant.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComUpsampleFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComWeightPrediction.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComYuv.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\AccessUnit.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\CommonDef.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\ContextModel.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\ContextModel3DBuffer.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\ContextTables.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\libmd5\libmd5.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\libmd5\MD5.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\NAL.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\SEI.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComAdaptiveLoopFilter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComBitCounter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComBitStream.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComCABACTables.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComDataCU.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComInterpolationFilter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComList.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComLoopFilter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComMotionInfo.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComMv.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPattern.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPic.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPicSym.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPicYuv.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPrediction.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRdCost.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRdCostWeightPrediction.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRom.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComSampleAdaptiveOffset.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComSlice.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComTrQuant.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComUpsampleFilter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComWeightPrediction.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComYuv.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TypeDef.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /trunk/build/vc9/TLibCommon_vc9.vcxproj
===================================================================
--- /trunk/build/vc9/TLibCommon_vc9.vcxproj	(revision 2)
+++ /trunk/build/vc9/TLibCommon_vc9.vcxproj	(revision 2)
@@ -0,0 +1,199 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug|x64">
+      <Configuration>Debug</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|x64">
+      <Configuration>Release</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectName>TLibCommon</ProjectName>
+    <ProjectGuid>{78018D78-F890-47E3-A0B7-09D273F0B11D}</ProjectGuid>
+    <RootNamespace>TLibCommon</RootNamespace>
+    <Keyword>Win32Proj</Keyword>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup>
+    <_ProjectFileVersion>10.0.40219.1</_ProjectFileVersion>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\ContextModel.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\ContextModel3DBuffer.cpp" />
+    <ClCompile Include="..\..\source\Lib\libmd5\libmd5.c" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComAdaptiveLoopFilter.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComBitStream.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComCABACTables.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComDataCU.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComInterpolationFilter.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComLoopFilter.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComMotionInfo.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPattern.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPic.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPicSym.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPicYuv.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPicYuvMD5.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPrediction.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComRdCost.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComRdCostWeightPrediction.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComRom.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComSampleAdaptiveOffset.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComSlice.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComTrQuant.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComUpsampleFilter.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComWeightPrediction.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComYuv.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\AccessUnit.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\CommonDef.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\ContextModel.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\ContextModel3DBuffer.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\ContextTables.h" />
+    <ClInclude Include="..\..\source\Lib\libmd5\libmd5.h" />
+    <ClInclude Include="..\..\source\Lib\libmd5\MD5.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\NAL.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\SEI.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComAdaptiveLoopFilter.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComBitCounter.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComBitStream.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComCABACTables.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComDataCU.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComInterpolationFilter.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComList.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComLoopFilter.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComMotionInfo.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComMv.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPattern.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPic.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPicSym.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPicYuv.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPrediction.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComRdCost.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComRdCostWeightPrediction.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComRom.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComSampleAdaptiveOffset.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComSlice.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComTrQuant.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComUpsampleFilter.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComWeightPrediction.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComYuv.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TypeDef.h" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: /trunk/build/vc9/TLibCommon_vc9.vcxproj.filters
===================================================================
--- /trunk/build/vc9/TLibCommon_vc9.vcxproj.filters	(revision 2)
+++ /trunk/build/vc9/TLibCommon_vc9.vcxproj.filters	(revision 2)
@@ -0,0 +1,194 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\ContextModel.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\ContextModel3DBuffer.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\libmd5\libmd5.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComAdaptiveLoopFilter.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComBitStream.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComCABACTables.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComDataCU.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComInterpolationFilter.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComLoopFilter.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComMotionInfo.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPattern.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPic.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPicSym.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPicYuv.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPicYuvMD5.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPrediction.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComRdCost.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComRdCostWeightPrediction.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComRom.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComSampleAdaptiveOffset.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComSlice.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComTrQuant.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComWeightPrediction.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComYuv.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComUpsampleFilter.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\AccessUnit.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\CommonDef.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\ContextModel.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\ContextModel3DBuffer.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\ContextTables.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\libmd5\libmd5.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\libmd5\MD5.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\NAL.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\SEI.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComAdaptiveLoopFilter.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComBitCounter.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComBitStream.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComCABACTables.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComDataCU.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComInterpolationFilter.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComList.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComLoopFilter.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComMotionInfo.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComMv.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPattern.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPic.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPicSym.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPicYuv.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPrediction.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComRdCost.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComRdCostWeightPrediction.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComRom.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComSampleAdaptiveOffset.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComSlice.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComTrQuant.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComWeightPrediction.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComYuv.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TypeDef.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComUpsampleFilter.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: /trunk/build/vc9/TLibCommon_vc9.vcxproj.user
===================================================================
--- /trunk/build/vc9/TLibCommon_vc9.vcxproj.user	(revision 2)
+++ /trunk/build/vc9/TLibCommon_vc9.vcxproj.user	(revision 2)
@@ -0,0 +1,3 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+</Project>
Index: /trunk/build/vc9/TLibDecoder_vc9.vcproj
===================================================================
--- /trunk/build/vc9/TLibDecoder_vc9.vcproj	(revision 2)
+++ /trunk/build/vc9/TLibDecoder_vc9.vcproj	(revision 2)
@@ -0,0 +1,393 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9.00"
+	Name="TLibDecoder"
+	ProjectGUID="{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}"
+	RootNamespace="TLibDecoder"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\AnnexBread.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\NALread.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\SEIread.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\SyntaxElementParser.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecCAVLC.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecCu.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecEntropy.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecGop.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecSbac.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecSlice.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecTop.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\AnnexBread.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\NALread.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\SEIread.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\SyntaxElementParser.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecBinCoder.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecCAVLC.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecCu.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecEntropy.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecGop.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecSbac.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecSlice.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecTop.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /trunk/build/vc9/TLibDecoder_vc9.vcxproj
===================================================================
--- /trunk/build/vc9/TLibDecoder_vc9.vcxproj	(revision 2)
+++ /trunk/build/vc9/TLibDecoder_vc9.vcxproj	(revision 2)
@@ -0,0 +1,165 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug|x64">
+      <Configuration>Debug</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|x64">
+      <Configuration>Release</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectName>TLibDecoder</ProjectName>
+    <ProjectGuid>{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}</ProjectGuid>
+    <RootNamespace>TLibDecoder</RootNamespace>
+    <Keyword>Win32Proj</Keyword>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup>
+    <_ProjectFileVersion>10.0.40219.1</_ProjectFileVersion>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\AnnexBread.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\NALread.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\SEIread.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\SyntaxElementParser.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecCAVLC.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecCu.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecEntropy.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecGop.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecSbac.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecSlice.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecTop.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\AnnexBread.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\NALread.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\SEIread.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\SyntaxElementParser.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecBinCoder.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecCAVLC.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecCu.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecEntropy.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecGop.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecSbac.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecSlice.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecTop.h" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: /trunk/build/vc9/TLibDecoder_vc9.vcxproj.filters
===================================================================
--- /trunk/build/vc9/TLibDecoder_vc9.vcxproj.filters	(revision 2)
+++ /trunk/build/vc9/TLibDecoder_vc9.vcxproj.filters	(revision 2)
@@ -0,0 +1,92 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{57c32785-e8b2-4ab2-82f6-091ce0690afe}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{8351b640-31d1-405d-a45f-7e5469df1a8c}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\AnnexBread.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\NALread.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\SEIread.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\SyntaxElementParser.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecCAVLC.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecCu.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecEntropy.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecGop.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecSbac.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecSlice.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecTop.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\AnnexBread.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\NALread.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\SEIread.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\SyntaxElementParser.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecBinCoder.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecCAVLC.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecCu.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecEntropy.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecGop.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecSbac.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecSlice.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecTop.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: /trunk/build/vc9/TLibDecoder_vc9.vcxproj.user
===================================================================
--- /trunk/build/vc9/TLibDecoder_vc9.vcxproj.user	(revision 2)
+++ /trunk/build/vc9/TLibDecoder_vc9.vcxproj.user	(revision 2)
@@ -0,0 +1,3 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+</Project>
Index: /trunk/build/vc9/TLibEncoder_vc9.vcproj
===================================================================
--- /trunk/build/vc9/TLibEncoder_vc9.vcproj	(revision 2)
+++ /trunk/build/vc9/TLibEncoder_vc9.vcproj	(revision 2)
@@ -0,0 +1,465 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9.00"
+	Name="TLibEncoder"
+	ProjectGUID="{47E90995-1FC5-4EE4-A94D-AD474169F0E1}"
+	RootNamespace="TLibEncoder"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\NALwrite.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\SEIwrite.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\SyntaxElementWriter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncAdaptiveLoopFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncAnalyze.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncBinCoderCABAC.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncBinCoderCABACCounter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncCavlc.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncCu.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncEntropy.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncGOP.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncPic.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncPreanalyzer.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncRateCtrl.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSampleAdaptiveOffset.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSbac.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSearch.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSlice.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncTop.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\WeightPredAnalysis.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\AnnexBwrite.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\NALwrite.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\SEIwrite.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\SyntaxElementWriter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncAdaptiveLoopFilter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncAnalyze.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncBinCoder.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncBinCoderCABAC.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncBinCoderCABACCounter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncCavlc.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncCfg.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncCu.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncEntropy.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncGOP.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncPic.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncPreanalyzer.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncRateCtrl.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSampleAdaptiveOffset.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSbac.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSearch.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSlice.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncTop.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\WeightPredAnalysis.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /trunk/build/vc9/TLibEncoder_vc9.vcxproj
===================================================================
--- /trunk/build/vc9/TLibEncoder_vc9.vcxproj	(revision 2)
+++ /trunk/build/vc9/TLibEncoder_vc9.vcxproj	(revision 2)
@@ -0,0 +1,183 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug|x64">
+      <Configuration>Debug</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|x64">
+      <Configuration>Release</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectName>TLibEncoder</ProjectName>
+    <ProjectGuid>{47E90995-1FC5-4EE4-A94D-AD474169F0E1}</ProjectGuid>
+    <RootNamespace>TLibEncoder</RootNamespace>
+    <Keyword>Win32Proj</Keyword>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup>
+    <_ProjectFileVersion>10.0.40219.1</_ProjectFileVersion>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\NALwrite.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\SEIwrite.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\SyntaxElementWriter.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncAdaptiveLoopFilter.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncAnalyze.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncBinCoderCABAC.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncBinCoderCABACCounter.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncCavlc.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncCu.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncEntropy.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncGOP.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncPic.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncPreanalyzer.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncRateCtrl.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSampleAdaptiveOffset.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSbac.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSearch.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSlice.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncTop.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\WeightPredAnalysis.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\AnnexBwrite.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\NALwrite.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\SEIwrite.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\SyntaxElementWriter.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncAdaptiveLoopFilter.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncAnalyze.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncBinCoder.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncBinCoderCABAC.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncBinCoderCABACCounter.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncCavlc.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncCfg.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncCu.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncEntropy.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncGOP.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncPic.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncPreanalyzer.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncRateCtrl.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSampleAdaptiveOffset.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSbac.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSearch.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSlice.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncTop.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\WeightPredAnalysis.h" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: /trunk/build/vc9/TLibEncoder_vc9.vcxproj.filters
===================================================================
--- /trunk/build/vc9/TLibEncoder_vc9.vcxproj.filters	(revision 2)
+++ /trunk/build/vc9/TLibEncoder_vc9.vcxproj.filters	(revision 2)
@@ -0,0 +1,146 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{65968186-a1e6-40bc-bda8-f69881ce59b4}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{cb19f901-43b3-4f82-9502-f2c1d70ac336}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\NALwrite.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\SEIwrite.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\SyntaxElementWriter.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncAdaptiveLoopFilter.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncAnalyze.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncBinCoderCABAC.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncBinCoderCABACCounter.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncCavlc.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncCu.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncEntropy.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncGOP.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncPic.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncPreanalyzer.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncRateCtrl.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSampleAdaptiveOffset.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSbac.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSearch.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSlice.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncTop.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\WeightPredAnalysis.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\AnnexBwrite.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\NALwrite.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\SEIwrite.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\SyntaxElementWriter.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncAdaptiveLoopFilter.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncAnalyze.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncBinCoder.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncBinCoderCABAC.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncBinCoderCABACCounter.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncCavlc.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncCfg.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncCu.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncEntropy.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncGOP.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncPic.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncPreanalyzer.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncRateCtrl.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSampleAdaptiveOffset.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSbac.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSearch.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSlice.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncTop.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\WeightPredAnalysis.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: /trunk/build/vc9/TLibEncoder_vc9.vcxproj.user
===================================================================
--- /trunk/build/vc9/TLibEncoder_vc9.vcxproj.user	(revision 2)
+++ /trunk/build/vc9/TLibEncoder_vc9.vcxproj.user	(revision 2)
@@ -0,0 +1,3 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+</Project>
Index: /trunk/build/vc9/TLibVideoIO_vc9.vcproj
===================================================================
--- /trunk/build/vc9/TLibVideoIO_vc9.vcproj	(revision 2)
+++ /trunk/build/vc9/TLibVideoIO_vc9.vcproj	(revision 2)
@@ -0,0 +1,301 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9,00"
+	Name="TLibVideoIO"
+	ProjectGUID="{5280C25A-D316-4BE7-AE50-29D72108624F}"
+	RootNamespace="TLibVideoIo"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibVideoIO\TVideoIOYuv.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibVideoIO\TVideoIOYuv.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /trunk/build/vc9/TLibVideoIO_vc9.vcxproj
===================================================================
--- /trunk/build/vc9/TLibVideoIO_vc9.vcxproj	(revision 2)
+++ /trunk/build/vc9/TLibVideoIO_vc9.vcxproj	(revision 2)
@@ -0,0 +1,142 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug|x64">
+      <Configuration>Debug</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|x64">
+      <Configuration>Release</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectName>TLibVideoIO</ProjectName>
+    <ProjectGuid>{5280C25A-D316-4BE7-AE50-29D72108624F}</ProjectGuid>
+    <RootNamespace>TLibVideoIo</RootNamespace>
+    <Keyword>Win32Proj</Keyword>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup>
+    <_ProjectFileVersion>10.0.40219.1</_ProjectFileVersion>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibVideoIO\TVideoIOYuv.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibVideoIO\TVideoIOYuv.h" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: /trunk/build/vc9/TLibVideoIO_vc9.vcxproj.filters
===================================================================
--- /trunk/build/vc9/TLibVideoIO_vc9.vcxproj.filters	(revision 2)
+++ /trunk/build/vc9/TLibVideoIO_vc9.vcxproj.filters	(revision 2)
@@ -0,0 +1,23 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{911df9cd-3c73-4c8c-b5f0-0e479fc64370}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{77db35f6-2e38-4135-84fc-4ceda8d818f7}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibVideoIO\TVideoIOYuv.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibVideoIO\TVideoIOYuv.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: /trunk/build/vc9/TLibVideoIO_vc9.vcxproj.user
===================================================================
--- /trunk/build/vc9/TLibVideoIO_vc9.vcxproj.user	(revision 2)
+++ /trunk/build/vc9/TLibVideoIO_vc9.vcxproj.user	(revision 2)
@@ -0,0 +1,3 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+</Project>
Index: /trunk/cfg/encoder_intra_he10.cfg
===================================================================
--- /trunk/cfg/encoder_intra_he10.cfg	(revision 2)
+++ /trunk/cfg/encoder_intra_he10.cfg	(revision 2)
@@ -0,0 +1,100 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+#ReconFile                     : rec.yuv
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+#IntraPeriod                   : 1           # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CDR, 2:IDR
+GOPSize                       : 1           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor temporal_id #ref_pics_active #ref_pics reference pictures 
+Frame1:  B    1   0        1        0           4                0         
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:EPZS
+SearchRange                   : 64          # (0: Search range is a Full frame)
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== Quantization =============
+#QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 0           # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInPPS         : 0           # Dbl params in PPS or SliceHeader (0=SliceHeader, 1=PPS)
+LoopFilterDisable             : 0           # Disable deblocking filter in slice header (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # Range: -13 ~ 13
+LoopFilterTcOffset_div2       : 0           # Range: -13 ~ 13
+
+#=========== Misc. ============
+InternalBitDepth              : 10          # internal bit-depth = BitDepth + BitIncrement
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+UniformSpacingIdc                   : 0                # 0: the column boundaries are indicated by ColumnWidth array, the row boundaries are indicated by RowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of columns in a picture minus 1
+ColumnWidthArray                    : 2 3              # Array containing ColumnWidth values in units of LCU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of rows in a picture minus 1
+RowHeightArray                      : 2                # Array containing RowHeight values in units of LCU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag           : 1                  # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across 
+
+#============ WaveFront ================
+WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+LosslessCuEnabled                   : 0                # 1: Set "qpprime_y_zero_transquant_bypass_flag=1" and enable the lossless mode as well as the RD-based mode selection process.
+TransquantBypassEnableFlag: 0  # Value of PPS flag.
+CUTransquantBypassFlagValue: 0 # Constant lossless-value signaling per CU, if TransquantBypassEnableFlag is 1.
+
+                                                        
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /trunk/cfg/encoder_intra_main.cfg
===================================================================
--- /trunk/cfg/encoder_intra_main.cfg	(revision 2)
+++ /trunk/cfg/encoder_intra_main.cfg	(revision 2)
@@ -0,0 +1,101 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+#ReconFile                     : rec.yuv
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+#IntraPeriod                   : 1           # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CDR, 2:IDR
+GOPSize                       : 1           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor temporal_id #ref_pics_active #ref_pics reference pictures 
+Frame1:  B    1   0        1        0           4                0             
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:EPZS
+SearchRange                   : 64          # (0: Search range is a Full frame)
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== Quantization =============
+#QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 0           # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInPPS         : 0           # Dbl params in PPS or SliceHeader (0=SliceHeader, 1=PPS)
+LoopFilterDisable             : 0           # Disable deblocking filter in slice header (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # Range: -13 ~ 13
+LoopFilterTcOffset_div2       : 0           # Range: -13 ~ 13
+
+#=========== Misc. ============
+InternalBitDepth              : 8           # internal bit-depth = BitDepth + BitIncrement
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+UniformSpacingIdc                   : 0                # 0: the column boundaries are indicated by ColumnWidth array, the row boundaries are indicated by RowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of columns in a picture minus 1
+ColumnWidthArray                    : 2 3              # Array containing ColumnWidth values in units of LCU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of rows in a picture minus 1
+RowHeightArray                      : 2                # Array containing RowHeight values in units of LCU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag           : 1                  # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across 
+
+#============ WaveFront ================
+WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+LosslessCuEnabled                   : 0                # 1: Set "qpprime_y_zero_transquant_bypass_flag=1" and enable the lossless mode as well as the RD-based mode selection process.
+TransquantBypassEnableFlag: 0  # Value of PPS flag.
+CUTransquantBypassFlagValue: 0 # Constant lossless-value signaling per CU, if TransquantBypassEnableFlag is 1.
+                                                       
+SEIpictureDigest										: 1
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /trunk/cfg/encoder_lowdelay_P_he10.cfg
===================================================================
--- /trunk/cfg/encoder_lowdelay_P_he10.cfg	(revision 2)
+++ /trunk/cfg/encoder_lowdelay_P_he10.cfg	(revision 2)
@@ -0,0 +1,109 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+#ReconFile                     : rec.yuv
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+#IntraPeriod                   : -1          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CDR, 2:IDR
+GOPSize                       : 4           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor temporal_id #ref_pics_active #ref_pics reference pictures predict deltaRPS #ref_idcs reference idcs 
+Frame1:  P    1   3        0.4624   0           4                4         -1 -5 -9 -13       0
+Frame2:  P    2   2        0.4624   0           4                4         -1 -2 -6 -10       1      -1       5         1 1 1 0 1
+Frame3:  P    3   3        0.4624   0           4                4         -1 -3 -7 -11       1      -1       5         0 1 1 1 1            
+Frame4:  P    4   1        0.578    0           4                4         -1 -4 -8 -12       1      -1       5         0 1 1 1 1
+ListCombination               : 1           # Use combined list for uni-prediction in B-slices
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:EPZS
+SearchRange                   : 64          # (0: Search range is a Full frame)
+BipredSearchRange             : 4           # Search range for bi-prediction refinement
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== Quantization =============
+#QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 0           # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInPPS         : 0           # Dbl params in PPS or SliceHeader (0=SliceHeader, 1=PPS)
+LoopFilterDisable             : 0           # Disable deblocking filter in slice header (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # Range: -13 ~ 13
+LoopFilterTcOffset_div2       : 0           # Range: -13 ~ 13
+
+#=========== Misc. ============
+InternalBitDepth              : 10          # internal bit-depth = BitDepth + BitIncrement
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+UniformSpacingIdc                   : 0                # 0: the column boundaries are indicated by ColumnWidth array, the row boundaries are indicated by RowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of columns in a picture minus 1
+ColumnWidthArray                    : 2 3              # Array containing ColumnWidth values in units of LCU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of rows in a picture minus 1
+RowHeightArray                      : 2                # Array containing RowHeight values in units of LCU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag           : 1                  # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across                                                       
+
+#============ WaveFront ================
+WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+LosslessCuEnabled                   : 0                # 1: Set "qpprime_y_zero_transquant_bypass_flag=1" and enable the lossless mode as well as the RD-based mode selection process.
+TransquantBypassEnableFlag: 0  # Value of PPS flag.
+CUTransquantBypassFlagValue: 0 # Constant lossless-value signaling per CU, if TransquantBypassEnableFlag is 1.
+
+#============ Rate Control ======================
+RateCtrl                            : 0                # 0: Disable rate control 1: Enable rate control
+TargetBitrate                       : 1000             # input target bitrate when RateCtrl is enable
+NumLCUInUnit                        : 1                # Number of LCU in an Unit. Fraction is not allowed
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /trunk/cfg/encoder_lowdelay_P_main.cfg
===================================================================
--- /trunk/cfg/encoder_lowdelay_P_main.cfg	(revision 2)
+++ /trunk/cfg/encoder_lowdelay_P_main.cfg	(revision 2)
@@ -0,0 +1,111 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+#ReconFile                     : rec.yuv
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+#IntraPeriod                   : -1          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CDR, 2:IDR
+GOPSize                       : 4           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor temporal_id #ref_pics_active #ref_pics reference pictures predict deltaRPS #ref_idcs reference idcs 
+Frame1:  P    1   3        0.4624   0           4                4         -1 -5 -9 -13       0
+Frame2:  P    2   2        0.4624   0           4                4         -1 -2 -6 -10       1      -1       5         1 1 1 0 1
+Frame3:  P    3   3        0.4624   0           4                4         -1 -3 -7 -11       1      -1       5         0 1 1 1 1            
+Frame4:  P    4   1        0.578    0           4                4         -1 -4 -8 -12       1      -1       5         0 1 1 1 1
+ListCombination               : 1           # Use combined list for uni-prediction in B-slices
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:EPZS
+SearchRange                   : 64          # (0: Search range is a Full frame)
+BipredSearchRange             : 4           # Search range for bi-prediction refinement
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== Quantization =============
+#QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 0           # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInPPS         : 0           # Dbl params in PPS or SliceHeader (0=SliceHeader, 1=PPS)
+LoopFilterDisable             : 0           # Disable deblocking filter in slice header (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # Range: -13 ~ 13
+LoopFilterTcOffset_div2       : 0           # Range: -13 ~ 13
+
+#=========== Misc. ============
+InternalBitDepth              : 8           # internal bit-depth = BitDepth + BitIncrement
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+UniformSpacingIdc                   : 0                # 0: the column boundaries are indicated by ColumnWidth array, the row boundaries are indicated by RowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of columns in a picture minus 1
+ColumnWidthArray                    : 2 3              # Array containing ColumnWidth values in units of LCU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of rows in a picture minus 1
+RowHeightArray                      : 2                # Array containing RowHeight values in units of LCU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag           : 1                  # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across                                                       
+
+#============ WaveFront ================
+WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+LosslessCuEnabled                   : 0                # 1: Set "qpprime_y_zero_transquant_bypass_flag=1" and enable the lossless mode as well as the RD-based mode selection process.
+TransquantBypassEnableFlag: 0  # Value of PPS flag.
+CUTransquantBypassFlagValue: 0 # Constant lossless-value signaling per CU, if TransquantBypassEnableFlag is 1.
+
+#============ Rate Control ======================
+RateCtrl                            : 0                # 0: Disable rate control 1: Enable rate control
+TargetBitrate                       : 1000             # input target bitrate when RateCtrl is enable
+NumLCUInUnit                        : 1                # Number of LCU in an Unit. Fraction is not allowed
+
+SEIpictureDigest										: 1
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /trunk/cfg/encoder_lowdelay_he10.cfg
===================================================================
--- /trunk/cfg/encoder_lowdelay_he10.cfg	(revision 2)
+++ /trunk/cfg/encoder_lowdelay_he10.cfg	(revision 2)
@@ -0,0 +1,109 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+#ReconFile                     : rec.yuv
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+#IntraPeriod                   : -1          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CDR, 2:IDR
+GOPSize                       : 4           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor temporal_id #ref_pics_active #ref_pics reference pictures predict deltaRPS #ref_idcs reference idcs 
+Frame1:  B    1   3        0.4624   0           4                4         -1 -5 -9 -13       0
+Frame2:  B    2   2        0.4624   0           4                4         -1 -2 -6 -10       1      -1       5         1 1 1 0 1
+Frame3:  B    3   3        0.4624   0           4                4         -1 -3 -7 -11       1      -1       5         0 1 1 1 1            
+Frame4:  B    4   1        0.578    0           4                4         -1 -4 -8 -12       1      -1       5         0 1 1 1 1
+ListCombination               : 1           # Use combined list for uni-prediction in B-slices
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:EPZS
+SearchRange                   : 64          # (0: Search range is a Full frame)
+BipredSearchRange             : 4           # Search range for bi-prediction refinement
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== Quantization =============
+#QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 0           # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInPPS         : 0           # Dbl params in PPS or SliceHeader (0=SliceHeader, 1=PPS)
+LoopFilterDisable             : 0           # Disable deblocking filter in slice header (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # Range: -13 ~ 13
+LoopFilterTcOffset_div2       : 0           # Range: -13 ~ 13
+
+#=========== Misc. ============
+InternalBitDepth              : 10          # internal bit-depth = BitDepth + BitIncrement
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+UniformSpacingIdc                   : 0                # 0: the column boundaries are indicated by ColumnWidth array, the row boundaries are indicated by RowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of columns in a picture minus 1
+ColumnWidthArray                    : 2 3              # Array containing ColumnWidth values in units of LCU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of rows in a picture minus 1
+RowHeightArray                      : 2                # Array containing RowHeight values in units of LCU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag           : 1                  # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across 
+
+#============ WaveFront ================
+WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+LosslessCuEnabled                   : 0                # 1: Set "qpprime_y_zero_transquant_bypass_flag=1" and enable the lossless mode as well as the RD-based mode selection process.
+TransquantBypassEnableFlag: 0  # Value of PPS flag.
+CUTransquantBypassFlagValue: 0 # Constant lossless-value signaling per CU, if TransquantBypassEnableFlag is 1.
+
+#============ Rate Control ======================
+RateCtrl                            : 0                # 0: Disable rate control 1: Enable rate control
+TargetBitrate                       : 1000             # input target bitrate when RateCtrl is enable
+NumLCUInUnit                        : 1                # Number of LCU in an Unit. Fraction is not allowed
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /trunk/cfg/encoder_lowdelay_main.cfg
===================================================================
--- /trunk/cfg/encoder_lowdelay_main.cfg	(revision 2)
+++ /trunk/cfg/encoder_lowdelay_main.cfg	(revision 2)
@@ -0,0 +1,109 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+#ReconFile                     : rec.yuv
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+#IntraPeriod                   : -1          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CDR, 2:IDR
+GOPSize                       : 4           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor temporal_id #ref_pics_active #ref_pics reference pictures predict deltaRPS #ref_idcs reference idcs 
+Frame1:  B    1   3        0.4624   0           4                4         -1 -5 -9 -13       0
+Frame2:  B    2   2        0.4624   0           4                4         -1 -2 -6 -10       1      -1       5         1 1 1 0 1
+Frame3:  B    3   3        0.4624   0           4                4         -1 -3 -7 -11       1      -1       5         0 1 1 1 1            
+Frame4:  B    4   1        0.578    0           4                4         -1 -4 -8 -12       1      -1       5         0 1 1 1 1
+ListCombination               : 1           # Use combined list for uni-prediction in B-slices
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:EPZS
+SearchRange                   : 64          # (0: Search range is a Full frame)
+BipredSearchRange             : 4           # Search range for bi-prediction refinement
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== Quantization =============
+#QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 0           # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInPPS         : 0           # Dbl params in PPS or SliceHeader (0=SliceHeader, 1=PPS)
+LoopFilterDisable             : 0           # Disable deblocking filter in slice header (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # Range: -13 ~ 13
+LoopFilterTcOffset_div2       : 0           # Range: -13 ~ 13
+
+#=========== Misc. ============
+InternalBitDepth              : 8           # internal bit-depth = BitDepth + BitIncrement
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+UniformSpacingIdc                   : 0                # 0: the column boundaries are indicated by ColumnWidth array, the row boundaries are indicated by RowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of columns in a picture minus 1
+ColumnWidthArray                    : 2 3              # Array containing ColumnWidth values in units of LCU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of rows in a picture minus 1
+RowHeightArray                      : 2                # Array containing RowHeight values in units of LCU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag           : 1                  # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across 
+
+#============ WaveFront ================
+WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+LosslessCuEnabled                   : 0                # 1: Set "qpprime_y_zero_transquant_bypass_flag=1" and enable the lossless mode as well as the RD-based mode selection process.
+TransquantBypassEnableFlag: 0  # Value of PPS flag.
+CUTransquantBypassFlagValue: 0 # Constant lossless-value signaling per CU, if TransquantBypassEnableFlag is 1.
+
+#============ Rate Control ======================
+RateCtrl                            : 0                # 0: Disable rate control 1: Enable rate control
+TargetBitrate                       : 1000             # input target bitrate when RateCtrl is enable
+NumLCUInUnit                        : 1                # Number of LCU in an Unit. Fraction is not allowed
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /trunk/cfg/encoder_randomaccess_he10.cfg
===================================================================
--- /trunk/cfg/encoder_randomaccess_he10.cfg	(revision 2)
+++ /trunk/cfg/encoder_randomaccess_he10.cfg	(revision 2)
@@ -0,0 +1,114 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+#ReconFile                     : rec.yuv
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+#IntraPeriod                   : 32          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 1           # Random Accesss 0:none, 1:CDR, 2:IDR
+GOPSize                       : 8           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor temporal_id #ref_pics_active #ref_pics reference pictures     predict deltaRPS #ref_idcs reference idcs 
+Frame1:  B    8   1        0.442    0           4                4         -8 -10 -12 -16         0
+Frame2:  B    4   2        0.3536   0           2                3         -4 -6  4               1       4        5         1 1 0 0 1
+Frame3:  B    2   3        0.3536   0           2                4         -2 -4  2 6             1       2        4         1 1 1 1  
+Frame4:  B    1   4        0.68     0           2                4         -1  1  3 7             1       1        5         1 0 1 1 1 
+Frame5:  B    3   4        0.68     0           2                4         -1 -3  1 5             1      -2        5         1 1 1 1 0
+Frame6:  B    6   3        0.3536   0           2                4         -2 -4 -6 2             1      -3        5         1 1 1 1 0
+Frame7:  B    5   4        0.68     0           2                4         -1 -5  1 3             1       1        5         1 0 1 1 1  
+Frame8:  B    7   4        0.68     0           2                4         -1 -3 -7 1             1      -2        5         1 1 1 1 0
+ListCombination               : 1           # Use combined list for uni-prediction in B-slices
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:EPZS
+SearchRange                   : 64          # (0: Search range is a Full frame)
+BipredSearchRange             : 4           # Search range for bi-prediction refinement
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== Quantization =============
+#QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 0           # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInPPS         : 0           # Dbl params in PPS or SliceHeader (0=SliceHeader, 1=PPS)
+LoopFilterDisable             : 0           # Disable deblocking filter in slice header (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # Range: -13 ~ 13
+LoopFilterTcOffset_div2       : 0           # Range: -13 ~ 13
+
+#=========== Misc. ============
+InternalBitDepth              : 10          # internal bit-depth = BitDepth + BitIncrement
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+UniformSpacingIdc                   : 0                # 0: the column boundaries are indicated by ColumnWidth array, the row boundaries are indicated by RowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of columns in a picture minus 1
+ColumnWidthArray                    : 2 3              # Array containing ColumnWidth values in units of LCU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of rows in a picture minus 1
+RowHeightArray                      : 2                # Array containing RowHeight values in units of LCU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag           : 1                  # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across                                                       
+
+#============ WaveFront ================
+WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+LosslessCuEnabled                   : 0                # 1: Set "qpprime_y_zero_transquant_bypass_flag=1" and enable the lossless mode as well as the RD-based mode selection process.
+TransquantBypassEnableFlag: 0  # Value of PPS flag.
+CUTransquantBypassFlagValue: 0 # Constant lossless-value signaling per CU, if TransquantBypassEnableFlag is 1.
+
+#============ Rate Control ======================
+RateCtrl                            : 0                # 0: Disable rate control 1: Enable rate control
+TargetBitrate                       : 1000             # input target bitrate when RateCtrl is enable
+NumLCUInUnit                        : 1                # Number of LCU in an Unit. Fraction is not allowed
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
+
Index: /trunk/cfg/encoder_randomaccess_main.cfg
===================================================================
--- /trunk/cfg/encoder_randomaccess_main.cfg	(revision 2)
+++ /trunk/cfg/encoder_randomaccess_main.cfg	(revision 2)
@@ -0,0 +1,116 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+#ReconFile                     : rec.yuv
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+#IntraPeriod                   : 32          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 1           # Random Accesss 0:none, 1:CDR, 2:IDR
+GOPSize                       : 8           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor temporal_id #ref_pics_active #ref_pics reference pictures     predict deltaRPS #ref_idcs reference idcs 
+Frame1:  B    8   1        0.442    0           4                4         -8 -10 -12 -16         0
+Frame2:  B    4   2        0.3536   0           2                3         -4 -6  4               1       4        5         1 1 0 0 1
+Frame3:  B    2   3        0.3536   0           2                4         -2 -4  2 6             1       2        4         1 1 1 1  
+Frame4:  B    1   4        0.68     0           2                4         -1  1  3 7             1       1        5         1 0 1 1 1 
+Frame5:  B    3   4        0.68     0           2                4         -1 -3  1 5             1      -2        5         1 1 1 1 0
+Frame6:  B    6   3        0.3536   0           2                4         -2 -4 -6 2             1      -3        5         1 1 1 1 0
+Frame7:  B    5   4        0.68     0           2                4         -1 -5  1 3             1       1        5         1 0 1 1 1  
+Frame8:  B    7   4        0.68     0           2                4         -1 -3 -7 1             1      -2        5         1 1 1 1 0
+ListCombination               : 1           # Use combined list for uni-prediction in B-slices
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:EPZS
+SearchRange                   : 64          # (0: Search range is a Full frame)
+BipredSearchRange             : 4           # Search range for bi-prediction refinement
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== Quantization =============
+#QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 0           # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInPPS         : 0           # Dbl params in PPS or SliceHeader (0=SliceHeader, 1=PPS)
+LoopFilterDisable             : 0           # Disable deblocking filter in slice header (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # Range: -13 ~ 13
+LoopFilterTcOffset_div2       : 0           # Range: -13 ~ 13
+
+#=========== Misc. ============
+InternalBitDepth              : 8           # internal bit-depth = BitDepth + BitIncrement
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+UniformSpacingIdc                   : 0                # 0: the column boundaries are indicated by ColumnWidth array, the row boundaries are indicated by RowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of columns in a picture minus 1
+ColumnWidthArray                    : 2 3              # Array containing ColumnWidth values in units of LCU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of rows in a picture minus 1
+RowHeightArray                      : 2                # Array containing RowHeight values in units of LCU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag           : 1                  # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across                                                       
+
+#============ WaveFront ================
+WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+LosslessCuEnabled                   : 0                # 1: Set "qpprime_y_zero_transquant_bypass_flag=1" and enable the lossless mode as well as the RD-based mode selection process.
+TransquantBypassEnableFlag: 0  # Value of PPS flag.
+CUTransquantBypassFlagValue: 0 # Constant lossless-value signaling per CU, if TransquantBypassEnableFlag is 1.
+
+#============ Rate Control ======================
+RateCtrl                            : 0                # 0: Disable rate control 1: Enable rate control
+TargetBitrate                       : 1000             # input target bitrate when RateCtrl is enable
+NumLCUInUnit                        : 1                # Number of LCU in an Unit. Fraction is not allowed
+
+SEIpictureDigest										: 1
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
+
Index: /trunk/cfg/per-sequence-svc/BasketballDrive-1.5x.cfg
===================================================================
--- /trunk/cfg/per-sequence-svc/BasketballDrive-1.5x.cfg	(revision 2)
+++ /trunk/cfg/per-sequence-svc/BasketballDrive-1.5x.cfg	(revision 2)
@@ -0,0 +1,19 @@
+NumLayers											: 2
+InputBitDepth                 : 8           # Input bitdepth
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 500         # Number of frames to be coded
+
+#======== File I/O ===============
+InputFile0                    : BasketballDrive_1280x720_50_zerophase_0.9pi.yuv
+FrameRate0                    : 50          # Frame Rate per second
+SourceWidth0                  : 1280        # Input  frame width
+SourceHeight0                 : 720         # Input  frame height
+IntraPeriod0                  : 48          # Period of I-Frame ( -1 = only first)
+QP0                           : 22
+
+InputFile1                    : BasketballDrive_1920x1080_50.yuv
+FrameRate1                    : 50          # Frame Rate per second
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+IntraPeriod1                  : 48          # Period of I-Frame ( -1 = only first)
+QP1                           : 20
Index: /trunk/cfg/per-sequence-svc/BasketballDrive-2x.cfg
===================================================================
--- /trunk/cfg/per-sequence-svc/BasketballDrive-2x.cfg	(revision 2)
+++ /trunk/cfg/per-sequence-svc/BasketballDrive-2x.cfg	(revision 2)
@@ -0,0 +1,20 @@
+NumLayers											: 2
+InputBitDepth                 : 8           # Input bitdepth
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 500         # Number of frames to be coded
+
+#======== File I/O ===============
+InputFile0                    : BasketballDrive_960x540_50_zerophase_0.9pi.yuv
+FrameRate0                    : 50          # Frame Rate per second
+SourceWidth0                  : 960         # Input  frame width
+SourceHeight0                 : 540         # Input  frame height
+IntraPeriod0                  : 48          # Period of I-Frame ( -1 = only first)
+QP0                           : 22
+CroppingMode0                 : 1           # automatic padding
+
+InputFile1                    : BasketballDrive_1920x1080_50.yuv
+FrameRate1                    : 50          # Frame Rate per second
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+IntraPeriod1                  : 48          # Period of I-Frame ( -1 = only first)
+QP1                           : 20
Index: /trunk/cfg/per-sequence-svc/BasketballDrive-SNR.cfg
===================================================================
--- /trunk/cfg/per-sequence-svc/BasketballDrive-SNR.cfg	(revision 2)
+++ /trunk/cfg/per-sequence-svc/BasketballDrive-SNR.cfg	(revision 2)
@@ -0,0 +1,19 @@
+NumLayers											: 2
+InputBitDepth                 : 8           # Input bitdepth
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 500         # Number of frames to be coded
+
+#======== File I/O ===============
+InputFile0                    : BasketballDrive_1920x1080_50.yuv
+FrameRate0                    : 50          # Frame Rate per second
+SourceWidth0                  : 1920        # Input  frame width
+SourceHeight0                 : 1080        # Input  frame height
+IntraPeriod0                  : 48          # Period of I-Frame ( -1 = only first)
+QP0                           : 22
+
+InputFile1                    : BasketballDrive_1920x1080_50.yuv
+FrameRate1                    : 50          # Frame Rate per second
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+IntraPeriod1                  : 48          # Period of I-Frame ( -1 = only first)
+QP1                           : 20
Index: /trunk/compat/msvc/stdint.h
===================================================================
--- /trunk/compat/msvc/stdint.h	(revision 2)
+++ /trunk/compat/msvc/stdint.h	(revision 2)
@@ -0,0 +1,13 @@
+#pragma once
+
+/* a minimal set of C99 types for use with MSVC */
+
+typedef signed char int8_t;
+typedef short int int16_t;
+typedef int int32_t;
+typedef __int64 int64_t;
+
+typedef unsigned char uint8_t;
+typedef unsigned short int uint16_t;
+typedef unsigned int uint32_t;
+typedef unsigned __int64 uint64_t;
Index: /trunk/doc/readme.txt
===================================================================
--- /trunk/doc/readme.txt	(revision 2)
+++ /trunk/doc/readme.txt	(revision 2)
@@ -0,0 +1,12 @@
+TAppEncoder -c cfg/encoder_randomaccess_main.cfg -c cfg/per-sequence-svc/BasketballDrive-2x.cfg -q0 22 -q1 22 -b str/BasketballDrive.bin -o0 rec/BasketballDrive_l0_rec.yuv -o1 rec/BasketballDrive_l1_rec.yuv
+
+TAppDecoder -b str/BasketballDrive.bin -ls 2 -o0 rec/BasketballDrive_l0_drec.yuv -o1 rec/BasketballDrive_l1_drec.yuv
+
+For AVC_BASE tests the following additionally should be used.
+
+In the encoder config file for the layer0 ONLY new line should be added. Strictly after InputFile. InputBLFile indicates the path to the BL yuv. Example:
+InputFile                     : O:\BasketballDrive_1280x720_50_zerophase_0.9pi.yuv
+InputBLFile                 : O:\BasketballDrive_l0_rec.yuv
+
+For decoder, new command line parameters additionally should be used as following
+-ibl BLrecon.yuv wdt BLwidth hgt BLheight
Index: /trunk/source/App/TAppDecoder/TAppDecCfg.cpp
===================================================================
--- /trunk/source/App/TAppDecoder/TAppDecCfg.cpp	(revision 2)
+++ /trunk/source/App/TAppDecoder/TAppDecCfg.cpp	(revision 2)
@@ -0,0 +1,198 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TAppDecCfg.cpp
+    \brief    Decoder configuration class
+*/
+
+#include <cstdio>
+#include <cstring>
+#include <string>
+#include "TAppDecCfg.h"
+#include "TAppCommon/program_options_lite.h"
+#if SVC_EXTENSION
+#include <cassert>
+#endif
+
+#ifdef WIN32
+#define strdup _strdup
+#endif
+
+using namespace std;
+namespace po = df::program_options_lite;
+
+//! \ingroup TAppDecoder
+//! \{
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/** \param argc number of arguments
+    \param argv array of arguments
+ */
+Bool TAppDecCfg::parseCfg( Int argc, Char* argv[] )
+{
+  bool do_help = false;
+  string cfg_BitstreamFile;
+#if SVC_EXTENSION
+  string cfg_ReconFile [MAX_LAYERS];
+  Int nLayerNum;
+#if AVC_BASE
+  string cfg_BLReconFile;
+#endif
+#else
+  string cfg_ReconFile;
+#endif
+#if TARGET_DECLAYERID_SET
+  string cfg_TargetDecLayerIdSetFile;
+#endif
+
+  po::Options opts;
+  opts.addOptions()
+  ("help", do_help, false, "this help text")
+  ("BitstreamFile,b", cfg_BitstreamFile, string(""), "bitstream input file name")
+#if SVC_EXTENSION
+  ("ReconFileL%d,-o%d",   cfg_ReconFile,   string(""), MAX_LAYERS, "Layer %d reconstructed YUV output file name\n"
+                                                     "YUV writing is skipped if omitted")
+#if AVC_BASE
+  ("BLReconFile,-ibl",    cfg_BLReconFile,  string(""), "BL reconstructed YUV input file name")
+  ("BLSourceWidth,-wdt",    m_iBLSourceWidth,        0, "BL source picture width")
+  ("BLSourceHeight,-hgt",   m_iBLSourceHeight,       0, "BL source picture height")
+#endif
+#else
+  ("ReconFile,o",     cfg_ReconFile,     string(""), "reconstructed YUV output file name\n"
+                                                     "YUV writing is skipped if omitted")
+#endif
+  ("SkipFrames,s", m_iSkipFrame, 0, "number of frames to skip before random access")
+  ("OutputBitDepth,d", m_outputBitDepth, 0u, "bit depth of YUV output file (use 0 for native depth)")
+#if SVC_EXTENSION
+  ("LayerNum,-ls", nLayerNum, 1, "Number of layers to be decoded.")
+#endif 
+  ("MaxTemporalLayer,t", m_iMaxTemporalLayer, -1, "Maximum Temporal Layer to be decoded. -1 to decode all layers")
+  ("SEIpictureDigest", m_decodedPictureHashSEIEnabled, 1, "Control handling of decoded picture hash SEI messages\n"
+                                              "\t3: checksum\n"
+                                              "\t2: CRC\n"
+                                              "\t1: MD5\n"
+                                              "\t0: ignore")
+#if TARGET_DECLAYERID_SET
+  ("TarDecLayerIdSetFile,l", cfg_TargetDecLayerIdSetFile, string(""), "targetDecLayerIdSet file name. The file should include white space separated LayerId values to be decoded. Omitting the option or a value of -1 in the file decodes all layers.")
+#endif
+  ;
+  po::setDefaults(opts);
+  const list<const char*>& argv_unhandled = po::scanArgv(opts, argc, (const char**) argv);
+
+  for (list<const char*>::const_iterator it = argv_unhandled.begin(); it != argv_unhandled.end(); it++)
+  {
+    fprintf(stderr, "Unhandled argument ignored: `%s'\n", *it);
+  }
+
+  if (argc == 1 || do_help)
+  {
+    po::doHelp(cout, opts);
+    return false;
+  }
+
+  /* convert std::string to c string for compatability */
+  m_pchBitstreamFile = cfg_BitstreamFile.empty() ? NULL : strdup(cfg_BitstreamFile.c_str());
+#if SVC_EXTENSION
+  m_tgtLayerId = nLayerNum - 1;
+  assert( m_tgtLayerId >= 0 );
+  for(UInt layer=0; layer<= m_tgtLayerId; layer++)
+  {
+    m_pchReconFile[layer] = cfg_ReconFile[layer].empty() ? NULL : strdup(cfg_ReconFile[layer].c_str());
+  }
+#if AVC_BASE
+  m_pchBLReconFile = cfg_BLReconFile.empty() ? NULL : strdup(cfg_BLReconFile.c_str());
+#endif
+#else
+  m_pchReconFile = cfg_ReconFile.empty() ? NULL : strdup(cfg_ReconFile.c_str());
+#endif
+
+  if (!m_pchBitstreamFile)
+  {
+    fprintf(stderr, "No input file specifed, aborting\n");
+    return false;
+  }
+
+#if TARGET_DECLAYERID_SET
+  if ( !cfg_TargetDecLayerIdSetFile.empty() )
+  {
+    FILE* targetDecLayerIdSetFile = fopen ( cfg_TargetDecLayerIdSetFile.c_str(), "r" );
+    if ( targetDecLayerIdSetFile )
+    {
+      Bool isLayerIdZeroIncluded = false;
+      while ( !feof(targetDecLayerIdSetFile) )
+      {
+        Int layerIdParsed = 0;
+        if ( fscanf( targetDecLayerIdSetFile, "%d ", &layerIdParsed ) != 1 )
+        {
+          if ( m_targetDecLayerIdSet.size() == 0 )
+          {
+            fprintf(stderr, "No LayerId could be parsed in file %s. Decoding all LayerIds as default.\n", cfg_TargetDecLayerIdSetFile.c_str() );
+          }
+          break;
+        }
+        if ( layerIdParsed  == -1 ) // The file includes a -1, which means all LayerIds are to be decoded.
+        {
+          m_targetDecLayerIdSet.clear(); // Empty set means decoding all layers.
+          break;
+        }
+        if ( layerIdParsed < 0 || layerIdParsed >= MAX_NUM_LAYER_IDS )
+        {
+          fprintf(stderr, "Warning! Parsed LayerId %d is not withing allowed range [0,%d]. Ignoring this value.\n", layerIdParsed, MAX_NUM_LAYER_IDS-1 );
+        }
+        else
+        {
+          isLayerIdZeroIncluded = layerIdParsed == 0 ? true : isLayerIdZeroIncluded;
+          m_targetDecLayerIdSet.push_back ( layerIdParsed );
+        }
+      }
+      fclose (targetDecLayerIdSetFile);
+      if ( m_targetDecLayerIdSet.size() > 0 && !isLayerIdZeroIncluded )
+      {
+        fprintf(stderr, "TargetDecLayerIdSet must contain LayerId=0, aborting" );
+        return false;
+      }
+    }
+    else
+    {
+      fprintf(stderr, "File %s could not be opened. Using all LayerIds as default.\n", cfg_TargetDecLayerIdSetFile.c_str() );
+    }
+  }
+#endif
+
+  return true;
+}
+
+//! \}
Index: /trunk/source/App/TAppDecoder/TAppDecCfg.h
===================================================================
--- /trunk/source/App/TAppDecoder/TAppDecCfg.h	(revision 2)
+++ /trunk/source/App/TAppDecoder/TAppDecCfg.h	(revision 2)
@@ -0,0 +1,97 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TAppDecCfg.h
+    \brief    Decoder configuration class (header)
+*/
+
+#ifndef __TAPPDECCFG__
+#define __TAPPDECCFG__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TLibCommon/CommonDef.h"
+#if TARGET_DECLAYERID_SET
+#include <vector>
+#endif
+
+//! \ingroup TAppDecoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// Decoder configuration class
+class TAppDecCfg
+{
+protected:
+  char*         m_pchBitstreamFile;                   ///< input bitstream file name
+#if SVC_EXTENSION
+  char*         m_pchReconFile [MAX_LAYERS];          ///< output reconstruction file name
+#if AVC_BASE
+  char*         m_pchBLReconFile;                     ///< input BL reconstruction file name
+  Int           m_iBLSourceWidth;
+  Int           m_iBLSourceHeight;
+#endif
+#else
+  char*         m_pchReconFile;                       ///< output reconstruction file name
+#endif
+  Int           m_iSkipFrame;                         ///< counter for frames prior to the random access point to skip
+  UInt          m_outputBitDepth;                     ///< bit depth used for writing output
+
+  Int           m_iMaxTemporalLayer;                  ///< maximum temporal layer to be decoded
+  Int           m_decodedPictureHashSEIEnabled;       ///< Checksum(3)/CRC(2)/MD5(1)/disable(0) acting on decoded picture hash SEI message
+
+#if SVC_EXTENSION
+  Int           m_tgtLayerId;                        ///< target layer ID
+#endif
+
+#if TARGET_DECLAYERID_SET
+  std::vector<Int> m_targetDecLayerIdSet;             ///< set of LayerIds to be included in the sub-bitstream extraction process.
+#endif
+  
+public:
+  TAppDecCfg()          {}
+  virtual ~TAppDecCfg() {}
+  
+  Bool  parseCfg        ( Int argc, Char* argv[] );   ///< initialize option class from configuration
+};
+
+//! \}
+
+#endif
+
+
Index: /trunk/source/App/TAppDecoder/TAppDecTop.cpp
===================================================================
--- /trunk/source/App/TAppDecoder/TAppDecTop.cpp	(revision 2)
+++ /trunk/source/App/TAppDecoder/TAppDecTop.cpp	(revision 2)
@@ -0,0 +1,655 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TAppDecTop.cpp
+    \brief    Decoder application class
+*/
+
+#include <list>
+#include <vector>
+#include <stdio.h>
+#include <fcntl.h>
+#include <assert.h>
+
+#include "TAppDecTop.h"
+#include "TLibDecoder/AnnexBread.h"
+#include "TLibDecoder/NALread.h"
+
+//! \ingroup TAppDecoder
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+
+TAppDecTop::TAppDecTop()
+{
+  ::memset (m_abDecFlag, 0, sizeof (m_abDecFlag));
+#if SVC_EXTENSION
+  for(UInt layer=0; layer < MAX_LAYERS; layer++)
+  {
+    m_aiPOCLastDisplay[layer]  = -MAX_INT;
+    m_apcTDecTop[layer] = &m_acTDecTop[layer];
+  }
+#else
+  m_iPOCLastDisplay  = -MAX_INT;
+#endif
+
+}
+
+Void TAppDecTop::create()
+{
+}
+
+Void TAppDecTop::destroy()
+{
+  if (m_pchBitstreamFile)
+  {
+    free (m_pchBitstreamFile);
+    m_pchBitstreamFile = NULL;
+  }
+#if SVC_EXTENSION   
+  for( Int i = 0; i < m_tgtLayerId; i++ )
+  {
+    if( m_pchReconFile[i] )
+    {
+      free ( m_pchReconFile[i] );
+      m_pchReconFile[i] = NULL;
+    }
+  }  
+#if AVC_BASE
+  if( m_pchBLReconFile )
+  {
+    free ( m_pchBLReconFile );
+    m_pchBLReconFile = NULL;
+  }
+#endif
+#else
+  if (m_pchReconFile)
+  {
+    free (m_pchReconFile);
+    m_pchReconFile = NULL;
+  }
+#endif
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/**
+ - create internal class
+ - initialize internal class
+ - until the end of the bitstream, call decoding function in TDecTop class
+ - delete allocated buffers
+ - destroy internal class
+ .
+ */
+#if SVC_EXTENSION
+Void TAppDecTop::decode()
+{
+  UInt                uiPOC;
+  TComList<TComPic*>* pcListPic = NULL;
+
+  ifstream bitstreamFile(m_pchBitstreamFile, ifstream::in | ifstream::binary);
+  if (!bitstreamFile)
+  {
+    fprintf(stderr, "\nfailed to open bitstream file `%s' for reading\n", m_pchBitstreamFile);
+    exit(EXIT_FAILURE);
+  }
+
+  InputByteStream bytestream(bitstreamFile);
+
+  // create & initialize internal classes
+  xCreateDecLib();
+  xInitDecLib  ();
+
+  // main decoder loop
+  bool recon_opened[MAX_LAYERS]; // reconstruction file not yet opened. (must be performed after SPS is seen)
+  for(UInt layer=0; layer<=m_tgtLayerId; layer++)
+  {
+    recon_opened[layer] = false;
+    m_aiPOCLastDisplay[layer] += m_iSkipFrame;      // set the last displayed POC correctly for skip forward.
+  }
+
+  UInt curLayerId = 0;     // current layer to be reconstructed
+
+#if AVC_BASE
+  TComPic pcBLPic;
+  FILE* pFile = fopen( m_pchBLReconFile, "rb" );
+  if( !pFile )
+  {
+    printf( "BL input reading error\n" );
+    exit(0);
+  }
+  TComList<TComPic*> *cListPic = m_acTDecTop[0].getListPic();
+  m_acTDecTop[0].setBLsize( m_iBLSourceWidth, m_iBLSourceHeight );
+  m_acTDecTop[0].setBLReconFile( pFile );
+  pcBLPic.setLayerId( 0 );
+  cListPic->pushBack( &pcBLPic );
+#endif
+
+  while (!!bitstreamFile)
+  {
+    /* location serves to work around a design fault in the decoder, whereby
+     * the process of reading a new slice that is the first slice of a new frame
+     * requires the TDecTop::decode() method to be called again with the same
+     * nal unit. */
+    streampos location = bitstreamFile.tellg();
+    AnnexBStats stats = AnnexBStats();
+    bool bPreviousPictureDecoded = false;
+
+    vector<uint8_t> nalUnit;
+    InputNALUnit nalu;
+    byteStreamNALUnit(bytestream, nalUnit, stats);
+
+    // call actual decoding function
+    bool bNewPicture = false;
+    bool bNewPOC = false;
+    if (nalUnit.empty())
+    {
+      /* this can happen if the following occur:
+       *  - empty input file
+       *  - two back-to-back start_code_prefixes
+       *  - start_code_prefix immediately followed by EOF
+       */
+      fprintf(stderr, "Warning: Attempt to decode an empty NAL unit\n");
+    }
+    else
+    {
+      read(nalu, nalUnit);
+#if TARGET_DECLAYERID_SET
+      if( (m_iMaxTemporalLayer >= 0 && nalu.m_temporalId > m_iMaxTemporalLayer) || !isNaluWithinTargetDecLayerIdSet(&nalu)  ||
+        (nalu.m_layerId > m_tgtLayerId) )
+#else
+      if(m_iMaxTemporalLayer >= 0 && nalu.m_temporalId > m_iMaxTemporalLayer ||
+        (nalu.m_layerId > m_tgtLayerId) )
+#endif
+      {
+        bNewPicture = false;
+      }
+      else
+      {
+        bNewPicture = m_acTDecTop[nalu.m_layerId].decode(nalu, m_iSkipFrame, m_aiPOCLastDisplay[nalu.m_layerId], curLayerId, bNewPOC);
+        if (bNewPicture)
+        {
+          bitstreamFile.clear();
+          /* location points to the current nalunit payload[1] due to the
+           * need for the annexB parser to read three extra bytes.
+           * [1] except for the first NAL unit in the file
+           *     (but bNewPicture doesn't happen then) */
+          bitstreamFile.seekg(location-streamoff(3));
+          bytestream.reset();
+        }
+        bPreviousPictureDecoded = true; 
+      }
+    }
+    if (bNewPicture || !bitstreamFile)
+    {
+      m_acTDecTop[curLayerId].executeDeblockAndAlf(uiPOC, pcListPic, m_iSkipFrame, m_aiPOCLastDisplay[curLayerId]);
+    }
+
+    if( pcListPic )
+    {
+      if ( m_pchReconFile[curLayerId] && !recon_opened[curLayerId] )
+      {
+        if ( m_outputBitDepth == 0 )
+        {
+          m_outputBitDepth = g_uiBitDepth + g_uiBitIncrement;
+        }
+
+        m_acTVideoIOYuvReconFile[curLayerId].open( m_pchReconFile[curLayerId], true, m_outputBitDepth, g_uiBitDepth + g_uiBitIncrement ); // write mode
+        recon_opened[curLayerId] = true;
+      }
+      if ( bNewPicture && bNewPOC && 
+           (   nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_IDR
+#if SUPPORT_FOR_RAP_N_LP
+            || nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_IDR_N_LP
+            || nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_BLA_N_LP
+#endif
+            || nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_BLANT
+            || nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_BLA ) )
+      {
+        xFlushOutput( pcListPic, curLayerId );
+      }
+      // write reconstruction to file
+      if(bNewPicture)
+      {
+        xWriteOutput( pcListPic, curLayerId, nalu.m_temporalId );
+      }
+    }
+  }
+  for(UInt layer = 0; layer <= m_tgtLayerId; layer++)
+  {
+    xFlushOutput( m_acTDecTop[layer].getListPic(), layer );
+  }
+  // delete buffers
+#if AVC_BASE
+  if( pFile )
+  {
+    fclose( pFile );
+  }
+  pcBLPic.destroy();
+
+  for(UInt layer = 1; layer <= m_tgtLayerId; layer++)
+#else
+  for(UInt layer = 0; layer <= m_tgtLayerId; layer++)
+#endif
+  {
+    m_acTDecTop[layer].deletePicBuffer();
+  }
+  
+  // destroy internal classes
+  xDestroyDecLib();
+}
+#else
+Void TAppDecTop::decode()
+{
+  UInt                uiPOC;
+  TComList<TComPic*>* pcListPic = NULL;
+
+  ifstream bitstreamFile(m_pchBitstreamFile, ifstream::in | ifstream::binary);
+  if (!bitstreamFile)
+  {
+    fprintf(stderr, "\nfailed to open bitstream file `%s' for reading\n", m_pchBitstreamFile);
+    exit(EXIT_FAILURE);
+  }
+
+  InputByteStream bytestream(bitstreamFile);
+
+  // create & initialize internal classes
+  xCreateDecLib();
+  xInitDecLib  ();
+  m_iPOCLastDisplay += m_iSkipFrame;      // set the last displayed POC correctly for skip forward.
+
+  // main decoder loop
+  bool recon_opened = false; // reconstruction file not yet opened. (must be performed after SPS is seen)
+
+  while (!!bitstreamFile)
+  {
+    /* location serves to work around a design fault in the decoder, whereby
+     * the process of reading a new slice that is the first slice of a new frame
+     * requires the TDecTop::decode() method to be called again with the same
+     * nal unit. */
+    streampos location = bitstreamFile.tellg();
+    AnnexBStats stats = AnnexBStats();
+    bool bPreviousPictureDecoded = false;
+
+    vector<uint8_t> nalUnit;
+    InputNALUnit nalu;
+    byteStreamNALUnit(bytestream, nalUnit, stats);
+
+    // call actual decoding function
+    bool bNewPicture = false;
+    if (nalUnit.empty())
+    {
+      /* this can happen if the following occur:
+       *  - empty input file
+       *  - two back-to-back start_code_prefixes
+       *  - start_code_prefix immediately followed by EOF
+       */
+      fprintf(stderr, "Warning: Attempt to decode an empty NAL unit\n");
+    }
+    else
+    {
+      read(nalu, nalUnit);
+#if TARGET_DECLAYERID_SET
+      if( (m_iMaxTemporalLayer >= 0 && nalu.m_temporalId > m_iMaxTemporalLayer) || !isNaluWithinTargetDecLayerIdSet(&nalu)  )
+#else
+      if(m_iMaxTemporalLayer >= 0 && nalu.m_temporalId > m_iMaxTemporalLayer)
+#endif
+      {
+        if(bPreviousPictureDecoded)
+        {
+          bNewPicture = true;
+          bPreviousPictureDecoded = false;
+        }
+        else
+        {
+          bNewPicture = false;
+        }
+      }
+      else
+      {
+        bNewPicture = m_cTDecTop.decode(nalu, m_iSkipFrame, m_iPOCLastDisplay);
+        if (bNewPicture)
+        {
+          bitstreamFile.clear();
+          /* location points to the current nalunit payload[1] due to the
+           * need for the annexB parser to read three extra bytes.
+           * [1] except for the first NAL unit in the file
+           *     (but bNewPicture doesn't happen then) */
+          bitstreamFile.seekg(location-streamoff(3));
+          bytestream.reset();
+        }
+        bPreviousPictureDecoded = true; 
+      }
+    }
+    if (bNewPicture || !bitstreamFile)
+    {
+      m_cTDecTop.executeDeblockAndAlf(uiPOC, pcListPic, m_iSkipFrame, m_iPOCLastDisplay);
+    }
+
+    if( pcListPic )
+    {
+      if ( m_pchReconFile && !recon_opened )
+      {
+        if ( m_outputBitDepth == 0 )
+        {
+          m_outputBitDepth = g_uiBitDepth + g_uiBitIncrement;
+        }
+
+        m_cTVideoIOYuvReconFile.open( m_pchReconFile, true, m_outputBitDepth, g_uiBitDepth + g_uiBitIncrement ); // write mode
+        recon_opened = true;
+      }
+      if ( bNewPicture && 
+           (   nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_IDR
+#if SUPPORT_FOR_RAP_N_LP
+            || nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_IDR_N_LP
+            || nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_BLA_N_LP
+#endif
+            || nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_BLANT
+            || nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_BLA ) )
+      {
+        xFlushOutput( pcListPic );
+      }
+      // write reconstruction to file
+      if(bNewPicture)
+      {
+        xWriteOutput( pcListPic, nalu.m_temporalId );
+      }
+    }
+  }
+  
+  xFlushOutput( pcListPic );
+  // delete buffers
+  m_cTDecTop.deletePicBuffer();
+  
+  // destroy internal classes
+  xDestroyDecLib();
+}
+#endif
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+Void TAppDecTop::xCreateDecLib()
+{
+#if SVC_EXTENSION
+  // initialize global variables
+  initROM();  
+
+  for(UInt layer = 0; layer <= m_tgtLayerId; layer++)
+  {
+    // set layer ID
+    m_acTDecTop[layer].setLayerId                      ( layer );
+
+    // create decoder class
+    m_acTDecTop[layer].create();
+
+    m_acTDecTop[layer].setLayerDec(m_apcTDecTop);   
+  }
+#else
+  // create decoder class
+  m_cTDecTop.create();
+#endif
+}
+
+Void TAppDecTop::xDestroyDecLib()
+{
+#if SVC_EXTENSION
+  // destroy ROM
+  destroyROM();
+
+  for(UInt layer = 0; layer <= m_tgtLayerId; layer++)
+  {
+    if ( m_pchReconFile[layer] )
+    {
+      m_acTVideoIOYuvReconFile[layer]. close();
+    }
+
+    // destroy decoder class
+    m_acTDecTop[layer].destroy();
+  }
+#else
+  if ( m_pchReconFile )
+  {
+    m_cTVideoIOYuvReconFile. close();
+  }
+  
+  // destroy decoder class
+  m_cTDecTop.destroy();
+#endif
+}
+
+Void TAppDecTop::xInitDecLib()
+{
+  // initialize decoder class
+#if SVC_EXTENSION
+  for(UInt layer = 0; layer <= m_tgtLayerId; layer++)
+  {
+    m_acTDecTop[layer].init();
+    m_acTDecTop[layer].setDecodedPictureHashSEIEnabled(m_decodedPictureHashSEIEnabled);
+    m_acTDecTop[layer].setNumLayer( m_tgtLayerId + 1 );
+  }
+
+#else
+  m_cTDecTop.init();
+  m_cTDecTop.setDecodedPictureHashSEIEnabled(m_decodedPictureHashSEIEnabled);
+#endif
+}
+
+/** \param pcListPic list of pictures to be written to file
+    \todo            DYN_REF_FREE should be revised
+ */
+#if SVC_EXTENSION
+Void TAppDecTop::xWriteOutput( TComList<TComPic*>* pcListPic, UInt layerId, UInt tId )
+#else
+Void TAppDecTop::xWriteOutput( TComList<TComPic*>* pcListPic, UInt tId )
+#endif
+{
+  TComList<TComPic*>::iterator iterPic   = pcListPic->begin();
+  Int not_displayed = 0;
+
+  while (iterPic != pcListPic->end())
+  {
+    TComPic* pcPic = *(iterPic);
+#if SVC_EXTENSION
+    if(pcPic->getOutputMark() && pcPic->getPOC() > m_aiPOCLastDisplay[layerId])
+#else
+    if(pcPic->getOutputMark() && pcPic->getPOC() > m_iPOCLastDisplay)
+#endif
+    {
+       not_displayed++;
+    }
+    iterPic++;
+  }
+  iterPic   = pcListPic->begin();
+  
+  while (iterPic != pcListPic->end())
+  {
+    TComPic* pcPic = *(iterPic);
+    TComSPS *sps = pcPic->getSlice(0)->getSPS();
+    
+#if SVC_EXTENSION
+    if ( pcPic->getOutputMark() && (not_displayed >  pcPic->getSlice(0)->getSPS()->getNumReorderPics(tId) && pcPic->getPOC() > m_aiPOCLastDisplay[layerId]))
+#else
+    if ( pcPic->getOutputMark() && (not_displayed >  pcPic->getSlice(0)->getSPS()->getNumReorderPics(tId) && pcPic->getPOC() > m_iPOCLastDisplay))
+#endif
+    {
+      // write to file
+       not_displayed--;
+#if SVC_EXTENSION
+      if ( m_pchReconFile[layerId] )
+      {
+        m_acTVideoIOYuvReconFile[layerId].write( pcPic->getPicYuvRec(), sps->getPicCropLeftOffset(), sps->getPicCropRightOffset(), sps->getPicCropTopOffset(), sps->getPicCropBottomOffset() );
+      }
+      
+      // update POC of display order
+      m_aiPOCLastDisplay[layerId] = pcPic->getPOC();
+#else
+      if ( m_pchReconFile )
+      {
+        m_cTVideoIOYuvReconFile.write( pcPic->getPicYuvRec(), sps->getPicCropLeftOffset(), sps->getPicCropRightOffset(), sps->getPicCropTopOffset(), sps->getPicCropBottomOffset() );
+      }
+      
+      // update POC of display order
+      m_iPOCLastDisplay = pcPic->getPOC();
+#endif
+      
+      // erase non-referenced picture in the reference picture list after display
+      if ( !pcPic->getSlice(0)->isReferenced() && pcPic->getReconMark() == true )
+      {
+#if !DYN_REF_FREE
+        pcPic->setReconMark(false);
+        
+        // mark it should be extended later
+        pcPic->getPicYuvRec()->setBorderExtension( false );
+        
+#else
+        pcPic->destroy();
+        pcListPic->erase( iterPic );
+        iterPic = pcListPic->begin(); // to the beginning, non-efficient way, have to be revised!
+        continue;
+#endif
+      }
+      pcPic->setOutputMark(false);
+    }
+    
+    iterPic++;
+  }
+}
+
+/** \param pcListPic list of pictures to be written to file
+    \todo            DYN_REF_FREE should be revised
+ */
+#if SVC_EXTENSION
+Void TAppDecTop::xFlushOutput( TComList<TComPic*>* pcListPic, UInt layerId )
+#else
+Void TAppDecTop::xFlushOutput( TComList<TComPic*>* pcListPic )
+#endif
+{
+  if(!pcListPic)
+  {
+    return;
+  } 
+  TComList<TComPic*>::iterator iterPic   = pcListPic->begin();
+
+  iterPic   = pcListPic->begin();
+  
+  while (iterPic != pcListPic->end())
+  {
+    TComPic* pcPic = *(iterPic);
+    TComSPS *sps = pcPic->getSlice(0)->getSPS();
+
+    if ( pcPic->getOutputMark() )
+    {
+      // write to file
+#if SVC_EXTENSION
+      if ( m_pchReconFile[layerId] )
+      {
+        m_acTVideoIOYuvReconFile[layerId].write( pcPic->getPicYuvRec(), sps->getPicCropLeftOffset(), sps->getPicCropRightOffset(), sps->getPicCropTopOffset(), sps->getPicCropBottomOffset() );
+      }
+      
+      // update POC of display order
+      m_aiPOCLastDisplay[layerId] = pcPic->getPOC();
+#else
+      if ( m_pchReconFile )
+      {
+        m_cTVideoIOYuvReconFile.write( pcPic->getPicYuvRec(), sps->getPicCropLeftOffset(), sps->getPicCropRightOffset(), sps->getPicCropTopOffset(), sps->getPicCropBottomOffset() );
+      }
+      
+      // update POC of display order
+      m_iPOCLastDisplay = pcPic->getPOC();
+#endif
+      
+      // erase non-referenced picture in the reference picture list after display
+      if ( !pcPic->getSlice(0)->isReferenced() && pcPic->getReconMark() == true )
+      {
+#if !DYN_REF_FREE
+        pcPic->setReconMark(false);
+        
+        // mark it should be extended later
+        pcPic->getPicYuvRec()->setBorderExtension( false );
+        
+#else
+        pcPic->destroy();
+        pcListPic->erase( iterPic );
+        iterPic = pcListPic->begin(); // to the beginning, non-efficient way, have to be revised!
+        continue;
+#endif
+      }
+      pcPic->setOutputMark(false);
+    }
+#if !SVC_EXTENSION
+#if !DYN_REF_FREE
+    if(pcPic)
+    {
+      pcPic->destroy();
+      delete pcPic;
+      pcPic = NULL;
+    }
+#endif
+#endif
+    iterPic++;
+  }
+#if SVC_EXTENSION
+  m_aiPOCLastDisplay[layerId] = -MAX_INT;
+#else
+  pcListPic->clear(); //k Cannot be cleared here. Otherwise, pictures will never be destroyed.
+  m_iPOCLastDisplay = -MAX_INT;
+#endif
+}
+
+#if TARGET_DECLAYERID_SET
+/** \param nalu Input nalu to check whether its LayerId is within targetDecLayerIdSet
+ */
+Bool TAppDecTop::isNaluWithinTargetDecLayerIdSet( InputNALUnit* nalu )
+{
+  if ( m_targetDecLayerIdSet.size() == 0 ) // By default, the set is empty, meaning all LayerIds are allowed
+  {
+    return true;
+  }
+  for (std::vector<Int>::iterator it = m_targetDecLayerIdSet.begin(); it != m_targetDecLayerIdSet.end(); it++)
+  {
+    if ( nalu->m_reservedZero6Bits == (*it) )
+    {
+      return true;
+    }
+  }
+  return false;
+}
+#endif
+
+//! \}
Index: /trunk/source/App/TAppDecoder/TAppDecTop.h
===================================================================
--- /trunk/source/App/TAppDecoder/TAppDecTop.h	(revision 2)
+++ /trunk/source/App/TAppDecoder/TAppDecTop.h	(revision 2)
@@ -0,0 +1,108 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TAppDecTop.h
+    \brief    Decoder application class (header)
+*/
+
+#ifndef __TAPPDECTOP__
+#define __TAPPDECTOP__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TLibVideoIO/TVideoIOYuv.h"
+#include "TLibCommon/TComList.h"
+#include "TLibCommon/TComPicYuv.h"
+#include "TLibDecoder/TDecTop.h"
+#include "TAppDecCfg.h"
+
+//! \ingroup TAppDecoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// decoder application class
+class TAppDecTop : public TAppDecCfg
+{
+private:
+  // class interface
+#if SVC_EXTENSION
+  TDecTop                         m_acTDecTop [MAX_LAYERS];                    ///< decoder class 
+  TDecTop*                        m_apcTDecTop [MAX_LAYERS];                   ///< decoder point class 
+  TVideoIOYuv                     m_acTVideoIOYuvReconFile [MAX_LAYERS];        ///< reconstruction YUV class
+#else
+  TDecTop                         m_cTDecTop;                     ///< decoder class
+  TVideoIOYuv                     m_cTVideoIOYuvReconFile;        ///< reconstruction YUV class
+#endif
+  
+  // for output control
+  Bool                            m_abDecFlag[ MAX_GOP ];         ///< decoded flag in one GOP
+#if SVC_EXTENSION
+  Int                             m_aiPOCLastDisplay [MAX_LAYERS]; ///< last POC in display order
+#else
+  Int                             m_iPOCLastDisplay;              ///< last POC in display order
+#endif
+  
+public:
+  TAppDecTop();
+  virtual ~TAppDecTop() {}
+  
+  Void  create            (); ///< create internal members
+  Void  destroy           (); ///< destroy internal members
+  Void  decode            (); ///< main decoding function
+  
+protected:
+  Void  xCreateDecLib     (); ///< create internal classes
+  Void  xDestroyDecLib    (); ///< destroy internal classes
+  Void  xInitDecLib       (); ///< initialize decoder class
+  
+#if SVC_EXTENSION
+  Void  xWriteOutput      ( TComList<TComPic*>* pcListPic, UInt layerId, UInt tId ); ///< write YUV to file
+  Void  xFlushOutput      ( TComList<TComPic*>* pcListPic, UInt layerId ); ///< flush all remaining decoded pictures to file
+#else
+  Void  xWriteOutput      ( TComList<TComPic*>* pcListPic , UInt tId); ///< write YUV to file
+  Void  xFlushOutput      ( TComList<TComPic*>* pcListPic ); ///< flush all remaining decoded pictures to file
+#endif
+#if TARGET_DECLAYERID_SET
+  Bool  isNaluWithinTargetDecLayerIdSet ( InputNALUnit* nalu ); ///< check whether given Nalu is within targetDecLayerIdSet
+#endif
+};
+
+//! \}
+
+#endif
+
Index: /trunk/source/App/TAppDecoder/decmain.cpp
===================================================================
--- /trunk/source/App/TAppDecoder/decmain.cpp	(revision 2)
+++ /trunk/source/App/TAppDecoder/decmain.cpp	(revision 2)
@@ -0,0 +1,96 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     decmain.cpp
+    \brief    Decoder application main
+*/
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <time.h>
+#include "TAppDecTop.h"
+
+//! \ingroup TAppDecoder
+//! \{
+
+bool g_md5_mismatch = false; ///< top level flag that indicates if there has been a decoding mismatch
+
+// ====================================================================================================================
+// Main function
+// ====================================================================================================================
+
+int main(int argc, char* argv[])
+{
+  TAppDecTop  cTAppDecTop;
+
+  // print information
+  fprintf( stdout, "\n" );
+  fprintf( stdout, "SMuC software: Decoder Version [%s]", NV_VERSION );
+  fprintf( stdout, NVM_ONOS );
+  fprintf( stdout, NVM_COMPILEDBY );
+  fprintf( stdout, NVM_BITS );
+  fprintf( stdout, "\n" );
+
+  // create application decoder class
+  cTAppDecTop.create();
+
+  // parse configuration
+  if(!cTAppDecTop.parseCfg( argc, argv ))
+  {
+    cTAppDecTop.destroy();
+    return 1;
+  }
+
+  // starting time
+  double dResult;
+  long lBefore = clock();
+
+  // call decoding function
+  cTAppDecTop.decode();
+
+  if (g_md5_mismatch)
+  {
+    printf("\n\n***ERROR*** A decoding mismatch occured: signalled md5sum does not match\n");
+  }
+
+  // ending time
+  dResult = (double)(clock()-lBefore) / CLOCKS_PER_SEC;
+  printf("\n Total Time: %12.3f sec.\n", dResult);
+
+  // destroy application decoder class
+  cTAppDecTop.destroy();
+
+  return g_md5_mismatch ? EXIT_FAILURE : EXIT_SUCCESS;
+}
+
+//! \}
Index: /trunk/source/App/TAppEncoder/TAppEncCfg.cpp
===================================================================
--- /trunk/source/App/TAppEncoder/TAppEncCfg.cpp	(revision 2)
+++ /trunk/source/App/TAppEncoder/TAppEncCfg.cpp	(revision 2)
@@ -0,0 +1,1338 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TAppEncCfg.cpp
+    \brief    Handle encoder configuration parameters
+*/
+
+#include <stdlib.h>
+#include <cassert>
+#include <cstring>
+#include <string>
+#include "TLibCommon/TComRom.h"
+#include "TAppEncCfg.h"
+#include "TAppCommon/program_options_lite.h"
+#include "TLibEncoder/TEncRateCtrl.h"
+#ifdef WIN32
+#define strdup _strdup
+#endif
+
+using namespace std;
+namespace po = df::program_options_lite;
+
+//! \ingroup TAppEncoder
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+
+TAppEncCfg::TAppEncCfg()
+#if SVC_EXTENSION
+: m_pchBitstreamFile()
+, m_pchColumnWidth()
+, m_pchRowHeight()
+, m_scalingListFile()
+#if REF_IDX_FRAMEWORK
+, m_elRapSliceBEnabled(0)
+#endif
+#else
+: m_pchInputFile()
+, m_pchBitstreamFile()
+, m_pchReconFile()
+, m_pchdQPFile()
+, m_pchColumnWidth()
+, m_pchRowHeight()
+, m_scalingListFile()
+#endif
+{
+#if SVC_EXTENSION
+  for(UInt layer=0; layer<MAX_LAYERS; layer++)
+  {
+    m_acLayerCfg[layer].setAppEncCfg(this);
+  }
+#else
+  m_aidQP = NULL;
+#endif
+}
+
+TAppEncCfg::~TAppEncCfg()
+{
+#if !SVC_EXTENSION
+  if ( m_aidQP )
+  {
+    delete[] m_aidQP;
+  }
+  free(m_pchInputFile); 
+#endif
+  free(m_pchBitstreamFile);
+#if !SVC_EXTENSION  
+  free(m_pchReconFile);
+  free(m_pchdQPFile);
+#endif
+  free(m_pchColumnWidth);
+  free(m_pchRowHeight);
+  free(m_scalingListFile);
+}
+
+Void TAppEncCfg::create()
+{
+}
+
+Void TAppEncCfg::destroy()
+{
+}
+
+std::istringstream &operator>>(std::istringstream &in, GOPEntry &entry)     //input
+{
+  in>>entry.m_sliceType;
+  in>>entry.m_POC;
+  in>>entry.m_QPOffset;
+  in>>entry.m_QPFactor;
+  in>>entry.m_temporalId;
+  in>>entry.m_numRefPicsActive;
+#if !TEMPORAL_LAYER_NON_REFERENCE
+  in>>entry.m_refPic;
+#endif
+  in>>entry.m_numRefPics;
+  for ( Int i = 0; i < entry.m_numRefPics; i++ )
+  {
+    in>>entry.m_referencePics[i];
+  }
+  in>>entry.m_interRPSPrediction;
+#if AUTO_INTER_RPS
+  if (entry.m_interRPSPrediction==1)
+  {
+#if !J0234_INTER_RPS_SIMPL
+    in>>entry.m_deltaRIdxMinus1;
+#endif
+    in>>entry.m_deltaRPS;
+    in>>entry.m_numRefIdc;
+    for ( Int i = 0; i < entry.m_numRefIdc; i++ )
+    {
+      in>>entry.m_refIdc[i];
+    }
+  }
+  else if (entry.m_interRPSPrediction==2)
+  {
+#if !J0234_INTER_RPS_SIMPL
+    in>>entry.m_deltaRIdxMinus1;
+#endif
+    in>>entry.m_deltaRPS;
+  }
+#else
+  if (entry.m_interRPSPrediction)
+  {
+#if !J0234_INTER_RPS_SIMPL
+    in>>entry.m_deltaRIdxMinus1;
+#endif
+    in>>entry.m_deltaRPS;
+    in>>entry.m_numRefIdc;
+    for ( Int i = 0; i < entry.m_numRefIdc; i++ )
+    {
+      in>>entry.m_refIdc[i];
+    }
+  }
+#endif
+  return in;
+}
+
+#if SVC_EXTENSION
+void TAppEncCfg::getDirFilename(string& filename, string& dir, const string path)
+{
+  size_t pos = path.find_last_of("\\");
+  if(pos != std::string::npos)
+  {
+    filename.assign(path.begin() + pos + 1, path.end());
+    dir.assign(path.begin(), path.begin() + pos + 1);
+  }
+  else
+  {
+    pos = path.find_last_of("/");
+    if(pos != std::string::npos)
+    {
+      filename.assign(path.begin() + pos + 1, path.end());
+      dir.assign(path.begin(), path.begin() + pos + 1);
+    }
+    else
+    {
+      filename = path;
+      dir.assign("");
+    }
+  }
+}
+#endif
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/** \param  argc        number of arguments
+    \param  argv        array of arguments
+    \retval             true when success
+ */
+Bool TAppEncCfg::parseCfg( Int argc, Char* argv[] )
+{
+  bool do_help = false;
+  
+#if SVC_EXTENSION
+  string  cfg_LayerCfgFile  [MAX_LAYERS];
+  string  cfg_BitstreamFile;
+  string* cfg_InputFile     [MAX_LAYERS];
+  string* cfg_ReconFile     [MAX_LAYERS];
+  Double* cfg_fQP           [MAX_LAYERS];
+
+  Int*    cfg_SourceWidth   [MAX_LAYERS]; 
+  Int*    cfg_SourceHeight  [MAX_LAYERS];
+  Int*    cfg_FrameRate     [MAX_LAYERS];
+  Int*    cfg_IntraPeriod   [MAX_LAYERS];
+  Int*    cfg_CroppingMode  [MAX_LAYERS];
+  for(UInt layer = 0; layer < MAX_LAYERS; layer++)
+  {
+    cfg_InputFile[layer]    = &m_acLayerCfg[layer].m_cInputFile;
+    cfg_ReconFile[layer]    = &m_acLayerCfg[layer].m_cReconFile;
+    cfg_fQP[layer]          = &m_acLayerCfg[layer].m_fQP;
+    cfg_SourceWidth[layer]  = &m_acLayerCfg[layer].m_iSourceWidth;
+    cfg_SourceHeight[layer] = &m_acLayerCfg[layer].m_iSourceHeight;
+    cfg_FrameRate[layer]    = &m_acLayerCfg[layer].m_iFrameRate; 
+    cfg_IntraPeriod[layer]  = &m_acLayerCfg[layer].m_iIntraPeriod; 
+    cfg_CroppingMode[layer] = &m_acLayerCfg[layer].m_croppingMode;
+  }
+#else
+  string cfg_InputFile;
+  string cfg_BitstreamFile;
+  string cfg_ReconFile;
+  string cfg_dQPFile;
+#endif
+  string cfg_ColumnWidth;
+  string cfg_RowHeight;
+  string cfg_ScalingListFile;
+  po::Options opts;
+  opts.addOptions()
+  ("help", do_help, false, "this help text")
+  ("c", po::parseConfigFile, "configuration file name")
+  
+  // File, I/O and source parameters
+#if SVC_EXTENSION
+  ("InputFile%d,-i%d",        cfg_InputFile,  string(""), MAX_LAYERS, "original YUV input file name for layer %d")
+  ("ReconFile%d,-o%d",        cfg_ReconFile,  string(""), MAX_LAYERS, "reconstruction YUV input file name for layer %d")
+  ("LayerConfig%d,-lc%d",     cfg_LayerCfgFile, string(""), MAX_LAYERS, "layer %d configuration file name")
+  ("BitstreamFile,b",         cfg_BitstreamFile, string(""), "bitstream output file name")
+  ("SourceWidth%d,-wdt%d",    cfg_SourceWidth, 0, MAX_LAYERS, "Source picture width for layer %d")
+  ("SourceHeight%d,-hgt%d",   cfg_SourceHeight, 0, MAX_LAYERS, "Source picture height for layer %d")
+  ("FrameRate%d,-fr%d",       cfg_FrameRate,  0, MAX_LAYERS, "Frame rate for layer %d")
+  ("LambdaModifier%d,-LM%d",  m_adLambdaModifier, ( double )1.0, MAX_TLAYER, "Lambda modifier for temporal layer %d")
+  ("CroppingMode%d",          cfg_CroppingMode,0, MAX_LAYERS, "Cropping mode (0: no cropping, 1:automatic padding, 2: padding, 3:cropping")
+  ("InputBitDepth",           m_uiInputBitDepth, 8u, "bit-depth of input file")
+  ("BitDepth",                m_uiInputBitDepth, 8u, "deprecated alias of InputBitDepth")
+  ("OutputBitDepth",          m_uiOutputBitDepth, 0u, "bit-depth of output file")
+  ("InternalBitDepth",        m_uiInternalBitDepth, 0u, "Internal bit-depth (BitDepth+BitIncrement)")
+#if AVC_BASE
+  ("InputBLFile,-ibl",        *cfg_InputFile[0],     string(""), "Original BL rec YUV input file name")
+#endif
+#if REF_IDX_FRAMEWORK
+  ("EnableElRapB,-use-rap-b",  m_elRapSliceBEnabled, 0, "Set ILP over base-layer I picture to B picture (default is P picture_")
+#endif
+#else
+  ("InputFile,i",           cfg_InputFile,     string(""), "Original YUV input file name")
+  ("BitstreamFile,b",       cfg_BitstreamFile, string(""), "Bitstream output file name")
+  ("ReconFile,o",           cfg_ReconFile,     string(""), "Reconstructed YUV output file name")
+  ("SourceWidth,-wdt",      m_iSourceWidth,        0, "Source picture width")
+  ("SourceHeight,-hgt",     m_iSourceHeight,       0, "Source picture height")
+  ("InputBitDepth",         m_uiInputBitDepth,    8u, "Bit-depth of input file")
+  ("BitDepth",              m_uiInputBitDepth,    8u, "Deprecated alias of InputBitDepth")
+  ("OutputBitDepth",        m_uiOutputBitDepth,   0u, "Bit-depth of output file")
+  ("InternalBitDepth",      m_uiInternalBitDepth, 0u, "Internal bit-depth (BitDepth+BitIncrement)")
+  ("CroppingMode",          m_croppingMode,        0, "Cropping mode (0: no cropping, 1:automatic padding, 2: padding, 3:cropping")
+  ("HorizontalPadding,-pdx",m_aiPad[0],            0, "Horizontal source padding for cropping mode 2")
+  ("VerticalPadding,-pdy",  m_aiPad[1],            0, "Vertical source padding for cropping mode 2")
+  ("CropLeft",              m_cropLeft,            0, "Left cropping for cropping mode 3")
+  ("CropRight",             m_cropRight,           0, "Right cropping for cropping mode 3")
+  ("CropTop",               m_cropTop,             0, "Top cropping for cropping mode 3")
+  ("CropBottom",            m_cropBottom,          0, "Bottom cropping for cropping mode 3")
+  ("FrameRate,-fr",         m_iFrameRate,          0, "Frame rate")
+#endif
+  ("FrameSkip,-fs",         m_FrameSkip,          0u, "Number of frames to skip at start of input YUV")
+  ("FramesToBeEncoded,f",   m_iFrameToBeEncoded,   0, "Number of frames to be encoded (default=all)")
+  
+#if SVC_EXTENSION
+  ("NumLayers",             m_numLayers, 1, "Number of layers to code")
+#endif
+
+  // Unit definition parameters
+  ("MaxCUWidth",              m_uiMaxCUWidth,             64u)
+  ("MaxCUHeight",             m_uiMaxCUHeight,            64u)
+  // todo: remove defaults from MaxCUSize
+  ("MaxCUSize,s",             m_uiMaxCUWidth,             64u, "Maximum CU size")
+  ("MaxCUSize,s",             m_uiMaxCUHeight,            64u, "Maximum CU size")
+  ("MaxPartitionDepth,h",     m_uiMaxCUDepth,              4u, "CU depth")
+  
+  ("QuadtreeTULog2MaxSize",   m_uiQuadtreeTULog2MaxSize,   6u, "Maximum TU size in logarithm base 2")
+  ("QuadtreeTULog2MinSize",   m_uiQuadtreeTULog2MinSize,   2u, "Minimum TU size in logarithm base 2")
+  
+  ("QuadtreeTUMaxDepthIntra", m_uiQuadtreeTUMaxDepthIntra, 1u, "Depth of TU tree for intra CUs")
+  ("QuadtreeTUMaxDepthInter", m_uiQuadtreeTUMaxDepthInter, 2u, "Depth of TU tree for inter CUs")
+  
+  // Coding structure paramters
+#if SVC_EXTENSION
+  ("IntraPeriod%d,-ip%d",  cfg_IntraPeriod, -1, MAX_LAYERS, "intra period in frames for layer %d, (-1: only first frame)")
+#else
+  ("IntraPeriod,-ip",         m_iIntraPeriod,              -1, "Intra period in frames, (-1: only first frame)")
+#endif
+  ("DecodingRefreshType,-dr", m_iDecodingRefreshType,       0, "Intra refresh type (0:none 1:CRA 2:IDR)")
+  ("GOPSize,g",               m_iGOPSize,                   1, "GOP size of temporal structure")
+  ("ListCombination,-lc",     m_bUseLComb,               true, "Combined reference list for uni-prediction estimation in B-slices")
+  // motion options
+  ("FastSearch",              m_iFastSearch,                1, "0:Full search  1:Diamond  2:PMVFAST")
+  ("SearchRange,-sr",         m_iSearchRange,              96, "Motion search range")
+  ("BipredSearchRange",       m_bipredSearchRange,          4, "Motion search range for bipred refinement")
+  ("HadamardME",              m_bUseHADME,               true, "Hadamard ME for fractional-pel")
+  ("ASR",                     m_bUseASR,                false, "Adaptive motion search range")
+
+#if !SVC_EXTENSION
+  // 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")
+  ("LambdaModifier7,-LM7", m_adLambdaModifier[ 7 ], ( double )1.0, "Lambda modifier for temporal layer 7")
+#endif
+
+  /* Quantization parameters */
+#if SVC_EXTENSION
+  ("QP%d,-q%d",     cfg_fQP,  30.0, MAX_LAYERS, "Qp value for layer %d, if value is float, QP is switched once during encoding")
+#else
+  ("QP,q",          m_fQP,             30.0, "Qp value, if value is float, QP is switched once during encoding")
+#endif
+  ("DeltaQpRD,-dqr",m_uiDeltaQpRD,       0u, "max dQp offset for slice")
+  ("MaxDeltaQP,d",  m_iMaxDeltaQP,        0, "max dQp offset for block")
+  ("MaxCuDQPDepth,-dqd",  m_iMaxCuDQPDepth,        0, "max depth for a minimum CuDQP")
+
+  ("CbQpOffset,-cbqpofs",  m_cbQpOffset,        0, "Chroma Cb QP Offset")
+  ("CrQpOffset,-crqpofs",  m_crQpOffset,        0, "Chroma Cr QP Offset")
+
+#if ADAPTIVE_QP_SELECTION
+  ("AdaptiveQpSelection,-aqps",   m_bUseAdaptQpSelect,           false, "AdaptiveQpSelection")
+#endif
+
+  ("AdaptiveQP,-aq",                m_bUseAdaptiveQP,           false, "QP adaptation based on a psycho-visual model")
+  ("MaxQPAdaptationRange,-aqr",     m_iQPAdaptationRange,           6, "QP adaptation range")
+#if !SVC_EXTENSION
+  ("dQPFile,m",                     cfg_dQPFile,           string(""), "dQP file name")
+#endif
+  ("RDOQ",                          m_bUseRDOQ,                  true )
+  
+  // Entropy coding parameters
+  ("SBACRD",                         m_bUseSBACRD,                      true, "SBAC based RD estimation")
+  
+  // Deblocking filter parameters
+  ("LoopFilterDisable",              m_bLoopFilterDisable,             false )
+  ("LoopFilterOffsetInPPS",          m_loopFilterOffsetInPPS,          false )
+  ("LoopFilterBetaOffset_div2",      m_loopFilterBetaOffsetDiv2,           0 )
+  ("LoopFilterTcOffset_div2",        m_loopFilterTcOffsetDiv2,             0 )
+  ("DeblockingFilterControlPresent", m_DeblockingFilterControlPresent, false )
+
+  // Coding tools
+#if !REMOVE_NSQT
+  ("NSQT",                    m_enableNSQT,              true, "Enable non-square transforms")
+#endif
+  ("AMP",                     m_enableAMP,               true, "Enable asymmetric motion partitions")
+#if !REMOVE_LMCHROMA
+  ("LMChroma",                m_bUseLMChroma,            true, "Intra chroma prediction based on reconstructed luma")
+#endif
+  ("TransformSkip",           m_useTransformSkip,        false, "Intra transform skipping")
+  ("TransformSkipFast",       m_useTransformSkipFast,    false, "Fast intra transform skipping")
+#if !REMOVE_ALF
+  ("ALF",                     m_bUseALF,                 true, "Enable Adaptive Loop Filter")
+#endif
+  ("SAO",                     m_bUseSAO,                 true, "Enable Sample Adaptive Offset")
+  ("MaxNumOffsetsPerPic",     m_maxNumOffsetsPerPic,     2048, "Max number of SAO offset per picture (Default: 2048)")   
+#if SAO_LCU_BOUNDARY
+  ("SAOLcuBoundary",          m_saoLcuBoundary,          false, "0: right/bottom LCU boundary areas skipped from SAO parameter estimation, 1: non-deblocked pixels are used for those areas")
+#endif
+  ("SAOLcuBasedOptimization", m_saoLcuBasedOptimization, true, "0: SAO picture-based optimization, 1: SAO LCU-based optimization ")
+#if !REMOVE_ALF
+  ("ALFLowLatencyEncode", m_alfLowLatencyEncoding, false, "Low-latency ALF encoding, 0: picture latency (trained from current frame), 1: LCU latency(trained from previous frame)")
+#endif
+  ("SliceMode",            m_iSliceMode,           0, "0: Disable all Recon slice limits, 1: Enforce max # of LCUs, 2: Enforce max # of bytes")
+    ("SliceArgument",        m_iSliceArgument,       0, "if SliceMode==1 SliceArgument represents max # of LCUs. if SliceMode==2 SliceArgument represents max # of bytes.")
+    ("DependentSliceMode",     m_iDependentSliceMode,    0, "0: Disable all dependent slice limits, 1: Enforce max # of LCUs, 2: Enforce constraint based dependent slices")
+    ("DependentSliceArgument", m_iDependentSliceArgument,0, "if DependentSliceMode==1 SliceArgument represents max # of LCUs. if DependentSliceMode==2 DependentSliceArgument represents max # of bins.")
+#if DEPENDENT_SLICES
+#if TILES_WPP_ENTROPYSLICES_FLAGS
+    ("EntropySliceEnabledFlag", m_entropySliceEnabledFlag, false, "Enable use of entropy slices instead of dependent slices." )
+#else
+    ("CabacIndependentFlag", m_bCabacIndependentFlag, false)
+#endif
+#endif
+#if !REMOVE_FGS
+    ("SliceGranularity",     m_iSliceGranularity,    0, "0: Slices always end at LCU borders. 1-3: slices may end at a depth of 1-3 below LCU level.")
+#endif
+    ("LFCrossSliceBoundaryFlag", m_bLFCrossSliceBoundaryFlag, true)
+
+    ("ConstrainedIntraPred", m_bUseConstrainedIntraPred, false, "Constrained Intra Prediction")
+    ("PCMEnabledFlag", m_usePCM         , false)
+    ("PCMLog2MaxSize", m_pcmLog2MaxSize, 5u)
+    ("PCMLog2MinSize", m_uiPCMLog2MinSize, 3u)
+
+    ("PCMInputBitDepthFlag", m_bPCMInputBitDepthFlag, true)
+    ("PCMFilterDisableFlag", m_bPCMFilterDisableFlag, false)
+    ("LosslessCuEnabled", m_useLossless, false)
+    ("weighted_pred_flag,-wpP",     m_bUseWeightPred, false, "weighted prediction flag (P-Slices)")
+    ("weighted_bipred_flag,-wpB",   m_useWeightedBiPred,    false,    "weighted bipred flag (B-Slices)")
+    ("Log2ParallelMergeLevel",      m_log2ParallelMergeLevel,     2u,          "Parallel merge estimation region")
+    ("UniformSpacingIdc",           m_iUniformSpacingIdr,            0,          "Indicates if the column and row boundaries are distributed uniformly")
+    ("NumTileColumnsMinus1",        m_iNumColumnsMinus1,             0,          "Number of columns in a picture minus 1")
+    ("ColumnWidthArray",            cfg_ColumnWidth,                 string(""), "Array containing ColumnWidth values in units of LCU")
+    ("NumTileRowsMinus1",           m_iNumRowsMinus1,                0,          "Number of rows in a picture minus 1")
+    ("RowHeightArray",              cfg_RowHeight,                   string(""), "Array containing RowHeight values in units of LCU")
+    ("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 TR; 2 TRR etc")
+    ("ScalingList",                 m_useScalingListId,              0,          "0: no scaling list, 1: default scaling lists, 2: scaling lists specified in ScalingListFile")
+    ("ScalingListFile",             cfg_ScalingListFile,             string(""), "Scaling list file name")
+    ("SignHideFlag,-SBH",                m_signHideFlag, 1)
+    ("MaxNumMergeCand",             m_maxNumMergeCand,             5u,         "Maximum number of merge candidates")
+
+  /* Misc. */
+  ("SEIpictureDigest",  m_decodePictureHashSEIEnabled, 0, "Control generation of decode picture hash SEI messages\n"
+                                              "\t3: checksum\n"
+                                              "\t2: CRC\n"
+                                              "\t1: use MD5\n"
+                                              "\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")
+  ("ECU", m_bUseEarlyCU, false, "Early CU setting") 
+  ("FDM", m_useFastDecisionForMerge, true, "Fast decision for Merge RD Cost") 
+  ("CFM", m_bUseCbfFastMode, false, "Cbf fast mode setting")
+  ("ESD", m_useEarlySkipDetection, false, "Early SKIP detection setting")
+  ("RateCtrl,-rc", m_enableRateCtrl, false, "Rate control on/off")
+  ("TargetBitrate,-tbr", m_targetBitrate, 0, "Input target bitrate")
+  ("NumLCUInUnit,-nu", m_numLCUInUnit, 0, "Number of LCUs in an Unit")
+
+  ("TransquantBypassEnableFlag", m_TransquantBypassEnableFlag, false, "transquant_bypass_enable_flag indicator in PPS")
+  ("CUTransquantBypassFlagValue", m_CUTransquantBypassFlagValue, false, "Fixed cu_transquant_bypass_flag value, when transquant_bypass_enable_flag is enabled")
+#if RECALCULATE_QP_ACCORDING_LAMBDA
+  ("RecalculateQPAccordingToLambda", m_recalculateQPAccordingToLambda, false, "Recalculate QP values according to lambda values. Do not suggest to be enabled in all intra case")
+#endif
+#if ACTIVE_PARAMETER_SETS_SEI_MESSAGE 
+  ("ActiveParameterSets", m_activeParameterSetsSEIEnabled, 0, "Control generation of active parameter sets SEI messages\n"
+                                                              "\t2: enable active parameter sets SEI message with active_sps_id\n"
+                                                              "\t1: enable active parameter sets SEI message without active_sps_id\n"
+                                                              "\t0: disable")
+#endif 
+#if SUPPORT_FOR_VUI
+  ("VuiParametersPresent,-vui",      m_vuiParametersPresentFlag,           false, "Enable generation of vui_parameters()")
+  ("AspectRatioInfoPresent",         m_aspectRatioInfoPresentFlag,         false, "Signals whether aspect_ratio_idc is present")
+  ("AspectRatioIdc",                 m_aspectRatioIdc,                         0, "aspect_ratio_idc")
+  ("SarWidth",                       m_sarWidth,                               0, "horizontal size of the sample aspect ratio")
+  ("SarHeight",                      m_sarHeight,                              0, "vertical size of the sample aspect ratio")
+  ("OverscanInfoPresent",            m_overscanInfoPresentFlag,            false, "Indicates whether cropped decoded pictures are suitable for display using overscan\n")
+  ("OverscanAppropriate",            m_overscanAppropriateFlag,            false, "Indicates whether cropped decoded pictures are suitable for display using overscan\n")
+  ("VideoSignalTypePresent",         m_videoSignalTypePresentFlag,         false, "Signals whether video_format, video_full_range_flag, and colour_description_present_flag are present")
+  ("VideoFormat",                    m_videoFormat,                            5, "Indicates representation of pictures")
+  ("VideoFullRange",                 m_videoFullRangeFlag,                 false, "Indicates the black level and range of luma and chroma signals")
+  ("ColourDescriptionPresent",       m_colourDescriptionPresentFlag,       false, "Signals whether colour_primaries, transfer_characteristics and matrix_coefficients are present")
+  ("ColourPrimaries",                m_colourPrimaries,                        2, "Indicates chromaticity coordinates of the source primaries")
+  ("TransferCharateristics",         m_transferCharacteristics,                2, "Indicates the opto-electronic transfer characteristics of the source")
+  ("MatrixCoefficients",             m_matrixCoefficients,                     2, "Describes the matrix coefficients used in deriving luma and chroma from RGB primaries")
+  ("ChromaLocInfoPresent",           m_chromaLocInfoPresentFlag,           false, "Signals whether chroma_sample_loc_type_top_field and chroma_sample_loc_type_bottom_field are present")
+  ("ChromaSampleLocTypeTopField",    m_chromaSampleLocTypeTopField,            0, "Specifies the location of chroma samples for top field")
+  ("ChromaSampleLocTypeBottomField", m_chromaSampleLocTypeBottomField,         0, "Specifies the location of chroma samples for bottom field")
+  ("NeutralChromaIndication",        m_neutralChromaIndicationFlag,        false, "Indicates that the value of all decoded chroma samples is equal to 1<<(BitDepthCr-1)")
+  ("BitstreamRestriction",           m_bitstreamRestrictionFlag,           false, "Signals whether bitstream restriction parameters are present")
+  ("TilesFixedStructure",            m_tilesFixedStructureFlag,            false, "Indicates that each active picture parameter set has the same values of the syntax elements related to tiles")
+  ("MotionVectorsOverPicBoundaries", m_motionVectorsOverPicBoundariesFlag, false, "Indicates that no samples outside the picture boundaries are used for inter prediction")
+  ("MaxBytesPerPicDenom",            m_maxBytesPerPicDenom,                    2, "Indicates a number of bytes not exceeded by the sum of the sizes of the VCL NAL units associated with any coded picture")
+  ("MaxBitsPerMinCuDenom",           m_maxBitsPerMinCuDenom,                   1, "Indicates an upper bound for the number of bits of coding_unit() data")
+  ("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")
+#endif
+#if RECOVERY_POINT_SEI
+  ("SEIRecoveryPoint",               m_recoveryPointSEIEnabled,                0, "Control generation of recovery point SEI messages")
+#endif
+#if BUFFERING_PERIOD_AND_TIMING_SEI
+  ("SEIBufferingPeriod",             m_bufferingPeriodSEIEnabled,              0, "Control generation of buffering period SEI messages")
+  ("SEIPictureTiming",               m_pictureTimingSEIEnabled,                0, "Control generation of picture timing SEI messages")
+#endif
+  ;
+  
+  for(Int i=1; i<MAX_GOP+1; i++) {
+    std::ostringstream cOSS;
+    cOSS<<"Frame"<<i;
+    opts.addOptions()(cOSS.str(), m_GOPList[i-1], GOPEntry());
+  }
+  po::setDefaults(opts);
+  const list<const char*>& argv_unhandled = po::scanArgv(opts, argc, (const char**) argv);
+
+  for (list<const char*>::const_iterator it = argv_unhandled.begin(); it != argv_unhandled.end(); it++)
+  {
+    fprintf(stderr, "Unhandled argument ignored: `%s'\n", *it);
+  }
+  
+  if (argc == 1 || do_help)
+  {
+    /* argc == 1: no options have been specified */
+    po::doHelp(cout, opts);
+    return false;
+  }
+  
+  /*
+   * Set any derived parameters
+   */
+  /* convert std::string to c string for compatability */
+#if SVC_EXTENSION
+  m_pchBitstreamFile = cfg_BitstreamFile.empty() ? NULL : strdup(cfg_BitstreamFile.c_str());
+#else
+  m_pchInputFile = cfg_InputFile.empty() ? NULL : strdup(cfg_InputFile.c_str());
+  m_pchBitstreamFile = cfg_BitstreamFile.empty() ? NULL : strdup(cfg_BitstreamFile.c_str());
+  m_pchReconFile = cfg_ReconFile.empty() ? NULL : strdup(cfg_ReconFile.c_str());
+  m_pchdQPFile = cfg_dQPFile.empty() ? NULL : strdup(cfg_dQPFile.c_str());
+#endif
+  
+  m_pchColumnWidth = cfg_ColumnWidth.empty() ? NULL: strdup(cfg_ColumnWidth.c_str());
+  m_pchRowHeight = cfg_RowHeight.empty() ? NULL : strdup(cfg_RowHeight.c_str());
+  m_scalingListFile = cfg_ScalingListFile.empty() ? NULL : strdup(cfg_ScalingListFile.c_str());
+ 
+#if !SVC_EXTENSION
+  // TODO:ChromaFmt assumes 4:2:0 below
+  switch (m_croppingMode)
+  {
+  case 0:
+    {
+      // no cropping or padding
+      m_cropLeft = m_cropRight = m_cropTop = m_cropBottom = 0;
+      m_aiPad[1] = m_aiPad[0] = 0;
+      break;
+    }
+  case 1:
+    {
+      // automatic padding to minimum CU size
+      Int minCuSize = m_uiMaxCUHeight >> (m_uiMaxCUDepth - 1);
+      if (m_iSourceWidth % minCuSize)
+      {
+        m_aiPad[0] = m_cropRight  = ((m_iSourceWidth / minCuSize) + 1) * minCuSize - m_iSourceWidth;
+        m_iSourceWidth  += m_cropRight;
+      }
+      if (m_iSourceHeight % minCuSize)
+      {
+        m_aiPad[1] = m_cropBottom = ((m_iSourceHeight / minCuSize) + 1) * minCuSize - m_iSourceHeight;
+        m_iSourceHeight += m_cropBottom;
+      }
+      if (m_aiPad[0] % TComSPS::getCropUnitX(CHROMA_420) != 0)
+      {
+        fprintf(stderr, "Error: picture width is not an integer multiple of the specified chroma subsampling\n");
+        exit(EXIT_FAILURE);
+      }
+      if (m_aiPad[1] % TComSPS::getCropUnitY(CHROMA_420) != 0)
+      {
+        fprintf(stderr, "Error: picture height is not an integer multiple of the specified chroma subsampling\n");
+        exit(EXIT_FAILURE);
+      }
+      break;
+    }
+  case 2:
+    {
+      //padding
+      m_iSourceWidth  += m_aiPad[0];
+      m_iSourceHeight += m_aiPad[1];
+      m_cropRight  = m_aiPad[0];
+      m_cropBottom = m_aiPad[1];
+      break;
+    }
+  case 3:
+    {
+      // cropping
+      if ((m_cropLeft == 0) && (m_cropRight == 0) && (m_cropTop == 0) && (m_cropBottom == 0))
+      {
+        fprintf(stderr, "Warning: Cropping enabled, but all cropping parameters set to zero\n");
+      }
+      if ((m_aiPad[1] != 0) || (m_aiPad[0]!=0))
+      {
+        fprintf(stderr, "Warning: Cropping enabled, padding parameters will be ignored\n");
+      }
+      m_aiPad[1] = m_aiPad[0] = 0;
+      break;
+    }
+  }
+  
+  // allocate slice-based dQP values
+  m_aidQP = new Int[ m_iFrameToBeEncoded + m_iGOPSize + 1 ];
+  ::memset( m_aidQP, 0, sizeof(Int)*( m_iFrameToBeEncoded + m_iGOPSize + 1 ) );
+  
+  // handling of floating-point QP values
+  // if QP is not integer, sequence is split into two sections having QP and QP+1
+  m_iQP = (Int)( m_fQP );
+  if ( m_iQP < m_fQP )
+  {
+    Int iSwitchPOC = (Int)( m_iFrameToBeEncoded - (m_fQP - m_iQP)*m_iFrameToBeEncoded + 0.5 );
+    
+    iSwitchPOC = (Int)( (Double)iSwitchPOC / m_iGOPSize + 0.5 )*m_iGOPSize;
+    for ( Int i=iSwitchPOC; i<m_iFrameToBeEncoded + m_iGOPSize + 1; i++ )
+    {
+      m_aidQP[i] = 1;
+    }
+  }
+  
+  // reading external dQP description from file
+  if ( m_pchdQPFile )
+  {
+    FILE* fpt=fopen( m_pchdQPFile, "r" );
+    if ( fpt )
+    {
+      Int iValue;
+      Int iPOC = 0;
+      while ( iPOC < m_iFrameToBeEncoded )
+      {
+        if ( fscanf(fpt, "%d", &iValue ) == EOF ) break;
+        m_aidQP[ iPOC ] = iValue;
+        iPOC++;
+      }
+      fclose(fpt);
+    }
+  }
+  m_iWaveFrontSubstreams = m_iWaveFrontSynchro ? (m_iSourceHeight + m_uiMaxCUHeight - 1) / m_uiMaxCUHeight : 1; 
+#endif
+  // check validity of input parameters
+  xCheckParameter();
+  
+  // set global varibles
+  xSetGlobal();
+  
+  // print-out parameters
+  xPrintParameter();
+  
+  return true;
+}
+
+// ====================================================================================================================
+// Private member functions
+// ====================================================================================================================
+
+Bool confirmPara(Bool bflag, const char* message);
+
+Void TAppEncCfg::xCheckParameter()
+{
+  if (!m_decodePictureHashSEIEnabled)
+  {
+    fprintf(stderr, "*************************************************************\n");
+    fprintf(stderr, "** WARNING: --SEIpictureDigest is now disabled by default. **\n");
+    fprintf(stderr, "**          Automatic verification of decoded pictures by  **\n");
+    fprintf(stderr, "**          a decoder requires this option to be enabled.  **\n");
+    fprintf(stderr, "*************************************************************\n");
+  }
+
+  bool check_failed = false; /* abort if there is a fatal configuration problem */
+#define xConfirmPara(a,b) check_failed |= confirmPara(a,b)
+  // check range of parameters
+  xConfirmPara( m_uiInputBitDepth < 8,                                                      "InputBitDepth must be at least 8" );
+#if !SVC_EXTENSION
+  xConfirmPara( m_iFrameRate <= 0,                                                          "Frame rate must be more than 1" );
+#endif
+  xConfirmPara( m_iFrameToBeEncoded <= 0,                                                   "Total Number Of Frames encoded must be more than 0" );
+  xConfirmPara( m_iGOPSize < 1 ,                                                            "GOP Size must be greater or equal to 1" );
+  xConfirmPara( m_iGOPSize > 1 &&  m_iGOPSize % 2,                                          "GOP Size must be a multiple of 2, if GOP Size is greater than 1" );
+#if !SVC_EXTENSION
+  xConfirmPara( (m_iIntraPeriod > 0 && m_iIntraPeriod < m_iGOPSize) || m_iIntraPeriod == 0, "Intra period must be more than GOP size, or -1 , not 0" );
+#endif
+  xConfirmPara( m_iDecodingRefreshType < 0 || m_iDecodingRefreshType > 2,                   "Decoding Refresh Type must be equal to 0, 1 or 2" );
+#if !SVC_EXTENSION
+  xConfirmPara( m_iQP <  -6 * ((Int)m_uiInternalBitDepth - 8) || m_iQP > 51,                "QP exceeds supported range (-QpBDOffsety to 51)" );
+#endif
+  xConfirmPara( m_loopFilterBetaOffsetDiv2 < -13 || m_loopFilterBetaOffsetDiv2 > 13,          "Loop Filter Beta Offset div. 2 exceeds supported range (-13 to 13)");
+  xConfirmPara( m_loopFilterTcOffsetDiv2 < -13 || m_loopFilterTcOffsetDiv2 > 13,              "Loop Filter Tc Offset div. 2 exceeds supported range (-13 to 13)");
+  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_iMaxDeltaQP > 7,                                                          "Absolute Delta QP exceeds supported range (0 to 7)" );
+  xConfirmPara( m_iMaxCuDQPDepth > m_uiMaxCUDepth - 1,                                          "Absolute depth for a minimum CuDQP exceeds maximum coding unit depth" );
+
+  xConfirmPara( m_cbQpOffset < -12,   "Min. Chroma Cb QP Offset is -12" );
+  xConfirmPara( m_cbQpOffset >  12,   "Max. Chroma Cb QP Offset is  12" );
+  xConfirmPara( m_crQpOffset < -12,   "Min. Chroma Cr QP Offset is -12" );
+  xConfirmPara( m_crQpOffset >  12,   "Max. Chroma Cr QP Offset is  12" );
+
+  xConfirmPara( m_iQPAdaptationRange <= 0,                                                  "QP Adaptation Range must be more than 0" );
+#if !SVC_EXTENSION
+  if (m_iDecodingRefreshType == 2)
+  {
+    xConfirmPara( m_iIntraPeriod > 0 && m_iIntraPeriod <= m_iGOPSize ,                      "Intra period must be larger than GOP size for periodic IDR pictures");
+  }
+#endif
+  xConfirmPara( (m_uiMaxCUWidth  >> m_uiMaxCUDepth) < 4,                                    "Minimum partition width size should be larger than or equal to 8");
+  xConfirmPara( (m_uiMaxCUHeight >> m_uiMaxCUDepth) < 4,                                    "Minimum partition height size should be larger than or equal to 8");
+  xConfirmPara( m_uiMaxCUWidth < 16,                                                        "Maximum partition width size should be larger than or equal to 16");
+  xConfirmPara( m_uiMaxCUHeight < 16,                                                       "Maximum partition height size should be larger than or equal to 16");
+#if !SVC_EXTENSION
+  xConfirmPara( (m_iSourceWidth  % (m_uiMaxCUWidth  >> (m_uiMaxCUDepth-1)))!=0,             "Resulting coded frame width must be a multiple of the minimum CU size");
+  xConfirmPara( (m_iSourceHeight % (m_uiMaxCUHeight >> (m_uiMaxCUDepth-1)))!=0,             "Resulting coded frame height must be a multiple of the minimum CU size");
+#endif
+  
+  xConfirmPara( m_uiQuadtreeTULog2MinSize < 2,                                        "QuadtreeTULog2MinSize must be 2 or greater.");
+  xConfirmPara( m_uiQuadtreeTULog2MinSize > 5,                                        "QuadtreeTULog2MinSize must be 5 or smaller.");
+  xConfirmPara( m_uiQuadtreeTULog2MaxSize < 2,                                        "QuadtreeTULog2MaxSize must be 2 or greater.");
+  xConfirmPara( m_uiQuadtreeTULog2MaxSize > 5,                                        "QuadtreeTULog2MaxSize must be 5 or smaller.");
+  xConfirmPara( m_uiQuadtreeTULog2MaxSize < m_uiQuadtreeTULog2MinSize,                "QuadtreeTULog2MaxSize must be greater than or equal to m_uiQuadtreeTULog2MinSize.");
+  xConfirmPara( (1<<m_uiQuadtreeTULog2MinSize)>(m_uiMaxCUWidth >>(m_uiMaxCUDepth-1)), "QuadtreeTULog2MinSize must not be greater than minimum CU size" ); // HS
+  xConfirmPara( (1<<m_uiQuadtreeTULog2MinSize)>(m_uiMaxCUHeight>>(m_uiMaxCUDepth-1)), "QuadtreeTULog2MinSize must not be greater than minimum CU size" ); // HS
+  xConfirmPara( ( 1 << m_uiQuadtreeTULog2MinSize ) > ( m_uiMaxCUWidth  >> m_uiMaxCUDepth ), "Minimum CU width must be greater than minimum transform size." );
+  xConfirmPara( ( 1 << m_uiQuadtreeTULog2MinSize ) > ( m_uiMaxCUHeight >> m_uiMaxCUDepth ), "Minimum CU height must be greater than minimum transform size." );
+  xConfirmPara( m_uiQuadtreeTUMaxDepthInter < 1,                                                         "QuadtreeTUMaxDepthInter must be greater than or equal to 1" );
+  xConfirmPara( m_uiQuadtreeTUMaxDepthInter > m_uiQuadtreeTULog2MaxSize - m_uiQuadtreeTULog2MinSize + 1, "QuadtreeTUMaxDepthInter must be less than or equal to the difference between QuadtreeTULog2MaxSize and QuadtreeTULog2MinSize plus 1" );
+  xConfirmPara( m_uiQuadtreeTUMaxDepthIntra < 1,                                                         "QuadtreeTUMaxDepthIntra must be greater than or equal to 1" );
+  xConfirmPara( m_uiQuadtreeTUMaxDepthIntra > m_uiQuadtreeTULog2MaxSize - m_uiQuadtreeTULog2MinSize + 1, "QuadtreeTUMaxDepthIntra must be less than or equal to the difference between QuadtreeTULog2MaxSize and QuadtreeTULog2MinSize plus 1" );
+  
+  xConfirmPara(  m_maxNumMergeCand < 1,  "MaxNumMergeCand must be 1 or greater.");
+  xConfirmPara(  m_maxNumMergeCand > 5,  "MaxNumMergeCand must be 5 or smaller.");
+
+#if !SVC_EXTENSION
+#if ADAPTIVE_QP_SELECTION
+  xConfirmPara( m_bUseAdaptQpSelect == true && m_iQP < 0,                                              "AdaptiveQpSelection must be disabled when QP < 0.");
+  xConfirmPara( m_bUseAdaptQpSelect == true && (m_cbQpOffset !=0 || m_crQpOffset != 0 ),               "AdaptiveQpSelection must be disabled when ChromaQpOffset is not equal to 0.");
+#endif
+#endif
+
+  if( m_usePCM)
+  {
+    xConfirmPara(  m_uiPCMLog2MinSize < 3,                                      "PCMLog2MinSize must be 3 or greater.");
+    xConfirmPara(  m_uiPCMLog2MinSize > 5,                                      "PCMLog2MinSize must be 5 or smaller.");
+    xConfirmPara(  m_pcmLog2MaxSize > 5,                                        "PCMLog2MaxSize must be 5 or smaller.");
+    xConfirmPara(  m_pcmLog2MaxSize < m_uiPCMLog2MinSize,                       "PCMLog2MaxSize must be equal to or greater than m_uiPCMLog2MinSize.");
+  }
+
+  xConfirmPara( m_iSliceMode < 0 || m_iSliceMode > 3, "SliceMode exceeds supported range (0 to 3)" );
+  if (m_iSliceMode!=0)
+  {
+    xConfirmPara( m_iSliceArgument < 1 ,         "SliceArgument should be larger than or equal to 1" );
+  }
+#if !REMOVE_FGS
+  if (m_iSliceMode==3)
+  {
+    xConfirmPara( m_iSliceGranularity > 0 ,      "When SliceMode == 3 is chosen, the SliceGranularity must be 0" );
+  }
+#endif
+  xConfirmPara( m_iDependentSliceMode < 0 || m_iDependentSliceMode > 2, "DependentSliceMode exceeds supported range (0 to 2)" );
+  if (m_iDependentSliceMode!=0)
+  {
+    xConfirmPara( m_iDependentSliceArgument < 1 ,         "DependentSliceArgument should be larger than or equal to 1" );
+  }
+#if !REMOVE_FGS
+  xConfirmPara( m_iSliceGranularity >= m_uiMaxCUDepth, "SliceGranularity must be smaller than maximum cu depth");
+  xConfirmPara( m_iSliceGranularity <0 || m_iSliceGranularity > 3, "SliceGranularity exceeds supported range (0 to 3)" );
+  xConfirmPara( m_iSliceGranularity > m_iMaxCuDQPDepth, "SliceGranularity must be smaller smaller than or equal to maximum dqp depth" );
+#endif
+  
+  bool tileFlag = (m_iNumColumnsMinus1 > 0 || m_iNumRowsMinus1 > 0 );
+#if !TILES_WPP_ENTROPYSLICES_FLAGS
+  xConfirmPara( tileFlag && m_iDependentSliceMode,            "Tile and Dependent Slice can not be applied together");
+#endif
+  xConfirmPara( tileFlag && m_iWaveFrontSynchro,            "Tile and Wavefront can not be applied together");
+#if !DEPENDENT_SLICES
+  xConfirmPara( m_iWaveFrontSynchro && m_iDependentSliceMode, "Wavefront and Dependent Slice can not be applied together");
+#endif
+#if DEPENDENT_SLICES
+#if TILES_WPP_ENTROPYSLICES_FLAGS
+  xConfirmPara( m_iWaveFrontSynchro && m_entropySliceEnabledFlag, "WaveFrontSynchro and EntropySliceEnabledFlag can not be applied together");
+#else
+  xConfirmPara( m_iWaveFrontSynchro && m_bCabacIndependentFlag, "Wavefront and CabacIndependentFlag can not be applied together");
+#endif
+#endif
+
+  //TODO:ChromaFmt assumes 4:2:0 below
+#if !SVC_EXTENSION
+  xConfirmPara( m_iSourceWidth  % TComSPS::getCropUnitX(CHROMA_420) != 0, "Picture width must be an integer multiple of the specified chroma subsampling");
+  xConfirmPara( m_iSourceHeight % TComSPS::getCropUnitY(CHROMA_420) != 0, "Picture height must be an integer multiple of the specified chroma subsampling");
+#endif
+
+#if !SVC_EXTENSION 
+  xConfirmPara( m_aiPad[0] % TComSPS::getCropUnitX(CHROMA_420) != 0, "Horizontal padding must be an integer multiple of the specified chroma subsampling");
+  xConfirmPara( m_aiPad[1] % TComSPS::getCropUnitY(CHROMA_420) != 0, "Vertical padding must be an integer multiple of the specified chroma subsampling");
+
+  xConfirmPara( m_cropLeft   % TComSPS::getCropUnitX(CHROMA_420) != 0, "Left cropping must be an integer multiple of the specified chroma subsampling");
+  xConfirmPara( m_cropRight  % TComSPS::getCropUnitX(CHROMA_420) != 0, "Right cropping must be an integer multiple of the specified chroma subsampling");
+  xConfirmPara( m_cropTop    % TComSPS::getCropUnitY(CHROMA_420) != 0, "Top cropping must be an integer multiple of the specified chroma subsampling");
+  xConfirmPara( m_cropBottom % TComSPS::getCropUnitY(CHROMA_420) != 0, "Bottom cropping must be an integer multiple of the specified chroma subsampling");
+#endif
+
+  // max CU width and height should be power of 2
+  UInt ui = m_uiMaxCUWidth;
+  while(ui)
+  {
+    ui >>= 1;
+    if( (ui & 1) == 1)
+      xConfirmPara( ui != 1 , "Width should be 2^n");
+  }
+  ui = m_uiMaxCUHeight;
+  while(ui)
+  {
+    ui >>= 1;
+    if( (ui & 1) == 1)
+      xConfirmPara( ui != 1 , "Height should be 2^n");
+  }
+  
+  Bool verifiedGOP=false;
+  Bool errorGOP=false;
+  Int checkGOP=1;
+  Int numRefs = 1;
+  Int refList[MAX_NUM_REF_PICS+1];
+  refList[0]=0;
+  Bool isOK[MAX_GOP];
+  for(Int i=0; i<MAX_GOP; i++) 
+  {
+    isOK[i]=false;
+  }
+  Int numOK=0;
+#if !SVC_EXTENSION
+  xConfirmPara( m_iIntraPeriod >=0&&(m_iIntraPeriod%m_iGOPSize!=0), "Intra period must be a multiple of GOPSize, or -1" );
+#endif
+
+  for(Int i=0; i<m_iGOPSize; i++)
+  {
+    if(m_GOPList[i].m_POC==m_iGOPSize)
+    {
+      xConfirmPara( m_GOPList[i].m_temporalId!=0 , "The last frame in each GOP must have temporal ID = 0 " );
+    }
+  }
+  
+  m_extraRPSs=0;
+
+#if SVC_EXTENSION
+  // verify layer configuration parameters
+  for(UInt layer=0; layer<m_numLayers; layer++)
+  {
+    if(m_acLayerCfg[layer].xCheckParameter())
+    {
+      printf("\nError: invalid configuration parameter found in layer %d \n", layer);
+      check_failed = true;
+    }
+  }
+#endif
+
+  //start looping through frames in coding order until we can verify that the GOP structure is correct.
+  while(!verifiedGOP&&!errorGOP) 
+  {
+    Int curGOP = (checkGOP-1)%m_iGOPSize;
+    Int curPOC = ((checkGOP-1)/m_iGOPSize)*m_iGOPSize + m_GOPList[curGOP].m_POC;    
+    if(m_GOPList[curGOP].m_POC<0) 
+    {
+      printf("\nError: found fewer Reference Picture Sets than GOPSize\n");
+      errorGOP=true;
+    }
+    else 
+    {
+      //check that all reference pictures are available, or have a POC < 0 meaning they might be available in the next GOP.
+      Bool beforeI = false;
+      for(Int i = 0; i< m_GOPList[curGOP].m_numRefPics; i++) 
+      {
+        Int absPOC = curPOC+m_GOPList[curGOP].m_referencePics[i];
+        if(absPOC < 0)
+        {
+          beforeI=true;
+        }
+        else 
+        {
+          Bool found=false;
+          for(Int j=0; j<numRefs; j++) 
+          {
+            if(refList[j]==absPOC) 
+            {
+              found=true;
+              for(Int k=0; k<m_iGOPSize; k++)
+              {
+                if(absPOC%m_iGOPSize == m_GOPList[k].m_POC%m_iGOPSize)
+                {
+#if TEMPORAL_LAYER_NON_REFERENCE
+                  if(m_GOPList[k].m_temporalId==m_GOPList[curGOP].m_temporalId)
+                  {
+                    m_GOPList[k].m_refPic = true;
+                  }
+#endif
+                  m_GOPList[curGOP].m_usedByCurrPic[i]=m_GOPList[k].m_temporalId<=m_GOPList[curGOP].m_temporalId;
+                }
+              }
+            }
+          }
+          if(!found)
+          {
+            printf("\nError: ref pic %d is not available for GOP frame %d\n",m_GOPList[curGOP].m_referencePics[i],curGOP+1);
+            errorGOP=true;
+          }
+        }
+      }
+      if(!beforeI&&!errorGOP)
+      {
+        //all ref frames were present
+        if(!isOK[curGOP]) 
+        {
+          numOK++;
+          isOK[curGOP]=true;
+          if(numOK==m_iGOPSize)
+          {
+            verifiedGOP=true;
+          }
+        }
+      }
+      else 
+      {
+        //create a new GOPEntry for this frame containing all the reference pictures that were available (POC > 0)
+        m_GOPList[m_iGOPSize+m_extraRPSs]=m_GOPList[curGOP];
+        Int newRefs=0;
+        for(Int i = 0; i< m_GOPList[curGOP].m_numRefPics; i++) 
+        {
+          Int absPOC = curPOC+m_GOPList[curGOP].m_referencePics[i];
+          if(absPOC>=0)
+          {
+            m_GOPList[m_iGOPSize+m_extraRPSs].m_referencePics[newRefs]=m_GOPList[curGOP].m_referencePics[i];
+            m_GOPList[m_iGOPSize+m_extraRPSs].m_usedByCurrPic[newRefs]=m_GOPList[curGOP].m_usedByCurrPic[i];
+            newRefs++;
+          }
+        }
+        Int numPrefRefs = m_GOPList[curGOP].m_numRefPicsActive;
+        
+        for(Int offset = -1; offset>-checkGOP; offset--)
+        {
+          //step backwards in coding order and include any extra available pictures we might find useful to replace the ones with POC < 0.
+          Int offGOP = (checkGOP-1+offset)%m_iGOPSize;
+          Int offPOC = ((checkGOP-1+offset)/m_iGOPSize)*m_iGOPSize + m_GOPList[offGOP].m_POC;
+#if TEMPORAL_LAYER_NON_REFERENCE
+          if(offPOC>=0&&m_GOPList[offGOP].m_temporalId<=m_GOPList[curGOP].m_temporalId)
+#else
+          if(offPOC>=0&&m_GOPList[offGOP].m_refPic&&m_GOPList[offGOP].m_temporalId<=m_GOPList[curGOP].m_temporalId) 
+#endif
+          {
+            Bool newRef=false;
+            for(Int i=0; i<numRefs; i++)
+            {
+              if(refList[i]==offPOC)
+              {
+                newRef=true;
+              }
+            }
+            for(Int i=0; i<newRefs; i++) 
+            {
+              if(m_GOPList[m_iGOPSize+m_extraRPSs].m_referencePics[i]==offPOC-curPOC)
+              {
+                newRef=false;
+              }
+            }
+            if(newRef) 
+            {
+              Int insertPoint=newRefs;
+              //this picture can be added, find appropriate place in list and insert it.
+#if TEMPORAL_LAYER_NON_REFERENCE
+              if(m_GOPList[offGOP].m_temporalId==m_GOPList[curGOP].m_temporalId)
+              {
+                m_GOPList[offGOP].m_refPic = true;
+              }
+#endif
+              for(Int j=0; j<newRefs; j++)
+              {
+                if(m_GOPList[m_iGOPSize+m_extraRPSs].m_referencePics[j]<offPOC-curPOC||m_GOPList[m_iGOPSize+m_extraRPSs].m_referencePics[j]>0)
+                {
+                  insertPoint = j;
+                  break;
+                }
+              }
+              Int prev = offPOC-curPOC;
+              Int prevUsed = m_GOPList[offGOP].m_temporalId<=m_GOPList[curGOP].m_temporalId;
+              for(Int j=insertPoint; j<newRefs+1; j++)
+              {
+                Int newPrev = m_GOPList[m_iGOPSize+m_extraRPSs].m_referencePics[j];
+                Int newUsed = m_GOPList[m_iGOPSize+m_extraRPSs].m_usedByCurrPic[j];
+                m_GOPList[m_iGOPSize+m_extraRPSs].m_referencePics[j]=prev;
+                m_GOPList[m_iGOPSize+m_extraRPSs].m_usedByCurrPic[j]=prevUsed;
+                prevUsed=newUsed;
+                prev=newPrev;
+              }
+              newRefs++;
+            }
+          }
+          if(newRefs>=numPrefRefs)
+          {
+            break;
+          }
+        }
+        m_GOPList[m_iGOPSize+m_extraRPSs].m_numRefPics=newRefs;
+        m_GOPList[m_iGOPSize+m_extraRPSs].m_POC = curPOC;
+        if (m_extraRPSs == 0)
+        {
+          m_GOPList[m_iGOPSize+m_extraRPSs].m_interRPSPrediction = 0;
+          m_GOPList[m_iGOPSize+m_extraRPSs].m_numRefIdc = 0;
+        }
+        else
+        {
+          Int rIdx =  m_iGOPSize + m_extraRPSs - 1;
+          Int refPOC = m_GOPList[rIdx].m_POC;
+          Int refPics = m_GOPList[rIdx].m_numRefPics;
+          Int newIdc=0;
+          for(Int i = 0; i<= refPics; i++) 
+          {
+            Int deltaPOC = ((i != refPics)? m_GOPList[rIdx].m_referencePics[i] : 0);  // check if the reference abs POC is >= 0
+            Int absPOCref = refPOC+deltaPOC;
+            Int refIdc = 0;
+            for (Int j = 0; j < m_GOPList[m_iGOPSize+m_extraRPSs].m_numRefPics; j++)
+            {
+              if ( (absPOCref - curPOC) == m_GOPList[m_iGOPSize+m_extraRPSs].m_referencePics[j])
+              {
+                if (m_GOPList[m_iGOPSize+m_extraRPSs].m_usedByCurrPic[j])
+                {
+                  refIdc = 1;
+                }
+                else
+                {
+                  refIdc = 2;
+                }
+              }
+            }
+            m_GOPList[m_iGOPSize+m_extraRPSs].m_refIdc[newIdc]=refIdc;
+            newIdc++;
+          }
+          m_GOPList[m_iGOPSize+m_extraRPSs].m_interRPSPrediction = 1;  
+          m_GOPList[m_iGOPSize+m_extraRPSs].m_numRefIdc = newIdc;
+          m_GOPList[m_iGOPSize+m_extraRPSs].m_deltaRPS = refPOC - m_GOPList[m_iGOPSize+m_extraRPSs].m_POC; 
+#if !J0234_INTER_RPS_SIMPL
+          m_GOPList[m_iGOPSize+m_extraRPSs].m_deltaRIdxMinus1 = 0; 
+#endif
+        }
+        curGOP=m_iGOPSize+m_extraRPSs;
+        m_extraRPSs++;
+      }
+      numRefs=0;
+      for(Int i = 0; i< m_GOPList[curGOP].m_numRefPics; i++) 
+      {
+        Int absPOC = curPOC+m_GOPList[curGOP].m_referencePics[i];
+        if(absPOC >= 0) 
+        {
+          refList[numRefs]=absPOC;
+          numRefs++;
+        }
+      }
+      refList[numRefs]=curPOC;
+      numRefs++;
+    }
+    checkGOP++;
+  }
+  xConfirmPara(errorGOP,"Invalid GOP structure given");
+  m_maxTempLayer = 1;
+  for(Int i=0; i<m_iGOPSize; i++) 
+  {
+    if(m_GOPList[i].m_temporalId >= m_maxTempLayer)
+    {
+      m_maxTempLayer = m_GOPList[i].m_temporalId+1;
+    }
+    xConfirmPara(m_GOPList[i].m_sliceType!='B'&&m_GOPList[i].m_sliceType!='P', "Slice type must be equal to B or P");
+  }
+  for(Int i=0; i<MAX_TLAYER; i++)
+  {
+    m_numReorderPics[i] = 0;
+    m_maxDecPicBuffering[i] = 0;
+  }
+  for(Int i=0; i<m_iGOPSize; i++) 
+  {
+    if(m_GOPList[i].m_numRefPics > m_maxDecPicBuffering[m_GOPList[i].m_temporalId])
+    {
+      m_maxDecPicBuffering[m_GOPList[i].m_temporalId] = m_GOPList[i].m_numRefPics;
+    }
+    Int highestDecodingNumberWithLowerPOC = 0; 
+    for(Int j=0; j<m_iGOPSize; j++)
+    {
+      if(m_GOPList[j].m_POC <= m_GOPList[i].m_POC)
+      {
+        highestDecodingNumberWithLowerPOC = j;
+      }
+    }
+    Int numReorder = 0;
+    for(Int j=0; j<highestDecodingNumberWithLowerPOC; j++)
+    {
+      if(m_GOPList[j].m_temporalId <= m_GOPList[i].m_temporalId && 
+        m_GOPList[j].m_POC > m_GOPList[i].m_POC)
+      {
+        numReorder++;
+      }
+    }    
+    if(numReorder > m_numReorderPics[m_GOPList[i].m_temporalId])
+    {
+      m_numReorderPics[m_GOPList[i].m_temporalId] = numReorder;
+    }
+  }
+  for(Int i=0; i<MAX_TLAYER-1; i++) 
+  {
+    // a lower layer can not have higher value of m_numReorderPics than a higher layer
+    if(m_numReorderPics[i+1] < m_numReorderPics[i])
+    {
+      m_numReorderPics[i+1] = m_numReorderPics[i];
+    }
+    // the value of num_reorder_pics[ i ] shall be in the range of 0 to max_dec_pic_buffering[ i ], inclusive
+    if(m_numReorderPics[i] > m_maxDecPicBuffering[i])
+    {
+      m_maxDecPicBuffering[i] = m_numReorderPics[i];
+    }
+    // a lower layer can not have higher value of m_uiMaxDecPicBuffering than a higher layer
+    if(m_maxDecPicBuffering[i+1] < m_maxDecPicBuffering[i])
+    {
+      m_maxDecPicBuffering[i+1] = m_maxDecPicBuffering[i];
+    }
+  }
+  // the value of num_reorder_pics[ i ] shall be in the range of 0 to max_dec_pic_buffering[ i ], inclusive
+  if(m_numReorderPics[MAX_TLAYER-1] > m_maxDecPicBuffering[MAX_TLAYER-1])
+  {
+    m_maxDecPicBuffering[MAX_TLAYER-1] = m_numReorderPics[MAX_TLAYER-1];
+  }
+
+  xConfirmPara( m_bUseLComb==false && m_numReorderPics[MAX_TLAYER-1]!=0, "ListCombination can only be 0 in low delay coding (more precisely when L0 and L1 are identical)" );  // Note however this is not the full necessary condition as ref_pic_list_combination_flag can only be 0 if L0 == L1.
+  xConfirmPara( m_iWaveFrontSynchro < 0, "WaveFrontSynchro cannot be negative" );
+#if !SVC_EXTENSION
+  xConfirmPara( m_iWaveFrontSubstreams <= 0, "WaveFrontSubstreams must be positive" );
+  xConfirmPara( m_iWaveFrontSubstreams > 1 && !m_iWaveFrontSynchro, "Must have WaveFrontSynchro > 0 in order to have WaveFrontSubstreams > 1" );
+#endif
+
+  xConfirmPara( m_decodePictureHashSEIEnabled<0 || m_decodePictureHashSEIEnabled>3, "this hash type is not correct!\n");
+
+#if !SVC_EXTENSION 
+  if(m_enableRateCtrl)
+  {
+    Int numLCUInWidth  = (m_iSourceWidth  / m_uiMaxCUWidth) + (( m_iSourceWidth  %  m_uiMaxCUWidth ) ? 1 : 0);
+    Int numLCUInHeight = (m_iSourceHeight / m_uiMaxCUHeight)+ (( m_iSourceHeight %  m_uiMaxCUHeight) ? 1 : 0);
+    Int numLCUInPic    =  numLCUInWidth * numLCUInHeight;
+
+    xConfirmPara( (numLCUInPic % m_numLCUInUnit) != 0, "total number of LCUs in a frame should be completely divided by NumLCUInUnit" );
+
+    m_iMaxDeltaQP       = MAX_DELTA_QP;
+    m_iMaxCuDQPDepth    = MAX_CUDQP_DEPTH;
+  }
+#endif
+
+  xConfirmPara(!m_TransquantBypassEnableFlag && m_CUTransquantBypassFlagValue, "CUTransquantBypassFlagValue cannot be 1 when TransquantBypassEnableFlag is 0");
+
+  xConfirmPara(m_log2ParallelMergeLevel < 2, "Log2ParallelMergeLevel should be larger than or equal to 2");
+
+#if ACTIVE_PARAMETER_SETS_SEI_MESSAGE
+  xConfirmPara(m_activeParameterSetsSEIEnabled < 0 || m_activeParameterSetsSEIEnabled > 2, "ActiveParametersSEIEnabled exceeds supported range (0 to 2)"); 
+#endif 
+
+#undef xConfirmPara
+  if (check_failed)
+  {
+    exit(EXIT_FAILURE);
+  }
+}
+
+/** \todo use of global variables should be removed later
+ */
+Void TAppEncCfg::xSetGlobal()
+{
+  // set max CU width & height
+  g_uiMaxCUWidth  = m_uiMaxCUWidth;
+  g_uiMaxCUHeight = m_uiMaxCUHeight;
+  
+  // compute actual CU depth with respect to config depth and max transform size
+  g_uiAddCUDepth  = 0;
+  while( (m_uiMaxCUWidth>>m_uiMaxCUDepth) > ( 1 << ( m_uiQuadtreeTULog2MinSize + g_uiAddCUDepth )  ) ) g_uiAddCUDepth++;
+  
+  m_uiMaxCUDepth += g_uiAddCUDepth;
+  g_uiAddCUDepth++;
+  g_uiMaxCUDepth = m_uiMaxCUDepth;
+  
+  // set internal bit-depth and constants
+#if FULL_NBIT
+  g_uiBitDepth = m_uiInternalBitDepth;
+  g_uiBitIncrement = 0;
+#else
+  g_uiBitDepth = 8;
+  g_uiBitIncrement = m_uiInternalBitDepth - g_uiBitDepth;
+#endif
+
+  g_uiBASE_MAX     = ((1<<(g_uiBitDepth))-1);
+  
+#if IBDI_NOCLIP_RANGE
+  g_uiIBDI_MAX     = g_uiBASE_MAX << g_uiBitIncrement;
+#else
+  g_uiIBDI_MAX     = ((1<<(g_uiBitDepth+g_uiBitIncrement))-1);
+#endif
+  
+  if (m_uiOutputBitDepth == 0)
+  {
+    m_uiOutputBitDepth = m_uiInternalBitDepth;
+  }
+
+  g_uiPCMBitDepthLuma = m_uiPCMBitDepthLuma = ((m_bPCMInputBitDepthFlag)? m_uiInputBitDepth : m_uiInternalBitDepth);
+  g_uiPCMBitDepthChroma = ((m_bPCMInputBitDepthFlag)? m_uiInputBitDepth : m_uiInternalBitDepth);
+}
+
+Void TAppEncCfg::xPrintParameter()
+{
+  printf("\n");
+#if SVC_EXTENSION  
+  printf("Total number of layers        : %d\n", m_numLayers            );
+  for(UInt layer=0; layer<m_numLayers; layer++)
+  {
+    printf("=== Layer %d settings === \n", layer);
+    m_acLayerCfg[layer].xPrintParameter();
+    printf("\n");
+  }
+  printf("=== Common configuration settings === \n");
+  printf("Bitstream      File          : %s\n", m_pchBitstreamFile      );
+#else
+  printf("Input          File          : %s\n", m_pchInputFile          );
+  printf("Bitstream      File          : %s\n", m_pchBitstreamFile      );
+  printf("Reconstruction File          : %s\n", m_pchReconFile          );
+  printf("Real     Format              : %dx%d %dHz\n", m_iSourceWidth - m_cropLeft - m_cropRight, m_iSourceHeight - m_cropTop - m_cropBottom, m_iFrameRate );
+  printf("Internal Format              : %dx%d %dHz\n", m_iSourceWidth, m_iSourceHeight, m_iFrameRate );
+#endif
+  printf("Frame index                  : %u - %d (%d frames)\n", m_FrameSkip, m_FrameSkip+m_iFrameToBeEncoded-1, m_iFrameToBeEncoded );
+  printf("CU size / depth              : %d / %d\n", m_uiMaxCUWidth, m_uiMaxCUDepth );
+  printf("RQT trans. size (min / max)  : %d / %d\n", 1 << m_uiQuadtreeTULog2MinSize, 1 << m_uiQuadtreeTULog2MaxSize );
+  printf("Max RQT depth inter          : %d\n", m_uiQuadtreeTUMaxDepthInter);
+  printf("Max RQT depth intra          : %d\n", m_uiQuadtreeTUMaxDepthIntra);
+  printf("Min PCM size                 : %d\n", 1 << m_uiPCMLog2MinSize);
+  printf("Motion search range          : %d\n", m_iSearchRange );
+#if !SVC_EXTENSION
+  printf("Intra period                 : %d\n", m_iIntraPeriod );
+#endif
+  printf("Decoding refresh type        : %d\n", m_iDecodingRefreshType );
+#if !SVC_EXTENSION
+  printf("QP                           : %5.2f\n", m_fQP );
+#endif
+  printf("Max dQP signaling depth      : %d\n", m_iMaxCuDQPDepth);
+
+  printf("Cb QP Offset                 : %d\n", m_cbQpOffset   );
+  printf("Cr QP Offset                 : %d\n", m_crQpOffset);
+
+  printf("QP adaptation                : %d (range=%d)\n", m_bUseAdaptiveQP, (m_bUseAdaptiveQP ? m_iQPAdaptationRange : 0) );
+  printf("GOP size                     : %d\n", m_iGOPSize );
+  printf("Internal bit depth           : %d\n", m_uiInternalBitDepth );
+  printf("PCM sample bit depth         : %d\n", m_uiPCMBitDepthLuma );
+  printf("RateControl                  : %d\n", m_enableRateCtrl);
+  if(m_enableRateCtrl)
+  {
+    printf("TargetBitrate                : %d\n", m_targetBitrate);
+    printf("NumLCUInUnit                 : %d\n", m_numLCUInUnit);
+  }
+  printf("Max Num Merge Candidates     : %d\n", m_maxNumMergeCand);
+  printf("\n");
+  
+  printf("TOOL CFG: ");
+#if !REMOVE_ALF
+  printf("ALF:%d ", m_bUseALF             );
+  printf("ALFLowLatencyEncode:%d ", m_alfLowLatencyEncoding?1:0);
+#endif
+  printf("IBD:%d ", !!g_uiBitIncrement);
+  printf("HAD:%d ", m_bUseHADME           );
+  printf("SRD:%d ", m_bUseSBACRD          );
+  printf("RDQ:%d ", m_bUseRDOQ            );
+  printf("SQP:%d ", m_uiDeltaQpRD         );
+  printf("ASR:%d ", m_bUseASR             );
+  printf("LComb:%d ", m_bUseLComb         );
+  printf("FEN:%d ", m_bUseFastEnc         );
+  printf("ECU:%d ", m_bUseEarlyCU         );
+  printf("FDM:%d ", m_useFastDecisionForMerge );
+  printf("CFM:%d ", m_bUseCbfFastMode         );
+  printf("ESD:%d ", m_useEarlySkipDetection  );
+  printf("RQT:%d ", 1     );
+#if !REMOVE_LMCHROMA
+  printf("LMC:%d ", m_bUseLMChroma        );
+#endif
+  printf("TransformSkip:%d ",     m_useTransformSkip              );
+  printf("TransformSkipFast:%d ", m_useTransformSkipFast       );
+#if REMOVE_FGS
+  printf("Slice: M=%d ", m_iSliceMode);
+#else
+  printf("Slice: G=%d M=%d ", m_iSliceGranularity, m_iSliceMode);
+#endif
+  if (m_iSliceMode!=0)
+  {
+    printf("A=%d ", m_iSliceArgument);
+  }
+  printf("DependentSlice: M=%d ",m_iDependentSliceMode);
+  if (m_iDependentSliceMode!=0)
+  {
+    printf("A=%d ", m_iDependentSliceArgument);
+  }
+  printf("CIP:%d ", m_bUseConstrainedIntraPred);
+  printf("SAO:%d ", (m_bUseSAO)?(1):(0));
+  printf("PCM:%d ", (m_usePCM && (1<<m_uiPCMLog2MinSize) <= m_uiMaxCUWidth)? 1 : 0);
+  printf("SAOLcuBasedOptimization:%d ", (m_saoLcuBasedOptimization)?(1):(0));
+
+  printf("LosslessCuEnabled:%d ", (m_useLossless)? 1:0 );
+  printf("WPP:%d ", (Int)m_bUseWeightPred);
+  printf("WPB:%d ", (Int)m_useWeightedBiPred);
+  printf("PME:%d ", m_log2ParallelMergeLevel);
+#if !SVC_EXTENSION
+  printf(" WaveFrontSynchro:%d WaveFrontSubstreams:%d",
+          m_iWaveFrontSynchro, m_iWaveFrontSubstreams);
+#endif
+  printf(" ScalingList:%d ", m_useScalingListId );
+  printf("TMVPMode:%d ", m_TMVPModeId     );
+#if ADAPTIVE_QP_SELECTION
+  printf("AQpS:%d", m_bUseAdaptQpSelect   );
+#endif
+
+  printf(" SignBitHidingFlag:%d ", m_signHideFlag);
+#if SVC_EXTENSION
+#if RECALCULATE_QP_ACCORDING_LAMBDA
+  printf("RecalQP:%d ", m_recalculateQPAccordingToLambda ? 1 : 0 );
+#endif
+#if REF_IDX_FRAMEWORK
+  printf("REF_IDX_FRAMEWORK:%d ", REF_IDX_FRAMEWORK);
+  printf("EL_RAP_SliceType: %d ", m_elRapSliceBEnabled);
+  printf("REF_IDX_ME_AROUND_ZEROMV:%d ", REF_IDX_ME_AROUND_ZEROMV);
+#else
+  printf("INTRA_BL:%d ", INTRA_BL);
+  printf("AVC_BASE:%d ", AVC_BASE);
+#if !AVC_BASE
+  printf("SVC_MVP:%d ", SVC_MVP );
+  printf("SVC_BL_CAND_INTRA:%d", SVC_BL_CAND_INTRA );
+#endif
+#endif
+#else
+#if RECALCULATE_QP_ACCORDING_LAMBDA
+  printf("RecalQP:%d", m_recalculateQPAccordingToLambda ? 1 : 0 );
+#endif
+#endif
+  printf("\n\n");
+  
+  fflush(stdout);
+}
+
+Bool confirmPara(Bool bflag, const char* message)
+{
+  if (!bflag)
+    return false;
+  
+  printf("Error: %s\n",message);
+  return true;
+}
+
+//! \}
Index: /trunk/source/App/TAppEncoder/TAppEncCfg.h
===================================================================
--- /trunk/source/App/TAppEncoder/TAppEncCfg.h	(revision 2)
+++ /trunk/source/App/TAppEncoder/TAppEncCfg.h	(revision 2)
@@ -0,0 +1,313 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TAppEncCfg.h
+    \brief    Handle encoder configuration parameters (header)
+*/
+
+#ifndef __TAPPENCCFG__
+#define __TAPPENCCFG__
+
+#include "TLibCommon/CommonDef.h"
+
+#include "TLibEncoder/TEncCfg.h"
+#if SVC_EXTENSION
+#include "TAppEncLayerCfg.h"
+#endif
+#include <sstream>
+//! \ingroup TAppEncoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// encoder configuration class
+class TAppEncCfg
+{
+protected:
+  // file I/O
+#if SVC_EXTENSION
+  TAppEncLayerCfg m_acLayerCfg [MAX_LAYERS]; 
+  Int       m_numLayers;                                     ///< number of layers
+
+  char*     m_pchBitstreamFile;                               ///< output bitstream file
+  Double    m_adLambdaModifier[ MAX_TLAYER ];                 ///< Lambda modifier array for each temporal layer
+  // source specification
+  unsigned int m_FrameSkip;                                   ///< number of skipped frames from the beginning
+  Int       m_iFrameToBeEncoded;                              ///< number of encoded frames
+#else
+  char*     m_pchInputFile;                                   ///< source file name
+  char*     m_pchBitstreamFile;                               ///< output bitstream file
+  char*     m_pchReconFile;                                   ///< output reconstruction file
+  Double    m_adLambdaModifier[ MAX_TLAYER ];                 ///< Lambda modifier array for each temporal layer
+  // source specification
+  Int       m_iFrameRate;                                     ///< source frame-rates (Hz)
+  unsigned int m_FrameSkip;                                   ///< number of skipped frames from the beginning
+  Int       m_iSourceWidth;                                   ///< source width in pixel
+  Int       m_iSourceHeight;                                  ///< source height in pixel
+  Int       m_croppingMode;
+  Int       m_cropLeft;
+  Int       m_cropRight;
+  Int       m_cropTop;
+  Int       m_cropBottom;
+  Int       m_iFrameToBeEncoded;                              ///< number of encoded frames
+  Int       m_aiPad[2];                                       ///< number of padded pixels for width and height
+  
+  // coding structure
+  Int       m_iIntraPeriod;                                   ///< period of I-slice (random access period)
+#endif
+  Int       m_iDecodingRefreshType;                           ///< random access type
+  Int       m_iGOPSize;                                       ///< GOP size of hierarchical structure
+  Int       m_extraRPSs;                                      ///< extra RPSs added to handle CRA
+  GOPEntry  m_GOPList[MAX_GOP];                               ///< the coding structure entries from the config file
+  Int       m_numReorderPics[MAX_TLAYER];                     ///< total number of reorder pictures
+  Int       m_maxDecPicBuffering[MAX_TLAYER];                 ///< total number of reference pictures needed for decoding
+  Bool      m_bUseLComb;                                      ///< flag for using combined reference list for uni-prediction in B-slices (JCTVC-D421)
+  Bool      m_useTransformSkip;                               ///< flag for enabling intra transform skipping
+  Bool      m_useTransformSkipFast;                           ///< flag for enabling fast intra transform skipping
+#if !REMOVE_NSQT
+  Bool      m_enableNSQT;                                     ///< flag for enabling NSQT
+#endif
+  Bool      m_enableAMP;
+  // coding quality
+#if !SVC_EXTENSION
+  Double    m_fQP;                                            ///< QP value of key-picture (floating point)
+  Int       m_iQP;                                            ///< QP value of key-picture (integer)
+  char*     m_pchdQPFile;                                     ///< QP offset for each slice (initialized from external file)
+  Int*      m_aidQP;                                          ///< array of slice QP values
+#endif
+  Int       m_iMaxDeltaQP;                                    ///< max. |delta QP|
+  UInt      m_uiDeltaQpRD;                                    ///< dQP range for multi-pass slice QP optimization
+  Int       m_iMaxCuDQPDepth;                                 ///< Max. depth for a minimum CuDQPSize (0:default)
+
+  Int       m_cbQpOffset;                                     ///< Chroma Cb QP Offset (0:default) 
+  Int       m_crQpOffset;                                     ///< Chroma Cr QP Offset (0:default)
+
+#if ADAPTIVE_QP_SELECTION
+  Bool      m_bUseAdaptQpSelect;
+#endif
+
+  Bool      m_bUseAdaptiveQP;                                 ///< Flag for enabling QP adaptation based on a psycho-visual model
+  Int       m_iQPAdaptationRange;                             ///< dQP range by QP adaptation
+  
+  Int       m_maxTempLayer;                                  ///< Max temporal layer
+
+  // coding unit (CU) definition
+  UInt      m_uiMaxCUWidth;                                   ///< max. CU width in pixel
+  UInt      m_uiMaxCUHeight;                                  ///< max. CU height in pixel
+  UInt      m_uiMaxCUDepth;                                   ///< max. CU depth
+  
+  // transfom unit (TU) definition
+  UInt      m_uiQuadtreeTULog2MaxSize;
+  UInt      m_uiQuadtreeTULog2MinSize;
+  
+  UInt      m_uiQuadtreeTUMaxDepthInter;
+  UInt      m_uiQuadtreeTUMaxDepthIntra;
+  
+  // coding tools (bit-depth)
+  UInt      m_uiInputBitDepth;                                ///< bit-depth of input file
+  UInt      m_uiOutputBitDepth;                               ///< bit-depth of output file
+  UInt      m_uiInternalBitDepth;                             ///< Internal bit-depth (BitDepth+BitIncrement)
+
+  // coding tools (PCM bit-depth)
+  Bool      m_bPCMInputBitDepthFlag;                          ///< 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+  UInt      m_uiPCMBitDepthLuma;                              ///< PCM bit-depth for luma
+
+  // coding tool (lossless)
+  Bool      m_useLossless;                                    ///< flag for using lossless coding
+  Bool      m_bUseSAO; 
+  Int       m_maxNumOffsetsPerPic;                            ///< SAO maximun number of offset per picture
+#if SAO_LCU_BOUNDARY
+  Bool      m_saoLcuBoundary;                                 ///< SAO parameter estimation using non-deblocked pixels for LCU bottom and right boundary areas
+#endif
+  Bool      m_saoLcuBasedOptimization;                        ///< SAO LCU-based optimization
+  // coding tools (loop filter)
+#if !REMOVE_ALF
+  Bool      m_bUseALF;                                        ///< flag for using adaptive loop filter
+  Bool      m_alfLowLatencyEncoding;
+#endif
+  Bool      m_bLoopFilterDisable;                             ///< flag for using deblocking filter
+  Bool      m_loopFilterOffsetInPPS;                         ///< offset for deblocking filter in 0 = slice header, 1 = PPS
+  Int       m_loopFilterBetaOffsetDiv2;                     ///< beta offset for deblocking filter
+  Int       m_loopFilterTcOffsetDiv2;                       ///< tc offset for deblocking filter
+  Bool      m_DeblockingFilterControlPresent;                 ///< deblocking filter control present flag in PPS
+ 
+#if !REMOVE_LMCHROMA
+  Bool      m_bUseLMChroma;                                  ///< JL: Chroma intra prediction based on luma signal
+#endif
+  
+  // coding tools (PCM)
+  Bool      m_usePCM;                                         ///< flag for using IPCM
+  UInt      m_pcmLog2MaxSize;                                 ///< log2 of maximum PCM block size
+  UInt      m_uiPCMLog2MinSize;                               ///< log2 of minimum PCM block size
+  Bool      m_bPCMFilterDisableFlag;                          ///< PCM filter disable flag
+
+  // coding tools (encoder-only parameters)
+  Bool      m_bUseSBACRD;                                     ///< flag for using RD optimization based on SBAC
+  Bool      m_bUseASR;                                        ///< flag for using adaptive motion search range
+  Bool      m_bUseHADME;                                      ///< flag for using HAD in sub-pel ME
+  Bool      m_bUseRDOQ;                                       ///< flag for using RD optimized quantization
+  Int       m_iFastSearch;                                    ///< ME mode, 0 = full, 1 = diamond, 2 = PMVFAST
+  Int       m_iSearchRange;                                   ///< ME search range
+  Int       m_bipredSearchRange;                              ///< ME search range for bipred refinement
+  Bool      m_bUseFastEnc;                                    ///< flag for using fast encoder setting
+  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_iSliceMode;           ///< 0: Disable all Recon slice limits, 1 : Maximum number of largest coding units per slice, 2: Maximum number of bytes in a slice
+  Int       m_iSliceArgument;       ///< If m_iSliceMode==1, m_iSliceArgument=max. # of largest coding units. If m_iSliceMode==2, m_iSliceArgument=max. # of bytes.
+  Int       m_iDependentSliceMode;    ///< 0: Disable all dependent slice limits, 1 : Maximum number of largest coding units per slice, 2: Constraint based dependent slice
+  Int       m_iDependentSliceArgument;///< If m_iDependentSliceMode==1, m_iEDependentSliceArgument=max. # of largest coding units. If m_iDependnetSliceMode==2, m_iDependnetSliceArgument=max. # of bins.
+#if DEPENDENT_SLICES
+#if TILES_WPP_ENTROPYSLICES_FLAGS
+  Bool      m_entropySliceEnabledFlag;
+#else
+  Bool       m_bCabacIndependentFlag;  // 0: CABAC dependence between slices, 1:CABAC independence between slices
+#endif
+#endif
+
+#if !REMOVE_FGS
+  Int       m_iSliceGranularity;///< 0: Slices always end at LCU borders. 1-3: slices may end at a depth of 1-3 below LCU level.
+#endif
+  Bool      m_bLFCrossSliceBoundaryFlag;  ///< 0: Cross-slice-boundary in-loop filtering 1: non-cross-slice-boundary in-loop filtering
+  Bool      m_bLFCrossTileBoundaryFlag;  //!< 1: Cross-tile-boundary in-loop filtering 0: non-cross-tile-boundary in-loop filtering
+  Int       m_iUniformSpacingIdr;
+  Int       m_iNumColumnsMinus1;
+  char*     m_pchColumnWidth;
+  Int       m_iNumRowsMinus1;
+  char*     m_pchRowHeight;
+  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.
+#if !SVC_EXTENSION
+  Int       m_iWaveFrontSubstreams; //< If iWaveFrontSynchro, this is the number of substreams per frame (dependent tiles) or per tile (independent tiles).
+#endif
+
+  Bool      m_bUseConstrainedIntraPred;                       ///< flag for using constrained intra prediction
+  
+  Int       m_decodePictureHashSEIEnabled;                    ///< Checksum(3)/CRC(2)/MD5(1)/disable(0) acting on decoded picture hash SEI message
+#if RECOVERY_POINT_SEI
+  Int       m_recoveryPointSEIEnabled;
+#endif
+#if BUFFERING_PERIOD_AND_TIMING_SEI
+  Int       m_bufferingPeriodSEIEnabled;
+  Int       m_pictureTimingSEIEnabled;
+#endif
+  // weighted prediction
+  Bool      m_bUseWeightPred;                                 ///< Use of explicit Weighting Prediction for P_SLICE
+  Bool      m_useWeightedBiPred;                                    ///< Use of Bi-Directional Weighting Prediction (B_SLICE)
+  
+  UInt      m_log2ParallelMergeLevel;                         ///< Parallel merge estimation region
+  UInt      m_maxNumMergeCand;                                ///< Max number of merge candidates
+
+  Int       m_TMVPModeId;
+  Int       m_signHideFlag;
+  Bool      m_enableRateCtrl;                                   ///< Flag for using rate control algorithm
+  Int       m_targetBitrate;                                 ///< target bitrate
+  Int       m_numLCUInUnit;                                  ///< Total number of LCUs in a frame should be completely divided by the NumLCUInUnit
+  Int       m_useScalingListId;                               ///< using quantization matrix
+  char*     m_scalingListFile;                                ///< quantization matrix file name
+
+  Bool      m_TransquantBypassEnableFlag;                     ///< transquant_bypass_enable_flag setting in PPS.
+  Bool      m_CUTransquantBypassFlagValue;                    ///< if transquant_bypass_enable_flag, the fixed value to use for the per-CU cu_transquant_bypass_flag.
+
+#if RECALCULATE_QP_ACCORDING_LAMBDA
+  Bool      m_recalculateQPAccordingToLambda;                 ///< recalculate QP value according to the lambda value
+#endif
+#if ACTIVE_PARAMETER_SETS_SEI_MESSAGE
+  Int       m_activeParameterSetsSEIEnabled;
+#endif 
+
+#if SUPPORT_FOR_VUI
+  Bool      m_vuiParametersPresentFlag;                       ///< enable generation of VUI parameters
+  Bool      m_aspectRatioInfoPresentFlag;                     ///< Signals whether aspect_ratio_idc is present
+  Int       m_aspectRatioIdc;                                 ///< aspect_ratio_idc
+  Int       m_sarWidth;                                       ///< horizontal size of the sample aspect ratio
+  Int       m_sarHeight;                                      ///< vertical size of the sample aspect ratio
+  Bool      m_overscanInfoPresentFlag;                        ///< Signals whether overscan_appropriate_flag is present
+  Bool      m_overscanAppropriateFlag;                        ///< Indicates whether cropped decoded pictures are suitable for display using overscan
+  Bool      m_videoSignalTypePresentFlag;                     ///< Signals whether video_format, video_full_range_flag, and colour_description_present_flag are present
+  Int       m_videoFormat;                                    ///< Indicates representation of pictures
+  Bool      m_videoFullRangeFlag;                             ///< Indicates the black level and range of luma and chroma signals
+  Bool      m_colourDescriptionPresentFlag;                   ///< Signals whether colour_primaries, transfer_characteristics and matrix_coefficients are present
+  Int       m_colourPrimaries;                                ///< Indicates chromaticity coordinates of the source primaries
+  Int       m_transferCharacteristics;                        ///< Indicates the opto-electronic transfer characteristics of the source
+  Int       m_matrixCoefficients;                             ///< Describes the matrix coefficients used in deriving luma and chroma from RGB primaries
+  Bool      m_chromaLocInfoPresentFlag;                       ///< Signals whether chroma_sample_loc_type_top_field and chroma_sample_loc_type_bottom_field are present
+  Int       m_chromaSampleLocTypeTopField;                    ///< Specifies the location of chroma samples for top field
+  Int       m_chromaSampleLocTypeBottomField;                 ///< Specifies the location of chroma samples for bottom field
+  Bool      m_neutralChromaIndicationFlag;                    ///< Indicates that the value of all decoded chroma samples is equal to 1<<(BitDepthCr-1)
+  Bool      m_bitstreamRestrictionFlag;                       ///< Signals whether bitstream restriction parameters are present
+  Bool      m_tilesFixedStructureFlag;                        ///< Indicates that each active picture parameter set has the same values of the syntax elements related to tiles
+  Bool      m_motionVectorsOverPicBoundariesFlag;             ///< Indicates that no samples outside the picture boundaries are used for inter prediction
+  Int       m_maxBytesPerPicDenom;                            ///< Indicates a number of bytes not exceeded by the sum of the sizes of the VCL NAL units associated with any coded picture
+  Int       m_maxBitsPerMinCuDenom;                           ///< Indicates an upper bound for the number of bits of coding_unit() data
+  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
+#endif
+#if REF_IDX_FRAMEWORK
+  Int       m_elRapSliceBEnabled;
+#endif
+  // internal member functions
+  Void  xSetGlobal      ();                                   ///< set global variables
+  Void  xCheckParameter ();                                   ///< check validity of configuration values
+  Void  xPrintParameter ();                                   ///< print configuration values
+  Void  xPrintUsage     ();                                   ///< print usage
+  
+public:
+  TAppEncCfg();
+  virtual ~TAppEncCfg();
+  
+public:
+  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
+  
+#if SVC_EXTENSION
+  Int  getNumFrameToBeEncoded()    {return m_iFrameToBeEncoded; }
+  Int  getNumLayer()               {return m_numLayers;        }
+  Int  getGOPSize()                {return m_iGOPSize;          }
+  UInt getInternalBitDepth()       {return m_uiInternalBitDepth; }
+  UInt getMaxCUWidth()             {return m_uiMaxCUWidth;      }
+  UInt getMaxCUHeight()            {return m_uiMaxCUHeight;     }
+  UInt getMaxCUDepth()             {return m_uiMaxCUDepth;      }
+  Int  getDecodingRefreshType()    {return m_iDecodingRefreshType; }
+  Void getDirFilename(string& filename, string& dir, const string path);
+  Int  getWaveFrontSynchro()        { return m_iWaveFrontSynchro; }
+#endif
+};// END CLASS DEFINITION TAppEncCfg
+
+//! \}
+
+#endif // __TAPPENCCFG__
+
Index: /trunk/source/App/TAppEncoder/TAppEncLayerCfg.cpp
===================================================================
--- /trunk/source/App/TAppEncoder/TAppEncLayerCfg.cpp	(revision 2)
+++ /trunk/source/App/TAppEncoder/TAppEncLayerCfg.cpp	(revision 2)
@@ -0,0 +1,239 @@
+/** \file     TAppEncLayerCfg.cpp
+    \brief    Handle encoder configuration parameters
+*/
+
+#include <stdlib.h>
+#include <cassert>
+#include <cstring>
+#include <string>
+#include "TLibCommon/TComRom.h"
+#include "TAppEncCfg.h"
+#include "TAppEncLayerCfg.h"
+#include "TAppCommon/program_options_lite.h"
+
+#ifdef WIN32
+#define strdup _strdup
+#endif
+
+using namespace std;
+namespace po = df::program_options_lite;
+
+//! \ingroup TAppEncoder
+//! \{
+
+
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+#if SVC_EXTENSION
+TAppEncLayerCfg::TAppEncLayerCfg()
+:m_cInputFile(string("")),
+ m_cReconFile(string("")),
+ m_croppingMode( 0 ),
+ m_aidQP(NULL)
+{
+  m_cropLeft = m_cropRight = m_cropTop = m_cropBottom = 0;
+  m_aiPad[1] = m_aiPad[0] = 0;
+}
+
+TAppEncLayerCfg::~TAppEncLayerCfg()
+{
+  if ( m_aidQP )
+  {
+    delete[] m_aidQP;
+  }
+}
+
+Void TAppEncLayerCfg::create()
+{
+}
+
+Void TAppEncLayerCfg::destroy()
+{
+}
+
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/** \param  argc        number of arguments
+    \param  argv        array of arguments
+    \retval             true when success
+ */
+bool TAppEncLayerCfg::parseCfg( const string& cfgFileName  )
+{
+  string cfg_InputFile;
+  string cfg_ReconFile;
+  string cfg_dQPFile;
+  po::Options opts;
+  opts.addOptions()
+  ("InputFile,i",           cfg_InputFile,  string(""), "original YUV input file name")
+#if AVC_BASE
+  ("InputBLFile,-ibl",      cfg_InputFile,  string(""), "original YUV input file name")
+#endif
+  ("ReconFile,o",           cfg_ReconFile,  string(""), "reconstructed YUV output file name")
+  ("SourceWidth,-wdt",      m_iSourceWidth,  0, "Source picture width")
+  ("SourceHeight,-hgt",     m_iSourceHeight, 0, "Source picture height")
+  ("CroppingMode",          m_croppingMode,  0, "Cropping mode (0: no cropping, 1:automatic padding, 2: padding, 3:cropping")
+  ("CropLeft",              m_cropLeft,      0, "Left cropping/padding for cropping mode 3")
+  ("CropRight",             m_cropRight,     0, "Right cropping/padding for cropping mode 3")
+  ("CropTop",               m_cropTop,       0, "Top cropping/padding for cropping mode 3")
+  ("CropBottom",            m_cropBottom,    0, "Bottom cropping/padding for cropping mode 3")
+  ("HorizontalPadding,-pdx",m_aiPad[0],      0, "horizontal source padding for cropping mode 2")
+  ("VerticalPadding,-pdy",  m_aiPad[1],      0, "vertical source padding for cropping mode 2")
+  ("IntraPeriod,-ip",       m_iIntraPeriod,  -1, "intra period in frames, (-1: only first frame)")
+  ("FrameRate,-fr",         m_iFrameRate,    0, "Frame rate")
+  ("dQPFile,m",             cfg_dQPFile, string(""), "dQP file name")
+  ("QP,q",                  m_fQP,          30.0, "Qp value, if value is float, QP is switched once during encoding")
+  ;
+  
+  po::setDefaults(opts);
+  po::parseConfigFile(opts, cfgFileName);
+
+  m_cInputFile = cfg_InputFile;
+  m_cReconFile = cfg_ReconFile;
+  m_pchdQPFile = cfg_dQPFile.empty() ? NULL : strdup(cfg_dQPFile.c_str());
+
+  // reading external dQP description from file
+  if ( m_pchdQPFile )
+  {
+    FILE* fpt=fopen( m_pchdQPFile, "r" );
+    if ( fpt )
+    {
+      Int iValue;
+      Int iPOC = 0;
+      while ( iPOC < m_cAppEncCfg->getNumFrameToBeEncoded() )
+      {
+        if ( fscanf(fpt, "%d", &iValue ) == EOF ) break;
+        m_aidQP[ iPOC ] = iValue;
+        iPOC++;
+      }
+      fclose(fpt);
+    }
+  }
+  return true;
+}
+
+Void TAppEncLayerCfg::xPrintParameter()
+{
+  printf("Input File                    : %s\n", m_cInputFile.c_str()  );
+  printf("Reconstruction File           : %s\n", m_cReconFile.c_str()  );
+  printf("Real     Format               : %dx%d %dHz\n", m_iSourceWidth - m_cropLeft - m_cropRight, m_iSourceHeight - m_cropTop - m_cropBottom, m_iFrameRate );
+  printf("Internal Format               : %dx%d %dHz\n", m_iSourceWidth, m_iSourceHeight, m_iFrameRate );
+  printf("QP                            : %5.2f\n", m_fQP );
+  printf("Intra period                  : %d\n", m_iIntraPeriod );
+#if SVC_EXTENSION
+  printf("WaveFrontSynchro:%d WaveFrontSubstreams:%d",
+          m_cAppEncCfg->getWaveFrontSynchro(), m_iWaveFrontSubstreams);
+#endif
+}
+
+Bool confirmPara(Bool bflag, const char* message);
+
+Bool TAppEncLayerCfg::xCheckParameter()
+{
+  switch (m_croppingMode)
+  {
+  case 0:
+    {
+      // no cropping or padding
+      m_cropLeft = m_cropRight = m_cropTop = m_cropBottom = 0;
+      m_aiPad[1] = m_aiPad[0] = 0;
+      break;
+    }
+  case 1:
+    {
+      // automatic padding to minimum CU size
+      Int minCuSize = m_cAppEncCfg->getMaxCUHeight() >> (m_cAppEncCfg->getMaxCUDepth() - 1);
+      if (m_iSourceWidth % minCuSize)
+      {
+        m_aiPad[0] = m_cropRight  = ((m_iSourceWidth / minCuSize) + 1) * minCuSize - m_iSourceWidth;
+        m_iSourceWidth  += m_cropRight;
+      }
+      if (m_iSourceHeight % minCuSize)
+      {
+        m_aiPad[1] = m_cropBottom = ((m_iSourceHeight / minCuSize) + 1) * minCuSize - m_iSourceHeight;
+        m_iSourceHeight += m_cropBottom;
+      }
+      break;
+    }
+  case 2:
+    {
+      //padding
+      m_iSourceWidth  += m_aiPad[0];
+      m_iSourceHeight += m_aiPad[1];
+      m_cropRight  = m_aiPad[0];
+      m_cropBottom = m_aiPad[1];
+      break;
+    }
+  case 3:
+    {
+      // cropping
+      if ((m_cropLeft == 0) && (m_cropRight == 0) && (m_cropTop == 0) && (m_cropBottom == 0))
+      {
+        fprintf(stderr, "Warning: Cropping enabled, but all cropping parameters set to zero\n");
+      }
+      if ((m_aiPad[1] != 0) || (m_aiPad[0]!=0))
+      {
+        fprintf(stderr, "Warning: Cropping enabled, padding parameters will be ignored\n");
+      }
+      m_aiPad[1] = m_aiPad[0] = 0;
+      break;
+    }
+  }
+
+  // allocate slice-based dQP values
+  Int iFrameToBeEncoded = m_cAppEncCfg->getNumFrameToBeEncoded();
+  Int iGOPSize = m_cAppEncCfg->getGOPSize();
+  if( m_aidQP == NULL )
+    m_aidQP = new Int[iFrameToBeEncoded + iGOPSize + 1 ];
+  ::memset( m_aidQP, 0, sizeof(Int)*( iFrameToBeEncoded + iGOPSize + 1 ) );
+
+  // handling of floating-point QP values
+  // if QP is not integer, sequence is split into two sections having QP and QP+1
+  m_iQP = (Int)( m_fQP );
+  if ( m_iQP < m_fQP )
+  {
+    Int iSwitchPOC = (Int)( iFrameToBeEncoded - (m_fQP - m_iQP)*iFrameToBeEncoded + 0.5 );
+    
+
+    iSwitchPOC = (Int)( (Double)iSwitchPOC / iGOPSize + 0.5 )*iGOPSize;
+    for ( Int i=iSwitchPOC; i<iFrameToBeEncoded + iGOPSize + 1; i++ )
+    {
+      m_aidQP[i] = 1;
+    }
+  }
+
+  UInt maxCUWidth = m_cAppEncCfg->getMaxCUWidth();
+  UInt maxCUHeight = m_cAppEncCfg->getMaxCUHeight();
+  UInt maxCUDepth = m_cAppEncCfg->getMaxCUDepth();
+  bool check_failed = false; /* abort if there is a fatal configuration problem */
+#define xConfirmPara(a,b) check_failed |= confirmPara(a,b)
+  // check range of parameters
+  xConfirmPara( m_iFrameRate <= 0,                                                          "Frame rate must be more than 1" );
+  xConfirmPara( (m_iSourceWidth  % (maxCUWidth  >> (maxCUDepth-1)))!=0,             "Resulting coded frame width must be a multiple of the minimum CU size");
+  xConfirmPara( (m_iSourceHeight % (maxCUHeight >> (maxCUDepth-1)))!=0,             "Resulting coded frame height must be a multiple of the minimum CU size");
+  xConfirmPara( (m_iIntraPeriod > 0 && m_iIntraPeriod < iGOPSize) || m_iIntraPeriod == 0, "Intra period must be more than GOP size, or -1 , not 0" );
+  if (m_cAppEncCfg->getDecodingRefreshType() == 2)
+  {
+    xConfirmPara( m_iIntraPeriod > 0 && m_iIntraPeriod <= iGOPSize ,                      "Intra period must be larger than GOP size for periodic IDR pictures");
+  }
+
+  xConfirmPara( m_iQP <  -6 * ((Int)m_cAppEncCfg->getInternalBitDepth() - 8) || m_iQP > 51,                "QP exceeds supported range (-QpBDOffsety to 51)" );
+
+  
+#if SVC_EXTENSION
+  m_iWaveFrontSubstreams = m_cAppEncCfg->getWaveFrontSynchro() ? (m_iSourceHeight + m_cAppEncCfg->getMaxCUHeight() - 1) / m_cAppEncCfg->getMaxCUHeight() : 1;
+  xConfirmPara( m_iWaveFrontSubstreams <= 0, "WaveFrontSubstreams must be positive" );
+  xConfirmPara( m_iWaveFrontSubstreams > 1 && !m_cAppEncCfg->getWaveFrontSynchro(), "Must have WaveFrontSynchro > 0 in order to have WaveFrontSubstreams > 1" );
+#endif
+
+#undef xConfirmPara
+  return check_failed;
+}
+
+#endif
+
+
+//! \}
Index: /trunk/source/App/TAppEncoder/TAppEncLayerCfg.h
===================================================================
--- /trunk/source/App/TAppEncoder/TAppEncLayerCfg.h	(revision 2)
+++ /trunk/source/App/TAppEncoder/TAppEncLayerCfg.h	(revision 2)
@@ -0,0 +1,86 @@
+
+/** \file     TAppEncLayerCfg.h
+    \brief    Handle encoder layer configuration parameters (header)
+*/
+#ifndef __TAPPENCLAYERCFG__
+#define __TAPPENCLAYERCFG__
+
+#include "TLibCommon/CommonDef.h"
+#include "TLibEncoder/TEncCfg.h"
+#include <sstream>
+
+using namespace std;
+#if SVC_EXTENSION
+class TAppEncCfg;
+#endif
+//! \ingroup TAppEncoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// encoder layer configuration class
+class TAppEncLayerCfg
+{
+  friend class TAppEncCfg;
+  friend class TAppEncTop;
+protected:
+  // file I/O0
+  string    m_cInputFile;                                     ///< source file name
+  string    m_cReconFile;                                     ///< output reconstruction file
+
+  Int       m_iFrameRate;                                     ///< source frame-rates (Hz)
+  Int       m_iSourceWidth;                                   ///< source width in pixel
+  Int       m_iSourceHeight;                                  ///< source height in pixel
+  Int       m_croppingMode;
+  Int       m_cropLeft;
+  Int       m_cropRight;
+  Int       m_cropTop;
+  Int       m_cropBottom;
+  Int       m_aiPad[2];                                       ///< number of padded pixels for width and height
+  Int       m_iIntraPeriod;                                   ///< period of I-slice (random access period)
+  Double    m_fQP;                                            ///< QP value of key-picture (floating point)
+
+#if SVC_EXTENSION
+  Int       m_iWaveFrontSubstreams; //< If iWaveFrontSynchro, this is the number of substreams per frame (dependent tiles) or per tile (independent tiles).
+#endif
+
+  Int       m_iQP;                                            ///< QP value of key-picture (integer)
+  char*     m_pchdQPFile;                                     ///< QP offset for each slice (initialized from external file)
+  Int*      m_aidQP;                                          ///< array of slice QP values
+  TAppEncCfg* m_cAppEncCfg;                                   ///< pointer to app encoder config
+public:
+  TAppEncLayerCfg();
+  virtual ~TAppEncLayerCfg();
+
+public:
+  Void  create    ();                                         ///< create option handling class
+  Void  destroy   ();                                         ///< destroy option handling class
+  bool  parseCfg  ( const string& cfgFileName );              ///< parse layer configuration file to fill member variables
+
+  Void  xPrintParameter();
+  Bool  xCheckParameter();
+
+  Void    setAppEncCfg(TAppEncCfg* p) {m_cAppEncCfg = p;          }
+  string  getInputFile()              {return m_cInputFile;       }
+  string  getReconFile()              {return m_cReconFile;       }
+  Int     getFrameRate()              {return m_iFrameRate;       }
+  Int     getSourceWidth()            {return m_iSourceWidth;     }
+  Int     getSourceHeight()           {return m_iSourceHeight;    }
+  Int     getCroppingMode()           {return m_croppingMode;     }
+  Int     getCropLeft()               {return m_cropLeft;         }
+  Int     getCropRight()              {return m_cropRight;        }
+  Int     getCropTop()                {return m_cropTop;          }
+  Int     getCropBottom()             {return m_cropBottom;       }
+  Int*    getPad()                    {return m_aiPad;            }
+  Double  getFloatQP()                {return m_fQP;              }
+
+  Int     getIntQP()                  {return m_iQP;              } 
+  Int*    getdQPs()                   {return m_aidQP;            }
+
+}; // END CLASS DEFINITION TAppEncLayerCfg
+
+//! \}
+
+#endif // __TAPPENCLAYERCFG__
Index: /trunk/source/App/TAppEncoder/TAppEncTop.cpp
===================================================================
--- /trunk/source/App/TAppEncoder/TAppEncTop.cpp	(revision 2)
+++ /trunk/source/App/TAppEncoder/TAppEncTop.cpp	(revision 2)
@@ -0,0 +1,1125 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TAppEncTop.cpp
+    \brief    Encoder application class
+*/
+
+#include <list>
+#include <fstream>
+#include <stdlib.h>
+#include <stdio.h>
+#include <fcntl.h>
+#include <assert.h>
+
+#include "TAppEncTop.h"
+#include "TLibEncoder/AnnexBwrite.h"
+
+using namespace std;
+
+//! \ingroup TAppEncoder
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+
+TAppEncTop::TAppEncTop()
+{
+  m_iFrameRcvd = 0;
+  m_totalBytes = 0;
+  m_essentialBytes = 0;
+#if SVC_EXTENSION
+  for(UInt layer=0; layer < MAX_LAYERS; layer++)
+  {
+    m_apcTEncTop[layer] = &m_acTEncTop[layer];
+  }
+#endif
+}
+
+TAppEncTop::~TAppEncTop()
+{
+}
+
+#if SVC_EXTENSION
+Void TAppEncTop::xInitLibCfg()
+{
+  for(UInt layer=0; layer<m_numLayers; layer++)
+  {
+    TComVPS vps;
+
+    vps.setMaxTLayers                       ( m_maxTempLayer );
+    vps.setMaxLayers                        ( 1 );
+    for(Int i = 0; i < MAX_TLAYER; i++)
+    {
+      vps.setNumReorderPics                 ( m_numReorderPics[i], i );
+      vps.setMaxDecPicBuffering             ( m_maxDecPicBuffering[i], i );
+    }
+    m_acTEncTop[layer].setVPS(&vps);
+    m_acTEncTop[layer].setFrameRate                    ( m_acLayerCfg[layer].getFrameRate() );
+    m_acTEncTop[layer].setFrameSkip                    ( m_FrameSkip );
+    m_acTEncTop[layer].setSourceWidth                  ( m_acLayerCfg[layer].getSourceWidth() );
+    m_acTEncTop[layer].setSourceHeight                 ( m_acLayerCfg[layer].getSourceHeight() );
+    m_acTEncTop[layer].setCroppingMode                 ( m_acLayerCfg[layer].getCroppingMode() );
+    m_acTEncTop[layer].setCropLeft                     ( m_acLayerCfg[layer].getCropLeft() );
+    m_acTEncTop[layer].setCropRight                    ( m_acLayerCfg[layer].getCropRight() );
+    m_acTEncTop[layer].setCropTop                      ( m_acLayerCfg[layer].getCropTop() );
+    m_acTEncTop[layer].setCropBottom                   ( m_acLayerCfg[layer].getCropBottom() );
+    m_acTEncTop[layer].setFrameToBeEncoded             ( m_iFrameToBeEncoded );
+
+    // set layer ID 
+    m_acTEncTop[layer].setLayerId ( layer ); 
+    m_acTEncTop[layer].setNumLayer ( m_numLayers );
+    m_acTEncTop[layer].setLayerEnc(m_apcTEncTop);
+
+
+    //====== Coding Structure ========
+    m_acTEncTop[layer].setIntraPeriod                  ( m_acLayerCfg[layer].m_iIntraPeriod );
+    m_acTEncTop[layer].setDecodingRefreshType          ( m_iDecodingRefreshType );
+    m_acTEncTop[layer].setGOPSize                      ( m_iGOPSize );
+    m_acTEncTop[layer].setGopList                      ( m_GOPList );
+    m_acTEncTop[layer].setExtraRPSs                    ( m_extraRPSs );
+    for(Int i = 0; i < MAX_TLAYER; i++)
+    {
+      m_acTEncTop[layer].setNumReorderPics             ( m_numReorderPics[i], i );
+      m_acTEncTop[layer].setMaxDecPicBuffering         ( m_maxDecPicBuffering[i], i );
+    }
+    for( UInt uiLoop = 0; uiLoop < MAX_TLAYER; ++uiLoop )
+    {
+      m_acTEncTop[layer].setLambdaModifier( uiLoop, m_adLambdaModifier[ uiLoop ] );
+    }
+    m_acTEncTop[layer].setQP                           ( m_acLayerCfg[layer].getIntQP() );
+
+    m_acTEncTop[layer].setPad                          ( m_acLayerCfg[layer].getPad() );
+
+    m_acTEncTop[layer].setMaxTempLayer                 ( m_maxTempLayer );
+#if !REMOVE_NSQT
+    m_acTEncTop[layer].setUseNSQT( m_enableNSQT );
+#endif
+    m_acTEncTop[layer].setUseAMP( m_enableAMP );
+
+    //===== Slice ========
+
+    //====== Loop/Deblock Filter ========
+    m_acTEncTop[layer].setLoopFilterDisable            ( m_bLoopFilterDisable       );
+    m_acTEncTop[layer].setLoopFilterOffsetInPPS        ( m_loopFilterOffsetInPPS );
+    m_acTEncTop[layer].setLoopFilterBetaOffset         ( m_loopFilterBetaOffsetDiv2  );
+    m_acTEncTop[layer].setLoopFilterTcOffset           ( m_loopFilterTcOffsetDiv2    );
+    m_acTEncTop[layer].setDeblockingFilterControlPresent( m_DeblockingFilterControlPresent);
+
+    //====== Motion search ========
+    m_acTEncTop[layer].setFastSearch                   ( m_iFastSearch  );
+    m_acTEncTop[layer].setSearchRange                  ( m_iSearchRange );
+    m_acTEncTop[layer].setBipredSearchRange            ( m_bipredSearchRange );
+
+    //====== Quality control ========
+    m_acTEncTop[layer].setMaxDeltaQP                   ( m_iMaxDeltaQP  );
+    m_acTEncTop[layer].setMaxCuDQPDepth                ( m_iMaxCuDQPDepth  );
+
+    m_acTEncTop[layer].setChromaCbQpOffset               ( m_cbQpOffset     );
+    m_acTEncTop[layer].setChromaCrQpOffset            ( m_crQpOffset  );
+
+#if ADAPTIVE_QP_SELECTION
+    m_acTEncTop[layer].setUseAdaptQpSelect             ( m_bUseAdaptQpSelect   );
+#endif
+
+    Int lowestQP;
+    lowestQP =  - ( (Int)(6*(g_uiBitDepth + g_uiBitIncrement - 8)) );
+
+    if ((m_iMaxDeltaQP == 0 ) && (m_acLayerCfg[layer].getIntQP() == lowestQP) && (m_useLossless == true))
+    {
+      m_bUseAdaptiveQP = false;
+    }
+    m_acTEncTop[layer].setUseAdaptiveQP                ( m_bUseAdaptiveQP  );
+    m_acTEncTop[layer].setQPAdaptationRange            ( m_iQPAdaptationRange );
+
+    //====== Tool list ========
+    m_acTEncTop[layer].setUseSBACRD                    ( m_bUseSBACRD   );
+    m_acTEncTop[layer].setDeltaQpRD                    ( m_uiDeltaQpRD  );
+    m_acTEncTop[layer].setUseASR                       ( m_bUseASR      );
+    m_acTEncTop[layer].setUseHADME                     ( m_bUseHADME    );
+#if !REMOVE_ALF
+    m_acTEncTop[layer].setUseALF                       ( m_bUseALF      );
+#endif
+    m_acTEncTop[layer].setUseLossless                  ( m_useLossless );
+    m_acTEncTop[layer].setUseLComb                     ( m_bUseLComb    );
+    m_acTEncTop[layer].setdQPs                         ( m_acLayerCfg[layer].getdQPs()        );
+    m_acTEncTop[layer].setUseRDOQ                      ( m_bUseRDOQ     );
+    m_acTEncTop[layer].setQuadtreeTULog2MaxSize        ( m_uiQuadtreeTULog2MaxSize );
+    m_acTEncTop[layer].setQuadtreeTULog2MinSize        ( m_uiQuadtreeTULog2MinSize );
+    m_acTEncTop[layer].setQuadtreeTUMaxDepthInter      ( m_uiQuadtreeTUMaxDepthInter );
+    m_acTEncTop[layer].setQuadtreeTUMaxDepthIntra      ( m_uiQuadtreeTUMaxDepthIntra );
+    m_acTEncTop[layer].setUseFastEnc                   ( m_bUseFastEnc  );
+    m_acTEncTop[layer].setUseEarlyCU                   ( m_bUseEarlyCU  ); 
+    m_acTEncTop[layer].setUseFastDecisionForMerge      ( m_useFastDecisionForMerge  );
+    m_acTEncTop[layer].setUseCbfFastMode            ( m_bUseCbfFastMode  );
+    m_acTEncTop[layer].setUseEarlySkipDetection            ( m_useEarlySkipDetection );
+
+#if !REMOVE_LMCHROMA
+    m_acTEncTop[layer].setUseLMChroma                  ( m_bUseLMChroma );
+#endif
+    m_acTEncTop[layer].setUseTransformSkip             ( m_useTransformSkip      );
+    m_acTEncTop[layer].setUseTransformSkipFast         ( m_useTransformSkipFast  );
+    m_acTEncTop[layer].setUseConstrainedIntraPred      ( m_bUseConstrainedIntraPred );
+    m_acTEncTop[layer].setPCMLog2MinSize          ( m_uiPCMLog2MinSize);
+    m_acTEncTop[layer].setUsePCM                       ( m_usePCM );
+    m_acTEncTop[layer].setPCMLog2MaxSize               ( m_pcmLog2MaxSize);
+    m_acTEncTop[layer].setMaxNumMergeCand              ( m_maxNumMergeCand );
+
+
+    //====== Weighted Prediction ========
+    m_acTEncTop[layer].setUseWP                   ( m_bUseWeightPred      );
+    m_acTEncTop[layer].setWPBiPred                ( m_useWeightedBiPred   );
+    //====== Parallel Merge Estimation ========
+    m_acTEncTop[layer].setLog2ParallelMergeLevelMinus2 ( m_log2ParallelMergeLevel - 2 );
+
+    //====== Slice ========
+    m_acTEncTop[layer].setSliceMode               ( m_iSliceMode                );
+    m_acTEncTop[layer].setSliceArgument           ( m_iSliceArgument            );
+
+    //====== Dependent Slice ========
+    m_acTEncTop[layer].setDependentSliceMode        ( m_iDependentSliceMode         );
+    m_acTEncTop[layer].setDependentSliceArgument    ( m_iDependentSliceArgument     );
+#if DEPENDENT_SLICES
+#if TILES_WPP_ENTROPYSLICES_FLAGS
+    m_acTEncTop[layer].setEntropySliceEnabledFlag   ( m_entropySliceEnabledFlag );
+#else
+    m_acTEncTop[layer].setCabacIndependentFlag      ( m_bCabacIndependentFlag   );
+#endif
+#endif
+    int iNumPartInCU = 1<<(m_uiMaxCUDepth<<1);
+    if(m_iDependentSliceMode==SHARP_FIXED_NUMBER_OF_LCU_IN_DEPENDENT_SLICE)
+    {
+#if REMOVE_FGS
+      m_acTEncTop[layer].setDependentSliceArgument ( m_iDependentSliceArgument * iNumPartInCU );
+#else
+      m_acTEncTop[layer].setDependentSliceArgument ( m_iDependentSliceArgument * ( iNumPartInCU >> ( m_iSliceGranularity << 1 ) ) );
+#endif
+    }
+    if(m_iSliceMode==AD_HOC_SLICES_FIXED_NUMBER_OF_LCU_IN_SLICE)
+    {
+#if REMOVE_FGS
+      m_acTEncTop[layer].setSliceArgument ( m_iSliceArgument * iNumPartInCU );
+#else
+      m_acTEncTop[layer].setSliceArgument ( m_iSliceArgument * ( iNumPartInCU >> ( m_iSliceGranularity << 1 ) ) );
+#endif
+    }
+    if(m_iSliceMode==AD_HOC_SLICES_FIXED_NUMBER_OF_TILES_IN_SLICE)
+    {
+      m_acTEncTop[layer].setSliceArgument ( m_iSliceArgument );
+    }
+
+#if !REMOVE_FGS
+    m_acTEncTop[layer].setSliceGranularity        ( m_iSliceGranularity         );
+#endif
+    if(m_iSliceMode == 0 )
+    {
+      m_bLFCrossSliceBoundaryFlag = true;
+    }
+    m_acTEncTop[layer].setLFCrossSliceBoundaryFlag( m_bLFCrossSliceBoundaryFlag );
+    m_acTEncTop[layer].setUseSAO ( m_bUseSAO );
+    m_acTEncTop[layer].setMaxNumOffsetsPerPic (m_maxNumOffsetsPerPic);
+
+#if SAO_LCU_BOUNDARY
+    m_acTEncTop[layer].setSaoLcuBoundary (m_saoLcuBoundary);
+#endif
+    m_acTEncTop[layer].setSaoLcuBasedOptimization (m_saoLcuBasedOptimization);
+    m_acTEncTop[layer].setPCMInputBitDepthFlag  ( m_bPCMInputBitDepthFlag); 
+    m_acTEncTop[layer].setPCMFilterDisableFlag  ( m_bPCMFilterDisableFlag); 
+
+    m_acTEncTop[layer].setDecodedPictureHashSEIEnabled(m_decodePictureHashSEIEnabled);
+#if RECOVERY_POINT_SEI
+    m_acTEncTop[layer].setRecoveryPointSEIEnabled( m_recoveryPointSEIEnabled );
+#endif
+#if BUFFERING_PERIOD_AND_TIMING_SEI
+    m_acTEncTop[layer].setBufferingPeriodSEIEnabled( m_bufferingPeriodSEIEnabled );
+    m_acTEncTop[layer].setPictureTimingSEIEnabled( m_pictureTimingSEIEnabled );
+#endif
+    m_acTEncTop[layer].setUniformSpacingIdr          ( m_iUniformSpacingIdr );
+    m_acTEncTop[layer].setNumColumnsMinus1           ( m_iNumColumnsMinus1 );
+    m_acTEncTop[layer].setNumRowsMinus1              ( m_iNumRowsMinus1 );
+    if(m_iUniformSpacingIdr==0)
+    {
+      m_acTEncTop[layer].setColumnWidth              ( m_pchColumnWidth );
+      m_acTEncTop[layer].setRowHeight                ( m_pchRowHeight );
+    }
+    m_acTEncTop[layer].xCheckGSParameters();
+    Int uiTilesCount          = (m_iNumRowsMinus1+1) * (m_iNumColumnsMinus1+1);
+    if(uiTilesCount == 1)
+    {
+      m_bLFCrossTileBoundaryFlag = true; 
+    }
+    m_acTEncTop[layer].setLFCrossTileBoundaryFlag( m_bLFCrossTileBoundaryFlag );
+    m_acTEncTop[layer].setWaveFrontSynchro           ( m_iWaveFrontSynchro );
+    m_acTEncTop[layer].setWaveFrontSubstreams        ( m_acLayerCfg[layer].m_iWaveFrontSubstreams );
+    m_acTEncTop[layer].setTMVPModeId ( m_TMVPModeId );
+    m_acTEncTop[layer].setUseScalingListId           ( m_useScalingListId  );
+    m_acTEncTop[layer].setScalingListFile            ( m_scalingListFile   );
+    m_acTEncTop[layer].setSignHideFlag(m_signHideFlag);
+#if !REMOVE_ALF
+    m_acTEncTop[layer].setALFLowLatencyEncoding( m_alfLowLatencyEncoding );
+#endif
+    m_acTEncTop[layer].setUseRateCtrl     ( m_enableRateCtrl);
+    m_acTEncTop[layer].setTargetBitrate   ( m_targetBitrate);
+    m_acTEncTop[layer].setNumLCUInUnit    ( m_numLCUInUnit);
+    m_acTEncTop[layer].setTransquantBypassEnableFlag(m_TransquantBypassEnableFlag);
+    m_acTEncTop[layer].setCUTransquantBypassFlagValue(m_CUTransquantBypassFlagValue);
+#if RECALCULATE_QP_ACCORDING_LAMBDA
+    m_acTEncTop[layer].setUseRecalculateQPAccordingToLambda( m_recalculateQPAccordingToLambda );
+#endif
+#if ACTIVE_PARAMETER_SETS_SEI_MESSAGE
+    m_acTEncTop[layer].setActiveParameterSetsSEIEnabled ( m_activeParameterSetsSEIEnabled ); 
+#endif 
+#if SUPPORT_FOR_VUI
+    m_acTEncTop[layer].setVuiParametersPresentFlag( m_vuiParametersPresentFlag );
+    m_acTEncTop[layer].setAspectRatioIdc( m_aspectRatioIdc );
+    m_acTEncTop[layer].setSarWidth( m_sarWidth );
+    m_acTEncTop[layer].setSarHeight( m_sarHeight );
+    m_acTEncTop[layer].setOverscanInfoPresentFlag( m_overscanInfoPresentFlag );
+    m_acTEncTop[layer].setOverscanAppropriateFlag( m_overscanAppropriateFlag );
+    m_acTEncTop[layer].setVideoSignalTypePresentFlag( m_videoSignalTypePresentFlag );
+    m_acTEncTop[layer].setVideoFormat( m_videoFormat );
+    m_acTEncTop[layer].setVideoFullRangeFlag( m_videoFullRangeFlag );
+    m_acTEncTop[layer].setColourDescriptionPresentFlag( m_colourDescriptionPresentFlag );
+    m_acTEncTop[layer].setColourPrimaries( m_colourPrimaries );
+    m_acTEncTop[layer].setTransferCharacteristics( m_transferCharacteristics );
+    m_acTEncTop[layer].setMatrixCoefficients( m_matrixCoefficients );
+    m_acTEncTop[layer].setChromaLocInfoPresentFlag( m_chromaLocInfoPresentFlag );
+    m_acTEncTop[layer].setChromaSampleLocTypeTopField( m_chromaSampleLocTypeTopField );
+    m_acTEncTop[layer].setChromaSampleLocTypeBottomField( m_chromaSampleLocTypeBottomField );
+    m_acTEncTop[layer].setNeutralChromaIndicationFlag( m_neutralChromaIndicationFlag );
+    m_acTEncTop[layer].setBitstreamRestrictionFlag( m_bitstreamRestrictionFlag );
+    m_acTEncTop[layer].setTilesFixedStructureFlag( m_tilesFixedStructureFlag );
+    m_acTEncTop[layer].setMotionVectorsOverPicBoundariesFlag( m_motionVectorsOverPicBoundariesFlag );
+    m_acTEncTop[layer].setMaxBytesPerPicDenom( m_maxBytesPerPicDenom );
+    m_acTEncTop[layer].setMaxBitsPerMinCuDenom( m_maxBitsPerMinCuDenom );
+    m_acTEncTop[layer].setLog2MaxMvLengthHorizontal( m_log2MaxMvLengthHorizontal );
+    m_acTEncTop[layer].setLog2MaxMvLengthVertical( m_log2MaxMvLengthVertical );
+#endif
+#if REF_IDX_FRAMEWORK
+    m_acTEncTop[layer].setElRapSliceTypeB(layer == 0? 0 : m_elRapSliceBEnabled);
+#endif
+  }
+}
+#else
+Void TAppEncTop::xInitLibCfg()
+{
+  TComVPS vps;
+  
+  vps.setMaxTLayers                       ( m_maxTempLayer );
+  vps.setMaxLayers                        ( 1 );
+  for(Int i = 0; i < MAX_TLAYER; i++)
+  {
+    vps.setNumReorderPics                 ( m_numReorderPics[i], i );
+    vps.setMaxDecPicBuffering             ( m_maxDecPicBuffering[i], i );
+  }
+  m_cTEncTop.setVPS(&vps);
+  m_cTEncTop.setFrameRate                    ( m_iFrameRate );
+  m_cTEncTop.setFrameSkip                    ( m_FrameSkip );
+  m_cTEncTop.setSourceWidth                  ( m_iSourceWidth );
+  m_cTEncTop.setSourceHeight                 ( m_iSourceHeight );
+  m_cTEncTop.setCroppingMode                 ( m_croppingMode );
+  m_cTEncTop.setCropLeft                     ( m_cropLeft );
+  m_cTEncTop.setCropRight                    ( m_cropRight );
+  m_cTEncTop.setCropTop                      ( m_cropTop );
+  m_cTEncTop.setCropBottom                   ( m_cropBottom );
+  m_cTEncTop.setFrameToBeEncoded             ( m_iFrameToBeEncoded );
+  
+  //====== Coding Structure ========
+  m_cTEncTop.setIntraPeriod                  ( m_iIntraPeriod );
+  m_cTEncTop.setDecodingRefreshType          ( m_iDecodingRefreshType );
+  m_cTEncTop.setGOPSize                      ( m_iGOPSize );
+  m_cTEncTop.setGopList                      ( m_GOPList );
+  m_cTEncTop.setExtraRPSs                    ( m_extraRPSs );
+  for(Int i = 0; i < MAX_TLAYER; i++)
+  {
+    m_cTEncTop.setNumReorderPics             ( m_numReorderPics[i], i );
+    m_cTEncTop.setMaxDecPicBuffering         ( m_maxDecPicBuffering[i], i );
+  }
+  for( UInt uiLoop = 0; uiLoop < MAX_TLAYER; ++uiLoop )
+  {
+    m_cTEncTop.setLambdaModifier( uiLoop, m_adLambdaModifier[ uiLoop ] );
+  }
+  m_cTEncTop.setQP                           ( m_iQP );
+  
+  m_cTEncTop.setPad                          ( m_aiPad );
+    
+  m_cTEncTop.setMaxTempLayer                 ( m_maxTempLayer );
+#if !REMOVE_NSQT
+  m_cTEncTop.setUseNSQT( m_enableNSQT );
+#endif
+  m_cTEncTop.setUseAMP( m_enableAMP );
+  
+  //===== Slice ========
+  
+  //====== Loop/Deblock Filter ========
+  m_cTEncTop.setLoopFilterDisable            ( m_bLoopFilterDisable       );
+  m_cTEncTop.setLoopFilterOffsetInPPS        ( m_loopFilterOffsetInPPS );
+  m_cTEncTop.setLoopFilterBetaOffset         ( m_loopFilterBetaOffsetDiv2  );
+  m_cTEncTop.setLoopFilterTcOffset           ( m_loopFilterTcOffsetDiv2    );
+  m_cTEncTop.setDeblockingFilterControlPresent( m_DeblockingFilterControlPresent);
+
+  //====== Motion search ========
+  m_cTEncTop.setFastSearch                   ( m_iFastSearch  );
+  m_cTEncTop.setSearchRange                  ( m_iSearchRange );
+  m_cTEncTop.setBipredSearchRange            ( m_bipredSearchRange );
+
+  //====== Quality control ========
+  m_cTEncTop.setMaxDeltaQP                   ( m_iMaxDeltaQP  );
+  m_cTEncTop.setMaxCuDQPDepth                ( m_iMaxCuDQPDepth  );
+
+  m_cTEncTop.setChromaCbQpOffset               ( m_cbQpOffset     );
+  m_cTEncTop.setChromaCrQpOffset            ( m_crQpOffset  );
+
+#if ADAPTIVE_QP_SELECTION
+  m_cTEncTop.setUseAdaptQpSelect             ( m_bUseAdaptQpSelect   );
+#endif
+
+  Int lowestQP;
+  lowestQP =  - ( (Int)(6*(g_uiBitDepth + g_uiBitIncrement - 8)) );
+
+  if ((m_iMaxDeltaQP == 0 ) && (m_iQP == lowestQP) && (m_useLossless == true))
+  {
+    m_bUseAdaptiveQP = false;
+  }
+  m_cTEncTop.setUseAdaptiveQP                ( m_bUseAdaptiveQP  );
+  m_cTEncTop.setQPAdaptationRange            ( m_iQPAdaptationRange );
+  
+  //====== Tool list ========
+  m_cTEncTop.setUseSBACRD                    ( m_bUseSBACRD   );
+  m_cTEncTop.setDeltaQpRD                    ( m_uiDeltaQpRD  );
+  m_cTEncTop.setUseASR                       ( m_bUseASR      );
+  m_cTEncTop.setUseHADME                     ( m_bUseHADME    );
+#if !REMOVE_ALF
+  m_cTEncTop.setUseALF                       ( m_bUseALF      );
+#endif
+  m_cTEncTop.setUseLossless                  ( m_useLossless );
+  m_cTEncTop.setUseLComb                     ( m_bUseLComb    );
+  m_cTEncTop.setdQPs                         ( m_aidQP        );
+  m_cTEncTop.setUseRDOQ                      ( m_bUseRDOQ     );
+  m_cTEncTop.setQuadtreeTULog2MaxSize        ( m_uiQuadtreeTULog2MaxSize );
+  m_cTEncTop.setQuadtreeTULog2MinSize        ( m_uiQuadtreeTULog2MinSize );
+  m_cTEncTop.setQuadtreeTUMaxDepthInter      ( m_uiQuadtreeTUMaxDepthInter );
+  m_cTEncTop.setQuadtreeTUMaxDepthIntra      ( m_uiQuadtreeTUMaxDepthIntra );
+  m_cTEncTop.setUseFastEnc                   ( m_bUseFastEnc  );
+  m_cTEncTop.setUseEarlyCU                   ( m_bUseEarlyCU  ); 
+  m_cTEncTop.setUseFastDecisionForMerge      ( m_useFastDecisionForMerge  );
+  m_cTEncTop.setUseCbfFastMode            ( m_bUseCbfFastMode  );
+  m_cTEncTop.setUseEarlySkipDetection            ( m_useEarlySkipDetection );
+
+#if !REMOVE_LMCHROMA
+  m_cTEncTop.setUseLMChroma                  ( m_bUseLMChroma );
+#endif
+  m_cTEncTop.setUseTransformSkip             ( m_useTransformSkip      );
+  m_cTEncTop.setUseTransformSkipFast         ( m_useTransformSkipFast  );
+  m_cTEncTop.setUseConstrainedIntraPred      ( m_bUseConstrainedIntraPred );
+  m_cTEncTop.setPCMLog2MinSize          ( m_uiPCMLog2MinSize);
+  m_cTEncTop.setUsePCM                       ( m_usePCM );
+  m_cTEncTop.setPCMLog2MaxSize               ( m_pcmLog2MaxSize);
+  m_cTEncTop.setMaxNumMergeCand              ( m_maxNumMergeCand );
+  
+
+  //====== Weighted Prediction ========
+  m_cTEncTop.setUseWP                   ( m_bUseWeightPred      );
+  m_cTEncTop.setWPBiPred                ( m_useWeightedBiPred   );
+  //====== Parallel Merge Estimation ========
+  m_cTEncTop.setLog2ParallelMergeLevelMinus2 ( m_log2ParallelMergeLevel - 2 );
+
+  //====== Slice ========
+  m_cTEncTop.setSliceMode               ( m_iSliceMode                );
+  m_cTEncTop.setSliceArgument           ( m_iSliceArgument            );
+
+  //====== Dependent Slice ========
+  m_cTEncTop.setDependentSliceMode        ( m_iDependentSliceMode         );
+  m_cTEncTop.setDependentSliceArgument    ( m_iDependentSliceArgument     );
+#if DEPENDENT_SLICES
+#if TILES_WPP_ENTROPYSLICES_FLAGS
+  m_cTEncTop.setEntropySliceEnabledFlag   ( m_entropySliceEnabledFlag );
+#else
+  m_cTEncTop.setCabacIndependentFlag      ( m_bCabacIndependentFlag   );
+#endif
+#endif
+  int iNumPartInCU = 1<<(m_uiMaxCUDepth<<1);
+  if(m_iDependentSliceMode==SHARP_FIXED_NUMBER_OF_LCU_IN_DEPENDENT_SLICE)
+  {
+#if REMOVE_FGS
+    m_cTEncTop.setDependentSliceArgument ( m_iDependentSliceArgument * iNumPartInCU );
+#else
+    m_cTEncTop.setDependentSliceArgument ( m_iDependentSliceArgument * ( iNumPartInCU >> ( m_iSliceGranularity << 1 ) ) );
+#endif
+  }
+  if(m_iSliceMode==AD_HOC_SLICES_FIXED_NUMBER_OF_LCU_IN_SLICE)
+  {
+#if REMOVE_FGS
+    m_cTEncTop.setSliceArgument ( m_iSliceArgument * iNumPartInCU );
+#else
+    m_cTEncTop.setSliceArgument ( m_iSliceArgument * ( iNumPartInCU >> ( m_iSliceGranularity << 1 ) ) );
+#endif
+  }
+  if(m_iSliceMode==AD_HOC_SLICES_FIXED_NUMBER_OF_TILES_IN_SLICE)
+  {
+    m_cTEncTop.setSliceArgument ( m_iSliceArgument );
+  }
+  
+#if !REMOVE_FGS
+  m_cTEncTop.setSliceGranularity        ( m_iSliceGranularity         );
+#endif
+  if(m_iSliceMode == 0 )
+  {
+    m_bLFCrossSliceBoundaryFlag = true;
+  }
+  m_cTEncTop.setLFCrossSliceBoundaryFlag( m_bLFCrossSliceBoundaryFlag );
+  m_cTEncTop.setUseSAO ( m_bUseSAO );
+  m_cTEncTop.setMaxNumOffsetsPerPic (m_maxNumOffsetsPerPic);
+
+#if SAO_LCU_BOUNDARY
+  m_cTEncTop.setSaoLcuBoundary (m_saoLcuBoundary);
+#endif
+  m_cTEncTop.setSaoLcuBasedOptimization (m_saoLcuBasedOptimization);
+  m_cTEncTop.setPCMInputBitDepthFlag  ( m_bPCMInputBitDepthFlag); 
+  m_cTEncTop.setPCMFilterDisableFlag  ( m_bPCMFilterDisableFlag); 
+
+  m_cTEncTop.setDecodedPictureHashSEIEnabled(m_decodePictureHashSEIEnabled);
+#if RECOVERY_POINT_SEI
+  m_cTEncTop.setRecoveryPointSEIEnabled( m_recoveryPointSEIEnabled );
+#endif
+#if BUFFERING_PERIOD_AND_TIMING_SEI
+  m_cTEncTop.setBufferingPeriodSEIEnabled( m_bufferingPeriodSEIEnabled );
+  m_cTEncTop.setPictureTimingSEIEnabled( m_pictureTimingSEIEnabled );
+#endif
+  m_cTEncTop.setUniformSpacingIdr          ( m_iUniformSpacingIdr );
+  m_cTEncTop.setNumColumnsMinus1           ( m_iNumColumnsMinus1 );
+  m_cTEncTop.setNumRowsMinus1              ( m_iNumRowsMinus1 );
+  if(m_iUniformSpacingIdr==0)
+  {
+    m_cTEncTop.setColumnWidth              ( m_pchColumnWidth );
+    m_cTEncTop.setRowHeight                ( m_pchRowHeight );
+  }
+  m_cTEncTop.xCheckGSParameters();
+  Int uiTilesCount          = (m_iNumRowsMinus1+1) * (m_iNumColumnsMinus1+1);
+  if(uiTilesCount == 1)
+  {
+    m_bLFCrossTileBoundaryFlag = true; 
+  }
+  m_cTEncTop.setLFCrossTileBoundaryFlag( m_bLFCrossTileBoundaryFlag );
+  m_cTEncTop.setWaveFrontSynchro           ( m_iWaveFrontSynchro );
+  m_cTEncTop.setWaveFrontSubstreams        ( m_iWaveFrontSubstreams );
+  m_cTEncTop.setTMVPModeId ( m_TMVPModeId );
+  m_cTEncTop.setUseScalingListId           ( m_useScalingListId  );
+  m_cTEncTop.setScalingListFile            ( m_scalingListFile   );
+  m_cTEncTop.setSignHideFlag(m_signHideFlag);
+#if !REMOVE_ALF
+  m_cTEncTop.setALFLowLatencyEncoding( m_alfLowLatencyEncoding );
+#endif
+  m_cTEncTop.setUseRateCtrl     ( m_enableRateCtrl);
+  m_cTEncTop.setTargetBitrate   ( m_targetBitrate);
+  m_cTEncTop.setNumLCUInUnit    ( m_numLCUInUnit);
+  m_cTEncTop.setTransquantBypassEnableFlag(m_TransquantBypassEnableFlag);
+  m_cTEncTop.setCUTransquantBypassFlagValue(m_CUTransquantBypassFlagValue);
+#if RECALCULATE_QP_ACCORDING_LAMBDA
+  m_cTEncTop.setUseRecalculateQPAccordingToLambda( m_recalculateQPAccordingToLambda );
+#endif
+#if ACTIVE_PARAMETER_SETS_SEI_MESSAGE
+  m_cTEncTop.setActiveParameterSetsSEIEnabled ( m_activeParameterSetsSEIEnabled ); 
+#endif 
+#if SUPPORT_FOR_VUI
+  m_cTEncTop.setVuiParametersPresentFlag( m_vuiParametersPresentFlag );
+  m_cTEncTop.setAspectRatioIdc( m_aspectRatioIdc );
+  m_cTEncTop.setSarWidth( m_sarWidth );
+  m_cTEncTop.setSarHeight( m_sarHeight );
+  m_cTEncTop.setOverscanInfoPresentFlag( m_overscanInfoPresentFlag );
+  m_cTEncTop.setOverscanAppropriateFlag( m_overscanAppropriateFlag );
+  m_cTEncTop.setVideoSignalTypePresentFlag( m_videoSignalTypePresentFlag );
+  m_cTEncTop.setVideoFormat( m_videoFormat );
+  m_cTEncTop.setVideoFullRangeFlag( m_videoFullRangeFlag );
+  m_cTEncTop.setColourDescriptionPresentFlag( m_colourDescriptionPresentFlag );
+  m_cTEncTop.setColourPrimaries( m_colourPrimaries );
+  m_cTEncTop.setTransferCharacteristics( m_transferCharacteristics );
+  m_cTEncTop.setMatrixCoefficients( m_matrixCoefficients );
+  m_cTEncTop.setChromaLocInfoPresentFlag( m_chromaLocInfoPresentFlag );
+  m_cTEncTop.setChromaSampleLocTypeTopField( m_chromaSampleLocTypeTopField );
+  m_cTEncTop.setChromaSampleLocTypeBottomField( m_chromaSampleLocTypeBottomField );
+  m_cTEncTop.setNeutralChromaIndicationFlag( m_neutralChromaIndicationFlag );
+  m_cTEncTop.setBitstreamRestrictionFlag( m_bitstreamRestrictionFlag );
+  m_cTEncTop.setTilesFixedStructureFlag( m_tilesFixedStructureFlag );
+  m_cTEncTop.setMotionVectorsOverPicBoundariesFlag( m_motionVectorsOverPicBoundariesFlag );
+  m_cTEncTop.setMaxBytesPerPicDenom( m_maxBytesPerPicDenom );
+  m_cTEncTop.setMaxBitsPerMinCuDenom( m_maxBitsPerMinCuDenom );
+  m_cTEncTop.setLog2MaxMvLengthHorizontal( m_log2MaxMvLengthHorizontal );
+  m_cTEncTop.setLog2MaxMvLengthVertical( m_log2MaxMvLengthVertical );
+#endif
+}
+#endif
+
+Void TAppEncTop::xCreateLib()
+{
+  // Video I/O
+#if SVC_EXTENSION
+  // initialize global variables
+  initROM();
+
+  for(UInt layer=0; layer<m_numLayers; layer++)
+  {
+    m_acTVideoIOYuvInputFile[layer].open( (char *)m_acLayerCfg[layer].getInputFile().c_str(),  false, m_uiInputBitDepth, m_uiInternalBitDepth );  // read  mode
+    m_acTVideoIOYuvInputFile[layer].skipFrames(m_FrameSkip, m_acLayerCfg[layer].getSourceWidth() - m_acLayerCfg[layer].getPad()[0], m_acLayerCfg[layer].getSourceHeight() - m_acLayerCfg[layer].getPad()[1]);
+
+    if (!m_acLayerCfg[layer].getReconFile().empty())
+    {
+      m_acTVideoIOYuvReconFile[layer].open((char *)m_acLayerCfg[layer].getReconFile().c_str(), true, m_uiOutputBitDepth, m_uiInternalBitDepth);  // write mode
+    }
+
+    m_acTEncTop[layer].create();
+  }
+#else
+  m_cTVideoIOYuvInputFile.open( m_pchInputFile,     false, m_uiInputBitDepth, m_uiInternalBitDepth );  // read  mode
+  m_cTVideoIOYuvInputFile.skipFrames(m_FrameSkip, m_iSourceWidth - m_aiPad[0], m_iSourceHeight - m_aiPad[1]);
+
+  if (m_pchReconFile)
+    m_cTVideoIOYuvReconFile.open(m_pchReconFile, true, m_uiOutputBitDepth, m_uiInternalBitDepth);  // write mode
+  
+  // Neo Decoder
+  m_cTEncTop.create();
+#endif
+}
+
+Void TAppEncTop::xDestroyLib()
+{
+  // Video I/O
+#if SVC_EXTENSION
+  // destroy ROM
+  destroyROM();
+
+  for(UInt layer=0; layer<m_numLayers; layer++)
+  {
+    m_acTVideoIOYuvInputFile[layer].close();
+    m_acTVideoIOYuvReconFile[layer].close();
+
+    m_acTEncTop[layer].destroy();
+  }
+#else
+  m_cTVideoIOYuvInputFile.close();
+  m_cTVideoIOYuvReconFile.close();
+  
+  // Neo Decoder
+  m_cTEncTop.destroy();
+#endif
+}
+
+Void TAppEncTop::xInitLib()
+{
+#if SVC_EXTENSION
+  for(UInt layer=0; layer<m_numLayers; layer++)
+  {
+    m_acTEncTop[layer].init();
+  }
+#else
+  m_cTEncTop.init();
+#endif
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/**
+ - create internal class
+ - initialize internal variable
+ - until the end of input YUV file, call encoding function in TEncTop class
+ - delete allocated buffers
+ - destroy internal class
+ .
+ */
+#if SVC_EXTENSION
+Void TAppEncTop::encode()
+{
+  fstream bitstreamFile(m_pchBitstreamFile, fstream::binary | fstream::out);
+  if (!bitstreamFile)
+  {
+    fprintf(stderr, "\nfailed to open bitstream file `%s' for writing\n", m_pchBitstreamFile);
+    exit(EXIT_FAILURE);
+  }
+
+  TComPicYuv*       pcPicYuvOrg [MAX_LAYERS];
+  TComPicYuv*       pcPicYuvRec = NULL;
+  
+  // initialize internal class & member variables
+
+  xInitLibCfg();
+  xCreateLib();
+  xInitLib();
+
+  // main encoder loop
+  Int   iNumEncoded, iTotalNumEncoded;
+  Bool  bEos = false, bBaseEos = false;
+  
+  list<AccessUnit> outputAccessUnits; ///< list of access units to write out.  is populated by the encoding process
+
+  for(UInt layer=0; layer<m_numLayers; layer++)
+  {
+    // allocate original YUV buffer
+    pcPicYuvOrg[layer] = new TComPicYuv;
+#if SVC_UPSAMPLING 
+    pcPicYuvOrg[layer]->create( m_acLayerCfg[layer].getSourceWidth(), m_acLayerCfg[layer].getSourceHeight(), m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth, NULL );
+#else
+    pcPicYuvOrg[layer]->create( m_acLayerCfg[layer].getSourceWidth(), m_acLayerCfg[layer].getSourceHeight(), m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth );
+#endif
+  }
+
+  Bool bFirstFrame = true;
+  while ( !bEos )
+  {
+    // Read enough frames 
+    Bool bFramesReadyToCode = false;
+    while(!bFramesReadyToCode)
+    {
+      for(UInt layer=0; layer<m_numLayers; layer++)
+      {
+        // get buffers
+        xGetBuffer(pcPicYuvRec, layer);
+
+        m_acTVideoIOYuvInputFile[layer].read( pcPicYuvOrg[layer], m_acLayerCfg[layer].getPad() );
+    
+        if(layer == m_numLayers-1)
+        {
+          // increase number of received frames
+          m_iFrameRcvd++;
+          // check end of file
+          bEos = ( m_acTVideoIOYuvInputFile[layer].isEof() == 1 ?   true : bBaseEos? true : bEos  );
+          bEos = ( m_iFrameRcvd == m_iFrameToBeEncoded ?    true : bEos   );
+        }
+        else
+        {
+          // check end of file of base layers
+          bBaseEos = ( m_acTVideoIOYuvInputFile[layer].isEof() == 1 ?   true : bBaseEos  );
+        }
+        m_acTEncTop[layer].encodePrep( bEos, pcPicYuvOrg[layer] );
+      }
+
+      bFramesReadyToCode = !(!bFirstFrame && ( m_acTEncTop[m_numLayers-1].getNumPicRcvd() != m_iGOPSize && m_iGOPSize ) && !bEos );
+    }
+
+    // loop through frames in one GOP 
+    for ( UInt iPicIdInGOP=0; iPicIdInGOP < (bFirstFrame? 1:m_iGOPSize); iPicIdInGOP++ )
+    {
+      // layer by layer for each frame
+      for(UInt layer=0; layer<m_numLayers; layer++)
+      {
+        // call encoding function for one frame
+        m_acTEncTop[layer].encode( pcPicYuvOrg[layer], m_acListPicYuvRec[layer], 
+          outputAccessUnits, iPicIdInGOP );
+      }
+    }
+
+    iTotalNumEncoded = 0;
+    for(UInt layer=0; layer<m_numLayers; layer++)
+    {
+      // write bistream to file if necessary
+      iNumEncoded = m_acTEncTop[layer].getNumPicRcvd();
+      if ( iNumEncoded > 0 )  
+      {
+        xWriteRecon(layer, iNumEncoded);
+        iTotalNumEncoded += iNumEncoded;
+      }
+      m_acTEncTop[layer].setNumPicRcvd( 0 );
+    }
+
+    // write bitstream out
+    if(iTotalNumEncoded)
+    {
+      xWriteStream(bitstreamFile, iTotalNumEncoded, outputAccessUnits);
+      outputAccessUnits.clear();
+    }
+
+    // print out summary
+    if (bEos)
+    {
+      printOutSummary();
+    }
+
+    bFirstFrame = false;
+  }
+
+  // delete original YUV buffer
+  for(UInt layer=0; layer<m_numLayers; layer++)
+  {
+    pcPicYuvOrg[layer]->destroy();
+    delete pcPicYuvOrg[layer];
+    pcPicYuvOrg[layer] = NULL;
+
+    // delete used buffers in encoder class
+    m_acTEncTop[layer].deletePicBuffer();
+  }
+  
+  // delete buffers & classes
+  xDeleteBuffer();
+  xDestroyLib();
+  
+  printRateSummary();
+
+  return;
+}
+
+
+Void TAppEncTop::printOutSummary()
+{
+  UInt layer;
+
+  // set frame rate
+  for(layer = 0; layer < m_numLayers; layer++)
+  {
+    m_gcAnalyzeAll[layer].setFrmRate( m_acLayerCfg[layer].getFrameRate());
+    m_gcAnalyzeI[layer].setFrmRate( m_acLayerCfg[layer].getFrameRate() );
+    m_gcAnalyzeP[layer].setFrmRate( m_acLayerCfg[layer].getFrameRate() );
+    m_gcAnalyzeB[layer].setFrmRate( m_acLayerCfg[layer].getFrameRate() );
+  }
+
+  //-- all
+  printf( "\n\nSUMMARY --------------------------------------------------------\n" );
+  printf( "\tTotal Frames |  "   "Bitrate    "  "Y-PSNR    "  "U-PSNR    "  "V-PSNR \n" );
+  for(layer = 0; layer < m_numLayers; layer++)
+  {
+    m_gcAnalyzeAll[layer].printOut('a', layer);
+  }
+    
+  printf( "\n\nI Slices--------------------------------------------------------\n" );
+  printf( "\tTotal Frames |  "   "Bitrate    "  "Y-PSNR    "  "U-PSNR    "  "V-PSNR \n" );
+  for(layer = 0; layer < m_numLayers; layer++)
+  {
+    m_gcAnalyzeI[layer].printOut('i', layer);
+  }
+    
+  printf( "\n\nP Slices--------------------------------------------------------\n" );
+  printf( "\tTotal Frames |  "   "Bitrate    "  "Y-PSNR    "  "U-PSNR    "  "V-PSNR \n" );
+  for(layer = 0; layer < m_numLayers; layer++)
+  {
+    m_gcAnalyzeP[layer].printOut('p', layer);
+  }
+    
+  printf( "\n\nB Slices--------------------------------------------------------\n" );
+  printf( "\tTotal Frames |  "   "Bitrate    "  "Y-PSNR    "  "U-PSNR    "  "V-PSNR \n" );
+  for(layer = 0; layer < m_numLayers; layer++)
+  {
+    m_gcAnalyzeB[layer].printOut('b', layer);
+  }
+}
+
+#else
+Void TAppEncTop::encode()
+{
+  fstream bitstreamFile(m_pchBitstreamFile, fstream::binary | fstream::out);
+  if (!bitstreamFile)
+  {
+    fprintf(stderr, "\nfailed to open bitstream file `%s' for writing\n", m_pchBitstreamFile);
+    exit(EXIT_FAILURE);
+  }
+
+  TComPicYuv*       pcPicYuvOrg = new TComPicYuv;
+  TComPicYuv*       pcPicYuvRec = NULL;
+  
+  // initialize internal class & member variables
+  xInitLibCfg();
+  xCreateLib();
+  xInitLib();
+  
+  // main encoder loop
+  Int   iNumEncoded = 0;
+  Bool  bEos = false;
+  
+  list<AccessUnit> outputAccessUnits; ///< list of access units to write out.  is populated by the encoding process
+
+  // allocate original YUV buffer
+  pcPicYuvOrg->create( m_iSourceWidth, m_iSourceHeight, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth );
+  
+  while ( !bEos )
+  {
+    // get buffers
+    xGetBuffer(pcPicYuvRec);
+
+    // read input YUV file
+    m_cTVideoIOYuvInputFile.read( pcPicYuvOrg, m_aiPad );
+    
+    // increase number of received frames
+    m_iFrameRcvd++;
+    
+    // check end of file
+    bEos = ( m_cTVideoIOYuvInputFile.isEof() == 1 ?   true : false  );
+    bEos = ( m_iFrameRcvd == m_iFrameToBeEncoded ?    true : bEos   );
+    
+    // call encoding function for one frame
+    m_cTEncTop.encode( bEos, pcPicYuvOrg, m_cListPicYuvRec, outputAccessUnits, iNumEncoded );
+    
+    // write bistream to file if necessary
+    if ( iNumEncoded > 0 )
+    {
+      xWriteOutput(bitstreamFile, iNumEncoded, outputAccessUnits);
+      outputAccessUnits.clear();
+    }
+  }
+  // delete original YUV buffer
+  pcPicYuvOrg->destroy();
+  delete pcPicYuvOrg;
+  pcPicYuvOrg = NULL;
+  
+  // delete used buffers in encoder class
+  m_cTEncTop.deletePicBuffer();
+  
+  // delete buffers & classes
+  xDeleteBuffer();
+  xDestroyLib();
+  
+  printRateSummary();
+
+  return;
+}
+#endif
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+/**
+ - application has picture buffer list with size of GOP
+ - picture buffer list acts as ring buffer
+ - end of the list has the latest picture
+ .
+ */
+#if SVC_EXTENSION
+Void TAppEncTop::xGetBuffer( TComPicYuv*& rpcPicYuvRec, UInt layer)
+{
+  assert( m_iGOPSize > 0 );
+  
+  // org. buffer
+  if ( m_acListPicYuvRec[layer].size() == (UInt)m_iGOPSize )
+  {
+    rpcPicYuvRec = m_acListPicYuvRec[layer].popFront();
+
+  }
+  else
+  {
+    rpcPicYuvRec = new TComPicYuv;
+    
+#if SVC_UPSAMPLING
+    rpcPicYuvRec->create( m_acLayerCfg[layer].getSourceWidth(), m_acLayerCfg[layer].getSourceHeight(), m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth, NULL );
+#else
+    rpcPicYuvRec->create( m_acLayerCfg[layer].getSourceWidth(), m_acLayerCfg[layer].getSourceHeight(), m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth );
+#endif
+
+  }
+  m_acListPicYuvRec[layer].pushBack( rpcPicYuvRec );
+}
+
+Void TAppEncTop::xDeleteBuffer( )
+{
+  for(UInt layer=0; layer<m_numLayers; layer++)
+  {
+    TComList<TComPicYuv*>::iterator iterPicYuvRec  = m_acListPicYuvRec[layer].begin();
+    
+    Int iSize = Int( m_acListPicYuvRec[layer].size() );
+    
+    for ( Int i = 0; i < iSize; i++ )
+    {
+      TComPicYuv*  pcPicYuvRec  = *(iterPicYuvRec++);
+      pcPicYuvRec->destroy();
+      delete pcPicYuvRec; pcPicYuvRec = NULL;
+    }
+  }  
+}
+
+
+
+Void TAppEncTop::xWriteRecon(UInt layer, Int iNumEncoded)
+{
+  Int i;
+  
+  TComList<TComPicYuv*>::iterator iterPicYuvRec = m_acListPicYuvRec[layer].end();
+  
+  for ( i = 0; i < iNumEncoded; i++ )
+  {
+    --iterPicYuvRec;
+  }
+  
+  for ( i = 0; i < iNumEncoded; i++ )
+  {
+    TComPicYuv*  pcPicYuvRec  = *(iterPicYuvRec++);
+    if (!m_acLayerCfg[layer].getReconFile().empty())
+    {
+      m_acTVideoIOYuvReconFile[layer].write( pcPicYuvRec, m_acLayerCfg[layer].getCropLeft(), m_acLayerCfg[layer].getCropRight(), 
+        m_acLayerCfg[layer].getCropTop(), m_acLayerCfg[layer].getCropBottom() );
+    }
+  }
+}
+
+
+Void TAppEncTop::xWriteStream(std::ostream& bitstreamFile, Int iNumEncoded, const std::list<AccessUnit>& accessUnits)
+{
+  Int i;
+  
+  list<AccessUnit>::const_iterator iterBitstream = accessUnits.begin();
+  
+  for ( i = 0; i < iNumEncoded; i++ )
+  {
+    const AccessUnit& au = *(iterBitstream++);
+    const vector<unsigned>& stats = writeAnnexB(bitstreamFile, au);
+    rateStatsAccum(au, stats);
+  }
+}
+
+#else // SVC_EXTENSION
+Void TAppEncTop::xGetBuffer( TComPicYuv*& rpcPicYuvRec)
+{
+  assert( m_iGOPSize > 0 );
+  
+  // org. buffer
+  if ( m_cListPicYuvRec.size() == (UInt)m_iGOPSize )
+  {
+    rpcPicYuvRec = m_cListPicYuvRec.popFront();
+
+  }
+  else
+  {
+    rpcPicYuvRec = new TComPicYuv;
+    
+    rpcPicYuvRec->create( m_iSourceWidth, m_iSourceHeight, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth );
+
+  }
+  m_cListPicYuvRec.pushBack( rpcPicYuvRec );
+}
+
+Void TAppEncTop::xDeleteBuffer( )
+{
+  TComList<TComPicYuv*>::iterator iterPicYuvRec  = m_cListPicYuvRec.begin();
+  
+  Int iSize = Int( m_cListPicYuvRec.size() );
+  
+  for ( Int i = 0; i < iSize; i++ )
+  {
+    TComPicYuv*  pcPicYuvRec  = *(iterPicYuvRec++);
+    pcPicYuvRec->destroy();
+    delete pcPicYuvRec; pcPicYuvRec = NULL;
+  }
+  
+}
+
+/** \param iNumEncoded  number of encoded frames
+ */
+Void TAppEncTop::xWriteOutput(std::ostream& bitstreamFile, Int iNumEncoded, const std::list<AccessUnit>& accessUnits)
+{
+  Int i;
+  
+  TComList<TComPicYuv*>::iterator iterPicYuvRec = m_cListPicYuvRec.end();
+  list<AccessUnit>::const_iterator iterBitstream = accessUnits.begin();
+  
+  for ( i = 0; i < iNumEncoded; i++ )
+  {
+    --iterPicYuvRec;
+  }
+  
+  for ( i = 0; i < iNumEncoded; i++ )
+  {
+    TComPicYuv*  pcPicYuvRec  = *(iterPicYuvRec++);
+    if (m_pchReconFile)
+    {
+      m_cTVideoIOYuvReconFile.write( pcPicYuvRec, m_cropLeft, m_cropRight, m_cropTop, m_cropBottom );
+    }
+
+    const AccessUnit& au = *(iterBitstream++);
+    const vector<unsigned>& stats = writeAnnexB(bitstreamFile, au);
+    rateStatsAccum(au, stats);
+  }
+}
+#endif
+
+/**
+ *
+ */
+void TAppEncTop::rateStatsAccum(const AccessUnit& au, const std::vector<unsigned>& annexBsizes)
+{
+  AccessUnit::const_iterator it_au = au.begin();
+  vector<unsigned>::const_iterator it_stats = annexBsizes.begin();
+
+  for (; it_au != au.end(); it_au++, it_stats++)
+  {
+    switch ((*it_au)->m_nalUnitType)
+    {
+#if NAL_UNIT_TYPES_J1003_D7
+    case NAL_UNIT_CODED_SLICE_TRAIL_R:
+    case NAL_UNIT_CODED_SLICE_TRAIL_N:
+    case NAL_UNIT_CODED_SLICE_TLA:
+    case NAL_UNIT_CODED_SLICE_TSA_N:
+    case NAL_UNIT_CODED_SLICE_STSA_R:
+    case NAL_UNIT_CODED_SLICE_STSA_N:
+    case NAL_UNIT_CODED_SLICE_BLA:
+    case NAL_UNIT_CODED_SLICE_BLANT:
+    case NAL_UNIT_CODED_SLICE_BLA_N_LP:
+    case NAL_UNIT_CODED_SLICE_IDR:
+    case NAL_UNIT_CODED_SLICE_IDR_N_LP:
+    case NAL_UNIT_CODED_SLICE_CRA:
+    case NAL_UNIT_CODED_SLICE_DLP:
+    case NAL_UNIT_CODED_SLICE_TFD:
+#else
+    case NAL_UNIT_CODED_SLICE:
+    case NAL_UNIT_CODED_SLICE_TFD:
+    case NAL_UNIT_CODED_SLICE_TLA:
+    case NAL_UNIT_CODED_SLICE_CRA:
+    case NAL_UNIT_CODED_SLICE_CRANT:
+    case NAL_UNIT_CODED_SLICE_BLA:
+    case NAL_UNIT_CODED_SLICE_BLANT:
+    case NAL_UNIT_CODED_SLICE_IDR:
+#endif
+    case NAL_UNIT_VPS:
+    case NAL_UNIT_SPS:
+    case NAL_UNIT_PPS:
+      m_essentialBytes += *it_stats;
+      break;
+    default:
+      break;
+    }
+
+    m_totalBytes += *it_stats;
+  }
+}
+
+void TAppEncTop::printRateSummary()
+{
+#if SVC_EXTENSION
+  double time = (double) m_iFrameRcvd / m_acLayerCfg[m_numLayers-1].getFrameRate();
+#else
+  double time = (double) m_iFrameRcvd / m_iFrameRate;
+#endif
+  printf("Bytes written to file: %u (%.3f kbps)\n", m_totalBytes, 0.008 * m_totalBytes / time);
+#if VERBOSE_RATE
+  printf("Bytes for SPS/PPS/Slice (Incl. Annex B): %u (%.3f kbps)\n", m_essentialBytes, 0.008 * m_essentialBytes / time);
+#endif
+}
+
+//! \}
Index: /trunk/source/App/TAppEncoder/TAppEncTop.h
===================================================================
--- /trunk/source/App/TAppEncoder/TAppEncTop.h	(revision 2)
+++ /trunk/source/App/TAppEncoder/TAppEncTop.h	(revision 2)
@@ -0,0 +1,126 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TAppEncTop.h
+    \brief    Encoder application class (header)
+*/
+
+#ifndef __TAPPENCTOP__
+#define __TAPPENCTOP__
+
+#include <list>
+#include <ostream>
+
+#include "TLibEncoder/TEncTop.h"
+#include "TLibVideoIO/TVideoIOYuv.h"
+#include "TLibCommon/AccessUnit.h"
+#include "TAppEncCfg.h"
+
+//! \ingroup TAppEncoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// encoder application class
+class TAppEncTop : public TAppEncCfg
+{
+private:
+  // class interface
+#if SVC_EXTENSION
+  TEncTop                    m_acTEncTop [MAX_LAYERS];                    ///< encoder class
+  TEncTop*                   m_apcTEncTop [MAX_LAYERS];                   ///< encoder pointer class
+  TVideoIOYuv                m_acTVideoIOYuvInputFile [MAX_LAYERS];       ///< input YUV file
+  TVideoIOYuv                m_acTVideoIOYuvReconFile [MAX_LAYERS];       ///< output reconstruction file
+
+  TComList<TComPicYuv*>      m_acListPicYuvRec [MAX_LAYERS];              ///< list of reconstruction YUV files
+#else
+  TEncTop                    m_cTEncTop;                    ///< encoder class
+  TVideoIOYuv                m_cTVideoIOYuvInputFile;       ///< input YUV file
+  TVideoIOYuv                m_cTVideoIOYuvReconFile;       ///< output reconstruction file
+  
+  TComList<TComPicYuv*>      m_cListPicYuvRec;              ///< list of reconstruction YUV files
+#endif
+
+  Int                        m_iFrameRcvd;                  ///< number of received frames
+  
+  unsigned m_essentialBytes;
+  unsigned m_totalBytes;
+protected:
+  // initialization
+  Void  xCreateLib        ();                               ///< create files & encoder class
+  Void  xInitLibCfg       ();                               ///< initialize internal variables
+  Void  xInitLib          ();                               ///< initialize encoder class
+  Void  xDestroyLib       ();                               ///< destroy encoder class
+  
+  /// obtain required buffers
+#if SVC_EXTENSION
+  Void xGetBuffer(TComPicYuv*& rpcPicYuvRec, UInt layer);
+#else
+  Void xGetBuffer(TComPicYuv*& rpcPicYuvRec);
+#endif
+  
+  /// delete allocated buffers
+  Void  xDeleteBuffer     ();
+  
+  // file I/O
+#if SVC_EXTENSION
+  Void xWriteRecon(UInt layer, Int iNumEncoded);
+  Void xWriteStream(std::ostream& bitstreamFile, Int iNumEncoded, const std::list<AccessUnit>& accessUnits);
+  Void printOutSummary();
+#else
+  Void xWriteOutput(std::ostream& bitstreamFile, Int iNumEncoded, const std::list<AccessUnit>& accessUnits); ///< write bitstream to file
+#endif
+  void rateStatsAccum(const AccessUnit& au, const std::vector<unsigned>& stats);
+  void printRateSummary();
+  
+public:
+  TAppEncTop();
+  virtual ~TAppEncTop();
+  
+  Void        encode      ();                               ///< main encoding function
+#if SVC_EXTENSION
+  TEncTop&    getTEncTop  (UInt layer)   { return  m_acTEncTop[layer]; }      ///< return encoder class pointer reference
+#else
+  TEncTop&    getTEncTop  ()   { return  m_cTEncTop; }      ///< return encoder class pointer reference
+#endif
+
+
+
+};// END CLASS DEFINITION TAppEncTop
+
+//! \}
+
+#endif // __TAPPENCTOP__
+
Index: /trunk/source/App/TAppEncoder/encmain.cpp
===================================================================
--- /trunk/source/App/TAppEncoder/encmain.cpp	(revision 2)
+++ /trunk/source/App/TAppEncoder/encmain.cpp	(revision 2)
@@ -0,0 +1,87 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     encmain.cpp
+    \brief    Encoder application main
+*/
+
+#include <time.h>
+#include "TAppEncTop.h"
+
+//! \ingroup TAppEncoder
+//! \{
+
+// ====================================================================================================================
+// Main function
+// ====================================================================================================================
+
+int main(int argc, char* argv[])
+{
+  TAppEncTop  cTAppEncTop;
+
+  // print information
+  fprintf( stdout, "\n" );
+  fprintf( stdout, "SMuC software: Encoder Version [%s]", NV_VERSION );
+  fprintf( stdout, NVM_ONOS );
+  fprintf( stdout, NVM_COMPILEDBY );
+  fprintf( stdout, NVM_BITS );
+  fprintf( stdout, "\n" );
+
+  // create application encoder class
+  cTAppEncTop.create();
+
+  // parse configuration
+  if(!cTAppEncTop.parseCfg( argc, argv ))
+  {
+    cTAppEncTop.destroy();
+    return 1;
+  }
+
+  // starting time
+  double dResult;
+  long lBefore = clock();
+
+  // call encoding function
+  cTAppEncTop.encode();
+
+  // ending time
+  dResult = (double)(clock()-lBefore) / CLOCKS_PER_SEC;
+  printf("\n Total Time: %12.3f sec.\n", dResult);
+
+  // destroy application encoder class
+  cTAppEncTop.destroy();
+
+  return 0;
+}
+
+//! \}
Index: /trunk/source/App/utils/BitrateTargeting/ExtractBitrates.cpp
===================================================================
--- /trunk/source/App/utils/BitrateTargeting/ExtractBitrates.cpp	(revision 2)
+++ /trunk/source/App/utils/BitrateTargeting/ExtractBitrates.cpp	(revision 2)
@@ -0,0 +1,164 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "ExtractBitrates.h"
+#include <string>
+#include <sstream>
+#include <cassert>
+#include <limits>
+#include <map>
+
+namespace
+{
+  /// Maintains a sum and a sample-count for calculating averages
+  class Tally
+  {
+    public:
+      
+      /// Contructs a new zeroed tally
+      Tally( ): m_sum( 0.0 ), m_numSlices( 0 ) { }
+      
+      /// Adds to the sum and increments the sample-count
+      void add( double in ) { ++m_numSlices; m_sum += in; }
+      
+      /// \return The calculated average
+      double average( ) const { return m_sum / ( double )m_numSlices; }
+    
+    private:
+      double m_sum;
+      unsigned long m_numSlices;
+  };
+  
+  /// Ignores all of the the characters up to and including a given character
+  /// \param line The line being read from
+  /// \param iLine The active input stream
+  /// \param character The character to ignore up to
+  /// \throw POCParseException if the stream goes bad before character is encountered or just after character is encountered
+  void ignoreUpTo( const std::string& line, std::istream& iLine, char character )
+  {
+    while( iLine.good( ) && character != iLine.get( ) )
+      ;
+    if( !iLine.good( ) ) throw POCParseException( line );
+  }
+  
+  /// Extracts the average bitrates for each of the temporal layers from the given log
+  /// \param i The input stream that represents the log
+  /// \return A map that countains the average bitrates for each temporal layer.  Each pair contains the QP value in first and the average bitrate in second.
+  /// \throw POCParseException if an error occured while parsing a POC line
+  std::map< unsigned char, double > extractBitratesForQPs( std::istream& i )
+  {
+    std::map< unsigned char, Tally > tallyMap;
+    
+    while( i.good( ) )
+    {
+      // Initialize variables for this line
+      std::string line;
+      std::getline( i, line );
+      std::istringstream iLine( line );
+      if( !iLine.good( ) ) continue;
+      
+      // Ignore the "POC"
+      if( iLine.get( ) != 'P' ) continue;
+      if( !iLine.good( ) ) continue;
+      if( iLine.get( ) != 'O' ) continue;
+      if( !iLine.good( ) ) continue;
+      if( iLine.get( ) != 'C' ) continue;
+      if( !iLine.good( ) ) throw POCParseException( line );
+      
+      ignoreUpTo( line, iLine, '(' );
+      
+      if( iLine.get( ) != ' ' ) throw POCParseException( line );
+      if( !iLine.good( ) ) throw POCParseException( line );
+      
+      if( 'I' == iLine.get( ) ) continue;
+      if( !iLine.good( ) ) throw POCParseException( line );
+      
+      ignoreUpTo( line, iLine, ' ' );
+      ignoreUpTo( line, iLine, ' ' );
+      
+      // Parse the qpIndex
+      long qpIndexLong;
+      iLine >> qpIndexLong;
+      if( ( long )std::numeric_limits< unsigned char >::max( ) < qpIndexLong ) throw POCParseException( line );
+      unsigned char qpIndex( ( unsigned char )qpIndexLong );
+      if( !iLine.good( ) ) throw POCParseException( line );
+      
+      ignoreUpTo( line, iLine, ')' );
+      ignoreUpTo( line, iLine, ' ' );
+      
+      // Parse the number of bits
+      unsigned long bitsULong;
+      iLine >> bitsULong;
+      if( !iLine.good( ) ) throw POCParseException( line );
+      
+      // Find the tally that corresponds to our QP.  If there is no such tally yet, then add a new one to the map.
+      std::map< unsigned char, Tally >::iterator iter( tallyMap.find( qpIndex ) );
+      if( tallyMap.end( ) == iter )
+      {
+        tallyMap[ qpIndex ] = Tally( );
+        iter = tallyMap.find( qpIndex );
+      }
+      assert( iter != tallyMap.end( ) );
+      
+      iter->second.add( ( double )bitsULong );
+    }
+    
+    // Populate and return the result based on all of the tallies
+    std::map< unsigned char, double > result;
+    for( std::map< unsigned char, Tally >::const_iterator iter( tallyMap.begin( ) ); iter != tallyMap.end( ); ++iter )
+    {
+      result[ iter->first ] = iter->second.average( );
+    }
+    return result;
+  }
+}
+
+std::vector< double > extractBitratesForTemporalLayers( std::istream& i )
+{
+  std::vector< double > result;
+  
+  std::map< unsigned char, double > bitratesForQPsMap( extractBitratesForQPs( i ) );
+  if( !bitratesForQPsMap.empty( ) )
+  {
+    unsigned char expectedNextQPIndex( bitratesForQPsMap.begin( )->first );
+    
+    for( std::map< unsigned char, double >::const_iterator i( bitratesForQPsMap.begin( ) ); i != bitratesForQPsMap.end( ); ++i )
+    {
+      if( i->first != expectedNextQPIndex ) throw NonContiguousQPSetException( );
+      ++expectedNextQPIndex;
+      result.push_back( i->second );
+    }
+  }
+  
+  return result;
+}
Index: /trunk/source/App/utils/BitrateTargeting/ExtractBitrates.h
===================================================================
--- /trunk/source/App/utils/BitrateTargeting/ExtractBitrates.h	(revision 2)
+++ /trunk/source/App/utils/BitrateTargeting/ExtractBitrates.h	(revision 2)
@@ -0,0 +1,71 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef EXTRACT_BITRATES_H
+#define EXTRACT_BITRATES_H
+
+#include "RuntimeError.h"
+#include <vector>
+
+/// An error occured while parsing a POC line from within a log file
+class POCParseException: public RuntimeError
+{
+  public:
+    POCParseException( const std::string& pocLine ): m_pocLine( pocLine ) { }
+    virtual ~POCParseException( ) throw ( ) { }
+  
+  protected:
+    void outputWhat( std::ostream& o ) const { o << "POC parse exception: " << m_pocLine; }
+  
+  private:
+    std::string m_pocLine;
+};
+
+/// The QP set from the log file was not contiguous.  The QP set must be contiguous to be able to convert the results into a vector.
+class NonContiguousQPSetException: public RuntimeError
+{
+  public:
+    virtual ~NonContiguousQPSetException( ) throw( ) { }
+  
+  protected:
+    void outputWhat( std::ostream& o ) const { o << "Non-contiguous QP set exception"; }
+};
+
+/// Extracts the average bitrates for each of the temporal layers from the given log
+/// \param i The input stream that represents the log
+/// \return A vector of doubles that contains the average bitrates for each temporal layer
+/// \throw POCParseException if an error occured while parsing a POC line
+/// \throw NonContiguousQPSetException if the QP set from the log file was not contiguous
+std::vector< double > extractBitratesForTemporalLayers( std::istream& i );
+
+#endif
Index: /trunk/source/App/utils/BitrateTargeting/ExtractBitratesMain.cpp
===================================================================
--- /trunk/source/App/utils/BitrateTargeting/ExtractBitratesMain.cpp	(revision 2)
+++ /trunk/source/App/utils/BitrateTargeting/ExtractBitratesMain.cpp	(revision 2)
@@ -0,0 +1,99 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <iostream>
+#include <cassert>
+#include "ExtractBitrates.h"
+
+/// In out, finds the first occurence of toFind and replaces it with "e"
+/// \pre toFind must have a size of 2
+/// \pre The first character in toFind muts be 'e'
+/// \pre out must contain toFind
+void replaceWithE( std::string &out, const std::string& toFind )
+{
+  assert( 2 == toFind.size( ) );
+  assert( 'e' == toFind[ 0 ] );
+  
+  std::string::size_type pos( out.find( toFind ) );
+  assert( pos != std::string::npos );
+  out.erase( pos + 1, 1 );
+}
+
+/// Formatted output for a double with appropriate formatting applied (correct number of digits, etc.)
+void outputDouble( std::ostream& left, double right )
+{
+  std::ostringstream oss;
+  oss.precision( 6 );
+  oss << std::scientific << right;
+  std::string s( oss.str( ) );
+  
+  replaceWithE( s, "e+" );
+  replaceWithE( s, "e0" );
+  
+  left << s;
+}
+
+int main( int, char** )
+{
+  try
+  {
+    std::vector< double > result( extractBitratesForTemporalLayers( std::cin ) );  // Extract the bitrate vector
+    
+    // Output the bitrate vector
+    if( 0 < result.size( ) )
+    {
+      std::vector< double >::const_iterator iter( result.begin( ) );
+      outputDouble( std::cout, *iter );
+      for( ; ; )
+      {
+        ++iter;
+        if( result.end( ) == iter )
+        {
+          break;
+        }
+        else
+        {
+          std::cout << " ";
+          outputDouble( std::cout, *iter );
+        }
+      }
+    }
+    
+    return 0;
+  }
+  catch( std::exception& e )
+  {
+    std::cerr << e.what( ) << std::endl;
+    return 1;
+  }
+}
Index: /trunk/source/App/utils/BitrateTargeting/GuessLambdaModifiers.cpp
===================================================================
--- /trunk/source/App/utils/BitrateTargeting/GuessLambdaModifiers.cpp	(revision 2)
+++ /trunk/source/App/utils/BitrateTargeting/GuessLambdaModifiers.cpp	(revision 2)
@@ -0,0 +1,397 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "GuessLambdaModifiers.h"
+#include <limits>
+#include <cassert>
+#include <cmath>
+
+namespace
+{
+  /// Formatted input for a bitrate vector
+  /// \param left The input stream that contains the bitrate vector
+  /// \param right The vector to be written to
+  /// \pre right must be empty
+  void parseBitrateVector( std::istream& left, std::vector< double >& right )
+  {
+    assert( right.empty( ) );
+    
+    for( ; ; )
+    {
+      assert( left.good( ) );
+      
+      double bitrate;
+      left >> bitrate;
+      if( left.fail( ) ) break;
+      if( bitrate <= ( double )0.0 )
+      {
+        left.setstate( std::istream::failbit );
+      }
+      else
+      {
+        right.push_back( bitrate );
+      }
+      if( !left.good( ) ) break;
+      
+      if( left.peek( ) == ' ' )
+      {
+        left.ignore( );
+      }
+      else
+      {
+        break;
+      }
+    }
+  }
+  
+  /// Makes a next guess for a single Lambda-modifier based on only one previous guess
+  /// \param initialAdjustmentParameter The proportionality to use between the target bitrate and the previous guess
+  /// \param target The target bitrate value that this Lambda-modifier is trying to reach
+  /// \param previousPoint The previous guess
+  /// \return The Lambda-modifier guess
+  /// \pre The given point must contain only positive non-zero values
+  double incrementLambdaModifier(
+      double initialAdjustmentParameter,
+      double targetBitrate,
+      const Point& previousPoint )
+  {
+    assert( ( double )0.0 < previousPoint.lambdaModifier );
+    assert( ( double )0.0 < previousPoint.bitrate );
+    
+    double extrapolated( previousPoint.lambdaModifier * targetBitrate / previousPoint.bitrate );
+    return previousPoint.lambdaModifier + initialAdjustmentParameter * ( extrapolated - previousPoint.lambdaModifier );
+  }
+}
+
+double polateLambdaModifier( double targetBitrate, const Point& point1, const Point& point2 )
+{
+  assert( 0.0 < point1.lambdaModifier );
+  assert( 0.0 < point2.lambdaModifier );
+  assert( 0.0 < point1.bitrate );
+  assert( 0.0 < point2.bitrate );
+  assert( point1.lambdaModifier != point2.lambdaModifier );
+  assert( point1.bitrate != point2.bitrate );
+  
+  // Calculate and return the result
+  double denominator( point1.bitrate - point2.bitrate );
+  double result( point1.lambdaModifier
+      + ( point1.lambdaModifier - point2.lambdaModifier ) / denominator * ( targetBitrate - point1.bitrate ) );
+  return result;
+}
+
+double guessLambdaModifier(
+    double initialAdjustmentParameter,
+    double targetBitrate,
+    const std::list< Point >& pointList,
+    double interDampeningFactor )
+{
+  assert( ( double )0.0 < interDampeningFactor );
+  assert( interDampeningFactor <= ( double )1.0 );
+  assert( !pointList.empty( ) );
+  
+  double preliminaryResult;
+  
+  if( 1 == pointList.size( ) )  // If there is only one prevous point, then we cannot interpolate, so we call incrementLambdaModifier
+  {
+    preliminaryResult = incrementLambdaModifier( initialAdjustmentParameter, targetBitrate, pointList.back( ) );
+  }
+  else  // If there are at least two previous points, then we may be able to interpolate
+  {
+    std::list< Point >::const_reverse_iterator i( pointList.rbegin( ) );
+    Point point1 = *i;
+    ++i;
+    Point point2 = *i;
+    
+    // If the slope is either horizontal or vertical, we cannot interpolate
+    if( point1.lambdaModifier == point2.lambdaModifier || point1.bitrate == point2.bitrate )
+    {
+      preliminaryResult = incrementLambdaModifier( initialAdjustmentParameter, targetBitrate, pointList.back( ) );
+    }
+    else  // If the slope is not horizontal and not vertical, we can interpolate
+    {
+      preliminaryResult = polateLambdaModifier( targetBitrate, point1, point2 );
+    }
+  }
+  
+  double previousResult( pointList.back( ).lambdaModifier );
+  
+  // Apply "intra dampening"
+  {
+    double intermediate( std::log( ( double )1.0 + std::abs( preliminaryResult - previousResult ) / previousResult ) );
+    assert( ( double )0.0 <= intermediate );
+    if( ( preliminaryResult - previousResult ) < 0.0 )
+    {
+      preliminaryResult = previousResult * ( ( double )1.0 - intermediate );
+    }
+    else
+    {
+      preliminaryResult = previousResult * ( ( double )1.0 + intermediate );
+    }
+  }
+  
+  // Apply "inter dampening factor".  If necessary, reduce the factor until a positive result is acheived.
+  double result;
+  do
+  {
+    result = previousResult + interDampeningFactor * ( preliminaryResult - previousResult );
+    interDampeningFactor /= ( double )2.0;
+  } while( result <= ( double )0.0 );
+  return result;
+}
+
+namespace
+{
+  /// Extracts a single point at the given index from a full meta-log entry
+  Point pointFromFullMetaLogEntry( unsigned char index, const MetaLogEntry< std::vector< double > >& fullEntry )
+  {
+    Point result;
+    result.lambdaModifier = fullEntry.lambdaModifiers[ index ];
+    result.bitrate = fullEntry.bitrateVector[ index ];
+    return result;
+  }
+  
+  /// Calculates the inter dampening factor based
+  /// \param parameter The inter dampening parameter which determines how severely the inter dampening factor is affected by Lambda-modifier changes at previous temporal layers
+  /// \param cumulativeDelta The sum of the percentage changes of the Lambda-modifiers at the previous temporal layers
+  /// \return The calculated inter dampening factor
+  /// \pre cumulativeDelta must be non-negative
+  /// \pre parameter must be non-negative
+  double interDampeningFactor( double parameter, double cumulativeDelta )
+  {
+    assert( 0.0 <= cumulativeDelta );
+    assert( 0.0 <= parameter );
+    return ( double )1.0 / ( parameter * cumulativeDelta + ( double )1.0 );
+  }
+}
+
+std::vector< double > guessLambdaModifiers(
+    double initialAdjustmentParameter,
+    const std::vector< double > &targetBitrateVector,
+    const std::list< MetaLogEntry< std::vector< double > > >& metaLogEntryList )
+{
+  assert( !targetBitrateVector.empty( ) );
+  assert( !metaLogEntryList.empty( ) );
+  
+  double cumulativeDelta( 0.0 );
+  std::vector< double > resultVector;
+  for( unsigned char i( 0 ); i < targetBitrateVector.size( ); ++i )
+  {
+    // Populate pointList with up to two of the previous points
+    std::list< Point > pointList;
+    std::list< MetaLogEntry< std::vector< double > > >::const_reverse_iterator j( metaLogEntryList.rbegin( ) );
+    pointList.push_front( pointFromFullMetaLogEntry( i, *j ) );
+    ++j;
+    if( j != metaLogEntryList.rend( ) ) pointList.push_front( pointFromFullMetaLogEntry( i, *j ) );
+    
+    // Calculate the new Lambda-modifier guess and add it to the result vector
+    const double newLambdaModifier( guessLambdaModifier(
+        initialAdjustmentParameter,
+        targetBitrateVector[ i ],  // target bitrate
+        pointList,
+        interDampeningFactor( 50.0, cumulativeDelta ) ) );
+    resultVector.push_back( newLambdaModifier );
+    
+    // Increment the cumulativeDelta
+    const double oldLambdaModifier( pointList.back( ).lambdaModifier );
+    cumulativeDelta += std::abs( newLambdaModifier - oldLambdaModifier ) / oldLambdaModifier;
+  }
+  
+  return resultVector;
+}
+
+namespace
+{
+  /// Ignores all of the the characters up to and including a given character
+  /// \param i The active input stream
+  /// \param character The character to ignore up to
+  /// \throw MetaLogParseException if the stream goes bad before character is encountered or just after character is encountered
+  void ignoreUpTo( std::istream& i, char character )
+  {
+    while( i.good( ) && character != i.get( ) )
+      ;
+    if( !i.good( ) ) throw MetaLogParseException( );
+  }
+  
+  /// Parses a Lambda-modifier map
+  /// \param right The map to write the output to
+  void parseLambdaModifierMap( std::istream& left, std::map< unsigned char, double >& right )
+  {
+    for( ; ; )
+    {
+      assert( left.good( ) );
+      
+      // Ignore the "-LM"
+      if( '-' != left.get( ) ) left.setstate( std::istream::failbit );
+      if( !left.good( ) ) break;
+      if( 'L' != left.get( ) ) left.setstate( std::istream::failbit );
+      if( !left.good( ) ) break;
+      if( 'M' != left.get( ) ) left.setstate( std::istream::failbit );
+      if( !left.good( ) ) break;
+      
+      // Parse the index
+      long indexLong;
+      left >> indexLong;
+      if( !left.good( ) ) break;
+      if( indexLong < std::numeric_limits< unsigned char >::min( ) ) left.setstate( std::istream::failbit );
+      if( std::numeric_limits< unsigned char >::max( ) < indexLong ) left.setstate( std::istream::failbit );
+      if( !left.good( ) ) break;
+      unsigned char index( ( unsigned char )indexLong );
+      
+      if( ' ' != left.get( ) ) left.setstate( std::istream::failbit );
+      if( !left.good( ) ) break;
+      
+      // Parse the Lambda-modifier
+      double lambdaModifier;
+      left >> lambdaModifier;
+      if( lambdaModifier <= ( double )0.0 || ( !right.empty( ) && ( right.count( index ) != 0 || index <= right.rbegin( )->first ) ) )
+      {
+        left.setstate( std::istream::failbit );
+      }
+      else
+      {
+        right[ index ] = lambdaModifier;
+      }
+      if( !left.good( ) ) break;
+      
+      // If we peek and see a space, then there should be more Lambda-modifiers to parse.  Otherwise, we are finished.
+      if( left.peek( ) == ' ' )
+      {
+        left.ignore( );
+      }
+      else
+      {
+        break;
+      }
+    }
+  }
+  
+  /// Extracts the indexes from the given maps
+  /// \return The set of indexes
+  std::set< unsigned char > indexSetFromMap( const std::map< unsigned char, double >& in )
+  {
+    std::set< unsigned char > result;
+    for( typename std::map< unsigned char, double >::const_iterator i( in.begin( ) ); i != in.end( ); ++i )
+    {
+      result.insert( i->first );
+    }
+    return result;
+  }
+}
+
+void guessLambdaModifiers(
+    std::ostream& o,
+    std::istream& initialAdjustmentParameterIstream,
+    std::istream& targetsIstream,
+    std::istream& metaLogIstream )
+{
+  // Parse the initialAdjustmentParameter
+  double initialAdjustmentParameter;
+  initialAdjustmentParameterIstream >> initialAdjustmentParameter;
+  if( initialAdjustmentParameterIstream.fail( ) || initialAdjustmentParameterIstream.good( ) )
+  {
+    throw InitialAdjustmentParameterParseException( );
+  }
+  
+  // Parse the targets
+  std::vector< double > targetVector;
+  parseBitrateVector( targetsIstream, targetVector );
+  if( targetVector.empty( ) || targetsIstream.fail( ) || targetsIstream.good( ) ) throw TargetsParseException( );
+  
+  // Parse the metalog
+  std::list< MetaLogEntry< std::map< unsigned char, double > > > metaLogEntryList;
+  do
+  {
+    // Parse the Lambda-modifiers
+    MetaLogEntry< std::map< unsigned char, double > > entry;
+    parseLambdaModifierMap( metaLogIstream, entry.lambdaModifiers );
+    if( !metaLogIstream.good( ) ) throw MetaLogParseException( );
+    
+    // Skip the ';'
+    if( ';' != metaLogIstream.get( ) ) throw MetaLogParseException( );
+    if( !metaLogIstream.good( ) ) throw MetaLogParseException( );
+    
+    // Parse the bitrates
+    parseBitrateVector( metaLogIstream, entry.bitrateVector );
+    if( metaLogIstream.fail( ) ) throw MetaLogParseException( );
+    metaLogEntryList.push_back( entry );
+    
+    if( !metaLogIstream.good( ) ) break;
+    if( metaLogIstream.get( ) != '\n' ) throw MetaLogParseException( );
+    metaLogIstream.peek( );
+  } while( metaLogIstream.good( ) );
+  if( metaLogEntryList.empty( ) ) throw MetaLogParseException( );  // The meta-log should not be empty
+  
+  // Initialize firstIndexVector and check that the sizes and indexes match
+  std::set< unsigned char > firstIndexSet( indexSetFromMap( metaLogEntryList.front( ).lambdaModifiers ) );
+  if( firstIndexSet.size( ) != targetVector.size( ) ) throw MismatchedIndexesException( );
+  for( std::list< MetaLogEntry< std::map< unsigned char, double > > >::const_iterator i( metaLogEntryList.begin( ) );
+      i != metaLogEntryList.end( );
+      ++i )
+  {
+    if( indexSetFromMap( i->lambdaModifiers ) != firstIndexSet ) throw MismatchedIndexesException( );
+    if( i->bitrateVector.size( ) != targetVector.size( ) ) throw MismatchedIndexesException( );
+  }
+  
+  // Initialize simplifiedMetaLogEntryList
+  std::list< MetaLogEntry< std::vector< double > > > simplifiedMetaLogEntryList;
+  for( std::list< MetaLogEntry< std::map< unsigned char, double > > >::const_iterator i( metaLogEntryList.begin( ) );
+      i != metaLogEntryList.end( );
+      ++i )
+  {
+    simplifiedMetaLogEntryList.push_back( MetaLogEntry< std::vector< double > >( ) );
+    for( std::map< unsigned char, double >::const_iterator j( i->lambdaModifiers.begin( ) ); j != i->lambdaModifiers.end( ); ++j )
+    {
+      simplifiedMetaLogEntryList.back( ).lambdaModifiers.push_back( j->second );
+    }
+    simplifiedMetaLogEntryList.back( ).bitrateVector = i->bitrateVector;
+  }
+  
+  // Run the calculations
+  std::vector< double > resultVector( guessLambdaModifiers( initialAdjustmentParameter, targetVector, simplifiedMetaLogEntryList ) );
+  
+  // Output the results
+  std::set< unsigned char >::const_iterator indexIter( firstIndexSet.begin( ) );
+  std::vector< double >::const_iterator resultIter( resultVector.begin( ) );
+  do
+  {
+    if( indexIter != firstIndexSet.begin( ) ) o << " ";
+    o << "-LM" << ( long )( *indexIter ) << " ";
+    o.setf( std::ostream::fixed, std::ostream::floatfield );
+    o.precision( 7 );
+    o << ( *resultIter );
+    
+    ++indexIter;
+    ++resultIter;
+  } while( indexIter != firstIndexSet.end( ) );
+  assert( resultIter == resultVector.end( ) );  // The index set and the result vector should be the same size
+}
Index: /trunk/source/App/utils/BitrateTargeting/GuessLambdaModifiers.h
===================================================================
--- /trunk/source/App/utils/BitrateTargeting/GuessLambdaModifiers.h	(revision 2)
+++ /trunk/source/App/utils/BitrateTargeting/GuessLambdaModifiers.h	(revision 2)
@@ -0,0 +1,148 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef CALCULATE_LAMBDA_MODIFIER_H
+#define CALCULATE_LAMBDA_MODIFIER_H
+
+#include "RuntimeError.h"
+#include <vector>
+#include <map>
+#include <list>
+#include <set>
+#include <limits>
+
+/// Thrown if there is an error parsing the initial adjustment parameter
+class InitialAdjustmentParameterParseException: public RuntimeError
+{
+  public:
+    virtual ~InitialAdjustmentParameterParseException( ) throw( ) { }
+  protected:
+    void outputWhat( std::ostream& o ) const { o << "Error parsing the initial-adjustment parameter"; }
+};
+
+/// Thrown if there is an error parsing the targets
+class TargetsParseException: public RuntimeError
+{
+  public:
+    virtual ~TargetsParseException( ) throw( ) { }
+  protected:
+    void outputWhat( std::ostream& o ) const { o << "Error parsing targets"; }
+};
+
+/// Thrown if there is an error parsing the meta-log
+class MetaLogParseException: public RuntimeError
+{
+  public:
+    virtual ~MetaLogParseException( ) throw( ) { }
+  protected:
+    void outputWhat( std::ostream& o ) const { o << "Error parsing meta log"; }
+};
+
+/// Thrown if there is a mismatch in the vector sizes or the Lambda-modifier indexes
+class MismatchedIndexesException: public RuntimeError
+{
+  public:
+    virtual ~MismatchedIndexesException( ) throw( ) { }
+  protected:
+    void outputWhat( std::ostream& o ) const { o << "Mismatched vector sizes or lambda modifier indexes"; }
+};
+
+/// Full meta-log entry
+template< typename TLambdaModifier >
+struct MetaLogEntry
+{
+  TLambdaModifier lambdaModifiers;
+  std::vector< double > bitrateVector;
+};
+
+/// Contains a Lambda-modifier and bitrate for only a single index
+struct Point
+{
+  double lambdaModifier;
+  double bitrate;
+};
+
+/// Performs interpolation/extrapolation to guess a single Lambda-modifier
+/// \param target The target bitrate value that this Lambda-modifier is trying to reach
+/// \param point1 One of the two previously tried points where first is the Lambda-modifier and second is the obtained bitrate
+/// \param point2 One of the two previously tried points where first is the Lambda-modifier and second is the obtained bitrate
+/// \return The interpolated Lambda-modifier guess
+/// \pre Both given points must contain only positive non-zero values for first and second
+/// \pre The given points must have different first values and different second values.  If either the first values are the same or the second values are the same, then we have either a vertical or horizontal slope, and thus, interpolation cannot be performed.
+double polateLambdaModifier( double targetBitrate, const Point& point1, const Point& point2 );
+
+/// Guesses a single Lambda-modifier
+/// \param initialAdjustmentParameter If interpolation/extrapolation cannot be performed, then this parameter is used in the "increment" process.
+/// \param targetBitrate The target bitrate value that this Lambda-modifier is trying to reach
+/// \param pointList The list of points that correspond with this index
+/// \param interDampeningFactor This factor is obtained based on guessed Lambda-modifiers for previous temporal layers.  In some cases, this factor will scale down the change of this Lambda-modifier so that we are not making too many severe Lambda-modifier changes for a single encoder run.
+/// \return The Lambda-modifier guess
+/// \pre pointList cannot be empty
+/// \pre interDampeningFactor must be greater than zero and less than or equal to 1 (0 < interDampeningFactor <= 1)
+double guessLambdaModifier(
+    double initialAdjustmentParameter,
+    double targetBitrate,
+    const std::list< Point >& pointList,
+    double interDampeningFactor );
+
+/// Guesses all of the Lambda-modifiers
+/// \param initialAdjustmentParameter If interpolation/extrapolation cannot be performed, then this parameter is used in the "increment" process.
+/// \param targetBitrateVector The target bitrate values that we are trying to reach
+/// \param metaLogEntryList All of the previously run Lambda-modifiers and their corresponding bitrates from the meta-log
+/// \return Vector containing all of the guessed Lambda-modifiers
+/// \pre targetBitrateVector cannot be empty
+/// \pre metaLogEntryList cannot be empty
+/// \pre The size of targetBitrateVector must be the same as the size of bitrateVector in every item in metaLogEntryList
+/// \pre The size of targetBitrateVector must be the same as the size of lambdaModifiers in every item in metaLogEntryList
+std::vector< double > guessLambdaModifiers(
+    double initialAdjustmentParameter,
+    const std::vector< double > &targetBitrateVector,
+    const std::list< MetaLogEntry< std::vector< double > > >& metaLogEntryList );
+
+/// Guesses all of the Lambda-modifiers
+/// This function performs all of the necessary input parsing.  It ends up calling the other guessLambdaModifiers overload to perform the actual calculations.
+/// \param o The output stream to write the guessed Lambda-modifiers to
+/// \param initialAdjustmentParameterIstream The input stream that contains the initial adjustment parameter
+/// \param targetIstream The input stream that contains the target bitrates
+/// \param metaLogIstream The input stream that contains the meta-log
+/// \throw InitialAdjustmentParameterParseException if there is an error parsing the initial adjustment parameter
+/// \throw TargetsParseException if there is an error parsing the target bitrates
+/// \throw MetaLogParseException if there is an error parsing the meta-log
+/// \throw MismatchedIndexesException if there is a mismatch in the vector sizes or the Lambda-modifier indexes
+void guessLambdaModifiers(
+    std::ostream& o,
+    std::istream& initialAdjustmentParameterIstream,
+    std::istream& targetsIstream,
+    std::istream& metaLogIstream );
+
+#endif
Index: /trunk/source/App/utils/BitrateTargeting/GuessLambdaModifiersMain.cpp
===================================================================
--- /trunk/source/App/utils/BitrateTargeting/GuessLambdaModifiersMain.cpp	(revision 2)
+++ /trunk/source/App/utils/BitrateTargeting/GuessLambdaModifiersMain.cpp	(revision 2)
@@ -0,0 +1,72 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+
+#include "RuntimeError.h"
+#include "GuessLambdaModifiers.h"
+#include <iostream>
+
+class WrongNumberOfArgumentsException: public RuntimeError
+{
+  public:
+    virtual ~WrongNumberOfArgumentsException( ) throw( ) { }
+  protected:
+    void outputWhat( std::ostream& o ) const { o << "Wrong number of arguments"; }
+};
+
+int main( int argc, char** ppArgv )
+{
+  try
+  {
+    if( argc != 3 ) throw WrongNumberOfArgumentsException( );
+    
+    std::string initialAdjustmentParameterString( ppArgv[ 1 ] );
+    std::istringstream initialAdjustmentParameterIstream( initialAdjustmentParameterString );
+    
+    std::string targetBitratesString( ppArgv[ 2 ] );
+    std::istringstream targetBitratesIstream( targetBitratesString );
+    
+    guessLambdaModifiers( std::cout, initialAdjustmentParameterIstream, targetBitratesIstream, std::cin );
+    return 0;
+  
+  }
+  catch( std::exception& e )
+  {
+    std::cerr << e.what( ) << std::endl;
+  }
+  catch( ... )
+  {
+    std::cerr << "Unknown exception" << std::endl;
+  }
+  return 1;
+}
Index: /trunk/source/App/utils/BitrateTargeting/RuntimeError.h
===================================================================
--- /trunk/source/App/utils/BitrateTargeting/RuntimeError.h	(revision 2)
+++ /trunk/source/App/utils/BitrateTargeting/RuntimeError.h	(revision 2)
@@ -0,0 +1,76 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef DIRECTORY_LIB_RUNTIME_ERROR_H
+#define DIRECTORY_LIB_RUNTIME_ERROR_H
+
+#include <sstream>
+#include <stdexcept>
+
+/// This class serves the same purpose as std::runtime_error, but it can be more convenient to use
+class RuntimeError: public std::runtime_error
+{
+  public:
+    RuntimeError( ): std::runtime_error( "" ), m_firstWhat( true ) { }
+    virtual ~RuntimeError( ) throw ( ) { }
+    
+    /// Implementation of the std::exception::what method
+    const char * what( ) const throw( )
+    {
+      if( m_firstWhat )
+      {
+        std::ostringstream o;
+        outputWhat( o );
+        m_what = o.str( );
+        m_firstWhat = false;
+      }
+      return m_what.c_str( );
+    }
+    
+  protected:
+    /// The implementing class implements this method to customize the what output
+    /// \param o The what stream is outputted to this parameter
+    virtual void outputWhat( std::ostream & o ) const =0;
+  
+  private:
+    mutable bool m_firstWhat;  ///< True i.f.f. the what method has not yet been called
+    mutable std::string m_what;  ///< Contains the what string.  Populated by the first call to the what method.
+};
+
+/// Convenient formatted output operator that just outputs the what string
+inline std::ostream& operator<<( std::ostream& left, const RuntimeError& right )
+{
+  return left << right.what( );
+}
+
+#endif
Index: /trunk/source/App/utils/BitrateTargeting/encode.shl
===================================================================
--- /trunk/source/App/utils/BitrateTargeting/encode.shl	(revision 2)
+++ /trunk/source/App/utils/BitrateTargeting/encode.shl	(revision 2)
@@ -0,0 +1,151 @@
+# The copyright in this software is being made available under the BSD
+# License, included below. This software may be subject to other third party
+# and contributor rights, including patent rights, and no such rights are
+# granted under this license.  
+#
+# Copyright (c) 2010-2012, ITU/ISO/IEC
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are met:
+#
+#  * Redistributions of source code must retain the above copyright notice,
+#    this list of conditions and the following disclaimer.
+#  * Redistributions in binary form must reproduce the above copyright notice,
+#    this list of conditions and the following disclaimer in the documentation
+#    and/or other materials provided with the distribution.
+#  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+#    be used to endorse or promote products derived from this software without
+#    specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+# THE POSSIBILITY OF SUCH DAMAGE.
+
+# This files contains shell code that is common to both encodeCommand.sh and targetBitrates.sh.
+
+# Run this function to validate a "-option value" pair of arguments
+function checkDollarTwo {
+  if [[ "" == $2 ]] ; then
+    printf "An argument must follow $1.\n" >&2
+    outputUsageAndExit
+  fi
+}
+
+# If the second argument is empty (not provided), output an error message and the usage, and then exit
+function verifyProvided {
+  if [[ "" == $2 ]] ; then
+    printf "The $1 parameter must be provided.\n" >&2
+    outputUsageAndExit
+  fi
+}
+
+function verifyNotDirectory {
+  if [[ `printf "$2\n" | grep '/$'` != "" ]] ; then
+    printf "The $1 parameter cannot be a directory.\n" >&2
+    outputUsageAndExit
+  fi
+}
+
+function verifyDirectory {
+  if [[ "" == `printf "$2\n" | grep '/$'` ]] ; then
+    printf "The $1 parameter must be a directory.\n" >&2
+    outputUsageAndExit
+  fi
+}
+
+function verifyConfigurationIdentifier {
+  case $configurationIdentifier in
+    ldLC) ;;
+    raLC) ;;
+    inLC) ;;
+    ldHE) ;;
+    raHE) ;;
+    inHE) ;;
+    *)
+      printf "The provided $CONFIGURATION_IDENTIFIER_STRING is invalid.  It must be \"ldLC\", \"raLC\", \"inLC\", \"ldHE\", \"raHE\", or \"inHE\".\n" >&2
+      outputUsageAndExit
+      ;;
+  esac
+}
+
+function verifyQ {
+  case $1 in
+    22)  ;;
+    27)  ;;
+    32)  ;;
+    37)  ;;
+    *)
+      printf "The provided $Q_STRING, \"$1\", is invalid.  It must be \"22\", \"27\", \"32\", or \"37\".\n" >&2
+      outputUsageAndExit
+    ;;
+  esac
+}
+
+Q_OPTION="-q"
+EXECUTABLE_OPTION="-e"
+CONFIGURATION_IDENTIFIER_OPTION="-ci"
+OUTPUT_DIRECTORY_OPTION="-o"
+EXTRA_ARGUMENTS_OPTION="-ea"
+CONFIGURATION_PATH_OPTION="-cp"
+CONFIGURATION_DIRECTORY_OPTION="-cd"
+
+Q_STRING="q ($Q_OPTION)"
+CONFIGURATION_IDENTIFIER_STRING="configuration identifier ($CONFIGURATION_IDENTIFIER_OPTION)"
+INPUT_NAME_STRING="input name"
+OUTPUT_DIRECTORY_STRING="output directory ($OUTPUT_DIRECTORY_OPTION)"
+
+USAGE_INDENT="  "
+INPUT_NAME_USAGE_STRING=inputName
+CONFIGURATION_IDENTIFIER_USAGE_STRING=configurationIdentifier
+Q_USAGE_STRING=q
+OUTPUT_DIRECTORY_USAGE_STRING=outputDirectory
+EXTRA_ARGUMENTS_USAGE_STRING=extraArguments
+
+function outputConfigurationIdentifierUsage {
+  echo "${USAGE_INDENT}$CONFIGURATION_IDENTIFIER_USAGE_STRING specifies the configuration (ldHE, ldLC, raHE, raLC, inHE, or inLC)." >&2
+}
+
+function outputQUsage {
+  echo "${USAGE_INDENT}$Q_USAGE_STRING is the QP value (22, 27, 32, or 37)." >&2
+}
+
+function outputOutputDirectoryUsage {
+  echo "${USAGE_INDENT}$OUTPUT_DIRECTORY_USAGE_STRING is the directory that will contain the output log, YUV, and bin." >&2
+}
+
+function outputInputNameUsage {
+  echo "${USAGE_INDENT}$INPUT_NAME_USAGE_STRING is the name of the input sequence.  Must be one of the following:" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}NebutaFestival_2560x1600_60_10bit_crop" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}SteamLocomotiveTrain_2560x1600_60_10bit_crop" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}Traffic_2560x1600_30_crop" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}PeopleOnStreet_2560x1600_30_crop" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}BQTerrace_1920x1080_60" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}BasketballDrive_1920x1080_50" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}Cactus_1920x1080_50" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}Kimono1_1920x1080_24" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}ParkScene_1920x1080_24" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}vidyo1_720p_60" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}vidyo3_720p_60" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}vidyo4_720p_60" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}RaceHorses_832x480_30" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}BQMall_832x480_60" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}PartyScene_832x480_50" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}BasketballDrill_832x480_50" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}RaceHorses_416x240_30" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}BQSquare_416x240_60" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}BlowingBubbles_416x240_50" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}BasketballPass_416x240_50" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}BasketballDrillText_832x480_50" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}Chinaspeed_1024x768_30" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}SlideEditing_1280x720_30" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}SlideShow_1280x720_20" >&2
+}
Index: /trunk/source/App/utils/BitrateTargeting/encodeCommand.sh
===================================================================
--- /trunk/source/App/utils/BitrateTargeting/encodeCommand.sh	(revision 2)
+++ /trunk/source/App/utils/BitrateTargeting/encodeCommand.sh	(revision 2)
@@ -0,0 +1,258 @@
+#! /bin/sh
+
+# The copyright in this software is being made available under the BSD
+# License, included below. This software may be subject to other third party
+# and contributor rights, including patent rights, and no such rights are
+# granted under this license.  
+#
+# Copyright (c) 2010-2012, ITU/ISO/IEC
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are met:
+#
+#  * Redistributions of source code must retain the above copyright notice,
+#    this list of conditions and the following disclaimer.
+#  * Redistributions in binary form must reproduce the above copyright notice,
+#    this list of conditions and the following disclaimer in the documentation
+#    and/or other materials provided with the distribution.
+#  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+#    be used to endorse or promote products derived from this software without
+#    specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+# THE POSSIBILITY OF SUCH DAMAGE.
+
+# Outputs a command to run the encoder for a given set of arguments.  The encoder typically requires a lot of arguments to run, so this script can be more convenient than running the encoder direcly because it automatically generates many of the arguments.
+
+# "Include" encode.shl which contains common shell script code related to encoding
+SUB_TOOLS_DIRECTORY=$(echo "$0" | sed -e 's/[^\/]*$//')
+. ${SUB_TOOLS_DIRECTORY}encode.shl
+
+USE_LOG_FILE_OPTION="-l"
+INPUT_DIRECTORY_OPTION="-id"
+NUM_FRAMES_OPTION="-f"
+
+function outputUsageAndExit {
+  local EXECUTABLE_USAGE_STRING=executable
+  local INPUT_DIRECTORY_USAGE_STRING=inputDirectory
+  local CONFIGURATION_PATH_USAGE_STRING=configurationPath
+  local CONFIGURATION_DIRECTORY_USAGE_STRING=configurationDirectory
+  local NUM_FRAMES_USAGE_STRING=numFrames
+  
+  echo "Usage: $0 $CONFIGURATION_IDENTIFIER_OPTION $CONFIGURATION_IDENTIFIER_USAGE_STRING ($CONFIGURATION_PATH_OPTION $CONFIGURATION_PATH_USAGE_STRING -or- $CONFIGURATION_DIRECTORY_OPTION $CONFIGURATION_DIRECTORY_USAGE_STRING) $Q_OPTION $Q_USAGE_STRING $EXECUTABLE_OPTION $EXECUTABLE_USAGE_STRING [$NUM_FRAMES_OPTION $NUM_FRAMES_USAGE_STRING] [$EXTRA_ARGUMENTS_OPTION $EXTRA_ARGUMENTS_USAGE_STRING] $OUTPUT_DIRECTORY_OPTION $OUTPUT_DIRECTORY_USAGE_STRING [$USE_LOG_FILE_OPTION] [$INPUT_DIRECTORY_OPTION $INPUT_DIRECTORY_USAGE_STRING] $INPUT_NAME_USAGE_STRING" >&2
+  outputConfigurationIdentifierUsage
+  echo "${USAGE_INDENT}$CONFIGURATION_PATH_USAGE_STRING is the path of the configuration file to use.  Either this or $CONFIGURATION_DIRECTORY_USAGE_STRING must be specified (but not both)." >&2
+  echo "${USAGE_INDENT}$CONFIGURATION_DIRECTORY_USAGE_STRING is the path of the directory that contains the configuration files.  The particular file will be chosen based on $CONFIGURATION_IDENTIFIER_USAGE_STRING.  Either this or $CONFIGURATION_PATH_USAGE_STRING must be specified (but not both)." >&2
+  outputQUsage
+  echo "${USAGE_INDENT}$EXECUTABLE_USAGE_STRING is the path of the encoder executable." >&2
+  echo "${USAGE_INDENT}$NUM_FRAMES_USAGE_STRING is the number of frames to encode.  If omitted, the entire sequence will be encoded." >&2
+  echo "${USAGE_INDENT}$EXTRA_ARGUMENTS_USAGE_STRING is any extra arguments that should be passed on to the encoder." >&2
+  outputOutputDirectoryUsage
+  echo "${USAGE_INDENT}If $USE_LOG_FILE_OPTION is specified, the encoder will output to a log file.  Otherwise it will output to the standard output." >&2
+  echo "${USAGE_INDENT}$INPUT_DIRECTORY_USAGE_STRING is the directory that contains the sequences.  The default value is the SEQUENCE_DIR environment variable." >&2
+  outputInputNameUsage
+  
+  exit 1
+}
+
+# Used to lookup the width, height, number of frames, and frame rate for a given sequence
+table=`printf "${table}\nNebutaFestival_2560x1600_60_10bit_crop          2560   1600   300        60"`
+table=`printf "${table}\nSteamLocomotiveTrain_2560x1600_60_10bit_crop    2560   1600   300        60"`
+table=`printf "${table}\nTraffic_2560x1600_30_crop                       2560   1600   150        30"`
+table=`printf "${table}\nPeopleOnStreet_2560x1600_30_crop                2560   1600   150        30"`
+table=`printf "${table}\nBQTerrace_1920x1080_60                          1920   1080   600        60"`
+table=`printf "${table}\nBasketballDrive_1920x1080_50                    1920   1080   500        50"`
+table=`printf "${table}\nCactus_1920x1080_50                             1920   1080   500        50"`
+table=`printf "${table}\nKimono1_1920x1080_24                            1920   1080   240        24"`
+table=`printf "${table}\nParkScene_1920x1080_24                          1920   1080   240        24"`
+table=`printf "${table}\nvidyo1_720p_60                                  1280    720   600        60"`
+table=`printf "${table}\nvidyo3_720p_60                                  1280    720   600        60"`
+table=`printf "${table}\nvidyo4_720p_60                                  1280    720   600        60"`
+table=`printf "${table}\nRaceHorses_832x480_30                            832    480   300        30"`
+table=`printf "${table}\nBQMall_832x480_60                                832    480   600        60"`
+table=`printf "${table}\nPartyScene_832x480_50                            832    480   500        50"`
+table=`printf "${table}\nBasketballDrill_832x480_50                       832    480   500        50"`
+table=`printf "${table}\nRaceHorses_416x240_30                            416    240   300        30"`
+table=`printf "${table}\nBQSquare_416x240_60                              416    240   600        60"`
+table=`printf "${table}\nBlowingBubbles_416x240_50                        416    240   500        50"`
+table=`printf "${table}\nBasketballPass_416x240_50                        416    240   500        50"`
+table=`printf "${table}\nBasketballDrillText_832x480_50                   832    480   500        50"`
+table=`printf "${table}\nChinaspeed_1024x768_30                          1024    768   500        30"`
+table=`printf "${table}\nSlideEditing_1280x720_30                        1280    720   300        30"`
+table=`printf "${table}\nSlideShow_1280x720_20                           1280    720   500        20"`
+
+EXECUTABLE_STRING="executable ($EXECUTABLE_OPTION)"
+INPUT_DIRECTORY_STRING="input directory ($INPUT_DIRECTORY_OPTION)"
+CONFIGURATION_PATH_STRING="configuration path ($CONFIGURATION_PATH_OPTION)"
+CONFIGURATION_DIRECTORY_STRING="configuration directory ($CONFIGURATION_DIRECTORY_OPTION)"
+
+inputDirectory="$SEQUENCE_DIR"  # The default input directory is taken from this environment variable
+
+# For every argument $1
+while [ "" != "$*" ] ; do
+  case $1 in
+    $USE_LOG_FILE_OPTION)
+      useLogFile=$1
+    ;;
+    -*)
+      checkDollarTwo "$1" "$2"
+      case $1 in
+        $EXECUTABLE_OPTION) executable=$2 ;;
+        $INPUT_DIRECTORY_OPTION) inputDirectory=$2 ;;
+        $EXTRA_ARGUMENTS_OPTION) extraArguments=$2 ;;
+        $Q_OPTION) q=$2 ;;
+        $OUTPUT_DIRECTORY_OPTION) outputDirectory=$2 ;;
+        $CONFIGURATION_IDENTIFIER_OPTION) configurationIdentifier=$2 ;;
+        $CONFIGURATION_PATH_OPTION) configurationPath=$2 ;;
+        $CONFIGURATION_DIRECTORY_OPTION) configurationDirectory=$2 ;;
+        $NUM_FRAMES_OPTION) numFrames=$2 ;;
+        *)
+          printf "You entered an invalid option: \"$1\".\n" >&2
+          outputUsageAndExit
+        ;;
+      esac
+      shift
+    ;;
+    *)
+      if [[ "" == $inputName ]] ; then
+        inputName=$1
+      else
+        printf "You entered too many arguments.\n" >&2
+        outputUsageAndExit
+      fi
+    ;;
+  esac
+  
+  shift
+done
+
+verifyProvided "$EXECUTABLE_STRING" "$executable"
+verifyNotDirectory "$EXECUTABLE_STRING" "$executable"
+
+verifyDirectory "$INPUT_DIRECTORY_STRING" "$inputDirectory"
+
+verifyProvided "$Q_STRING" "$q"
+verifyQ $q
+
+verifyProvided "$OUTPUT_DIRECTORY_STRING" "$outputDirectory"
+verifyDirectory "$OUTPUT_DIRECTORY_STRING" "$outputDirectory"
+
+verifyProvided "$CONFIGURATION_IDENTIFIER_STRING" "$configurationIdentifier"
+verifyConfigurationIdentifier "$configurationIdentifier"
+
+# Validate $configurationPath or $configurationDirectory
+if [[ $configurationPath != "" ]] ; then
+  verifyNotDirectory "$CONFIGURATION_PATH_STRING" "$configurationPath"
+else
+  if [[ "" == $configurationDirectory ]] ; then
+    printf "You must enter a $CONFIGURATION_PATH_STRING or $CONFIGURATION_DIRECTORY_STRING.\n" >&2
+    outputUsageAndExit
+  else
+    verifyDirectory "$CONFIGURATION_DIRECTORY_STRING" "$configurationDirectory"
+  fi
+fi
+
+verifyProvided "$INPUT_NAME_STRING" "$inputName"
+verifyNotDirectory "$INPUT_NAME_STRING" "$inputName"
+
+# If configurationPath is not already populated, populate it based on the configuration directory and the configuration identifier
+if [[ "" == $configurationPath ]] ; then
+  configurationPath="${configurationDirectory}encoder_"
+  case $configurationIdentifier in
+    ldLC) configurationPath="${configurationPath}lowdelay_loco" ;;
+    raLC) configurationPath="${configurationPath}randomaccess_loco" ;;
+    inLC) configurationPath="${configurationPath}intra_loco" ;;
+    ldHE) configurationPath="${configurationPath}lowdelay" ;;
+    raHE) configurationPath="${configurationPath}randomaccess" ;;
+    *)    configurationPath="${configurationPath}intra" ;;  # inHE
+  esac
+  configurationPath="${configurationPath}.cfg"
+fi
+
+# Validate the input name and populate masterLine which contains the line from the table for the given sequence
+masterLine=`printf "$table" | grep -i "^$inputName "`
+if [[ "" == $masterLine ]] ; then
+  printf "Invalid input name.\n" >&2
+  outputUsageAndExit
+fi
+
+# If numFrames is not yet initialized, initialize it by looking up the values in the table
+if [[ "" == $numFrames ]] ; then
+  numFrames=`printf -- "$masterLine" | awk '{ print $4 }'`
+fi
+
+# Initialize these variables by looking up the values in the table
+frameRate=`printf -- "$masterLine" | awk '{ print $5 }'`
+width=`printf -- "$masterLine" | awk '{ print $2 }'`
+height=`printf -- "$masterLine" | awk '{ print $3 }'`
+
+# Initialize intraPeriod
+case $configurationIdentifier in
+  ld*)
+    intraPeriod="-1"
+  ;;
+  ra*)
+    if [[ 20 == "$frameRate" ]] ; then
+      intraPeriod="16"
+    else
+      intraPeriod=$(expr "$frameRate" + 4)
+      intraPeriod=$(expr "$intraPeriod" / 8)
+      intraPeriod=$(expr "$intraPeriod" \* 8)
+    fi
+  ;;
+  in*)
+    intraPeriod="1"
+  ;;
+  *)
+    outputConfigurationIdentifierErrorAndExit
+  ;;
+esac
+
+# Initialize tenBit if the given sequence is 10-bit
+printf -- "$inputName" | grep -i '10bit' > /dev/null
+case $? in
+  0)  tenBit="--InputBitDepth=10 "
+    ;;
+  1)  ;;
+  *)  exit $?
+    ;;
+esac
+
+outputPathBegin="${outputDirectory}${inputName}_${configurationIdentifier}_q${q}"
+
+# Output the command
+printf -- "$executable "
+printf -- "-c $configurationPath "
+printf -- "-i $inputDirectory$inputName.yuv "
+printf -- "-f $numFrames "
+printf -- "-fr $frameRate "
+printf -- "-wdt $width "
+printf -- "-hgt $height "
+printf -- "-ip $intraPeriod "
+printf -- "$tenBit"
+if [[ $tenBit != "" ]] ; then
+  printf " "
+fi
+printf -- "$extraArguments"
+if [[ $extraArguments != "" ]] ; then
+  printf -- " "
+fi
+printf -- "-q $q "
+printf -- "-b $outputPathBegin.bin "
+printf -- "-o $outputPathBegin.yuv "
+if [[ "" != $useLogFile ]] ; then
+  printf -- "&> $outputPathBegin.log"
+fi
+printf "\n"
+
+exit 0
Index: /trunk/source/App/utils/BitrateTargeting/makefile
===================================================================
--- /trunk/source/App/utils/BitrateTargeting/makefile	(revision 2)
+++ /trunk/source/App/utils/BitrateTargeting/makefile	(revision 2)
@@ -0,0 +1,54 @@
+# The copyright in this software is being made available under the BSD
+# License, included below. This software may be subject to other third party
+# and contributor rights, including patent rights, and no such rights are
+# granted under this license.  
+#
+# Copyright (c) 2010-2012, ITU/ISO/IEC
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are met:
+#
+#  * Redistributions of source code must retain the above copyright notice,
+#    this list of conditions and the following disclaimer.
+#  * Redistributions in binary form must reproduce the above copyright notice,
+#    this list of conditions and the following disclaimer in the documentation
+#    and/or other materials provided with the distribution.
+#  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+#    be used to endorse or promote products derived from this software without
+#    specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+# THE POSSIBILITY OF SUCH DAMAGE.
+
+CPPFLAGS = -D NDEBUG -Wall -Wextra
+
+extractBitratesObjects = ExtractBitrates.o ExtractBitratesMain.o
+extractBitratesExecutable = extractBitrates.exe
+
+guessLambdaModifiersObjects = GuessLambdaModifiers.o GuessLambdaModifiersMain.o
+guessLambdaModifiersExecutable = guessLambdaModifiers.exe
+
+all: $(extractBitratesExecutable) $(guessLambdaModifiersExecutable)
+
+$(extractBitratesExecutable): $(extractBitratesObjects)
+	g++ -o $@ $(extractBitratesObjects)
+$(guessLambdaModifiersExecutable): $(guessLambdaModifiersObjects)
+	g++ -o $@ $(guessLambdaModifiersObjects)
+
+ExtractBitrates.o: ExtractBitrates.h RuntimeError.h
+ExtractBitratesMain.o: ExtractBitrates.h RuntimeError.h
+GuessLambdaModifiers.o: GuessLambdaModifiers.h RuntimeError.h
+GuessLambdaModifiersMain.o: GuessLambdaModifiers.h RuntimeError.h
+
+clean:
+	rm $(extractBitratesExecutable) $(extractBitratesObjects) $(guessLambdaModifiersExecutable) $(guessLambdaModifiersObjects)
Index: /trunk/source/App/utils/BitrateTargeting/targetBitrates.sh
===================================================================
--- /trunk/source/App/utils/BitrateTargeting/targetBitrates.sh	(revision 2)
+++ /trunk/source/App/utils/BitrateTargeting/targetBitrates.sh	(revision 2)
@@ -0,0 +1,409 @@
+#! /bin/sh
+
+# The copyright in this software is being made available under the BSD
+# License, included below. This software may be subject to other third party
+# and contributor rights, including patent rights, and no such rights are
+# granted under this license.  
+#
+# Copyright (c) 2010-2012, ITU/ISO/IEC
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are met:
+#
+#  * Redistributions of source code must retain the above copyright notice,
+#    this list of conditions and the following disclaimer.
+#  * Redistributions in binary form must reproduce the above copyright notice,
+#    this list of conditions and the following disclaimer in the documentation
+#    and/or other materials provided with the distribution.
+#  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+#    be used to endorse or promote products derived from this software without
+#    specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+# THE POSSIBILITY OF SUCH DAMAGE.
+
+
+SUB_TOOLS_DIRECTORY=$(echo "$0" | sed -e 's/[^\/]*$//')
+. ${SUB_TOOLS_DIRECTORY}encode.shl
+
+LAMBDA_MODIFIER_PREFIX="LM"
+
+RESUME_MODE_OPTION="-rm"
+TARGET_BITRATES_OPTION="-tb"
+INITIAL_LAMBDA_MODIFIERS_OPTION="-il"
+ENCODE_COMMAND_ARGS_OPTION="-ca"
+
+function outputUsageAndExit {
+  local TARGET_BITRATES_USAGE_STRING=targetBitrates
+  local INITIAL_LAMBDA_MODIFIERS_USAGE_STRING=initialLambdaModifiers
+  local ENCODE_COMMAND_ARGS_USAGE_STRING=encodeCommandArgs
+  
+  echo "Usage: $0 [$RESUME_MODE_OPTION] $CONFIGURATION_IDENTIFIER_OPTION $CONFIGURATION_IDENTIFIER_USAGE_STRING $Q_OPTION $Q_USAGE_STRING $TARGET_BITRATES_OPTION $TARGET_BITRATES_USAGE_STRING [$INITIAL_LAMBDA_MODIFIERS_OPTION $INITIAL_LAMBDA_MODIFIERS_USAGE_STRING] [$ENCODE_COMMAND_ARGS_OPTION $ENCODE_COMMAND_ARGS_USAGE_STRING] [$EXTRA_ARGUMENTS_OPTION $EXTRA_ARGUMENTS_USAGE_STRING] $OUTPUT_DIRECTORY_OPTION $OUTPUT_DIRECTORY_USAGE_STRING $INPUT_NAME_USAGE_STRING" >&2
+  echo "${USAGE_INDENT}$RESUME_MODE_OPTION engages resume mode which allows the user to resume an execution that was interrupted before completion."
+  outputConfigurationIdentifierUsage
+  outputQUsage
+  echo "${USAGE_INDENT}$TARGET_BITRATES_USAGE_STRING is the target bitrates.  For example: \"23:35 24:3473242 etc...\"." >&2
+  echo "${USAGE_INDENT}$INITIAL_LAMBDA_MODIFIERS_USAGE_STRING is the Lambda-modifiers to use for the first guess.  For example: \"$-{LAMBDA_MODIFIER_PREFIX}23 1e0 $-{LAMBDA_MODIFIER_PREFIX}24 0.98 etc...\"" >&2
+  echo "${USAGE_INDENT}$ENCODE_COMMAND_ARGS_USAGE_STRING is the extra arguments to be passed to encodeCommand.sh.  The common arguments that are available to both $0 and encodeCommand.sh should not be passed though this argument.  For example, don't pass $Q_OPTION here because it is an option of $0.  $EXECUTABLE_OPTION and ($CONFIGURATION_PATH_OPTION or $CONFIGURATION_DIRECTORY_OPTION) must be passed through this argument.  For example, \"$ENCODE_COMMAND_ARGS_OPTION '$EXECUTABLE_OPTION ~/bin/encode.exe $CONFIGURATION_DIRECTORY_OPTION ~/cfg/'\"." >&2
+  echo "${USAGE_INDENT}$EXTRA_ARGUMENTS_USAGE_STRING specifies extra arguments to be passed directly to the encoder (not to encodeCommand.sh)." >&2
+  outputOutputDirectoryUsage
+  outputInputNameUsage
+  
+  exit 1
+}
+
+NORMAL_MODE="NORMAL_MODE"
+RESUME_MODE="RESUME_MODE"
+mode="$NORMAL_MODE"
+
+# For every argument $1
+while [ "" != "$*" ] ; do
+  case $1 in
+    $RESUME_MODE_OPTION)
+      mode="$RESUME_MODE"
+    ;;
+    -*)
+      checkDollarTwo "$1" "$2"
+      case $1 in
+        $EXTRA_ARGUMENTS_OPTION) extraArguments=$2 ;;
+        $Q_OPTION) q=$2 ;;
+        $OUTPUT_DIRECTORY_OPTION) outputDirectory=$2 ;;
+        $CONFIGURATION_IDENTIFIER_OPTION) configurationIdentifier=$2 ;;
+        $TARGET_BITRATES_OPTION) targetBitrates=$2 ;;
+        $INITIAL_LAMBDA_MODIFIERS_OPTION) initialLambdaModifiers=$2 ;;
+        $ENCODE_COMMAND_ARGS_OPTION) encodeCommandArgs=$2 ;;
+        *)
+          printf "You entered an invalid option: \"$1\".\n" >&2
+          outputUsageAndExit
+        ;;
+      esac
+      shift
+    ;;
+    *)
+      if [[ "" == $inputName ]] ; then
+        inputName=$1
+      else
+        printf "You entered too many arguments.\n" >&2
+        outputUsageAndExit
+      fi
+    ;;
+  esac
+  
+  shift
+done
+
+verifyProvided "$Q_STRING" "$q"
+verifyQ $q
+
+verifyProvided "$OUTPUT_DIRECTORY_STRING" "$outputDirectory"
+verifyDirectory "$OUTPUT_DIRECTORY_STRING" "$outputDirectory"
+
+verifyProvided "$CONFIGURATION_IDENTIFIER_STRING" "$configurationIdentifier"
+verifyConfigurationIdentifier "$configurationIdentifier"
+
+verifyProvided "target bitrates ($TARGET_BITRATES_OPTION)" "$targetBitrates"
+verifyProvided "$INPUT_NAME_STRING" "$inputName"
+
+outputPathBegin="${outputDirectory}${inputName}_${configurationIdentifier}_q${q}"
+logPath="$outputPathBegin.log"
+metaLogPath="${outputPathBegin}_meta.log"
+
+TRUE=true
+
+# Outputs "$TRUE" if the given file exist.  Outputs nothing if the given file does not exist.  The first argument is the path to the supposed file.
+function doesFileExist {
+  ls $1 &> /dev/null
+  if [[ 0 == "$?" ]] ; then
+    echo "$TRUE"
+  fi
+}
+
+# Validate the mode (normal or resume) based on whether or not the meta-log file already exists
+if [[ "$TRUE" == "$(doesFileExist "$metaLogPath")" ]] ; then
+  if [[ "$NORMAL_MODE" == "$mode" ]] ; then
+    echo "$metaLogPath already exists.  Consider using resume-mode." >&2
+    outputUsageAndExit
+  else  # Resume-mode
+    cat "$metaLogPath"  # Output the pre-existing meta-log so we can resume where we left off
+  fi
+else  # Meta-log file does not exist
+  if [[ "$RESUME_MODE" == "$mode" ]] ; then
+    echo "$metaLogPath does not exist and resume-mode is enabled." >&2
+    outputUsageAndExit
+  fi
+fi
+
+# Outputs the number of elements in the given bitrate vector
+function bitrateVectorSize {
+  echo "$1" | sed -e 's/[^ ]//g' | wc -c | sed -e 's/^ *//'
+}
+
+# Initialize targetBitrateVectorSize
+targetBitrateVectorSize="$(bitrateVectorSize "$targetBitrates")"
+
+# Outputs the product of the two input values
+function multiply {
+  echo | awk "{print $1 * $2}"
+}
+
+# Extracts the bitrate at the given index from the given bitrate vector.  The first argument is the given index and the second argument in the given bitrate vector.
+function extractBitrateFromVector {
+  local localIndex=$(expr "$1" "+" "1")
+  echo "$2" | awk "{ print \$$localIndex }"
+}
+
+# Outputs a bitrate vector by multiplying the $targetBitrates vector by a given scalar.  The first argument is the given scalar.
+function populateBitrates {
+  local lI=0
+  local lResult=""
+  while true ; do
+    local lTargetBitrate=$(extractBitrateFromVector "$lI" "$targetBitrates")
+    if [[ "" == "$lTargetBitrate" ]] ; then
+      break;
+    fi
+    local lNew=$(multiply "$lTargetBitrate" "$1")
+    lResult="$lResult $lNew"
+    ((++lI))
+  done
+  echo "$lResult" | sed -e 's/^ //'
+}
+
+# Initialize the ranges
+outerRangeMins=$(populateBitrates "0.980")
+innerRangeMins=$(populateBitrates "0.985")
+innerRangeMaxs=$(populateBitrates "1.015")
+outerRangeMaxs=$(populateBitrates "1.020")
+
+# Outputs the given string to the meta-log (both the file and stdout) with no newline character.  The first argument is the string to output.
+function outputToMetaLogNoNewline {
+  toPrint=`echo $1 | sed -e 's/%/%%/g'`
+  printf -- "$toPrint"
+  printf -- "$toPrint" >> $metaLogPath
+}
+
+# Outputs the given string to the meta-log (both the file and stdout) with a newline character.  The first argument is the string to output.
+function outputToMetaLogWithNewline {
+  echo "$1"
+  echo "$1" >> $metaLogPath
+}
+
+# Extracts the Lambda-modifier at the given index from $lambdaModifiers.  The first argument is the given index.
+function extractLambdaModifier {
+  printf -- "$lambdaModifiers" | sed -e 's/^-//' | sed -e 's/ -/\
+/g' | grep "${LAMBDA_MODIFIER_PREFIX}$1 " | sed -e 's/^[^ ]* //'
+}
+
+# Outputs the given Lambda-modifier with a fixed number of decimal points.  The first argument is the given Lambda-modifier.
+function formatLambdaModifier {
+  printf "%.7f" "$1"
+}
+
+# Outputs $lambdaModifiers to the meta-log with proper formatting
+function outputLambdaModifiersToMetaLog {
+  local lI=0
+  local lLambdaModifier=$(extractLambdaModifier "$lI")
+  local lLambdaModifier=$(formatLambdaModifier "$lLambdaModifier")
+  local lOutput="-${LAMBDA_MODIFIER_PREFIX}$lI $lLambdaModifier"
+  while true ; do
+    ((++lI))
+    local lLambdaModifier=$(extractLambdaModifier "$lI")
+    if [[ "" == "$lLambdaModifier" ]] ; then
+      break
+    fi
+    local lLambdaModifier=$(formatLambdaModifier "$lLambdaModifier")
+    local lOutput="$lOutput -${LAMBDA_MODIFIER_PREFIX}$lI $lLambdaModifier"
+  done
+  outputToMetaLogNoNewline "$lOutput;"
+}
+
+# Initialize lambdaModifiers and output it to the meta-log
+if [[ "$RESUME_MODE" == "$mode" ]] ; then
+  if [[ "" == "$initialLambdaModifiers" ]] ; then  # If no initial lambda-modifiers provided, use default value
+    lambdaModifiers=$(tail -n 1 < "$metaLogPath" | sed -e 's/;$//')
+  else  # Initial lambda-modifiers provided
+    echo "You cannot use $RESUME_MODE and specify the initial lambda-modifiers.  In resume-mode, the lambda-modifiers will be retreived from the last line of the meta-log." >&2
+    outputUsageAndExit
+  fi
+else
+  if [[ "" == "$initialLambdaModifiers" ]] ; then  # If no initial lambda-modifiers provided, use default value
+    lambdaModifiers="-${LAMBDA_MODIFIER_PREFIX}0 1"
+    for (( i=1; i<"$targetBitrateVectorSize"; ++i )); do
+      lambdaModifiers="$lambdaModifiers -${LAMBDA_MODIFIER_PREFIX}${i} 1"
+    done
+  else  # Initial lambda-modifiers provided
+    lambdaModifiers="$initialLambdaModifiers"
+  fi
+  outputLambdaModifiersToMetaLog
+fi
+
+# Calculates the difference percentage between the given target bitrate and the given bitrate, appropriately formats this difference percentage, and then outputs it.  The first argument is the given target bitrate and the second argument is the given bitrate.
+function calculateAndFormatDifferencePercentage {
+  # Calculate the result and format it with the right number of decimal places
+  local result=$(echo | awk "{print 100*($2-$1)/$1}")
+  local result=$(printf "%.3f" "$result")
+  
+  # Separate the sign from the result
+  local sign=$(echo "$result" | sed -e 's/[^-]*$//')
+  if [[ "$sign" != "-" ]] ; then
+    local sign="+"
+  fi
+  local result=$(echo "$result" | sed -e 's/^-//')
+  
+  # Pad leading zereos to make two digits before the decimal point
+  if [[ 2 == $(echo "$result" | sed -e 's/\..*$//' | wc -c | sed -e 's/^ *//') ]] ; then
+    local result="0$result"
+  fi
+  
+  # Output the result including the sign and the percent sign
+  echo "${sign}${result}%"
+}
+
+# Outputs $TRUE i.f.f. the first argument is less than the second argument
+function lessOrEqual {
+  echo | awk "{ if($1 < $2) print \"$TRUE\" }"
+}
+
+# Outputs $TRUE i.f.f. the second argument is greater than the first argument and less than the third argument ($1 < $2 < $3)
+function isInRange {
+  if [[ "$TRUE" == $(lessOrEqual "$1" "$2") ]] ; then
+    if [[ "$TRUE" == $(lessOrEqual "$2" "$3") ]] ; then
+      echo "$TRUE"
+    fi
+  fi
+}
+
+# From the given bitrate vector, outputs the "bad" bitrates by filtering out the "good" bitrates.  The first argument is the index of the last good bitrate and the second argument is the given bitrate vector.  If the first argument is -1, then the given bitrate vector is outputted in its entirety.
+function filterOutGoodBitrates {
+  local result="$2"
+  for (( i=0; i<="$1"; ++i )); do
+    result=$(echo "$result" | sed -e 's/^[^ ]* //')
+  done
+  echo "$result"
+}
+
+# Outputs a given line from the given variable.  The first argument is the line number to output and the second argument is the given variable to extract the line from.
+function outputLine {
+  echo "$2" | head -n "$(expr "$1" + 1)" | tail -n 1
+}
+
+# Initialize iterationCount
+if [[ "$RESUME_MODE" == "$mode" ]] ; then
+  iterationCount=$(wc -l < "$metaLogPath" | sed -e 's/^ *//')
+else
+  iterationCount=0
+fi
+
+ITERATION_COUNT_LIMIT=50  # The number of attempts to make before giving up
+
+while true ; do  # The main loop
+  
+  # Run the encoder
+  sh ${SUB_TOOLS_DIRECTORY}encodeCommand.sh $inputName $encodeCommandArgs $CONFIGURATION_IDENTIFIER_OPTION $configurationIdentifier $Q_OPTION $q $OUTPUT_DIRECTORY_OPTION $outputDirectory -ea "$extraArguments $lambdaModifiers" | sh > $logPath
+  if [[ $? != 0 ]] ; then
+    printf "Unexpected exit status from encodeCommand.sh\n" >&2
+    exit 1
+  fi
+  
+  # Extract and output the bitrates
+  bitrates=`${SUB_TOOLS_DIRECTORY}extractBitrates.exe < $logPath`
+  outputToMetaLogNoNewline "$bitrates;"
+  
+  # Make sure that the index set of the extracted bitrates matches the index set of the target bitrates
+  if [[ "$targetBitrateVectorSize" != "$(bitrateVectorSize "$bitrates")" ]] ; then
+    echo "Index set from the extracted bitrates does not match the index set from the target bitrates" >&2
+    exit 1
+  fi
+  
+  # Calculate the bitrate difference percentages and output them to the meta-log
+  percentages="$(calculateAndFormatDifferencePercentage "$(extractBitrateFromVector "0" "$targetBitrates")" "$(extractBitrateFromVector "0" "$bitrates")")"
+  for (( i=1; i<"$targetBitrateVectorSize"; ++i )); do
+    percentages="$percentages $(calculateAndFormatDifferencePercentage "$(extractBitrateFromVector "$i" "$targetBitrates")" "$(extractBitrateFromVector "$i" "$bitrates")")"
+  done
+  outputToMetaLogNoNewline "$percentages;"
+  
+  # Initialize and output areBitratesSatismodifiery
+  areBitratesSatisfactory=yes
+  for (( i=0; ; ++i )) ; do
+    outerRangeMin=$(extractBitrateFromVector "$i" "$outerRangeMins")
+    bitrate=$(extractBitrateFromVector "$i" "$bitrates")
+    outerRangeMax=$(extractBitrateFromVector "$i" "$outerRangeMaxs")
+    if [[ "" == "$bitrate" ]] ; then
+      break
+    fi
+    if [[ $(isInRange "$outerRangeMin" "$bitrate" "$outerRangeMax") != "$TRUE" ]] ; then
+      areBitratesSatisfactory=no
+      break
+    fi
+  done
+  outputToMetaLogWithNewline "$areBitratesSatisfactory"
+  
+  # Exit if we are finished or if we have iterated too many times
+  if [[ yes == $areBitratesSatisfactory ]] ; then
+    mv "$logPath" "${outputPathBegin}_final.log"
+    exit 0
+  else
+    # Rename the deprecated log
+    countString="$iterationCount"
+    if [[ 1 == `printf -- "$countString" | wc -c | sed -e 's/^ *//'` ]] ; then
+      countString="0$countString"
+    fi
+    mv "$logPath" "${outputPathBegin}_dep${countString}.log"
+    
+    ((++iterationCount))
+    if [[ "$ITERATION_COUNT_LIMIT" == "$iterationCount" ]] ; then
+      outputToMetaLogWithNewline "Could not reach target bitrates"
+      exit 1
+    fi
+  fi
+  
+  filteredMetaLog=$(sed -e 's/;[^;]*$//' < $metaLogPath | sed -e 's/;[^;]*$//')
+  bitratesFromMetaLog=$(printf -- "$filteredMetaLog" | sed -e 's/^[^;]*;//')
+  
+  # Initialize goodIndex
+  goodIndex=-1
+  for (( i=0; i<"$targetBitrateVectorSize"; ++i )); do
+    innerRangeMin=$(extractBitrateFromVector "$i" "$innerRangeMins")
+    bitrate=$(extractBitrateFromVector "$i" "$bitrates")
+    innerRangeMax=$(extractBitrateFromVector "$i" "$innerRangeMaxs")
+    if [[ "$TRUE" == $(isInRange "$innerRangeMin" "$bitrate" "$innerRangeMax") ]] ; then
+      goodIndex="$i"
+    else
+      break
+    fi
+  done
+  
+  badBitrates=$(filterOutGoodBitrates "$goodIndex" "$bitratesFromMetaLog")
+  lambdaModifiersFromMetaLog=`printf -- "$filteredMetaLog" | sed -e 's/;[^;]*$//'`
+  badLambdaModifiers=`printf -- "$lambdaModifiersFromMetaLog" | sed -e "s/^.*-${LAMBDA_MODIFIER_PREFIX}$goodIndex [^ ]* //"`
+  lineCount=`printf -- "$badBitrates\n" | wc -l | sed -e 's/^ *//'`
+  
+  # Initialize guessLambdaModifiersIn
+  guessLambdaModifiersIn="$(outputLine 0 "$badLambdaModifiers");$(outputLine 0 "$badBitrates")"
+  for (( i=1; i<"$lineCount"; ++i )); do
+    guessLambdaModifiersIn="$(printf -- "$guessLambdaModifiersIn\n$(outputLine "$i" "$badLambdaModifiers");$(outputLine "$i" "$badBitrates")")"
+  done
+  
+  # Run guessLambdaModifiers
+  guessedLambdaModifiers=$(printf -- "$guessLambdaModifiersIn" | ${SUB_TOOLS_DIRECTORY}guessLambdaModifiers.exe "-.5" "$(filterOutGoodBitrates "$goodIndex" "$targetBitrates")")
+  if [[ $? != 0 ]] ; then
+    printf "Unexpected exit status from guessLambdaModifiers.exe\n" >&2
+    exit 1
+  fi
+  
+  # Initialize lambdaModifiers and output them to the meta-log
+  lastLambdaModifiersFromMetaLog=`printf -- "$filteredMetaLog" | tail -n 1 | sed -e "s/;[^;]*$//"`
+  goodLambdaModifiersFromMetaLog=`printf -- "$lastLambdaModifiersFromMetaLog" | tail -n 1 | sed -e "s/-${LAMBDA_MODIFIER_PREFIX}$(expr "$goodIndex" + 1).*$//"`
+  lambdaModifiers="${goodLambdaModifiersFromMetaLog}${guessedLambdaModifiers}"
+  outputLambdaModifiersToMetaLog
+  
+done
Index: /trunk/source/App/utils/annexBbytecount.cpp
===================================================================
--- /trunk/source/App/utils/annexBbytecount.cpp	(revision 2)
+++ /trunk/source/App/utils/annexBbytecount.cpp	(revision 2)
@@ -0,0 +1,233 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <stdint.h>
+#include <cassert>
+#include <fstream>
+#include <sstream>
+#include <iostream>
+#include <string.h>
+
+#include "TLibDecoder/AnnexBread.h"
+
+using namespace std;
+
+static struct {
+  AnnexBStats expected;
+  unsigned data_len;
+  const char data[10];
+} tests[] = {
+  /* trivial cases: startcode, no payload */
+  {{0, 0, 3, 0, 0}, 3, {0,0,1}},
+  {{0, 1, 3, 0, 0}, 4, {0,0,0,1}},
+  {{2, 1, 3, 0, 0}, 6, {0,0,0,0,0,1}},
+  /* trivial cases: startcode, payload */
+  {{0, 0, 3, 1, 0}, 4, {0,0,1,2}},
+  {{0, 0, 3, 2, 0}, 5, {0,0,1,2,0}},
+  {{0, 0, 3, 3, 0}, 6, {0,0,1,2,0,0}},
+  {{0, 0, 3, 1, 3}, 7, {0,0,1,2,0,0,0}},
+  /* trivial cases: two nal units: extract the first */
+  {{0, 0, 3, 1, 0}, 8, {0,0,1,2,0,0,1,3}},
+  {{0, 0, 3, 1, 0}, 9, {0,0,1,2,0,0,0,1,3}},
+  {{0, 0, 3, 1, 1}, 10, {0,0,1,2,0,0,0,0,1,3}},
+  /* edge cases with EOF near start*/
+  {{0, 0, 0, 0, 0}, 0, {}},
+  {{1, 0, 0, 0, 0}, 1, {0}},
+  {{2, 0, 0, 0, 0}, 2, {0,0}},
+  {{3, 0, 0, 0, 0}, 3, {0,0,0}},
+};
+
+void selftest()
+{
+  /* test */
+  for (unsigned i = 0; i < sizeof(tests)/sizeof(*tests); i++)
+  {
+    istringstream in(string(tests[i].data, tests[i].data_len));
+    InputByteStream bs(in);
+
+    AnnexBStats actual = AnnexBStats();
+    vector<uint8_t> nalUnit;
+
+    byteStreamNALUnit(bs, nalUnit, actual);
+
+    cout << "Self-Test: " << i << ", {";
+    for (unsigned j = 0; j < tests[i].data_len; j++)
+    {
+      cout << hex << (unsigned int)tests[i].data[j] << dec;
+      if (j < tests[i].data_len-1)
+        cout << ",";
+    }
+    cout << "} ";
+
+    bool ok = true;
+#define VERIFY(a,b,m) \
+  if (a.m != b.m) { \
+    ok = false; \
+    cout << endl << "  MISSMATCH " #m << ", E(" << b.m << ") != " << a.m; \
+  }
+    VERIFY(actual, tests[i].expected, m_numLeadingZero8BitsBytes);
+    VERIFY(actual, tests[i].expected, m_numZeroByteBytes);
+    VERIFY(actual, tests[i].expected, m_numStartCodePrefixBytes);
+    VERIFY(actual, tests[i].expected, m_numBytesInNALUnit);
+    VERIFY(actual, tests[i].expected, m_numTrailingZero8BitsBytes);
+#undef VERIFY
+    if (ok)
+      cout << "OK";
+    cout << endl;
+  }
+}
+
+int main(int argc, char*argv[])
+{
+  selftest();
+
+  if (argc != 2)
+    return 0;
+
+  ifstream in(argv[1], ifstream::in | ifstream::binary);
+  InputByteStream bs(in);
+
+  AnnexBStats annexBStatsTotal = AnnexBStats();
+  AnnexBStats annexBStatsTotal_VCL = AnnexBStats();
+  AnnexBStats annexBStatsTotal_Filler = AnnexBStats();
+  AnnexBStats annexBStatsTotal_Other = AnnexBStats();
+  unsigned numNALUnits = 0;
+
+  cout << "NALUnits:" << endl;
+  while (!!in)
+  {
+    AnnexBStats annexBStatsSingle = AnnexBStats();
+    vector<uint8_t> nalUnit;
+
+    byteStreamNALUnit(bs, nalUnit, annexBStatsSingle);
+
+    int nal_unit_type = -1;
+    if (annexBStatsSingle.m_numBytesInNALUnit)
+    {
+      nal_unit_type = nalUnit[0] & 0x1f;
+    }
+
+    cout << " - NALU: #" << numNALUnits << " nal_unit_type:" << nal_unit_type << endl
+         << "   num_bytes(leading_zero_8bits): " << annexBStatsSingle.m_numLeadingZero8BitsBytes << endl
+         << "   num_bytes(zero_byte): " << annexBStatsSingle.m_numZeroByteBytes << endl
+         << "   num_bytes(start_code_prefix_one_3bytes): " << annexBStatsSingle.m_numStartCodePrefixBytes << endl
+         << "   NumBytesInNALunit: " << annexBStatsSingle.m_numBytesInNALUnit << endl
+         << "   num_bytes(trailing_zero_8bits): " << annexBStatsSingle.m_numTrailingZero8BitsBytes << endl
+         ;
+
+    annexBStatsTotal += annexBStatsSingle;
+    numNALUnits++;
+
+    if (!annexBStatsSingle.m_numBytesInNALUnit)
+      continue;
+
+    /* identify the NAL unit type and add stats to the correct
+     * accumulators */
+    switch (nalUnit[0] & 0x1f) {
+    case 1: case 2: case 3: case 4: case 5:
+      annexBStatsTotal_VCL += annexBStatsSingle;
+      break;
+    case 12:
+      annexBStatsTotal_Filler += annexBStatsSingle;
+      break;
+    default:
+      annexBStatsTotal_Other += annexBStatsSingle;
+    };
+  }
+
+  cout << "Summary: " << endl
+       << "  num_bytes(leading_zero_8bits): " << annexBStatsTotal.m_numLeadingZero8BitsBytes << endl
+       << "  num_bytes(zero_byte): " << annexBStatsTotal.m_numZeroByteBytes << endl
+       << "  num_bytes(start_code_prefix_one_3bytes): " << annexBStatsTotal.m_numStartCodePrefixBytes << endl
+       << "  NumBytesInNALunit: " << annexBStatsTotal.m_numBytesInNALUnit << endl
+       << "  num_bytes(trailing_zero_8bits): " << annexBStatsTotal.m_numTrailingZero8BitsBytes << endl
+       ;
+
+  cout << "Summary(VCL): " << endl
+       << "  num_bytes(leading_zero_8bits): " << annexBStatsTotal_VCL.m_numLeadingZero8BitsBytes << endl
+       << "  num_bytes(zero_byte): " << annexBStatsTotal_VCL.m_numZeroByteBytes << endl
+       << "  num_bytes(start_code_prefix_one_3bytes): " << annexBStatsTotal_VCL.m_numStartCodePrefixBytes << endl
+       << "  NumBytesInNALunit: " << annexBStatsTotal_VCL.m_numBytesInNALUnit << endl
+       << "  num_bytes(trailing_zero_8bits): " << annexBStatsTotal_VCL.m_numTrailingZero8BitsBytes << endl
+       ;
+
+  cout << "Summary(Filler): " << endl
+       << "  num_bytes(leading_zero_8bits): " << annexBStatsTotal_Filler.m_numLeadingZero8BitsBytes << endl
+       << "  num_bytes(zero_byte): " << annexBStatsTotal_Filler.m_numZeroByteBytes << endl
+       << "  num_bytes(start_code_prefix_one_3bytes): " << annexBStatsTotal_Filler.m_numStartCodePrefixBytes << endl
+       << "  NumBytesInNALunit: " << annexBStatsTotal_Filler.m_numBytesInNALUnit << endl
+       << "  num_bytes(trailing_zero_8bits): " << annexBStatsTotal_Filler.m_numTrailingZero8BitsBytes << endl
+       ;
+
+  cout << "Summary(Other): " << endl
+       << "  num_bytes(leading_zero_8bits): " << annexBStatsTotal_Other.m_numLeadingZero8BitsBytes << endl
+       << "  num_bytes(zero_byte): " << annexBStatsTotal_Other.m_numZeroByteBytes << endl
+       << "  num_bytes(start_code_prefix_one_3bytes): " << annexBStatsTotal_Other.m_numStartCodePrefixBytes << endl
+       << "  NumBytesInNALunit: " << annexBStatsTotal_Other.m_numBytesInNALUnit << endl
+       << "  num_bytes(trailing_zero_8bits): " << annexBStatsTotal_Other.m_numTrailingZero8BitsBytes << endl
+       ;
+
+  /* The first such type of bitstream, called Type I bitstream, is a
+   * NAL unit stream containing only the VCL NAL units and filler data
+   * NAL units for all access units in the bitstream.
+   */
+  unsigned totalBytes_T1HRD = annexBStatsTotal_VCL.m_numBytesInNALUnit + annexBStatsTotal_Filler.m_numBytesInNALUnit;
+
+  /*The second type of bitstream, called a Type II bitstream,
+   * contains, in addition to the VCL NAL units and filler data NAL
+   * units for all access units in the bitstream, at least one of
+   * the following:
+   *  (a) additional non-VCL NAL units other than filler data NAL
+   *      units.
+   */
+  unsigned totalBytes_T2aHRD = annexBStatsTotal.m_numBytesInNALUnit;
+
+  /*  (b) all leading_zero_8bits, zero_byte,
+   *      start_code_prefix_one_3bytes, and trailing_zero_8bits syntax
+   *      elements that form a byte stream from the NAL unit stream (as
+   *      specified in Annex B)
+   */
+  unsigned totalBytes_T2abHRD = 0;
+  totalBytes_T2abHRD += annexBStatsTotal.m_numLeadingZero8BitsBytes;
+  totalBytes_T2abHRD += annexBStatsTotal.m_numZeroByteBytes;
+  totalBytes_T2abHRD += annexBStatsTotal.m_numStartCodePrefixBytes;
+  totalBytes_T2abHRD += annexBStatsTotal.m_numBytesInNALUnit;
+  totalBytes_T2abHRD += annexBStatsTotal.m_numTrailingZero8BitsBytes;
+
+  cout << "Totals (bytes):" << endl;
+  cout << "  Type1 HRD: " << totalBytes_T1HRD << endl;
+  cout << "  Type2 HRD: " << totalBytes_T2aHRD << endl;
+  cout << "  Type2b HRD: " << totalBytes_T2abHRD << endl;
+
+  return 0;
+}
Index: /trunk/source/App/utils/convert_NtoMbit_YCbCr.cpp
===================================================================
--- /trunk/source/App/utils/convert_NtoMbit_YCbCr.cpp	(revision 2)
+++ /trunk/source/App/utils/convert_NtoMbit_YCbCr.cpp	(revision 2)
@@ -0,0 +1,117 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <cstdlib>
+
+#include "TLibCommon/TComPicYuv.h"
+#include "TLibVideoIO/TVideoIOYuv.h"
+#include "TAppCommon/program_options_lite.h"
+
+using namespace std;
+namespace po = df::program_options_lite;
+
+int main(int argc, const char** argv)
+{
+  bool do_help;
+  string filename_in, filename_out;
+  unsigned int width, height;
+  unsigned int bitdepth_in, bitdepth_out;
+  unsigned int num_frames;
+  unsigned int num_frames_skip;
+
+  po::Options opts;
+  opts.addOptions()
+  ("help", do_help, false, "this help text")
+  ("InputFile,i", filename_in, string(""), "input file to convert")
+  ("OutputFile,o", filename_out, string(""), "output file")
+  ("SourceWidth", width, 0u, "source picture width")
+  ("SourceHeight", height, 0u, "source picture height")
+  ("InputBitDepth", bitdepth_in, 8u, "bit-depth of input file")
+  ("OutputBitDepth", bitdepth_out, 8u, "bit-depth of output file")
+  ("NumFrames", num_frames, 0xffffffffu, "number of frames to process")
+  ("FrameSkip,-fs", num_frames_skip, 0u, "Number of frames to skip at start of input YUV")
+  ;
+
+  po::setDefaults(opts);
+  po::scanArgv(opts, argc, argv);
+
+  if (argc == 1 || do_help)
+  {
+    /* argc == 1: no options have been specified */
+    po::doHelp(cout, opts);
+    return EXIT_FAILURE;
+  }
+
+  TVideoIOYuv input;
+  TVideoIOYuv output;
+
+  input.open((char*)filename_in.c_str(), false, bitdepth_in, bitdepth_out);
+  output.open((char*)filename_out.c_str(), true, bitdepth_out, bitdepth_out);
+
+  input.skipFrames(num_frames_skip, width, height);
+
+  TComPicYuv frame;
+  frame.create( width, height, 1, 1, 0 );
+
+  int pad[2] = {0, 0};
+
+  unsigned int num_frames_processed = 0;
+  while (!input.isEof()) 
+  {
+    if (! input.read(&frame, pad))
+    {
+      break;
+    }
+#if 0
+    Pel* img = frame.getLumaAddr();
+    for (int y = 0; y < height; y++) 
+    {
+      for (int x = 0; x < height; x++)
+        img[x] = 0;
+      img += frame.getStride();
+    }
+    img = frame.getLumaAddr();
+    img[0] = 1;
+#endif
+
+    output.write(&frame);
+    num_frames_processed++;
+    if (num_frames_processed == num_frames)
+      break;
+  }
+
+  input.close();
+  output.close();
+
+  return EXIT_SUCCESS;
+}
Index: /trunk/source/Lib/TAppCommon/program_options_lite.cpp
===================================================================
--- /trunk/source/Lib/TAppCommon/program_options_lite.cpp	(revision 2)
+++ /trunk/source/Lib/TAppCommon/program_options_lite.cpp	(revision 2)
@@ -0,0 +1,497 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include <stdlib.h>
+#include <iostream>
+#include <fstream>
+#include <sstream>
+#include <string>
+#include <list>
+#include <map>
+#include "program_options_lite.h"
+
+using namespace std;
+
+//! \ingroup TAppCommon
+//! \{
+
+namespace df
+{
+  namespace program_options_lite
+  {
+    
+    Options::~Options()
+    {
+      for(Options::NamesPtrList::iterator it = opt_list.begin(); it != opt_list.end(); it++)
+      {
+        delete *it;
+      }
+    }
+    
+    void Options::addOption(OptionBase *opt)
+    {
+      Names* names = new Names();
+      names->opt = opt;
+      string& opt_string = opt->opt_string;
+      
+      size_t opt_start = 0;
+      for (size_t opt_end = 0; opt_end != string::npos;)
+      {
+        opt_end = opt_string.find_first_of(',', opt_start);
+        bool force_short = 0;
+        if (opt_string[opt_start] == '-')
+        {
+          opt_start++;
+          force_short = 1;
+        }
+        string opt_name = opt_string.substr(opt_start, opt_end - opt_start);
+        if (force_short || opt_name.size() == 1)
+        {
+          names->opt_short.push_back(opt_name);
+          opt_short_map[opt_name].push_back(names);
+        }
+        else
+        {
+          names->opt_long.push_back(opt_name);
+          opt_long_map[opt_name].push_back(names);
+        }
+        opt_start += opt_end + 1;
+      }
+      opt_list.push_back(names);
+    }
+
+    /* Helper method to initiate adding options to Options */
+    OptionSpecific Options::addOptions()
+    {
+      return OptionSpecific(*this);
+    }
+    
+    static void setOptions(Options::NamesPtrList& opt_list, const string& value)
+    {
+      /* multiple options may be registered for the same name:
+       *   allow each to parse value */
+      for (Options::NamesPtrList::iterator it = opt_list.begin(); it != opt_list.end(); ++it)
+      {
+        (*it)->opt->parse(value);
+      }
+    }
+
+    static const char spaces[41] = "                                        ";
+    
+    /* format help text for a single option:
+     * using the formatting: "-x, --long",
+     * if a short/long option isn't specified, it is not printed
+     */
+    static void doHelpOpt(ostream& out, const Options::Names& entry, unsigned pad_short = 0)
+    {
+      pad_short = min(pad_short, 8u);
+
+      if (!entry.opt_short.empty())
+      {
+        unsigned pad = max((int)pad_short - (int)entry.opt_short.front().size(), 0);
+        out << "-" << entry.opt_short.front();
+        if (!entry.opt_long.empty())
+        {
+          out << ", ";
+        }
+        out << &(spaces[40 - pad]);
+      }
+      else
+      {
+        out << "   ";
+        out << &(spaces[40 - pad_short]);
+      }
+
+      if (!entry.opt_long.empty())
+      {
+        out << "--" << entry.opt_long.front();
+      }
+    }
+    
+    /* format the help text */
+    void doHelp(ostream& out, Options& opts, unsigned columns)
+    {
+      const unsigned pad_short = 3;
+      /* first pass: work out the longest option name */
+      unsigned max_width = 0;
+      for(Options::NamesPtrList::iterator it = opts.opt_list.begin(); it != opts.opt_list.end(); it++)
+      {
+        ostringstream line(ios_base::out);
+        doHelpOpt(line, **it, pad_short);
+        max_width = max(max_width, (unsigned) line.tellp());
+      }
+
+      unsigned opt_width = min(max_width+2, 28u + pad_short) + 2;
+      unsigned desc_width = columns - opt_width;
+      
+      /* second pass: write out formatted option and help text.
+       *  - align start of help text to start at opt_width
+       *  - if the option text is longer than opt_width, place the help
+       *    text at opt_width on the next line.
+       */
+      for(Options::NamesPtrList::iterator it = opts.opt_list.begin(); it != opts.opt_list.end(); it++)
+      {
+        ostringstream line(ios_base::out);
+        line << "  ";
+        doHelpOpt(line, **it, pad_short);
+
+        const string& opt_desc = (*it)->opt->opt_desc;
+        if (opt_desc.empty())
+        {
+          /* no help text: output option, skip further processing */
+          cout << line.str() << endl;
+          continue;
+        }
+        size_t currlength = size_t(line.tellp());
+        if (currlength > opt_width)
+        {
+          /* if option text is too long (and would collide with the
+           * help text, split onto next line */
+          line << endl;
+          currlength = 0;
+        }
+        /* split up the help text, taking into account new lines,
+         *   (add opt_width of padding to each new line) */
+        for (size_t newline_pos = 0, cur_pos = 0; cur_pos != string::npos; currlength = 0)
+        {
+          /* print any required padding space for vertical alignment */
+          line << &(spaces[40 - opt_width + currlength]);
+          newline_pos = opt_desc.find_first_of('\n', newline_pos);
+          if (newline_pos != string::npos)
+          {
+            /* newline found, print substring (newline needn't be stripped) */
+            newline_pos++;
+            line << opt_desc.substr(cur_pos, newline_pos - cur_pos);
+            cur_pos = newline_pos;
+            continue;
+          }
+          if (cur_pos + desc_width > opt_desc.size())
+          {
+            /* no need to wrap text, remainder is less than avaliable width */
+            line << opt_desc.substr(cur_pos);
+            break;
+          }
+          /* find a suitable point to split text (avoid spliting in middle of word) */
+          size_t split_pos = opt_desc.find_last_of(' ', cur_pos + desc_width);
+          if (split_pos != string::npos)
+          {
+            /* eat up multiple space characters */
+            split_pos = opt_desc.find_last_not_of(' ', split_pos) + 1;
+          }
+          
+          /* bad split if no suitable space to split at.  fall back to width */
+          bool bad_split = split_pos == string::npos || split_pos <= cur_pos;
+          if (bad_split)
+          {
+            split_pos = cur_pos + desc_width;
+          }
+          line << opt_desc.substr(cur_pos, split_pos - cur_pos);
+          
+          /* eat up any space for the start of the next line */
+          if (!bad_split)
+          {
+            split_pos = opt_desc.find_first_not_of(' ', split_pos);
+          }
+          cur_pos = newline_pos = split_pos;
+          
+          if (cur_pos >= opt_desc.size())
+          {
+            break;
+          }
+          line << endl;
+        }
+
+        cout << line.str() << endl;
+      }
+    }
+    
+    bool storePair(Options& opts, bool allow_long, bool allow_short, const string& name, const string& value)
+    {
+      bool found = false;
+      Options::NamesMap::iterator opt_it;
+      if (allow_long)
+      {
+        opt_it = opts.opt_long_map.find(name);
+        if (opt_it != opts.opt_long_map.end())
+        {
+          found = true;
+        }
+      }
+      
+      /* check for the short list */
+      if (allow_short && !(found && allow_long))
+      {
+        opt_it = opts.opt_short_map.find(name);
+        if (opt_it != opts.opt_short_map.end())
+        {
+          found = true;
+        }
+      }
+
+      if (!found)
+      {
+        /* not found */
+        cerr << "Unknown option: `" << name << "' (value:`" << value << "')" << endl;
+        return false;
+      }
+
+      setOptions((*opt_it).second, value);
+      return true;
+    }
+    
+    bool storePair(Options& opts, const string& name, const string& value)
+    {
+      return storePair(opts, true, true, name, value);
+    }
+    
+    /**
+     * returns number of extra arguments consumed
+     */
+    unsigned parseGNU(Options& opts, unsigned argc, const char* argv[])
+    {
+      /* gnu style long options can take the forms:
+       *  --option=arg
+       *  --option arg
+       */
+      string arg(argv[0]);
+      size_t arg_opt_start = arg.find_first_not_of('-');
+      size_t arg_opt_sep = arg.find_first_of('=');
+      string option = arg.substr(arg_opt_start, arg_opt_sep - arg_opt_start);
+      
+      unsigned extra_argc_consumed = 0;
+      if (arg_opt_sep == string::npos)
+      {
+        /* no argument found => argument in argv[1] (maybe) */
+        /* xxx, need to handle case where option isn't required */
+#if 0
+        /* commented out, to return to true GNU style processing
+        * where longopts have to include an =, otherwise they are
+        * booleans */
+        if (argc == 1)
+          return 0; /* run out of argv for argument */
+        extra_argc_consumed = 1;
+#endif
+        if(!storePair(opts, true, false, option, "1"))
+        {
+          return 0;
+        }
+      }
+      else
+      {
+        /* argument occurs after option_sep */
+        string val = arg.substr(arg_opt_sep + 1);
+        storePair(opts, true, false, option, val);
+      }
+
+      return extra_argc_consumed;
+    }
+
+    unsigned parseSHORT(Options& opts, unsigned argc, const char* argv[])
+    {
+      /* short options can take the forms:
+       *  --option arg
+       *  -option arg
+       */
+      string arg(argv[0]);
+      size_t arg_opt_start = arg.find_first_not_of('-');
+      string option = arg.substr(arg_opt_start);
+      /* lookup option */
+
+      /* argument in argv[1] */
+      /* xxx, need to handle case where option isn't required */
+      if (argc == 1)
+      {
+        cerr << "Not processing option without argument `" << option << "'" << endl;
+        return 0; /* run out of argv for argument */
+      }
+      storePair(opts, false, true, option, string(argv[1]));
+
+      return 1;
+    }
+    
+    list<const char*>
+    scanArgv(Options& opts, unsigned argc, const char* argv[])
+    {
+      /* a list for anything that didn't get handled as an option */
+      list<const char*> non_option_arguments;
+
+      for(unsigned i = 1; i < argc; i++)
+      {
+        if (argv[i][0] != '-')
+        {
+          non_option_arguments.push_back(argv[i]);
+          continue;
+        }
+
+        if (argv[i][1] == 0)
+        {
+          /* a lone single dash is an argument (usually signifying stdin) */
+          non_option_arguments.push_back(argv[i]);
+          continue;
+        }
+
+        if (argv[i][1] != '-')
+        {
+          /* handle short (single dash) options */
+#if 0
+          i += parsePOSIX(opts, argc - i, &argv[i]);
+#else
+          i += parseSHORT(opts, argc - i, &argv[i]);
+#endif
+          continue;
+        }
+
+        if (argv[i][2] == 0)
+        {
+          /* a lone double dash ends option processing */
+          while (++i < argc)
+            non_option_arguments.push_back(argv[i]);
+          break;
+        }
+
+        /* handle long (double dash) options */
+        i += parseGNU(opts, argc - i, &argv[i]);
+      }
+
+      return non_option_arguments;
+    }
+    
+    void scanLine(Options& opts, string& line)
+    {
+      /* strip any leading whitespace */
+      size_t start = line.find_first_not_of(" \t\n\r");
+      if (start == string::npos)
+      {
+        /* blank line */
+        return;
+      }
+      if (line[start] == '#')
+      {
+        /* comment line */
+        return;
+      }
+      /* look for first whitespace or ':' after the option end */
+      size_t option_end = line.find_first_of(": \t\n\r",start);
+      string option = line.substr(start, option_end - start);
+
+      /* look for ':', eat up any whitespace first */
+      start = line.find_first_not_of(" \t\n\r", option_end);
+      if (start == string::npos)
+      {
+        /* error: badly formatted line */
+        return;
+      }
+      if (line[start] != ':')
+      {
+        /* error: badly formatted line */
+        return;
+      }
+
+      /* look for start of value string -- eat up any leading whitespace */
+      start = line.find_first_not_of(" \t\n\r", ++start);
+      if (start == string::npos)
+      {
+        /* error: badly formatted line */
+        return;
+      }
+
+      /* extract the value part, which may contain embedded spaces
+       * by searching for a word at a time, until we hit a comment or end of line */
+      size_t value_end = start;
+      do
+      {
+        if (line[value_end] == '#')
+        {
+          /* rest of line is a comment */
+          value_end--;
+          break;
+        }
+        value_end = line.find_first_of(" \t\n\r", value_end);
+        /* consume any white space, incase there is another word.
+         * any trailing whitespace will be removed shortly */
+        value_end = line.find_first_not_of(" \t\n\r", value_end);
+      }
+      while (value_end != string::npos);
+      /* strip any trailing space from value*/
+      value_end = line.find_last_not_of(" \t\n\r", value_end);
+
+      string value;
+      if (value_end >= start)
+      {
+        value = line.substr(start, value_end +1 - start);
+      }
+      else
+      {
+        /* error: no value */
+        return;
+      }
+
+      /* store the value in option */
+      storePair(opts, true, false, option, value);
+    }
+
+    void scanFile(Options& opts, istream& in)
+    {
+      do
+      {
+        string line;
+        getline(in, line);
+        scanLine(opts, line);
+      }
+      while(!!in);
+    }
+
+    /* for all options in opts, set their storage to their specified
+     * default value */
+    void setDefaults(Options& opts)
+    {
+      for(Options::NamesPtrList::iterator it = opts.opt_list.begin(); it != opts.opt_list.end(); it++)
+      {
+        (*it)->opt->setDefault();
+      }
+    }
+
+    void parseConfigFile(Options& opts, const string& filename)
+    {
+      ifstream cfgstream(filename.c_str(), ifstream::in);
+      if (!cfgstream)
+      {
+        cerr << "Failed to open config file: `" << filename << "'" << endl;
+        exit(EXIT_FAILURE);
+      }
+      scanFile(opts, cfgstream);
+    }
+
+  };
+};
+
+//! \}
Index: /trunk/source/Lib/TAppCommon/program_options_lite.h
===================================================================
--- /trunk/source/Lib/TAppCommon/program_options_lite.h	(revision 2)
+++ /trunk/source/Lib/TAppCommon/program_options_lite.h	(revision 2)
@@ -0,0 +1,263 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include <iostream>
+#include <sstream>
+#include <string>
+#include <list>
+#include <map>
+#include "TLibCommon/TypeDef.h"
+
+//! \ingroup TAppCommon
+//! \{
+
+
+namespace df
+{
+  namespace program_options_lite
+  {
+    struct Options;
+    
+    void doHelp(std::ostream& out, Options& opts, unsigned columns = 80);
+    unsigned parseGNU(Options& opts, unsigned argc, const char* argv[]);
+    unsigned parseSHORT(Options& opts, unsigned argc, const char* argv[]);
+    std::list<const char*> scanArgv(Options& opts, unsigned argc, const char* argv[]);
+    void scanLine(Options& opts, std::string& line);
+    void scanFile(Options& opts, std::istream& in);
+    void setDefaults(Options& opts);
+    void parseConfigFile(Options& opts, const std::string& filename);
+    bool storePair(Options& opts, const std::string& name, const std::string& value);
+    
+    /** OptionBase: Virtual base class for storing information relating to a
+     * specific option This base class describes common elements.  Type specific
+     * information should be stored in a derived class. */
+    struct OptionBase
+    {
+      OptionBase(const std::string& name, const std::string& desc)
+      : opt_string(name), opt_desc(desc)
+      {};
+      
+      virtual ~OptionBase() {}
+      
+      /* parse argument arg, to obtain a value for the option */
+      virtual void parse(const std::string& arg) = 0;
+      /* set the argument to the default value */
+      virtual void setDefault() = 0;
+      
+      std::string opt_string;
+      std::string opt_desc;
+    };
+    
+    /** Type specific option storage */
+    template<typename T>
+    struct Option : public OptionBase
+    {
+      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)
+      {}
+      
+      void parse(const std::string& arg);
+      
+      void setDefault()
+      {
+        opt_storage = opt_default_val;
+      }
+      
+      T& opt_storage;
+      T opt_default_val;
+    };
+    
+    /* Generic parsing */
+    template<typename T>
+    inline void
+    Option<T>::parse(const std::string& arg)
+    {
+      std::istringstream arg_ss (arg,std::istringstream::in);
+      arg_ss >> opt_storage;
+    }
+    
+    /* string parsing is specialized -- copy the whole string, not just the
+     * first word */
+    template<>
+    inline void
+    Option<std::string>::parse(const std::string& arg)
+    {
+      opt_storage = arg;
+    }
+    
+    /** Option class for argument handling using a user provided function */
+    struct OptionFunc : public OptionBase
+    {
+      typedef void (Func)(Options&, const std::string&);
+      
+      OptionFunc(const std::string& name, Options& parent_, Func *func_, const std::string& desc)
+      : OptionBase(name, desc), parent(parent_), func(func_)
+      {}
+      
+      void parse(const std::string& arg)
+      {
+        func(parent, arg);
+      }
+      
+      void setDefault()
+      {
+        return;
+      }
+      
+    private:
+      Options& parent;
+      void (*func)(Options&, const std::string&);
+    };
+    
+    class OptionSpecific;
+    struct Options
+    {
+      ~Options();
+      
+      OptionSpecific addOptions();
+      
+      struct Names
+      {
+        Names() : opt(0) {};
+        ~Names()
+        {
+          if (opt)
+            delete opt;
+        }
+        std::list<std::string> opt_long;
+        std::list<std::string> opt_short;
+        OptionBase* opt;
+      };
+
+      void addOption(OptionBase *opt);
+      
+      typedef std::list<Names*> NamesPtrList;
+      NamesPtrList opt_list;
+      
+      typedef std::map<std::string, NamesPtrList> NamesMap;
+      NamesMap opt_long_map;
+      NamesMap opt_short_map;
+    };
+    
+    /* Class with templated overloaded operator(), for use by Options::addOptions() */
+    class OptionSpecific
+    {
+    public:
+      OptionSpecific(Options& parent_) : parent(parent_) {}
+      
+      /**
+       * Add option described by name to the parent Options list,
+       *   with storage for the option's value
+       *   with default_val as the default value
+       *   with desc as an optional help description
+       */
+      template<typename T>
+      OptionSpecific&
+      operator()(const std::string& name, T& storage, T default_val, const std::string& desc = "")
+      {
+        parent.addOption(new Option<T>(name, storage, default_val, desc));
+        return *this;
+      }
+#if 1 //SVC_EXTENSION
+      template<typename T>
+      OptionSpecific&
+        operator()(const std::string& name, T* storage, T default_val, unsigned uiMaxNum, const std::string& desc = "" )
+      {
+        std::string cNameBuffer;
+        std::string cDescriptionBuffer;
+
+        cNameBuffer       .resize( name.size() + 10 );
+        cDescriptionBuffer.resize( desc.size() + 10 );
+
+        for ( unsigned int uiK = 0; uiK < uiMaxNum; uiK++ )
+        {
+          // isn't there are sprintf function for string??
+          sprintf((char*) cNameBuffer.c_str()       ,name.c_str(),uiK,uiK);
+          sprintf((char*) cDescriptionBuffer.c_str(),desc.c_str(),uiK,uiK);
+
+          size_t pos = cNameBuffer.find_first_of('\0');
+          if(pos != std::string::npos)
+            cNameBuffer.resize(pos);
+
+          parent.addOption(new Option<T>( cNameBuffer, (storage[uiK]), default_val, cDescriptionBuffer ));
+        }
+
+        return *this;
+      }
+
+      template<typename T>
+      OptionSpecific&
+        operator()(const std::string& name, T** storage, T default_val, unsigned uiMaxNum, const std::string& desc = "" )
+      {
+        std::string cNameBuffer;
+        std::string cDescriptionBuffer;
+
+        cNameBuffer       .resize( name.size() + 10 );
+        cDescriptionBuffer.resize( desc.size() + 10 );
+
+        for ( unsigned int uiK = 0; uiK < uiMaxNum; uiK++ )
+        {
+          // isn't there are sprintf function for string??
+          sprintf((char*) cNameBuffer.c_str()       ,name.c_str(),uiK,uiK);
+          sprintf((char*) cDescriptionBuffer.c_str(),desc.c_str(),uiK,uiK);
+
+          size_t pos = cNameBuffer.find_first_of('\0');
+          if(pos != std::string::npos)
+            cNameBuffer.resize(pos);
+
+          parent.addOption(new Option<T>( cNameBuffer, *(storage[uiK]), default_val, cDescriptionBuffer ));
+        }
+
+        return *this;
+      }
+#endif
+      /**
+       * Add option described by name to the parent Options list,
+       *   with desc as an optional help description
+       * instead of storing the value somewhere, a function of type
+       * OptionFunc::Func is called.  It is upto this function to correctly
+       * handle evaluating the option's value.
+       */
+      OptionSpecific&
+      operator()(const std::string& name, OptionFunc::Func *func, const std::string& desc = "")
+      {
+        parent.addOption(new OptionFunc(name, parent, func, desc));
+        return *this;
+      }
+    private:
+      Options& parent;
+    };
+    
+  }; /* namespace: program_options_lite */
+}; /* namespace: df */
+
+//! \}
Index: /trunk/source/Lib/TLibCommon/AccessUnit.h
===================================================================
--- /trunk/source/Lib/TLibCommon/AccessUnit.h	(revision 2)
+++ /trunk/source/Lib/TLibCommon/AccessUnit.h	(revision 2)
@@ -0,0 +1,71 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** 
+ \file     AccessUnit.h
+ \brief    Access Unit class (header)
+ */
+
+#pragma once
+
+#include <list>
+#include "NAL.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+/**
+ * An AccessUnit is a list of one or more NAL units, according to the
+ * working draft.  All NAL units within the object belong to the same
+ * access unit.
+ *
+ * NALUnits held in the AccessUnit list are in EBSP format.  Attempting
+ * to insert an OutputNALUnit into the access unit will automatically cause
+ * the nalunit to have its headers written and anti-emulation performed.
+ *
+ * The AccessUnit owns all pointers stored within.  Destroying the
+ * AccessUnit will delete all contained objects.
+ */
+class AccessUnit : public std::list<NALUnitEBSP*>
+{
+public:
+  ~AccessUnit()
+  {
+    for (AccessUnit::iterator it = this->begin(); it != this->end(); it++)
+    {
+      delete *it;
+    }
+  }
+};
+
+//! \}
Index: /trunk/source/Lib/TLibCommon/CommonDef.h
===================================================================
--- /trunk/source/Lib/TLibCommon/CommonDef.h	(revision 2)
+++ /trunk/source/Lib/TLibCommon/CommonDef.h	(revision 2)
@@ -0,0 +1,305 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     CommonDef.h
+    \brief    Defines constants, macros and tool parameters
+*/
+
+#ifndef __COMMONDEF__
+#define __COMMONDEF__
+
+#include <algorithm>
+
+#if _MSC_VER > 1000
+// disable "signed and unsigned mismatch"
+#pragma warning( disable : 4018 )
+// disable bool coercion "performance warning"
+#pragma warning( disable : 4800 )
+#endif // _MSC_VER > 1000
+#include "TypeDef.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Version information
+// ====================================================================================================================
+
+#define NV_VERSION        "0.1"                 ///< Current software version
+
+// ====================================================================================================================
+// Platform information
+// ====================================================================================================================
+
+#ifdef __GNUC__
+#define NVM_COMPILEDBY  "[GCC %d.%d.%d]", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__
+#ifdef __IA64__
+#define NVM_ONARCH    "[on 64-bit] "
+#else
+#define NVM_ONARCH    "[on 32-bit] "
+#endif
+#endif
+
+#ifdef __INTEL_COMPILER
+#define NVM_COMPILEDBY  "[ICC %d]", __INTEL_COMPILER
+#elif  _MSC_VER
+#define NVM_COMPILEDBY  "[VS %d]", _MSC_VER
+#endif
+
+#ifndef NVM_COMPILEDBY
+#define NVM_COMPILEDBY "[Unk-CXX]"
+#endif
+
+#ifdef _WIN32
+#define NVM_ONOS        "[Windows]"
+#elif  __linux
+#define NVM_ONOS        "[Linux]"
+#elif  __CYGWIN__
+#define NVM_ONOS        "[Cygwin]"
+#elif __APPLE__
+#define NVM_ONOS        "[Mac OS X]"
+#else
+#define NVM_ONOS "[Unk-OS]"
+#endif
+
+#define NVM_BITS          "[%d bit] ", (sizeof(void*) == 8 ? 64 : 32) ///< used for checking 64-bit O/S
+
+#ifndef NULL
+#define NULL              0
+#endif
+
+// ====================================================================================================================
+// Common constants
+// ====================================================================================================================
+
+#define _SUMMARY_OUT_               0           ///< print-out PSNR results of all slices to summary.txt
+#define _SUMMARY_PIC_               0           ///< print-out PSNR results for each slice type to summary.txt
+
+#define MAX_GOP                     64          ///< max. value of hierarchical GOP size
+
+#if REF_IDX_FRAMEWORK
+#define MAX_NUM_REF                 5           ///< max. value of multiple reference frames
+#else
+#define MAX_NUM_REF                 4           ///< max. value of multiple reference frames
+#endif
+#define MAX_NUM_REF_LC              8           ///< max. value of combined reference frames
+
+#define MAX_UINT                    0xFFFFFFFFU ///< max. value of unsigned 32-bit integer
+#define MAX_INT                     2147483647  ///< max. value of signed 32-bit integer
+#define MAX_INT64                   0x7FFFFFFFFFFFFFFFLL  ///< max. value of signed 64-bit integer
+#define MAX_DOUBLE                  1.7e+308    ///< max. value of double-type value
+
+#define MIN_QP                      0
+#define MAX_QP                      51
+
+#define NOT_VALID                   -1
+
+#if SVC_EXTENSION
+#define MAX_PAD_SIZE                16
+#endif
+
+// ====================================================================================================================
+// Macro functions
+// ====================================================================================================================
+extern UInt g_uiIBDI_MAX;
+
+/** clip x, such that 0 <= x <= #g_uiIBDI_MAX */
+template <typename T> inline T Clip(T x) { return std::min<T>(T(g_uiIBDI_MAX), std::max<T>( T(0), x)); }
+
+/** clip a, such that minVal <= a <= maxVal */
+template <typename T> inline T Clip3( T minVal, T maxVal, T a) { return std::min<T> (std::max<T> (minVal, a) , maxVal); }  ///< general min/max clip
+
+#define DATA_ALIGN                  1                                                                 ///< use 32-bit aligned malloc/free
+#if     DATA_ALIGN && _WIN32 && ( _MSC_VER > 1300 )
+#define xMalloc( type, len )        _aligned_malloc( sizeof(type)*(len), 32 )
+#define xFree( ptr )                _aligned_free  ( ptr )
+#else
+#define xMalloc( type, len )        malloc   ( sizeof(type)*(len) )
+#define xFree( ptr )                free     ( ptr )
+#endif
+
+#define FATAL_ERROR_0(MESSAGE, EXITCODE)                      \
+{                                                             \
+  printf(MESSAGE);                                            \
+  exit(EXITCODE);                                             \
+}
+
+
+// ====================================================================================================================
+// Coding tool configuration
+// ====================================================================================================================
+
+// AMVP: advanced motion vector prediction
+#define AMVP_MAX_NUM_CANDS          2           ///< max number of final candidates
+#define AMVP_MAX_NUM_CANDS_MEM      3           ///< max number of candidates
+// MERGE
+#define MRG_MAX_NUM_CANDS           5
+
+// Reference memory management
+#define DYN_REF_FREE                0           ///< dynamic free of reference memories
+
+// Explicit temporal layer QP offset
+#define MAX_TLAYER                  8           ///< max number of temporal layer
+#define HB_LAMBDA_FOR_LDC           1           ///< use of B-style lambda for non-key pictures in low-delay mode
+
+// Fast estimation of generalized B in low-delay mode
+#define GPB_SIMPLE                  1           ///< Simple GPB mode
+#if     GPB_SIMPLE
+#define GPB_SIMPLE_UNI              1           ///< Simple mode for uni-direction
+#endif
+
+// Fast ME using smoother MV assumption
+#define FASTME_SMOOTHER_MV          1           ///< reduce ME time using faster option
+
+// Adaptive search range depending on POC difference
+#define ADAPT_SR_SCALE              1           ///< division factor for adaptive search range
+
+#define CLIP_TO_709_RANGE           0
+
+// IBDI range restriction for skipping clip
+#define IBDI_NOCLIP_RANGE           0           ///< restrict max. value after IBDI to skip clip
+
+// Early-skip threshold (encoder)
+#define EARLY_SKIP_THRES            1.50        ///< if RD < thres*avg[BestSkipRD]
+
+#define MAX_NUM_REF_PICS 16
+
+#define MAX_CHROMA_FORMAT_IDC      3
+
+#if NAL_UNIT_TYPES_J1003_D7
+// TODO: Existing names used for the different NAL unit types can be altered to better reflect the names in the spec.
+//       However, the names in the spec are not yet stable at this point. Once the names are stable, a cleanup 
+//       effort can be done without use of macros to alter the names used to indicate the different NAL unit types.
+#endif
+enum NalUnitType
+{
+  NAL_UNIT_UNSPECIFIED_0 = 0,
+#if NAL_UNIT_TYPES_J1003_D7
+  NAL_UNIT_CODED_SLICE_TRAIL_R,   // 1
+  NAL_UNIT_CODED_SLICE_TRAIL_N,   // 2
+  NAL_UNIT_CODED_SLICE_TLA,       // 3   // Current name in the spec: TSA_R
+  NAL_UNIT_CODED_SLICE_TSA_N,     // 4
+  NAL_UNIT_CODED_SLICE_STSA_R,    // 5
+  NAL_UNIT_CODED_SLICE_STSA_N,    // 6
+  NAL_UNIT_CODED_SLICE_BLA,       // 7   // Current name in the spec: BLA_W_TFD
+  NAL_UNIT_CODED_SLICE_BLANT,     // 8   // Current name in the spec: BLA_W_DLP
+  NAL_UNIT_CODED_SLICE_BLA_N_LP,  // 9
+  NAL_UNIT_CODED_SLICE_IDR,       // 10  // Current name in the spec: IDR_W_LP
+  NAL_UNIT_CODED_SLICE_IDR_N_LP,  // 11
+  NAL_UNIT_CODED_SLICE_CRA,       // 12
+  NAL_UNIT_CODED_SLICE_DLP,       // 13
+  NAL_UNIT_CODED_SLICE_TFD,       // 14
+#else
+  NAL_UNIT_CODED_SLICE,           // 1
+  NAL_UNIT_CODED_SLICE_TFD,       // 2
+  NAL_UNIT_CODED_SLICE_TLA,       // 3
+  NAL_UNIT_CODED_SLICE_CRA,       // 4
+  NAL_UNIT_CODED_SLICE_CRANT,     // 5
+  NAL_UNIT_CODED_SLICE_BLA,       // 6
+  NAL_UNIT_CODED_SLICE_BLANT,     // 7
+  NAL_UNIT_CODED_SLICE_IDR,       // 8
+  NAL_UNIT_RESERVED_9,
+  NAL_UNIT_RESERVED_10,
+  NAL_UNIT_RESERVED_11,
+  NAL_UNIT_RESERVED_12,
+  NAL_UNIT_RESERVED_13,
+  NAL_UNIT_RESERVED_14,
+#endif
+  NAL_UNIT_RESERVED_15,
+  NAL_UNIT_RESERVED_16,
+  NAL_UNIT_RESERVED_17,
+  NAL_UNIT_RESERVED_18,
+  NAL_UNIT_RESERVED_19,
+  NAL_UNIT_RESERVED_20,
+  NAL_UNIT_RESERVED_21,
+  NAL_UNIT_RESERVED_22,
+  NAL_UNIT_RESERVED_23,
+  NAL_UNIT_RESERVED_24,
+  NAL_UNIT_VPS,                   // 25
+  NAL_UNIT_SPS,                   // 26
+  NAL_UNIT_PPS,                   // 27
+#if NAL_UNIT_TYPES_J1003_D7
+  NAL_UNIT_ACCESS_UNIT_DELIMITER, // 28
+  NAL_UNIT_EOS,                   // 29
+  NAL_UNIT_EOB,                   // 30
+  NAL_UNIT_FILLER_DATA,           // 31
+  NAL_UNIT_SEI,                   // 32
+#else
+#if REMOVE_APS
+  NAL_UNIT_RESERVED_28,
+#else
+  NAL_UNIT_APS,                   // 28
+#endif
+  NAL_UNIT_ACCESS_UNIT_DELIMITER, // 29
+  NAL_UNIT_FILLER_DATA,           // 30
+  NAL_UNIT_SEI,                   // 31
+  NAL_UNIT_RESERVED_32,
+#endif
+  NAL_UNIT_RESERVED_33,
+  NAL_UNIT_RESERVED_34,
+  NAL_UNIT_RESERVED_35,
+  NAL_UNIT_RESERVED_36,
+  NAL_UNIT_RESERVED_37,
+  NAL_UNIT_RESERVED_38,
+  NAL_UNIT_RESERVED_39,
+  NAL_UNIT_RESERVED_40,
+  NAL_UNIT_RESERVED_41,
+  NAL_UNIT_RESERVED_42,
+  NAL_UNIT_RESERVED_43,
+  NAL_UNIT_RESERVED_44,
+  NAL_UNIT_RESERVED_45,
+  NAL_UNIT_RESERVED_46,
+  NAL_UNIT_RESERVED_47,
+  NAL_UNIT_UNSPECIFIED_48,
+  NAL_UNIT_UNSPECIFIED_49,
+  NAL_UNIT_UNSPECIFIED_50,
+  NAL_UNIT_UNSPECIFIED_51,
+  NAL_UNIT_UNSPECIFIED_52,
+  NAL_UNIT_UNSPECIFIED_53,
+  NAL_UNIT_UNSPECIFIED_54,
+  NAL_UNIT_UNSPECIFIED_55,
+  NAL_UNIT_UNSPECIFIED_56,
+  NAL_UNIT_UNSPECIFIED_57,
+  NAL_UNIT_UNSPECIFIED_58,
+  NAL_UNIT_UNSPECIFIED_59,
+  NAL_UNIT_UNSPECIFIED_60,
+  NAL_UNIT_UNSPECIFIED_61,
+  NAL_UNIT_UNSPECIFIED_62,
+  NAL_UNIT_UNSPECIFIED_63,
+  NAL_UNIT_INVALID,
+};
+
+//! \}
+
+#endif // end of #ifndef  __COMMONDEF__
+
Index: /trunk/source/Lib/TLibCommon/ContextModel.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/ContextModel.cpp	(revision 2)
+++ /trunk/source/Lib/TLibCommon/ContextModel.cpp	(revision 2)
@@ -0,0 +1,129 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     ContextModel.cpp
+    \brief    context model class
+*/
+
+#include <algorithm>
+
+#include "ContextModel.h"
+
+using namespace std;
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/**
+ - initialize context model with respect to QP and initialization value
+ .
+ \param  qp         input QP value
+ \param  initValue  8 bit initialization value
+ */
+Void ContextModel::init( Int qp, Int initValue )
+{
+  qp = Clip3(0, 51, qp);
+
+  Int  slope      = (initValue>>4)*5 - 45;
+  Int  offset     = ((initValue&15)<<3)-16;
+  Int  initState  =  min( max( 1, ( ( ( slope * qp ) >> 4 ) + offset ) ), 126 );
+  UInt mpState    = (initState >= 64 );
+  m_ucState       = ( (mpState? (initState - 64):(63 - initState)) <<1) + mpState;
+}
+
+const UChar ContextModel::m_aucNextStateMPS[ 128 ] =
+{
+  2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
+  18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
+  34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
+  50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65,
+  66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
+  82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97,
+  98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113,
+  114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 124, 125, 126, 127
+};
+
+const UChar ContextModel::m_aucNextStateLPS[ 128 ] =
+{
+  1, 0, 0, 1, 2, 3, 4, 5, 4, 5, 8, 9, 8, 9, 10, 11,
+  12, 13, 14, 15, 16, 17, 18, 19, 18, 19, 22, 23, 22, 23, 24, 25,
+  26, 27, 26, 27, 30, 31, 30, 31, 32, 33, 32, 33, 36, 37, 36, 37,
+  38, 39, 38, 39, 42, 43, 42, 43, 44, 45, 44, 45, 46, 47, 48, 49,
+  48, 49, 50, 51, 52, 53, 52, 53, 54, 55, 54, 55, 56, 57, 58, 59,
+  58, 59, 60, 61, 60, 61, 60, 61, 62, 63, 64, 65, 64, 65, 66, 67,
+  66, 67, 66, 67, 68, 69, 68, 69, 70, 71, 70, 71, 70, 71, 72, 73,
+  72, 73, 72, 73, 74, 75, 74, 75, 74, 75, 76, 77, 76, 77, 126, 127
+};
+
+#if FAST_BIT_EST
+UChar ContextModel::m_nextState[128][2];
+
+Void ContextModel::buildNextStateTable()
+{
+  for (Int i = 0; i < 128; i++)
+  {
+    for (Int j = 0; j < 2; j++)
+    {
+      m_nextState[i][j] = ((i&1) == j) ? m_aucNextStateMPS[i] : m_aucNextStateLPS[i];
+    }
+  }
+}
+#endif
+
+const Int ContextModel::m_entropyBits[128] =
+{
+#if FAST_BIT_EST
+  // Corrected table, most notably for last state
+  0x07b23, 0x085f9, 0x074a0, 0x08cbc, 0x06ee4, 0x09354, 0x067f4, 0x09c1b, 0x060b0, 0x0a62a, 0x05a9c, 0x0af5b, 0x0548d, 0x0b955, 0x04f56, 0x0c2a9,
+  0x04a87, 0x0cbf7, 0x045d6, 0x0d5c3, 0x04144, 0x0e01b, 0x03d88, 0x0e937, 0x039e0, 0x0f2cd, 0x03663, 0x0fc9e, 0x03347, 0x10600, 0x03050, 0x10f95,
+  0x02d4d, 0x11a02, 0x02ad3, 0x12333, 0x0286e, 0x12cad, 0x02604, 0x136df, 0x02425, 0x13f48, 0x021f4, 0x149c4, 0x0203e, 0x1527b, 0x01e4d, 0x15d00,
+  0x01c99, 0x166de, 0x01b18, 0x17017, 0x019a5, 0x17988, 0x01841, 0x18327, 0x016df, 0x18d50, 0x015d9, 0x19547, 0x0147c, 0x1a083, 0x0138e, 0x1a8a3,
+  0x01251, 0x1b418, 0x01166, 0x1bd27, 0x01068, 0x1c77b, 0x00f7f, 0x1d18e, 0x00eda, 0x1d91a, 0x00e19, 0x1e254, 0x00d4f, 0x1ec9a, 0x00c90, 0x1f6e0,
+  0x00c01, 0x1fef8, 0x00b5f, 0x208b1, 0x00ab6, 0x21362, 0x00a15, 0x21e46, 0x00988, 0x2285d, 0x00934, 0x22ea8, 0x008a8, 0x239b2, 0x0081d, 0x24577,
+  0x007c9, 0x24ce6, 0x00763, 0x25663, 0x00710, 0x25e8f, 0x006a0, 0x26a26, 0x00672, 0x26f23, 0x005e8, 0x27ef8, 0x005ba, 0x284b5, 0x0055e, 0x29057,
+  0x0050c, 0x29bab, 0x004c1, 0x2a674, 0x004a7, 0x2aa5e, 0x0046f, 0x2b32f, 0x0041f, 0x2c0ad, 0x003e7, 0x2ca8d, 0x003ba, 0x2d323, 0x0010c, 0x3bfbb
+#else
+  0x08000, 0x08000, 0x076da, 0x089a0, 0x06e92, 0x09340, 0x0670a, 0x09cdf, 0x06029, 0x0a67f, 0x059dd, 0x0b01f, 0x05413, 0x0b9bf, 0x04ebf, 0x0c35f,
+  0x049d3, 0x0ccff, 0x04546, 0x0d69e, 0x0410d, 0x0e03e, 0x03d22, 0x0e9de, 0x0397d, 0x0f37e, 0x03619, 0x0fd1e, 0x032ee, 0x106be, 0x02ffa, 0x1105d,
+  0x02d37, 0x119fd, 0x02aa2, 0x1239d, 0x02836, 0x12d3d, 0x025f2, 0x136dd, 0x023d1, 0x1407c, 0x021d2, 0x14a1c, 0x01ff2, 0x153bc, 0x01e2f, 0x15d5c,
+  0x01c87, 0x166fc, 0x01af7, 0x1709b, 0x0197f, 0x17a3b, 0x0181d, 0x183db, 0x016d0, 0x18d7b, 0x01595, 0x1971b, 0x0146c, 0x1a0bb, 0x01354, 0x1aa5a,
+  0x0124c, 0x1b3fa, 0x01153, 0x1bd9a, 0x01067, 0x1c73a, 0x00f89, 0x1d0da, 0x00eb7, 0x1da79, 0x00df0, 0x1e419, 0x00d34, 0x1edb9, 0x00c82, 0x1f759,
+  0x00bda, 0x200f9, 0x00b3c, 0x20a99, 0x00aa5, 0x21438, 0x00a17, 0x21dd8, 0x00990, 0x22778, 0x00911, 0x23118, 0x00898, 0x23ab8, 0x00826, 0x24458,
+  0x007ba, 0x24df7, 0x00753, 0x25797, 0x006f2, 0x26137, 0x00696, 0x26ad7, 0x0063f, 0x27477, 0x005ed, 0x27e17, 0x0059f, 0x287b6, 0x00554, 0x29156,
+  0x0050e, 0x29af6, 0x004cc, 0x2a497, 0x0048d, 0x2ae35, 0x00451, 0x2b7d6, 0x00418, 0x2c176, 0x003e2, 0x2cb15, 0x003af, 0x2d4b5, 0x0037f, 0x2de55
+#endif
+};
+//! \}
Index: /trunk/source/Lib/TLibCommon/ContextModel.h
===================================================================
--- /trunk/source/Lib/TLibCommon/ContextModel.h	(revision 2)
+++ /trunk/source/Lib/TLibCommon/ContextModel.h	(revision 2)
@@ -0,0 +1,105 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+
+/** \file     ContextModel.h
+    \brief    context model class (header)
+*/
+
+#ifndef __CONTEXT_MODEL__
+#define __CONTEXT_MODEL__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "CommonDef.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// context model class
+class ContextModel
+{
+public:
+  ContextModel  ()                        { m_ucState = 0; m_binsCoded = 0; }
+  ~ContextModel ()                        {}
+  
+  UChar getState  ()                { return ( m_ucState >> 1 ); }                    ///< get current state
+  UChar getMps    ()                { return ( m_ucState  & 1 ); }                    ///< get curret MPS
+  Void  setStateAndMps( UChar ucState, UChar ucMPS) { m_ucState = (ucState << 1) + ucMPS; } ///< set state and MPS
+  
+  Void init ( Int qp, Int initValue );   ///< initialize state with initial probability
+  
+  Void updateLPS ()
+  {
+    m_ucState = m_aucNextStateLPS[ m_ucState ];
+  }
+  
+  Void updateMPS ()
+  {
+    m_ucState = m_aucNextStateMPS[ m_ucState ];
+  }
+  
+  Int getEntropyBits(Short val) { return m_entropyBits[m_ucState ^ val]; }
+    
+#if FAST_BIT_EST
+  Void update( Int binVal )
+  {
+    m_ucState = m_nextState[m_ucState][binVal];
+  }
+  static Void buildNextStateTable();
+  static Int getEntropyBitsTrm( Int val ) { return m_entropyBits[126 ^ val]; }
+#endif
+  Void setBinsCoded(UInt val)   { m_binsCoded = val;  }
+  UInt getBinsCoded()           { return m_binsCoded;   }
+  
+private:
+  UChar         m_ucState;                                                                  ///< internal state variable
+  static const  UChar m_aucNextStateMPS[ 128 ];
+  static const  UChar m_aucNextStateLPS[ 128 ];
+  static const Int m_entropyBits[ 128 ];
+#if FAST_BIT_EST
+  static UChar m_nextState[128][2];
+#endif
+  UInt          m_binsCoded;
+};
+
+//! \}
+
+#endif
+
Index: /trunk/source/Lib/TLibCommon/ContextModel3DBuffer.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/ContextModel3DBuffer.cpp	(revision 2)
+++ /trunk/source/Lib/TLibCommon/ContextModel3DBuffer.cpp	(revision 2)
@@ -0,0 +1,120 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     ContextModel3DBuffer.cpp
+    \brief    context model 3D buffer class
+*/
+
+#include "ContextModel3DBuffer.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+
+ContextModel3DBuffer::ContextModel3DBuffer( UInt uiSizeZ, UInt uiSizeY, UInt uiSizeX, ContextModel *basePtr, Int &count )
+: m_sizeX  ( uiSizeX )
+, m_sizeXY ( uiSizeX * uiSizeY )
+, m_sizeXYZ( uiSizeX * uiSizeY * uiSizeZ )
+{
+  // allocate 3D buffer
+  m_contextModel = basePtr;
+  count += m_sizeXYZ;
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/**
+ * Initialize 3D buffer with respect to slicetype, QP and given initial probability table
+ *
+ * \param  eSliceType      slice type
+ * \param  iQp             input QP value
+ * \param  psCtxModel      given probability table
+ */
+Void ContextModel3DBuffer::initBuffer( SliceType sliceType, Int qp, UChar* ctxModel )
+{
+  ctxModel += sliceType * m_sizeXYZ;
+  
+  for ( Int n = 0; n < m_sizeXYZ; n++ )
+  {
+    m_contextModel[ n ].init( qp, ctxModel[ n ] );
+    m_contextModel[ n ].setBinsCoded( 0 );
+  }
+}
+
+/**
+ * Calculate the cost of choosing a probability table based on the current probability of CABAC at encoder
+ *
+ * \param  sliceType      slice type
+ * \param  qp             input QP value
+ * \param  ctxModel      given probability table
+ */
+UInt ContextModel3DBuffer::calcCost( SliceType sliceType, Int qp, UChar* ctxModel )
+{
+  UInt cost = 0;
+  ctxModel += sliceType * m_sizeXYZ;
+
+  for ( Int n = 0; n < m_sizeXYZ; n++ )
+  {
+    ContextModel tmpContextModel;
+    tmpContextModel.init( qp, ctxModel[ n ] );
+
+    // Map the 64 CABAC states to their corresponding probability values
+    static Double aStateToProbLPS[] = {0.50000000, 0.47460857, 0.45050660, 0.42762859, 0.40591239, 0.38529900, 0.36573242, 0.34715948, 0.32952974, 0.31279528, 0.29691064, 0.28183267, 0.26752040, 0.25393496, 0.24103941, 0.22879875, 0.21717969, 0.20615069, 0.19568177, 0.18574449, 0.17631186, 0.16735824, 0.15885931, 0.15079198, 0.14313433, 0.13586556, 0.12896592, 0.12241667, 0.11620000, 0.11029903, 0.10469773, 0.09938088, 0.09433404, 0.08954349, 0.08499621, 0.08067986, 0.07658271, 0.07269362, 0.06900203, 0.06549791, 0.06217174, 0.05901448, 0.05601756, 0.05317283, 0.05047256, 0.04790942, 0.04547644, 0.04316702, 0.04097487, 0.03889405, 0.03691890, 0.03504406, 0.03326442, 0.03157516, 0.02997168, 0.02844963, 0.02700488, 0.02563349, 0.02433175, 0.02309612, 0.02192323, 0.02080991, 0.01975312, 0.01875000};
+
+    Double probLPS          = aStateToProbLPS[ m_contextModel[ n ].getState() ];
+    Double prob0, prob1;
+    if (m_contextModel[ n ].getMps()==1)
+    {
+      prob0 = probLPS;
+      prob1 = 1.0-prob0;
+    }
+    else
+    {
+      prob1 = probLPS;
+      prob0 = 1.0-prob1;
+    }
+
+    if (m_contextModel[ n ].getBinsCoded()>0)
+    {
+      cost += (UInt) (prob0 * tmpContextModel.getEntropyBits( 0 ) + prob1 * tmpContextModel.getEntropyBits( 1 ));
+    }
+  }
+
+  return cost;
+}
+//! \}
Index: /trunk/source/Lib/TLibCommon/ContextModel3DBuffer.h
===================================================================
--- /trunk/source/Lib/TLibCommon/ContextModel3DBuffer.h	(revision 2)
+++ /trunk/source/Lib/TLibCommon/ContextModel3DBuffer.h	(revision 2)
@@ -0,0 +1,98 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     ContextModel3DBuffer.h
+    \brief    context model 3D buffer class (header)
+*/
+
+#ifndef _HM_CONTEXT_MODEL_3DBUFFER_H_
+#define _HM_CONTEXT_MODEL_3DBUFFER_H_
+
+#include <stdio.h>
+#include <assert.h>
+#include <memory.h>
+
+#include "CommonDef.h"
+#include "ContextModel.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// context model 3D buffer class
+class ContextModel3DBuffer
+{
+protected:
+  ContextModel* m_contextModel; ///< array of context models
+  const UInt    m_sizeX;        ///< X size of 3D buffer
+  const UInt    m_sizeXY;       ///< X times Y size of 3D buffer
+  const UInt    m_sizeXYZ;      ///< total size of 3D buffer
+  
+public:
+  ContextModel3DBuffer  ( UInt uiSizeZ, UInt uiSizeY, UInt uiSizeX, ContextModel *basePtr, Int &count );
+  ~ContextModel3DBuffer () {}
+  
+  // access functions
+  ContextModel& get( UInt uiZ, UInt uiY, UInt uiX )
+  {
+    return  m_contextModel[ uiZ * m_sizeXY + uiY * m_sizeX + uiX ];
+  }
+  ContextModel* get( UInt uiZ, UInt uiY )
+  {
+    return &m_contextModel[ uiZ * m_sizeXY + uiY * m_sizeX ];
+  }
+  ContextModel* get( UInt uiZ )
+  {
+    return &m_contextModel[ uiZ * m_sizeXY ];
+  }
+  
+  // initialization & copy functions
+  Void initBuffer( SliceType eSliceType, Int iQp, UChar* ctxModel );          ///< initialize 3D buffer by slice type & QP
+  
+  UInt calcCost( SliceType sliceType, Int qp, UChar* ctxModel );      ///< determine cost of choosing a probability table based on current probabilities
+  /** copy from another buffer
+   * \param src buffer to copy from
+   */
+  Void copyFrom( ContextModel3DBuffer* src )
+  {
+    assert( m_sizeXYZ == src->m_sizeXYZ );
+    ::memcpy( m_contextModel, src->m_contextModel, sizeof(ContextModel) * m_sizeXYZ );
+  }
+};
+
+//! \}
+
+#endif // _HM_CONTEXT_MODEL_3DBUFFER_H_
Index: /trunk/source/Lib/TLibCommon/ContextTables.h
===================================================================
--- /trunk/source/Lib/TLibCommon/ContextTables.h	(revision 2)
+++ /trunk/source/Lib/TLibCommon/ContextTables.h	(revision 2)
@@ -0,0 +1,469 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * 
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     ContextTables.h
+    \brief    Defines constants and tables for SBAC
+    \todo     number of context models is not matched to actual use, should be fixed
+*/
+
+#ifndef __CONTEXTTABLES__
+#define __CONTEXTTABLES__
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+#define MAX_NUM_CTX_MOD             512       ///< maximum number of supported contexts
+
+#define NUM_SPLIT_FLAG_CTX            3       ///< number of context models for split flag
+#define NUM_SKIP_FLAG_CTX             3       ///< number of context models for skip flag
+
+#define NUM_MERGE_FLAG_EXT_CTX        1       ///< number of context models for merge flag of merge extended
+#define NUM_MERGE_IDX_EXT_CTX         1       ///< number of context models for merge index of merge extended
+
+#define NUM_ALF_CTRL_FLAG_CTX         1       ///< number of context models for ALF control flag
+#define NUM_PART_SIZE_CTX             4       ///< number of context models for partition size
+#define NUM_CU_AMP_CTX                1       ///< number of context models for partition size (AMP)
+#define NUM_PRED_MODE_CTX             1       ///< number of context models for prediction mode
+
+#define NUM_ADI_CTX                   1       ///< number of context models for intra prediction
+
+#define NUM_CHROMA_PRED_CTX           2       ///< number of context models for intra prediction (chroma)
+#define NUM_INTER_DIR_CTX             5       ///< number of context models for inter prediction direction
+#define NUM_MV_RES_CTX                2       ///< number of context models for motion vector difference
+
+#if REF_IDX_BYPASS
+#define NUM_REF_NO_CTX                2       ///< number of context models for reference index
+#else
+#define NUM_REF_NO_CTX                4       ///< number of context models for reference index
+#endif
+#if TRANS_SPLIT_FLAG_CTX_REDUCTION
+#define NUM_TRANS_SUBDIV_FLAG_CTX     3       ///< number of context models for transform subdivision flags
+#else
+#define NUM_TRANS_SUBDIV_FLAG_CTX     10      ///< number of context models for transform subdivision flags
+#endif
+#define NUM_QT_CBF_CTX                5       ///< number of context models for QT CBF
+#define NUM_QT_ROOT_CBF_CTX           1       ///< number of context models for QT ROOT CBF
+#define NUM_DELTA_QP_CTX              3       ///< number of context models for dQP
+
+#define NUM_SIG_CG_FLAG_CTX           2       ///< number of context models for MULTI_LEVEL_SIGNIFICANCE
+
+#if REMOVAL_8x2_2x8_CG
+#define NUM_SIG_FLAG_CTX              42      ///< number of context models for sig flag
+#define NUM_SIG_FLAG_CTX_LUMA         27      ///< number of context models for luma sig flag
+#define NUM_SIG_FLAG_CTX_CHROMA       15      ///< number of context models for chroma sig flag
+#else
+#define NUM_SIG_FLAG_CTX              45      ///< number of context models for sig flag
+#define NUM_SIG_FLAG_CTX_LUMA         24      ///< number of context models for luma sig flag
+#define NUM_SIG_FLAG_CTX_CHROMA       21      ///< number of context models for chroma sig flag
+#endif
+
+#define NUM_CTX_LAST_FLAG_XY          15      ///< number of context models for last coefficient position
+
+#define NUM_ONE_FLAG_CTX              24      ///< number of context models for greater than 1 flag
+#define NUM_ONE_FLAG_CTX_LUMA         16      ///< number of context models for greater than 1 flag of luma
+#define NUM_ONE_FLAG_CTX_CHROMA        8      ///< number of context models for greater than 1 flag of chroma
+#define NUM_ABS_FLAG_CTX               6      ///< number of context models for greater than 2 flag
+#define NUM_ABS_FLAG_CTX_LUMA          4      ///< number of context models for greater than 2 flag of luma
+#define NUM_ABS_FLAG_CTX_CHROMA        2      ///< number of context models for greater than 2 flag of chroma
+
+#define NUM_MVP_IDX_CTX               2       ///< number of context models for MVP index
+
+#define NUM_ALF_FLAG_CTX              1       ///< number of context models for ALF flag
+#define NUM_ALF_UVLC_CTX              2       ///< number of context models for ALF UVLC (filter length)
+#define NUM_ALF_SVLC_CTX              3       ///< number of context models for ALF SVLC (filter coeff.)
+#if !SAO_ABS_BY_PASS
+#define NUM_SAO_UVLC_CTX              2       ///< number of context models for SAO UVLC
+#endif
+#if SAO_MERGE_ONE_CTX
+#define NUM_SAO_MERGE_FLAG_CTX        1       ///< number of context models for SAO merge flags
+#else
+#if SAO_SINGLE_MERGE
+#define NUM_SAO_MERGE_LEFT_FLAG_CTX   1       ///< number of context models for SAO Merge-Left flag
+#else
+#define NUM_SAO_MERGE_LEFT_FLAG_CTX   3       ///< number of context models for AO SVLC (filter coeff.)
+#endif
+#define NUM_SAO_MERGE_UP_FLAG_CTX     1       ///< number of context models for AO SVLC (filter coeff.)
+#endif
+#if SAO_TYPE_CODING
+#define NUM_SAO_TYPE_IDX_CTX          1       ///< number of context models for SAO type index
+#else
+#define NUM_SAO_TYPE_IDX_CTX          2       ///< number of context models for AO SVLC (filter coeff.)
+#endif
+
+#if INTRA_BL
+#define NUM_INTRA_BL_PRED_CTX         3
+#endif
+
+#define NUM_TRANSFORMSKIP_FLAG_CTX    1       ///< number of context models for transform skipping 
+#define NUM_CU_TRANSQUANT_BYPASS_FLAG_CTX  1 
+#define CNU                          154      ///< dummy initialization value for unused context models 'Context model Not Used'
+
+// ====================================================================================================================
+// Tables
+// ====================================================================================================================
+
+// initial probability for cu_transquant_bypass flag
+static const UChar
+INIT_CU_TRANSQUANT_BYPASS_FLAG[3][NUM_CU_TRANSQUANT_BYPASS_FLAG_CTX] =
+{
+  { 154 }, 
+  { 154 }, 
+  { 154 }, 
+};
+
+// initial probability for split flag
+static const UChar 
+INIT_SPLIT_FLAG[3][NUM_SPLIT_FLAG_CTX] =  
+{
+  { 107,  139,  126, },
+  { 107,  139,  126, }, 
+  { 139,  141,  157, }, 
+};
+
+static const UChar 
+INIT_SKIP_FLAG[3][NUM_SKIP_FLAG_CTX] =  
+{
+  { 197,  185,  201, }, 
+  { 197,  185,  201, }, 
+  { CNU,  CNU,  CNU, }, 
+};
+
+static const UChar 
+INIT_ALF_CTRL_FLAG[3][NUM_ALF_CTRL_FLAG_CTX] = 
+{
+  { 102, }, 
+  { 102, }, 
+  { 118, }, 
+};
+
+static const UChar 
+INIT_MERGE_FLAG_EXT[3][NUM_MERGE_FLAG_EXT_CTX] = 
+{
+  { 154, }, 
+  { 110, }, 
+  { CNU, }, 
+};
+
+static const UChar 
+INIT_MERGE_IDX_EXT[3][NUM_MERGE_IDX_EXT_CTX] =  
+{
+  { 137, }, 
+  { 122, }, 
+  { CNU, }, 
+};
+
+static const UChar 
+INIT_PART_SIZE[3][NUM_PART_SIZE_CTX] =  
+{
+  { 154,  139,  CNU,  CNU, }, 
+  { 154,  139,  CNU,  CNU, }, 
+  { 184,  CNU,  CNU,  CNU, }, 
+};
+
+static const UChar 
+INIT_CU_AMP_POS[3][NUM_CU_AMP_CTX] =  
+{
+  { 154, }, 
+  { 154, }, 
+  { CNU, }, 
+};
+
+static const UChar 
+INIT_PRED_MODE[3][NUM_PRED_MODE_CTX] = 
+{
+  { 134, }, 
+  { 149, }, 
+  { CNU, }, 
+};
+
+static const UChar 
+INIT_INTRA_PRED_MODE[3][NUM_ADI_CTX] = 
+{
+  { 183, }, 
+  { 154, }, 
+  { 184, }, 
+};
+
+static const UChar 
+INIT_CHROMA_PRED_MODE[3][NUM_CHROMA_PRED_CTX] = 
+{
+  { 152,  139, }, 
+  { 152,  139, }, 
+  {  63,  139, }, 
+};
+
+static const UChar 
+INIT_INTER_DIR[3][NUM_INTER_DIR_CTX] = 
+{
+  {  95,   79,   63,   31,  31, }, 
+  {  95,   79,   63,   31,  31, }, 
+  { CNU,  CNU,  CNU,  CNU, CNU, }, 
+};
+
+static const UChar 
+INIT_MVD[3][NUM_MV_RES_CTX] =  
+{
+  { 169,  198, }, 
+  { 140,  198, }, 
+  { CNU,  CNU, }, 
+};
+
+#if REF_IDX_BYPASS
+static const UChar 
+INIT_REF_PIC[3][NUM_REF_NO_CTX] =  
+{
+  { 153,  153 }, 
+  { 153,  153 }, 
+  { CNU,  CNU }, 
+};
+#else
+static const UChar 
+INIT_REF_PIC[3][NUM_REF_NO_CTX] =  
+{
+  { 153,  153,  168,  CNU, }, 
+  { 153,  153,  139,  CNU, }, 
+  { CNU,  CNU,  CNU,  CNU, }, 
+};
+#endif
+
+static const UChar 
+INIT_DQP[3][NUM_DELTA_QP_CTX] = 
+{
+  { 154,  154,  154, }, 
+  { 154,  154,  154, }, 
+  { 154,  154,  154, }, 
+};
+
+static const UChar 
+INIT_QT_CBF[3][2*NUM_QT_CBF_CTX] =  
+{
+  { 153,  111,  CNU,  CNU,  CNU,  149,   92,  167,  CNU,  CNU, }, 
+  { 153,  111,  CNU,  CNU,  CNU,  149,  107,  167,  CNU,  CNU, }, 
+  { 111,  141,  CNU,  CNU,  CNU,   94,  138,  182,  CNU,  CNU, }, 
+};
+
+static const UChar 
+INIT_QT_ROOT_CBF[3][NUM_QT_ROOT_CBF_CTX] = 
+{
+  {  79, }, 
+  {  79, }, 
+  { CNU, }, 
+};
+
+static const UChar 
+INIT_LAST[3][2*NUM_CTX_LAST_FLAG_XY] =  
+{
+  { 125,  110,  124,  110,   95,   94,  125,  111,  111,   79,  125,  126,  111,  111,   79,
+    108,  123,   93,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU, 
+  }, 
+  { 125,  110,   94,  110,   95,   79,  125,  111,  110,   78,  110,  111,  111,   95,   94,
+    108,  123,  108,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,
+  }, 
+  { 110,  110,  124,  125,  140,  153,  125,  127,  140,  109,  111,  143,  127,  111,   79, 
+    108,  123,   63,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU, 
+  }, 
+};
+
+static const UChar 
+INIT_SIG_CG_FLAG[3][2 * NUM_SIG_CG_FLAG_CTX] =  
+{
+  { 121,  140,  
+    61,  154, 
+  }, 
+  { 121,  140, 
+    61,  154, 
+  }, 
+  {  91,  171,  
+    134,  141, 
+  }, 
+};
+
+static const UChar 
+INIT_SIG_FLAG[3][NUM_SIG_FLAG_CTX] = 
+{
+#if REMOVAL_8x2_2x8_CG
+  { 170,  154,  139,  153,  139,  123,  123,   63,  124,  166,  183,  140,  136,  153,  154,  166,  183,  140,  136,  153,  154,  166,  183,  140,  136,  153,  154,  170,  153,  138,  138,  122,  121,  122,  121,  167,  151,  183,  140,  151,  183,  140,  }, 
+  { 155,  154,  139,  153,  139,  123,  123,   63,  153,  166,  183,  140,  136,  153,  154,  166,  183,  140,  136,  153,  154,  166,  183,  140,  136,  153,  154,  170,  153,  123,  123,  107,  121,  107,  121,  167,  151,  183,  140,  151,  183,  140,  }, 
+  { 111,  111,  125,  110,  110,   94,  124,  108,  124,  107,  125,  141,  179,  153,  125,  107,  125,  141,  179,  153,  125,  107,  125,  141,  179,  153,  125,  140,  139,  182,  182,  152,  136,  152,  136,  153,  136,  139,  111,  136,  139,  111,  }, 
+#else
+  { 170,      154,  139,  153,  139,  123,  123,   63,  124,     153, 153, 152, 152, 152, 137, 152, 137, 137,      166,  183,  140,  136,  153,  154,      170,     153, 138, 138,  122, 121,   122, 121,   167,     153,  167,  136,  121,  122,  136,  121,  122,   91,      151,  183,  140,  }, 
+  { 155,      154,  139,  153,  139,  123,  123,   63,  153,     153, 153, 152, 152, 152, 137, 152, 137, 122,      166,  183,  140,  136,  153,  154,      170,     153, 123, 123,  107, 121,   107, 121,   167,     153,  167,  136,  149,  107,  136,  121,  122,   91,      151,  183,  140,  }, 
+  { 111,      111,  125,  110,  110,   94,  124,  108,  124,     139, 139, 139, 168, 124, 138, 124, 138, 107,      107,  125,  141,  179,  153,  125,      140,     139, 182, 182,  152, 136,   152, 136,   153,     182,  137,  149,  192,  152,  224,  136,   31,  136,      136,  139,  111,  }, 
+#endif
+};
+
+static const UChar 
+INIT_ONE_FLAG[3][NUM_ONE_FLAG_CTX] = 
+{
+  { 154,  196,  167,  167,  154,  152,  167,  182,  182,  134,  149,  136,  153,  121,  136,  122,  169,  208,  166,  167,  154,  152,  167,  182, }, 
+  { 154,  196,  196,  167,  154,  152,  167,  182,  182,  134,  149,  136,  153,  121,  136,  137,  169,  194,  166,  167,  154,  167,  137,  182, }, 
+  { 140,   92,  137,  138,  140,  152,  138,  139,  153,   74,  149,   92,  139,  107,  122,  152,  140,  179,  166,  182,  140,  227,  122,  197, }, 
+};
+
+static const UChar 
+INIT_ABS_FLAG[3][NUM_ABS_FLAG_CTX] =  
+{
+  { 107,  167,   91,  107,  107,  167, }, 
+  { 107,  167,   91,  122,  107,  167, }, 
+  { 138,  153,  136,  167,  152,  152, }, 
+};
+
+static const UChar 
+INIT_MVP_IDX[3][NUM_MVP_IDX_CTX] =  
+{
+  { 168,  CNU, }, 
+  { 168,  CNU, }, 
+  { CNU,  CNU, }, 
+};
+
+static const UChar 
+INIT_ALF_FLAG[3][NUM_ALF_FLAG_CTX] = 
+{
+  { 153, }, 
+  { 153, }, 
+  { 153, }, 
+};
+
+static const UChar 
+INIT_ALF_UVLC[3][NUM_ALF_UVLC_CTX] = 
+{
+  { 154,  154, }, 
+  { 154,  154, }, 
+  { 140,  154, }, 
+};
+
+static const UChar 
+INIT_ALF_SVLC[3][NUM_ALF_SVLC_CTX] =  
+{
+  { 141,  154,  159, }, 
+  { 141,  154,  189, }, 
+  { 187,  154,  159, }, 
+};
+#if !SAO_ABS_BY_PASS
+static const UChar 
+INIT_SAO_UVLC[3][NUM_SAO_UVLC_CTX] =  
+{
+  { 200,  140, }, 
+  { 185,  140, }, 
+  { 143,  140, }, 
+};
+#endif
+#if SAO_MERGE_ONE_CTX
+static const UChar 
+INIT_SAO_MERGE_FLAG[3][NUM_SAO_MERGE_FLAG_CTX] = 
+{
+  { 153,  }, 
+  { 153,  }, 
+  { 153,  }, 
+};
+#else
+static const UChar 
+INIT_SAO_MERGE_LEFT_FLAG[3][NUM_SAO_MERGE_LEFT_FLAG_CTX] = 
+{
+#if SAO_SINGLE_MERGE
+  { 153, }, 
+  { 153, }, 
+  { 153, }, 
+#else
+  { 153,  153,  153, }, 
+  { 153,  153,  153, }, 
+  { 153,  153,  153, }, 
+#endif
+};
+
+static const UChar 
+INIT_SAO_MERGE_UP_FLAG[3][NUM_SAO_MERGE_UP_FLAG_CTX] = 
+{
+  { 153, }, 
+  { 153, }, 
+  { 175, }, 
+};
+#endif
+
+static const UChar 
+INIT_SAO_TYPE_IDX[3][NUM_SAO_TYPE_IDX_CTX] = 
+{
+#if SAO_TYPE_CODING
+  { 200, }, 
+  { 185, }, 
+  { 160, }, 
+#else
+  { 200,  140, }, 
+  { 185,  140, }, 
+  { 160,  140, }, 
+#endif
+};
+
+#if TRANS_SPLIT_FLAG_CTX_REDUCTION
+static const UChar
+INIT_TRANS_SUBDIV_FLAG[3][NUM_TRANS_SUBDIV_FLAG_CTX] =
+{
+  { 153,  138,  138, },
+  { 124,  138,   94, },
+  { 224,  167,  122, },
+};
+#else
+static const UChar 
+INIT_TRANS_SUBDIV_FLAG[3][NUM_TRANS_SUBDIV_FLAG_CTX] = 
+{
+{ CNU,  153,  138,  138,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU, }, 
+{ CNU,  124,  138,   94,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU, }, 
+{ CNU,  224,  167,  122,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU, }, 
+};
+#endif
+
+
+#if INTRA_BL
+static const UChar 
+INIT_INTRA_BL_PRED_FLAG[3][NUM_INTRA_BL_PRED_CTX] = 
+{
+  { 185,  185,  201, }, 
+  { 197,  197,  185, }, 
+  { 197,  197,  185, }, 
+};
+#endif
+static const UChar
+INIT_TRANSFORMSKIP_FLAG[3][2*NUM_TRANSFORMSKIP_FLAG_CTX] = 
+{
+  { 139,  139}, 
+  { 139,  139}, 
+  { 139,  139}, 
+};
+//! \}
+
+
+#endif
Index: /trunk/source/Lib/TLibCommon/NAL.h
===================================================================
--- /trunk/source/Lib/TLibCommon/NAL.h	(revision 2)
+++ /trunk/source/Lib/TLibCommon/NAL.h	(revision 2)
@@ -0,0 +1,143 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#pragma once
+
+#include <vector>
+#include <sstream>
+#include "CommonDef.h"
+
+class TComOutputBitstream;
+
+/**
+ * Represents a single NALunit header and the associated RBSPayload
+ */
+struct NALUnit
+{
+  NalUnitType m_nalUnitType; ///< nal_unit_type
+#if !REMOVE_NAL_REF_FLAG
+  Bool        m_nalRefFlag;  ///< nal_ref_flag
+#endif
+  UInt        m_temporalId;  ///< temporal_id
+#if SVC_EXTENSION
+  UInt        m_layerId;   ///< layer id
+#endif
+#if TARGET_DECLAYERID_SET
+  UInt        m_reservedZero6Bits; ///< reserved_zero_6bits
+#endif
+
+  /** construct an NALunit structure with given header values. */
+  NALUnit(
+    NalUnitType nalUnitType,
+#if !REMOVE_NAL_REF_FLAG
+    Bool        nalRefFlag,
+#endif
+#if TARGET_DECLAYERID_SET
+    Int         temporalId = 0,
+#if SVC_EXTENSION
+    UInt        layerId = 0,
+#endif
+    Int         reservedZero6Bits = 0)
+#else
+#if SVC_EXTENSION
+    UInt        layerId = 0,
+    Int         temporalId = 0)
+#else
+    Int         temporalId = 0)
+#endif
+#endif
+    :m_nalUnitType (nalUnitType)
+#if !REMOVE_NAL_REF_FLAG
+    ,m_nalRefFlag  (nalRefFlag)
+#endif
+    ,m_temporalId  (temporalId)
+#if SVC_EXTENSION
+    ,m_layerId   (layerId)
+#endif
+#if TARGET_DECLAYERID_SET
+    ,m_reservedZero6Bits(reservedZero6Bits)
+#endif
+  {}
+
+  /** default constructor - no initialization; must be perfomed by user */
+  NALUnit() {}
+
+  /** returns true if the NALunit is a slice NALunit */
+  bool isSlice()
+  {
+#if NAL_UNIT_TYPES_J1003_D7
+    return m_nalUnitType == NAL_UNIT_CODED_SLICE_TRAIL_R
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_TRAIL_N
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_TLA
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_TSA_N
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_STSA_R
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_STSA_N
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_BLA
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_BLANT
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_BLA_N_LP
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_IDR
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_IDR_N_LP
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_CRA
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_DLP
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_TFD;
+#else
+    return m_nalUnitType == NAL_UNIT_CODED_SLICE_IDR
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_BLANT
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_BLA
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_CRANT
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_CRA
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_TLA
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_TFD
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE;
+#endif
+  }
+};
+
+struct OutputNALUnit;
+
+/**
+ * A single NALunit, with complete payload in EBSP format.
+ */
+struct NALUnitEBSP : public NALUnit
+{
+  std::ostringstream m_nalUnitData;
+
+  /**
+   * convert the OutputNALUnit #nalu# into EBSP format by writing out
+   * the NALUnit header, then the rbsp_bytes including any
+   * emulation_prevention_three_byte symbols.
+   */
+  NALUnitEBSP(OutputNALUnit& nalu);
+};
+//! \}
+//! \}
Index: /trunk/source/Lib/TLibCommon/SEI.h
===================================================================
--- /trunk/source/Lib/TLibCommon/SEI.h	(revision 2)
+++ /trunk/source/Lib/TLibCommon/SEI.h	(revision 2)
@@ -0,0 +1,245 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#pragma once
+
+//! \ingroup TLibCommon
+//! \{
+#if BUFFERING_PERIOD_AND_TIMING_SEI
+class TComSPS;
+#endif
+
+/**
+ * Abstract class representing an SEI message with lightweight RTTI.
+ */
+class SEI
+{
+public:
+  enum PayloadType
+  {
+#if BUFFERING_PERIOD_AND_TIMING_SEI
+    BUFFERING_PERIOD       = 0,
+    PICTURE_TIMING         = 1,
+#endif
+    USER_DATA_UNREGISTERED = 5,
+#if RECOVERY_POINT_SEI
+    RECOVERY_POINT         = 6,
+#endif
+#if ACTIVE_PARAMETER_SETS_SEI_MESSAGE 
+    ACTIVE_PARAMETER_SETS = 131, 
+#endif 
+    DECODED_PICTURE_HASH   = 256,
+  };
+  
+  SEI() {}
+  virtual ~SEI() {}
+  
+  virtual PayloadType payloadType() const = 0;
+};
+
+class SEIuserDataUnregistered : public SEI
+{
+public:
+  PayloadType payloadType() const { return USER_DATA_UNREGISTERED; }
+
+  SEIuserDataUnregistered()
+    : userData(0)
+    {}
+
+  virtual ~SEIuserDataUnregistered()
+  {
+    delete userData;
+  }
+
+  unsigned char uuid_iso_iec_11578[16];
+  unsigned userDataLength;
+  unsigned char *userData;
+};
+
+class SEIDecodedPictureHash : public SEI
+{
+public:
+  PayloadType payloadType() const { return DECODED_PICTURE_HASH; }
+
+  SEIDecodedPictureHash() {}
+  virtual ~SEIDecodedPictureHash() {}
+  
+  enum Method
+  {
+    MD5,
+    CRC,
+    CHECKSUM,
+    RESERVED,
+  } method;
+
+  unsigned char digest[3][16];
+};
+
+#if ACTIVE_PARAMETER_SETS_SEI_MESSAGE  
+class SEIActiveParameterSets : public SEI 
+{
+public:
+  PayloadType payloadType() const { return ACTIVE_PARAMETER_SETS; }
+
+  SEIActiveParameterSets() 
+    :activeSPSIdPresentFlag(1)
+    ,activeParamSetSEIExtensionFlag(0)
+  {}
+  virtual ~SEIActiveParameterSets() {}
+
+  Int activeVPSId; 
+  Int activeSPSIdPresentFlag;
+  Int activeSeqParamSetId; 
+  Int activeParamSetSEIExtensionFlag; 
+};
+#endif 
+
+#if BUFFERING_PERIOD_AND_TIMING_SEI
+class SEIBufferingPeriod : public SEI
+{
+public:
+  PayloadType payloadType() const { return BUFFERING_PERIOD; }
+
+  SEIBufferingPeriod()
+  :m_sps (NULL)
+  {}
+  virtual ~SEIBufferingPeriod() {}
+
+  UInt m_seqParameterSetId;
+  Bool m_altCpbParamsPresentFlag;
+  UInt m_initialCpbRemovalDelay         [MAX_CPB_CNT][2];
+  UInt m_initialCpbRemovalDelayOffset   [MAX_CPB_CNT][2];
+  UInt m_initialAltCpbRemovalDelay      [MAX_CPB_CNT][2];
+  UInt m_initialAltCpbRemovalDelayOffset[MAX_CPB_CNT][2];
+  TComSPS* m_sps;
+};
+class SEIPictureTiming : public SEI
+{
+public:
+  PayloadType payloadType() const { return PICTURE_TIMING; }
+
+  SEIPictureTiming()
+  : m_numNalusInDuMinus1      (NULL)
+  , m_duCpbRemovalDelayMinus1 (NULL)
+  , m_sps                     (NULL)
+  {}
+  virtual ~SEIPictureTiming()
+  {
+    if( m_numNalusInDuMinus1 != NULL )
+    {
+      delete m_numNalusInDuMinus1;
+    }
+    if( m_duCpbRemovalDelayMinus1  != NULL )
+    {
+      delete m_duCpbRemovalDelayMinus1;
+    }
+  }
+
+  UInt  m_auCpbRemovalDelay;
+  UInt  m_picDpbOutputDelay;
+  UInt  m_numDecodingUnitsMinus1;
+  Bool  m_duCommonCpbRemovalDelayFlag;
+  UInt  m_duCommonCpbRemovalDelayMinus1;
+  UInt* m_numNalusInDuMinus1;
+  UInt* m_duCpbRemovalDelayMinus1;
+  TComSPS* m_sps;
+};
+#endif
+#if RECOVERY_POINT_SEI
+class SEIRecoveryPoint : public SEI
+{
+public:
+  PayloadType payloadType() const { return RECOVERY_POINT; }
+
+  SEIRecoveryPoint() {}
+  virtual ~SEIRecoveryPoint() {}
+
+  Int  m_recoveryPocCnt;
+  Bool m_exactMatchingFlag;
+  Bool m_brokenLinkFlag;
+};
+#endif
+/**
+ * A structure to collate all SEI messages.  This ought to be replaced
+ * with a list of std::list<SEI*>.  However, since there is only one
+ * user of the SEI framework, this will do initially */
+class SEImessages
+{
+public:
+  SEImessages()
+    : user_data_unregistered(0)
+#if ACTIVE_PARAMETER_SETS_SEI_MESSAGE  
+    , active_parameter_sets(0)
+#endif 
+    , picture_digest(0)
+#if BUFFERING_PERIOD_AND_TIMING_SEI
+    , buffering_period(0)
+    , picture_timing(0)
+#endif
+#if RECOVERY_POINT_SEI
+    , recovery_point(0)
+#endif
+    {}
+
+  ~SEImessages()
+  {
+    delete user_data_unregistered;
+#if ACTIVE_PARAMETER_SETS_SEI_MESSAGE  
+    delete active_parameter_sets; 
+#endif 
+    delete picture_digest;
+#if BUFFERING_PERIOD_AND_TIMING_SEI
+    delete buffering_period;
+    delete picture_timing;
+#endif
+#if RECOVERY_POINT_SEI
+    delete recovery_point;
+#endif
+  }
+
+  SEIuserDataUnregistered* user_data_unregistered;
+#if ACTIVE_PARAMETER_SETS_SEI_MESSAGE  
+  SEIActiveParameterSets* active_parameter_sets; 
+#endif 
+  SEIDecodedPictureHash* picture_digest;
+#if BUFFERING_PERIOD_AND_TIMING_SEI
+  SEIBufferingPeriod* buffering_period;
+  SEIPictureTiming* picture_timing;
+  TComSPS* m_pSPS;
+#endif
+#if RECOVERY_POINT_SEI
+  SEIRecoveryPoint* recovery_point;
+#endif
+};
+
+//! \}
Index: /trunk/source/Lib/TLibCommon/TComAdaptiveLoopFilter.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComAdaptiveLoopFilter.cpp	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComAdaptiveLoopFilter.cpp	(revision 2)
@@ -0,0 +1,1147 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComAdaptiveLoopFilter.cpp
+    \brief    adaptive loop filter class
+*/
+
+#include "TComAdaptiveLoopFilter.h"
+#include <string.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <math.h>
+
+#if !REMOVE_ALF
+//! \ingroup TLibCommon
+//! \{
+
+
+// ====================================================================================================================
+// Tables
+// ====================================================================================================================
+
+Int TComAdaptiveLoopFilter::weightsShape1Sym[ALF_MAX_NUM_COEF+1] = 
+{ 
+              2,
+              2,
+           2, 2, 2,
+  2, 2, 2, 2, 1, 
+              1
+};
+
+Int depthIntShape1Sym[ALF_MAX_NUM_COEF+1] = 
+{
+              6,
+              7,
+           7, 8, 7,
+  5, 6, 7, 8, 9, 
+              9  
+};
+Int* pDepthIntTabShapes[NUM_ALF_FILTER_SHAPE] =
+{ 
+  depthIntShape1Sym
+};
+
+Int kTableShape1[ALF_MAX_NUM_COEF] = 
+{      
+              1,
+              2,
+           3, 4, 3,
+  1, 3, 3, 5, 0, 
+};
+
+Int* kTableTabShapes[NUM_ALF_FILTER_SHAPE] =
+{ 
+  kTableShape1
+};
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+/// ALFParam
+const ALFParam& ALFParam::operator= (const ALFParam& src)
+{
+  if(this->componentID < 0)
+  {
+    this->create(src.componentID);
+  }
+  this->copy(src);
+  return *this;
+}
+
+Void ALFParam::create(Int cID)
+{
+  const Int numCoef = ALF_MAX_NUM_COEF;
+
+  this->componentID       = cID;
+  this->alf_flag          = 0;
+  this->filters_per_group = 1; // this value keeps 1 for chroma componenet
+  this->startSecondFilter = -1;
+  this->filterPattern     = NULL;
+  this->coeffmulti        = NULL;
+  this->filter_shape      = 0;
+  this->num_coeff         = numCoef;
+
+  switch(cID)
+  {
+  case ALF_Y:
+    {
+      this->coeffmulti = new Int*[NO_VAR_BINS];
+      for(Int i=0; i< NO_VAR_BINS; i++)
+      {
+        this->coeffmulti[i] = new Int[numCoef];
+        ::memset(this->coeffmulti[i], 0, sizeof(Int)*numCoef);
+      }
+      this->filterPattern = new Int[NO_VAR_BINS];
+      ::memset(this->filterPattern, 0, sizeof(Int)*NO_VAR_BINS);
+    }
+    break;
+  case ALF_Cb:
+  case ALF_Cr:
+    {
+      this->coeffmulti = new Int*[1];
+      this->coeffmulti[0] = new Int[numCoef];
+    }
+    break;
+  default:
+    {
+      printf("Not a legal component ID\n");
+      assert(0);
+      exit(-1);
+    }
+  }
+}
+
+Void ALFParam::destroy()
+{
+  if(this->componentID >=0)
+  {
+    switch(this->componentID)
+    {
+    case ALF_Y:
+      {
+        for(Int i=0; i< NO_VAR_BINS; i++)
+        {
+          delete[] this->coeffmulti[i];
+        }
+        delete[] this->coeffmulti;
+        delete[] this->filterPattern;
+      }
+      break;
+    case ALF_Cb:
+    case ALF_Cr:
+      {
+        delete[] this->coeffmulti[0];
+        delete[] this->coeffmulti;
+      }
+      break;
+    default:
+      {
+        printf("Not a legal component ID\n");
+        assert(0);
+        exit(-1);
+      }
+    }
+
+  }
+}
+
+Void ALFParam::copy(const ALFParam& src)
+{
+  const Int numCoef = ALF_MAX_NUM_COEF;
+
+  this->componentID       = src.componentID;
+  this->alf_flag          = src.alf_flag;
+  if(this->alf_flag == 1)
+  {
+    this->filters_per_group = src.filters_per_group;
+    this->filter_shape      = src.filter_shape;
+    this->num_coeff         = src.num_coeff;
+
+    switch(this->componentID)
+    {
+    case ALF_Cb:
+    case ALF_Cr:
+      {
+        ::memcpy(this->coeffmulti[0], src.coeffmulti[0], sizeof(Int)*numCoef);
+      }
+      break;
+    case ALF_Y:
+      {
+        this->startSecondFilter = src.startSecondFilter;
+        ::memcpy(this->filterPattern, src.filterPattern, sizeof(Int)*NO_VAR_BINS);
+        for(Int i=0; i< (Int)NO_VAR_BINS; i++)
+        {
+          ::memcpy(this->coeffmulti[i], src.coeffmulti[i], sizeof(Int)*numCoef);
+        }
+
+      }
+      break;
+    default:
+      {
+        printf("not a legal component ID\n");
+        assert(0);
+        exit(-1);
+      }
+
+    }
+  }
+  else
+  {
+    //reset
+    this->filters_per_group = 0;
+  }
+}
+
+TComAdaptiveLoopFilter::TComAdaptiveLoopFilter()
+{
+  m_pcTempPicYuv = NULL;
+  m_iSGDepth     = 0;
+  m_pcPic        = NULL;
+  m_ppSliceAlfLCUs = NULL;
+  m_pvpAlfLCU    = NULL;
+  m_pvpSliceTileAlfLCU = NULL;
+  m_varImg = NULL;
+  m_filterCoeffSym = NULL;
+}
+
+static Pel Clip_post(int high, int val)
+{
+  return (Pel)(((val > high)? high: val));
+}
+
+Void TComAdaptiveLoopFilter::create( Int iPicWidth, Int iPicHeight, UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxCUDepth )
+{
+  destroy();
+  if ( !m_pcTempPicYuv )
+  {
+    m_pcTempPicYuv = new TComPicYuv;
+    m_pcTempPicYuv->create( iPicWidth, iPicHeight, uiMaxCUWidth, uiMaxCUHeight, uiMaxCUDepth );
+  }
+  m_img_height = iPicHeight;
+  m_img_width = iPicWidth;
+  m_varImg = new Pel*[m_img_height];
+  m_varImg[0] = new Pel[m_img_height*m_img_width];
+  for(Int j=1; j< m_img_height; j++)
+  {
+    m_varImg[j] = m_varImg[0] + (j*m_img_width);
+  }
+
+  m_filterCoeffSym = new Int*[NO_VAR_BINS];
+  for(Int g=0 ; g< (Int)NO_VAR_BINS; g++)
+  {
+    m_filterCoeffSym[g] = new Int[ALF_MAX_NUM_COEF];
+  }
+  UInt uiNumLCUsInWidth   = m_img_width  / uiMaxCUWidth;
+  UInt uiNumLCUsInHeight  = m_img_height / uiMaxCUHeight;
+
+  uiNumLCUsInWidth  += ( m_img_width % uiMaxCUWidth ) ? 1 : 0;
+  uiNumLCUsInHeight += ( m_img_height % uiMaxCUHeight ) ? 1 : 0;
+
+  m_uiNumCUsInFrame = uiNumLCUsInWidth* uiNumLCUsInHeight; 
+
+  m_numLCUInPicWidth = uiNumLCUsInWidth;
+  m_numLCUInPicHeight= uiNumLCUsInHeight;
+  m_lcuHeight = uiMaxCUHeight;
+  m_lineIdxPadBot = m_lcuHeight - 4 - 3; // DFRegion, Vertical Taps
+  m_lineIdxPadTop = m_lcuHeight - 4; // DFRegion
+
+  m_lcuHeightChroma = m_lcuHeight>>1;
+  m_lineIdxPadBotChroma = m_lcuHeightChroma - 2 - 3; // DFRegion, Vertical Taps
+  m_lineIdxPadTopChroma = m_lcuHeightChroma - 2 ; // DFRegion
+
+  m_lcuWidth = uiMaxCUWidth;
+  m_lcuWidthChroma = (m_lcuWidth >>1);
+
+  //calculate RA filter indexes
+  Int regionTable[NO_VAR_BINS] = {0, 1, 4, 5, 15, 2, 3, 6, 14, 11, 10, 7, 13, 12,  9,  8}; 
+  Int xInterval = ((( (m_img_width +m_lcuWidth -1) / m_lcuWidth) +1) /4 *m_lcuWidth) ;  
+  Int yInterval = ((((m_img_height +m_lcuHeight -1) / m_lcuHeight) +1) /4 *m_lcuHeight) ;
+  Int shiftH = (Int)(log((double)VAR_SIZE_H)/log(2.0));
+  Int shiftW = (Int)(log((double)VAR_SIZE_W)/log(2.0));
+  int yIndex, xIndex;
+  int yIndexOffset;
+
+  for(Int i = 0; i < m_img_height; i=i+4)
+  {
+    yIndex = (yInterval == 0)?(3):(Clip_post( 3, i / yInterval));
+    yIndexOffset = yIndex * 4 ;
+    for(Int j = 0; j < m_img_width; j=j+4)
+    {
+      xIndex = (xInterval==0)?(3):(Clip_post( 3, j / xInterval));
+      m_varImg[i>>shiftH][j>>shiftW] = regionTable[yIndexOffset + xIndex];
+    }
+  }
+}
+
+Void TComAdaptiveLoopFilter::destroy()
+{
+  if ( m_pcTempPicYuv )
+  {
+    m_pcTempPicYuv->destroy();
+    delete m_pcTempPicYuv;
+    m_pcTempPicYuv = NULL;
+  }
+  if(m_varImg != NULL)
+  {
+    delete[] m_varImg[0];
+    delete[] m_varImg;
+    m_varImg = NULL;
+  }
+  if(m_filterCoeffSym != NULL)
+  {
+    for(Int g=0 ; g< (Int)NO_VAR_BINS; g++)
+    {
+      delete[] m_filterCoeffSym[g];
+    }
+    delete[] m_filterCoeffSym; 
+    m_filterCoeffSym = NULL;
+  }
+}
+
+// --------------------------------------------------------------------------------------------------------------------
+// interface function for actual ALF process
+// --------------------------------------------------------------------------------------------------------------------
+
+/** ALF reconstruction process for one picture
+ * \param [in, out] pcPic the decoded/filtered picture (input: decoded picture; output filtered picture)
+ * \param [in] vAlfCUCtrlParam ALF CU-on/off control parameters
+ * \param [in] isAlfCoefInSlice ALF coefficient in slice (true) or ALF coefficient in APS (false) 
+ */
+Void TComAdaptiveLoopFilter::ALFProcess(TComPic* pcPic, ALFParam** alfParam, std::vector<Bool>* sliceAlfEnabled)
+{
+  TComPicYuv* pcPicYuvRec    = pcPic->getPicYuvRec();
+  TComPicYuv* pcPicYuvExtRec = m_pcTempPicYuv;
+  pcPicYuvRec   ->copyToPic          ( pcPicYuvExtRec );
+  pcPicYuvExtRec->setBorderExtension ( false );
+  pcPicYuvExtRec->extendPicBorder    ();
+
+  Int lumaStride   = pcPicYuvExtRec->getStride();
+  Int chromaStride = pcPicYuvExtRec->getCStride();
+
+  for(Int compIdx =0; compIdx < NUM_ALF_COMPONENT; compIdx++)
+  {
+    Pel* pDec         = getPicBuf(pcPicYuvExtRec, compIdx);
+    Pel* pRest        = getPicBuf(pcPicYuvRec, compIdx);
+    Int  stride       = (compIdx == ALF_Y)?(lumaStride):(chromaStride);
+    Int  formatShift = (compIdx == ALF_Y)?(0):(1);
+
+    recALF(compIdx, sliceAlfEnabled[compIdx], alfParam[compIdx], pDec, pRest, stride, formatShift);
+  }
+
+}
+
+/** ALF Reconstruction for each component
+ * \param [in] compIdx color component index
+ * \param [in] alfLCUParams alf parameters 
+ * \param [in] pDec decoded picture
+ * \param [in, out] pRest filtered picture
+ * \param [in] stride picture stride in memory
+ * \param [in] formatShift luma component (false) or chroma component (1)
+ * \param [in] alfCUCtrlParam ALF CU-on/off control parameters 
+ * \param [in] caculateBAIdx calculate BA filter index (true) or BA filter index array is ready (false)
+ */
+Void TComAdaptiveLoopFilter::recALF(Int compIdx, std::vector<Bool>& sliceAlfEnabled, ALFParam* alfParam, Pel* pDec, Pel* pRest, Int stride, Int formatShift)
+{
+  for(Int s=0; s< m_uiNumSlicesInPic; s++)
+  {
+    if((!m_pcPic->getValidSlice(s))||(!sliceAlfEnabled[s]))
+    {
+      continue;
+    }
+    assert(alfParam->alf_flag == 1);    
+    reconstructCoefInfo(compIdx, alfParam, m_filterCoeffSym, m_varIndTab); //reconstruct ALF coefficients & related parameters 
+
+    Int numTilesInSlice = (Int)m_pvpSliceTileAlfLCU[s].size();
+    for(Int t=0; t< numTilesInSlice; t++)
+    {
+      std::vector<AlfLCUInfo*> & vpAlfLCU = m_pvpSliceTileAlfLCU[s][t];
+      Pel* pSrc = pDec;
+
+      if(m_bUseNonCrossALF)
+      {
+        pSrc = getPicBuf(m_pcSliceYuvTmp, compIdx);
+        copyRegion(vpAlfLCU, pSrc, pDec, stride, formatShift);
+        extendRegionBorder(vpAlfLCU, pSrc, stride, formatShift);
+      }
+      filterRegion(compIdx, (alfParam->filters_per_group == 1), vpAlfLCU, pSrc, pRest, stride, formatShift);
+    } //tile
+  } //slice
+}
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+/** 
+ \param filter         filter coefficient
+ \param filterLength   filter length
+ \param isChroma       1: chroma, 0: luma
+ */
+Void TComAdaptiveLoopFilter::checkFilterCoeffValue( Int *filter, Int filterLength, Bool isChroma )
+{
+  Int maxValueNonCenter = 1 * (1 << ALF_NUM_BIT_SHIFT) - 1;
+  Int minValueNonCenter = 0 - 1 * (1 << ALF_NUM_BIT_SHIFT);
+  Int maxValueCenter    = 2 * (1 << ALF_NUM_BIT_SHIFT) - 1;
+  Int minValueCenter    = 0 ; 
+
+  for(Int i = 0; i < filterLength-1; i++)
+  {
+    filter[i] = Clip3(minValueNonCenter, maxValueNonCenter, filter[i]);
+  }
+
+  filter[filterLength-1] = Clip3(minValueCenter, maxValueCenter, filter[filterLength-1]);
+}
+
+
+/** Initialize the variables for one ALF LCU
+ * \param rAlfLCU to-be-initialized ALF LCU
+ * \param sliceID slice index
+ * \param tileID tile index
+ * \param pcCU CU data pointer
+ * \param maxNumSUInLCU maximum number of SUs in one LCU
+ */
+Void TComAdaptiveLoopFilter::InitAlfLCUInfo(AlfLCUInfo& rAlfLCU, Int sliceID, Int tileID, TComDataCU* pcCU, UInt maxNumSUInLCU)
+{
+  //pcCU
+  rAlfLCU.pcCU     = pcCU;
+  //sliceID
+  rAlfLCU.sliceID = sliceID;
+  //tileID
+  rAlfLCU.tileID  = tileID;
+
+  //numSGU, vpAlfBLock;
+  std::vector<NDBFBlockInfo>& vNDBFBlock = *(pcCU->getNDBFilterBlocks());
+  rAlfLCU.vpAlfBlock.clear();
+  rAlfLCU.numSGU = 0;
+  for(Int i=0; i< vNDBFBlock.size(); i++)
+  {
+    if( vNDBFBlock[i].sliceID == sliceID)
+    {
+      rAlfLCU.vpAlfBlock.push_back( &(vNDBFBlock[i])  );
+      rAlfLCU.numSGU ++;
+    }
+  }
+  //startSU
+  rAlfLCU.startSU = rAlfLCU.vpAlfBlock.front()->startSU;
+  //endSU
+  rAlfLCU.endSU   = rAlfLCU.vpAlfBlock.back()->endSU;
+  //bAllSUsInLCUInSameSlice
+  rAlfLCU.bAllSUsInLCUInSameSlice = (rAlfLCU.startSU == 0)&&( rAlfLCU.endSU == maxNumSUInLCU -1);
+}
+
+/** create and initialize variables for picture ALF processing
+ * \param pcPic picture-level data pointer
+ * \param numSlicesInPic number of slices in picture
+ */
+Void TComAdaptiveLoopFilter::createPicAlfInfo(TComPic* pcPic, Int numSlicesInPic)
+{
+  m_uiNumSlicesInPic = numSlicesInPic;
+#if REMOVE_FGS
+  m_iSGDepth         = 0;
+#else
+  m_iSGDepth         = pcPic->getSliceGranularityForNDBFilter();
+#endif
+  
+  m_bUseNonCrossALF = ( pcPic->getIndependentSliceBoundaryForNDBFilter() || pcPic->getIndependentTileBoundaryForNDBFilter());
+  m_pcPic = pcPic;
+
+  m_ppSliceAlfLCUs = new AlfLCUInfo*[m_uiNumSlicesInPic];
+  m_pvpAlfLCU = new std::vector< AlfLCUInfo* >[m_uiNumSlicesInPic];
+  m_pvpSliceTileAlfLCU = new std::vector< std::vector< AlfLCUInfo* > >[m_uiNumSlicesInPic];
+
+  for(Int s=0; s< m_uiNumSlicesInPic; s++)
+  {
+    m_ppSliceAlfLCUs[s] = NULL;
+    if(!pcPic->getValidSlice(s))
+    {
+      continue;
+    }
+
+    std::vector< TComDataCU* >& vSliceLCUPointers = pcPic->getOneSliceCUDataForNDBFilter(s);
+    Int                         numLCU           = (Int)vSliceLCUPointers.size();
+
+    //create Alf LCU info
+    m_ppSliceAlfLCUs[s] = new AlfLCUInfo[numLCU];
+    for(Int i=0; i< numLCU; i++)
+    {
+      TComDataCU* pcCU       = vSliceLCUPointers[i];
+      if(pcCU->getPic()==0)
+      {
+        continue;
+      }
+      Int         currTileID = pcPic->getPicSym()->getTileIdxMap(pcCU->getAddr());
+
+      InitAlfLCUInfo(m_ppSliceAlfLCUs[s][i], s, currTileID, pcCU, pcPic->getNumPartInCU());
+    }
+
+    //distribute Alf LCU info pointers to slice container
+    std::vector< AlfLCUInfo* >&    vpSliceAlfLCU     = m_pvpAlfLCU[s]; 
+    vpSliceAlfLCU.reserve(numLCU);
+    vpSliceAlfLCU.resize(0);
+    std::vector< std::vector< AlfLCUInfo* > > &vpSliceTileAlfLCU = m_pvpSliceTileAlfLCU[s];
+    Int prevTileID = -1;
+    Int numValidTilesInSlice = 0;
+
+    for(Int i=0; i< numLCU; i++)
+    {
+      AlfLCUInfo* pcAlfLCU = &(m_ppSliceAlfLCUs[s][i]);
+
+      //container of Alf LCU pointers for slice processing
+      vpSliceAlfLCU.push_back( pcAlfLCU);
+
+      if(pcAlfLCU->tileID != prevTileID)
+      {
+        if(prevTileID == -1 || pcPic->getIndependentTileBoundaryForNDBFilter())
+        {
+          prevTileID = pcAlfLCU->tileID;
+          numValidTilesInSlice ++;
+          vpSliceTileAlfLCU.resize(numValidTilesInSlice);
+        }
+      }
+      //container of Alf LCU pointers for tile processing 
+      vpSliceTileAlfLCU[numValidTilesInSlice-1].push_back(pcAlfLCU);
+    }
+
+    assert( vpSliceAlfLCU.size() == numLCU);
+  }
+
+  if(m_bUseNonCrossALF)
+  {
+    m_pcSliceYuvTmp = pcPic->getYuvPicBufferForIndependentBoundaryProcessing();
+  }
+}
+
+/** Destroy ALF slice units
+ */
+Void TComAdaptiveLoopFilter::destroyPicAlfInfo()
+{
+  for(Int s=0; s< m_uiNumSlicesInPic; s++)
+  {
+    if(m_ppSliceAlfLCUs[s] != NULL)
+    {
+      delete[] m_ppSliceAlfLCUs[s];
+      m_ppSliceAlfLCUs[s] = NULL;
+    }
+  }
+  delete[] m_ppSliceAlfLCUs;
+  m_ppSliceAlfLCUs = NULL;
+
+  delete[] m_pvpAlfLCU;
+  m_pvpAlfLCU = NULL;
+
+  delete[] m_pvpSliceTileAlfLCU;
+  m_pvpSliceTileAlfLCU = NULL;
+}
+
+/** Copy region pixels
+ * \param vpAlfLCU ALF LCU data container
+ * \param pPicDst destination picture buffer
+ * \param pPicSrc source picture buffer
+ * \param stride stride size of picture buffer
+ * \param formatShift region size adjustment according to component size
+ */
+Void TComAdaptiveLoopFilter::copyRegion(std::vector< AlfLCUInfo* > &vpAlfLCU, Pel* pPicDst, Pel* pPicSrc, Int stride, Int formatShift)
+{
+  Int extSize = 4;
+  Int posX, posY, width, height, offset;
+  Pel *pPelDst, *pPelSrc;
+  
+  for(Int idx =0; idx < vpAlfLCU.size(); idx++)
+  {
+    AlfLCUInfo& cAlfLCU = *(vpAlfLCU[idx]);
+    for(Int n=0; n < cAlfLCU.numSGU; n++)
+    {
+      NDBFBlockInfo& rSGU = cAlfLCU[n];
+
+      posX     = (Int)(rSGU.posX   >> formatShift);
+      posY     = (Int)(rSGU.posY   >> formatShift);
+      width    = (Int)(rSGU.width  >> formatShift);
+      height   = (Int)(rSGU.height >> formatShift);
+      offset   = ( (posY- extSize) * stride)+ (posX -extSize);
+      pPelDst  = pPicDst + offset;    
+      pPelSrc  = pPicSrc + offset;    
+
+      for(Int j=0; j< (height + (extSize<<1)); j++)
+      {
+        ::memcpy(pPelDst, pPelSrc, sizeof(Pel)*(width + (extSize<<1)));
+        pPelDst += stride;
+        pPelSrc += stride;
+      }
+    }
+  }
+}
+
+/** Extend region boundary 
+ * \param [in] vpAlfLCU ALF LCU data container
+ * \param [in,out] pPelSrc picture buffer
+ * \param [in] stride stride size of picture buffer
+ * \param [in] formatShift region size adjustment according to component size
+ */
+Void TComAdaptiveLoopFilter::extendRegionBorder(std::vector< AlfLCUInfo* > &vpAlfLCU, Pel* pPelSrc, Int stride, Int formatShift)
+{
+  UInt extSize = 4;
+  UInt width, height;
+  UInt posX, posY;
+  Pel* pPel;
+  Bool* pbAvail;
+  for(Int idx = 0; idx < vpAlfLCU.size(); idx++)
+  {
+    AlfLCUInfo& rAlfLCU = *(vpAlfLCU[idx]);
+    for(Int n =0; n < rAlfLCU.numSGU; n++)
+    {
+      NDBFBlockInfo& rSGU = rAlfLCU[n];
+      if(rSGU.allBordersAvailable)
+      {
+        continue;
+      }
+      posX     = rSGU.posX >> formatShift;
+      posY     = rSGU.posY >> formatShift;
+      width    = rSGU.width >> formatShift;
+      height   = rSGU.height >> formatShift;
+      pbAvail  = rSGU.isBorderAvailable;    
+      pPel     = pPelSrc + (posY * stride)+ posX;    
+      extendBorderCoreFunction(pPel, stride, pbAvail, width, height, extSize);
+    }
+  }
+}
+
+/** Core function for extending slice/tile boundary 
+ * \param [in, out] pPel processing block pointer
+ * \param [in] stride picture buffer stride
+ * \param [in] pbAvail neighboring blocks availabilities
+ * \param [in] width block width
+ * \param [in] height block height
+ * \param [in] extSize boundary extension size
+ */
+Void TComAdaptiveLoopFilter::extendBorderCoreFunction(Pel* pPel, Int stride, Bool* pbAvail, UInt width, UInt height, UInt extSize)
+{
+  Pel* pPelDst;
+  Pel* pPelSrc;
+  Int i, j;
+
+  for(Int pos =0; pos < NUM_SGU_BORDER; pos++)
+  {
+    if(pbAvail[pos])
+    {
+      continue;
+    }
+
+    switch(pos)
+    {
+    case SGU_L:
+      {
+        pPelDst = pPel - extSize;
+        pPelSrc = pPel;
+        for(j=0; j< height; j++)
+        {
+          for(i=0; i< extSize; i++)
+          {
+            pPelDst[i] = *pPelSrc;
+          }
+          pPelDst += stride;
+          pPelSrc += stride;
+        }
+      }
+      break;
+    case SGU_R:
+      {
+        pPelDst = pPel + width;
+        pPelSrc = pPelDst -1;
+        for(j=0; j< height; j++)
+        {
+          for(i=0; i< extSize; i++)
+          {
+            pPelDst[i] = *pPelSrc;
+          }
+          pPelDst += stride;
+          pPelSrc += stride;
+        }
+
+      }
+      break;
+    case SGU_T:
+      {
+        pPelSrc = pPel;
+        pPelDst = pPel - stride;
+        for(j=0; j< extSize; j++)
+        {
+          ::memcpy(pPelDst, pPelSrc, sizeof(Pel)*width);
+          pPelDst -= stride;
+        }
+      }
+      break;
+    case SGU_B:
+      {
+        pPelDst = pPel + height*stride;
+        pPelSrc = pPelDst - stride;
+        for(j=0; j< extSize; j++)
+        {
+          ::memcpy(pPelDst, pPelSrc, sizeof(Pel)*width);
+          pPelDst += stride;
+        }
+
+      }
+      break;
+    case SGU_TL:
+      {
+        if( (!pbAvail[SGU_T]) && (!pbAvail[SGU_L]))
+        {
+          pPelSrc = pPel  - extSize;
+          pPelDst = pPelSrc - stride;
+          for(j=0; j< extSize; j++)
+          {
+            ::memcpy(pPelDst, pPelSrc, sizeof(Pel)*extSize);
+            pPelDst -= stride;
+          }         
+        }
+      }
+      break;
+    case SGU_TR:
+      {
+        if( (!pbAvail[SGU_T]) && (!pbAvail[SGU_R]))
+        {
+          pPelSrc = pPel + width;
+          pPelDst = pPelSrc - stride;
+          for(j=0; j< extSize; j++)
+          {
+            ::memcpy(pPelDst, pPelSrc, sizeof(Pel)*extSize);
+            pPelDst -= stride;
+          }
+
+        }
+
+      }
+      break;
+    case SGU_BL:
+      {
+        if( (!pbAvail[SGU_B]) && (!pbAvail[SGU_L]))
+        {
+          pPelDst = pPel + height*stride; pPelDst-= extSize;
+          pPelSrc = pPelDst - stride;
+          for(j=0; j< extSize; j++)
+          {
+            ::memcpy(pPelDst, pPelSrc, sizeof(Pel)*extSize);
+            pPelDst += stride;
+          }
+
+        }
+      }
+      break;
+    case SGU_BR:
+      {
+        if( (!pbAvail[SGU_B]) && (!pbAvail[SGU_R]))
+        {
+          pPelDst = pPel + height*stride; pPelDst += width;
+          pPelSrc = pPelDst - stride;
+          for(j=0; j< extSize; j++)
+          {
+            ::memcpy(pPelDst, pPelSrc, sizeof(Pel)*extSize);
+            pPelDst += stride;
+          }
+        }
+      }
+      break;
+    default:
+      {
+        printf("Not a legal neighboring availability\n");
+        assert(0);
+        exit(-1);
+      }
+    }
+  }
+}
+
+Void TComAdaptiveLoopFilter::reconstructCoefficients(ALFParam* alfParam, Int** filterCoeff)
+{
+  for(Int g=0; g< alfParam->filters_per_group; g++)
+  {
+    Int sum = 0;
+    for(Int i=0; i< alfParam->num_coeff-1; i++)
+    {
+      sum += (2 * alfParam->coeffmulti[g][i]);
+      filterCoeff[g][i] = alfParam->coeffmulti[g][i];
+    }
+    Int coeffPred = (1<<ALF_NUM_BIT_SHIFT) - sum;
+    filterCoeff[g][alfParam->num_coeff-1] = coeffPred + alfParam->coeffmulti[g][alfParam->num_coeff-1];
+  }
+}
+
+Void TComAdaptiveLoopFilter::reconstructCoefInfo(Int compIdx, ALFParam* alfParam, Int** filterCoeff, Int* varIndTab)
+{
+  if(compIdx == ALF_Y)
+  {
+    ::memset(varIndTab, 0, NO_VAR_BINS * sizeof(Int));
+    if(alfParam->filters_per_group > 1)
+    {
+      for(Int i = 1; i < NO_VAR_BINS; ++i)
+      {
+        if(alfParam->filterPattern[i])
+        {
+          varIndTab[i] = varIndTab[i-1] + 1;
+        }
+        else
+        {
+          varIndTab[i] = varIndTab[i-1];
+        }
+      }
+    }
+  }
+  reconstructCoefficients(alfParam, filterCoeff);
+}
+
+/** filter process without CU-On/Off control
+ * \param [in] alfLCUParam ALF parameters 
+ * \param [in] regionLCUInfo ALF CU-on/off control parameters 
+ * \param [in] pDec decoded picture
+ * \param [out] pRest filtered picture
+ * \param [in] stride picture stride in memory
+ * \param [in] formatShift luma component (0) or chroma component (1)
+ * \param [in] caculateBAIdx calculate BA filter index (true) or BA filter index array is ready (false)
+ */
+Void TComAdaptiveLoopFilter::filterRegion(Int compIdx, Bool isSingleFilter, std::vector<AlfLCUInfo*>& regionLCUInfo, Pel* pDec, Pel* pRest, Int stride, Int formatShift)
+{
+  Int height, width;
+  Int ypos =0, xpos=0;
+  for(Int i=0; i< regionLCUInfo.size(); i++)
+  {
+    AlfLCUInfo& alfLCUinfo = *(regionLCUInfo[i]); 
+    TComDataCU* pcCU = alfLCUinfo.pcCU;
+
+    if(pcCU->getAlfLCUEnabled(compIdx))
+    {
+      //filtering process
+      for(Int j=0; j< alfLCUinfo.numSGU; j++)
+      {
+        ypos    = (Int)(alfLCUinfo[j].posY   >> formatShift);
+        xpos    = (Int)(alfLCUinfo[j].posX   >> formatShift);
+        height = (Int)(alfLCUinfo[j].height >> formatShift);
+        width  = (Int)(alfLCUinfo[j].width  >> formatShift);
+
+        filterOneCompRegion(pRest, pDec, stride, (compIdx!=ALF_Y), ypos, ypos+height, xpos, xpos+width, m_filterCoeffSym, m_varIndTab, m_varImg);
+      }
+    } //alf_flag == 1
+  }
+}
+
+/** filtering pixels
+ * \param [out] imgRes filtered picture
+ * \param [in] imgPad decoded picture 
+ * \param [in] stride picture stride in memory
+ * \param [in] isChroma chroma component (true) or luma component (false)
+ * \param [in] yPos y position of the top-left pixel in one to-be-filtered region
+ * \param [in] yPosEnd y position of the right-bottom pixel in one to-be-filtered region
+ * \param [in] xPos x position of the top-left pixel in one to-be-filtered region
+ * \param [in] xPosEnd x position of the right-bottom pixel in one to-be-filtered region
+ * \param [in] filterSet filter coefficients
+ * \param [in] mergeTable the merged groups in block-based adaptation mode
+ * \param [in] varImg BA filter index array 
+ */
+Void TComAdaptiveLoopFilter::filterOneCompRegion(Pel *imgRes, Pel *imgPad, Int stride, Bool isChroma
+                                                , Int yPos, Int yPosEnd, Int xPos, Int xPosEnd
+                                                , Int** filterSet, Int* mergeTable, Pel** varImg
+                                                )
+{
+  static Int numBitsMinus1= (Int)ALF_NUM_BIT_SHIFT;
+  static Int offset       = (1<<( (Int)ALF_NUM_BIT_SHIFT-1));
+  static Int shiftHeight  = (Int)(log((double)VAR_SIZE_H)/log(2.0));
+  static Int shiftWidth   = (Int)(log((double)VAR_SIZE_W)/log(2.0));
+
+  Pel *imgPad1,*imgPad2,*imgPad3, *imgPad4, *imgPad5, *imgPad6;
+  Pel *var = varImg[yPos>>shiftHeight] + (xPos>>shiftWidth);;
+  Int i, j, pixelInt;
+  Int *coef = NULL;
+
+  coef    = filterSet[0];
+  imgPad += (yPos*stride);
+  imgRes += (yPos*stride);
+
+  Int yLineInLCU;
+  Int paddingLine;
+  //Int varInd = 0;
+  Int lcuHeight     = isChroma ? m_lcuHeightChroma     : m_lcuHeight;
+  Int lineIdxPadBot = isChroma ? m_lineIdxPadBotChroma : m_lineIdxPadBot;
+  Int lineIdxPadTop = isChroma ? m_lineIdxPadTopChroma : m_lineIdxPadTop;
+  Int img_height    = isChroma ? m_img_height>>1       : m_img_height;
+
+  for(i= yPos; i< yPosEnd; i++)
+  {
+    yLineInLCU = i % lcuHeight;
+
+    if(isChroma && yLineInLCU == 0 && i>0)
+    {
+      paddingLine = yLineInLCU + 2;
+      imgPad1 = imgPad + stride;
+      imgPad2 = imgPad - stride;
+      imgPad3 = imgPad + 2*stride;
+      imgPad4 = imgPad - 2*stride;
+      imgPad5 = (paddingLine < 3) ? imgPad : imgPad + 3*stride;
+      imgPad6 = (paddingLine < 3) ? imgPad : imgPad - min(paddingLine, 3)*stride;
+    }
+    else if(yLineInLCU<lineIdxPadBot || i-yLineInLCU+lcuHeight >= img_height)
+    {
+      imgPad1 = imgPad +   stride;
+      imgPad2 = imgPad -   stride;
+      imgPad3 = imgPad + 2*stride;
+      imgPad4 = imgPad - 2*stride;
+      imgPad5 = imgPad + 3*stride;
+      imgPad6 = imgPad - 3*stride;
+    }
+    else if (yLineInLCU<lineIdxPadTop)
+    {
+      paddingLine = - yLineInLCU + lineIdxPadTop - 1;
+      imgPad1 = (paddingLine < 1) ? imgPad : imgPad + min(paddingLine, 1)*stride;
+      imgPad2 = (paddingLine < 1) ? imgPad : imgPad - stride;
+      imgPad3 = (paddingLine < 2) ? imgPad : imgPad + min(paddingLine, 2)*stride;
+      imgPad4 = (paddingLine < 2) ? imgPad : imgPad - 2*stride;
+      imgPad5 = (paddingLine < 3) ? imgPad : imgPad + min(paddingLine, 3)*stride;
+      imgPad6 = (paddingLine < 3) ? imgPad : imgPad - 3*stride;
+    }
+    else
+    {
+      paddingLine = yLineInLCU - lineIdxPadTop ;
+      imgPad1 = (paddingLine < 1) ? imgPad : imgPad + stride;
+      imgPad2 = (paddingLine < 1) ? imgPad : imgPad - min(paddingLine, 1)*stride;
+      imgPad3 = (paddingLine < 2) ? imgPad : imgPad + 2*stride;
+      imgPad4 = (paddingLine < 2) ? imgPad : imgPad - min(paddingLine, 2)*stride;
+      imgPad5 = (paddingLine < 3) ? imgPad : imgPad + 3*stride;
+      imgPad6 = (paddingLine < 3) ? imgPad : imgPad - min(paddingLine, 3)*stride;
+    } 
+
+    if(!isChroma)
+    {
+      var = varImg[i>>shiftHeight] + (xPos>>shiftWidth);
+    }
+
+    for(j= xPos; j< xPosEnd ; j++)
+    {
+      if (!isChroma && j % VAR_SIZE_W==0) 
+      {
+        coef = filterSet[mergeTable[*(var++)]];
+      }
+
+      pixelInt  = coef[0]* (imgPad5[j  ] + imgPad6[j  ]);
+
+      pixelInt += coef[1]* (imgPad3[j  ] + imgPad4[j  ]);
+
+      pixelInt += coef[2]* (imgPad1[j+1] + imgPad2[j-1]);
+      pixelInt += coef[3]* (imgPad1[j  ] + imgPad2[j  ]);
+      pixelInt += coef[4]* (imgPad1[j-1] + imgPad2[j+1]);
+
+      pixelInt += coef[5]* (imgPad[j+4] + imgPad[j-4]);
+      pixelInt += coef[6]* (imgPad[j+3] + imgPad[j-3]);
+      pixelInt += coef[7]* (imgPad[j+2] + imgPad[j-2]);
+      pixelInt += coef[8]* (imgPad[j+1] + imgPad[j-1]);
+      pixelInt += coef[9]* (imgPad[j  ]);
+
+      pixelInt=(Int)((pixelInt+offset) >> numBitsMinus1);
+      imgRes[j] = Clip( pixelInt );
+    }
+
+    imgPad += stride;
+    imgRes += stride;
+  }  
+}
+
+Pel* TComAdaptiveLoopFilter::getPicBuf(TComPicYuv* pPicYuv, Int compIdx)
+{
+  Pel* pBuf = NULL;
+  switch(compIdx)
+  {
+  case ALF_Y:
+    {
+      pBuf = pPicYuv->getLumaAddr();
+    }
+    break;
+  case ALF_Cb:
+    {
+      pBuf = pPicYuv->getCbAddr();
+    }
+    break;
+  case ALF_Cr:
+    {
+      pBuf = pPicYuv->getCrAddr();
+    }
+    break;
+  default:
+    {
+      printf("Not a legal component ID for ALF\n");
+      assert(0);
+      exit(-1);
+    }
+  }
+
+  return pBuf;
+}
+
+
+
+/** PCM LF disable process. 
+ * \param pcPic picture (TComPic) pointer
+ * \returns Void
+ *
+ * \note Replace filtered sample values of PCM mode blocks with the transmitted and reconstructed ones.
+ */
+Void TComAdaptiveLoopFilter::PCMLFDisableProcess (TComPic* pcPic)
+{
+  xPCMRestoration(pcPic);
+}
+
+/** Picture-level PCM restoration. 
+ * \param pcPic picture (TComPic) pointer
+ * \returns Void
+ */
+Void TComAdaptiveLoopFilter::xPCMRestoration(TComPic* pcPic)
+{
+  Bool  bPCMFilter = (pcPic->getSlice(0)->getSPS()->getUsePCM() && pcPic->getSlice(0)->getSPS()->getPCMFilterDisableFlag())? true : false;
+
+  if(bPCMFilter || pcPic->getSlice(0)->getPPS()->getTransquantBypassEnableFlag())
+  {
+    for( UInt uiCUAddr = 0; uiCUAddr < pcPic->getNumCUsInFrame() ; uiCUAddr++ )
+    {
+      TComDataCU* pcCU = pcPic->getCU(uiCUAddr);
+
+      xPCMCURestoration(pcCU, 0, 0); 
+    } 
+  }
+}
+
+/** PCM CU restoration. 
+ * \param pcCU pointer to current CU
+ * \param uiAbsPartIdx part index
+ * \param uiDepth CU depth
+ * \returns Void
+ */
+Void TComAdaptiveLoopFilter::xPCMCURestoration ( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth )
+{
+  TComPic* pcPic     = pcCU->getPic();
+  UInt uiCurNumParts = pcPic->getNumPartInCU() >> (uiDepth<<1);
+  UInt uiQNumParts   = uiCurNumParts>>2;
+
+  // go to sub-CU
+  if( pcCU->getDepth(uiAbsZorderIdx) > uiDepth )
+  {
+    for ( UInt uiPartIdx = 0; uiPartIdx < 4; uiPartIdx++, uiAbsZorderIdx+=uiQNumParts )
+    {
+      UInt uiLPelX   = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsZorderIdx] ];
+      UInt uiTPelY   = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsZorderIdx] ];
+      if( ( uiLPelX < pcCU->getSlice()->getSPS()->getPicWidthInLumaSamples() ) && ( uiTPelY < pcCU->getSlice()->getSPS()->getPicHeightInLumaSamples() ) )
+        xPCMCURestoration( pcCU, uiAbsZorderIdx, uiDepth+1 );
+    }
+    return;
+  }
+
+  // restore PCM samples
+  if ((pcCU->getIPCMFlag(uiAbsZorderIdx)&& pcPic->getSlice(0)->getSPS()->getPCMFilterDisableFlag()) || pcCU->isLosslessCoded( uiAbsZorderIdx))
+  {
+    xPCMSampleRestoration (pcCU, uiAbsZorderIdx, uiDepth, TEXT_LUMA    );
+    xPCMSampleRestoration (pcCU, uiAbsZorderIdx, uiDepth, TEXT_CHROMA_U);
+    xPCMSampleRestoration (pcCU, uiAbsZorderIdx, uiDepth, TEXT_CHROMA_V);
+  }
+}
+
+/** PCM sample restoration. 
+ * \param pcCU pointer to current CU
+ * \param uiAbsPartIdx part index
+ * \param uiDepth CU depth
+ * \param ttText texture component type
+ * \returns Void
+ */
+Void TComAdaptiveLoopFilter::xPCMSampleRestoration (TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, TextType ttText)
+{
+  TComPicYuv* pcPicYuvRec = pcCU->getPic()->getPicYuvRec();
+  Pel* piSrc;
+  Pel* piPcm;
+  UInt uiStride;
+  UInt uiWidth;
+  UInt uiHeight;
+  UInt uiPcmLeftShiftBit; 
+  UInt uiX, uiY;
+  UInt uiMinCoeffSize = pcCU->getPic()->getMinCUWidth()*pcCU->getPic()->getMinCUHeight();
+  UInt uiLumaOffset   = uiMinCoeffSize*uiAbsZorderIdx;
+  UInt uiChromaOffset = uiLumaOffset>>2;
+
+  if( ttText == TEXT_LUMA )
+  {
+    piSrc = pcPicYuvRec->getLumaAddr( pcCU->getAddr(), uiAbsZorderIdx);
+    piPcm = pcCU->getPCMSampleY() + uiLumaOffset;
+    uiStride  = pcPicYuvRec->getStride();
+    uiWidth  = (g_uiMaxCUWidth >> uiDepth);
+    uiHeight = (g_uiMaxCUHeight >> uiDepth);
+    if ( pcCU->isLosslessCoded(uiAbsZorderIdx) )
+    {
+      uiPcmLeftShiftBit = 0;
+    }
+    else
+    {
+        uiPcmLeftShiftBit = g_uiBitDepth + g_uiBitIncrement - pcCU->getSlice()->getSPS()->getPCMBitDepthLuma();
+    }
+  }
+  else
+  {
+    if( ttText == TEXT_CHROMA_U )
+    {
+      piSrc = pcPicYuvRec->getCbAddr( pcCU->getAddr(), uiAbsZorderIdx );
+      piPcm = pcCU->getPCMSampleCb() + uiChromaOffset;
+    }
+    else
+    {
+      piSrc = pcPicYuvRec->getCrAddr( pcCU->getAddr(), uiAbsZorderIdx );
+      piPcm = pcCU->getPCMSampleCr() + uiChromaOffset;
+    }
+
+    uiStride = pcPicYuvRec->getCStride();
+    uiWidth  = ((g_uiMaxCUWidth >> uiDepth)/2);
+    uiHeight = ((g_uiMaxCUWidth >> uiDepth)/2);
+    if ( pcCU->isLosslessCoded(uiAbsZorderIdx) )
+    {
+      uiPcmLeftShiftBit = 0;
+    }
+    else
+    {
+      uiPcmLeftShiftBit = g_uiBitDepth + g_uiBitIncrement - pcCU->getSlice()->getSPS()->getPCMBitDepthChroma();
+    }
+  }
+
+  for( uiY = 0; uiY < uiHeight; uiY++ )
+  {
+    for( uiX = 0; uiX < uiWidth; uiX++ )
+    {
+      piSrc[uiX] = (piPcm[uiX] << uiPcmLeftShiftBit);
+    }
+    piPcm += uiWidth;
+    piSrc += uiStride;
+  }
+}
+//! \}
+#endif
Index: /trunk/source/Lib/TLibCommon/TComAdaptiveLoopFilter.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComAdaptiveLoopFilter.h	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComAdaptiveLoopFilter.h	(revision 2)
@@ -0,0 +1,196 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComAdaptiveLoopFilter.h
+    \brief    adaptive loop filter class (header)
+*/
+
+#ifndef __TCOMADAPTIVELOOPFILTER__
+#define __TCOMADAPTIVELOOPFILTER__
+
+#include "CommonDef.h"
+#include "TComPic.h"
+
+#if !REMOVE_ALF
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+#define ALF_MAX_NUM_COEF     10    //!< maximum number of filter coefficients
+#define ALF_NUM_BIT_SHIFT     8    ///< bit shift parameter for quantization of ALF param.
+
+#define VAR_SIZE_H            4
+#define VAR_SIZE_W            4
+#define NO_VAR_BINS           16 
+#define NO_FILTERS            16
+#define MAX_SCAN_VAL          13
+#define MAX_EXP_GOLOMB        16
+
+
+
+/// Luma/Chroma component ID
+enum ALFComponentID
+{
+  ALF_Y = 0,
+  ALF_Cb,
+  ALF_Cr,
+  NUM_ALF_COMPONENT
+};
+///
+/// Filter shape
+///
+enum ALFFilterShape
+{
+  ALF_CROSS9x7_SQUARE3x3 = 0,
+  NUM_ALF_FILTER_SHAPE
+};
+
+extern Int* kTableTabShapes[NUM_ALF_FILTER_SHAPE];
+extern Int depthIntShape1Sym[ALF_MAX_NUM_COEF+1];
+extern Int *pDepthIntTabShapes[NUM_ALF_FILTER_SHAPE];
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+///
+/// LCU-based ALF processing info
+///
+struct AlfLCUInfo
+{
+  TComDataCU* pcCU;            //!< TComDataCU pointer
+  Int         sliceID;        //!< slice ID
+  Int         tileID;         //!< tile ID
+  UInt        numSGU;        //!< number of slice granularity blocks 
+  UInt        startSU;       //!< starting SU z-scan address in LCU
+  UInt        endSU;         //!< ending SU z-scan address in LCU
+  Bool        bAllSUsInLCUInSameSlice; //!< true: all SUs in this LCU belong to same slice
+  std::vector<NDBFBlockInfo*> vpAlfBlock; //!< container for filter block pointers
+
+  NDBFBlockInfo& operator[] (Int idx) { return *( vpAlfBlock[idx]); } //!< [] operator
+  AlfLCUInfo():pcCU(NULL), sliceID(0), tileID(0), numSGU(0), startSU(0), endSU(0), bAllSUsInLCUInSameSlice(false) {} //!< constructor
+};
+
+
+///
+/// adaptive loop filter class
+///
+class TComAdaptiveLoopFilter
+{
+
+protected: //protected member variables
+
+  // filter shape information
+  static Int weightsShape1Sym[ALF_MAX_NUM_COEF+1];
+  // temporary buffer
+  TComPicYuv*   m_pcTempPicYuv;                          ///< temporary picture buffer for ALF processing
+  TComPicYuv* m_pcSliceYuvTmp;    //!< temporary picture buffer pointer when non-across slice boundary ALF is enabled
+
+
+  //filter coefficients buffer
+  Int **m_filterCoeffSym;
+
+  //classification
+  Int      m_varIndTab[NO_VAR_BINS];
+  Pel** m_varImg;
+
+  //parameters
+  Int   m_img_height;
+  Int   m_img_width;
+  Bool  m_bUseNonCrossALF;       //!< true for performing non-cross slice boundary ALF
+  UInt  m_uiNumSlicesInPic;      //!< number of slices in picture
+  Int   m_iSGDepth;              //!< slice granularity depth
+  UInt  m_uiNumCUsInFrame;
+  Int m_lcuWidth;
+  Int m_lcuWidthChroma;
+  Int m_lcuHeight;
+  Int m_lineIdxPadBot;
+  Int m_lineIdxPadTop;
+
+  Int m_lcuHeightChroma;
+  Int m_lineIdxPadBotChroma;
+  Int m_lineIdxPadTopChroma;
+
+  //slice
+  TComPic* m_pcPic;
+  AlfLCUInfo** m_ppSliceAlfLCUs;
+  std::vector< AlfLCUInfo* > *m_pvpAlfLCU;
+  std::vector< std::vector< AlfLCUInfo* > > *m_pvpSliceTileAlfLCU;
+  Int m_numLCUInPicWidth;
+  Int m_numLCUInPicHeight;
+private: //private member variables
+
+
+protected: //protected methods
+  Pel* getPicBuf(TComPicYuv* pPicYuv, Int compIdx);
+  Void recALF(Int compIdx, std::vector<Bool>& sliceAlfEnabled, ALFParam* alfParam, Pel* pDec, Pel* pRest, Int stride, Int formatShift);
+  Void reconstructCoefInfo(Int compIdx, ALFParam* alfLCUParam, Int** filterCoeff, Int* varIndTab= NULL);
+  Void reconstructCoefficients(ALFParam* alfLCUParam, Int** filterCoeff);
+  Void filterRegion(Int compIdx, Bool isSingleFilter, std::vector<AlfLCUInfo*>& regionLCUInfo, Pel* pDec, Pel* pRest, Int stride, Int formatShift);
+  Void filterOneCompRegion(Pel *imgRes, Pel *imgPad, Int stride, Bool isChroma, Int yPos, Int yPosEnd, Int xPos, Int xPosEnd, Int** filterSet, Int* mergeTable, Pel** varImg);  
+
+  Void InitAlfLCUInfo(AlfLCUInfo& rAlfLCU, Int sliceID, Int tileID, TComDataCU* pcCU, UInt maxNumSUInLCU);
+  Void checkFilterCoeffValue( Int *filter, Int filterLength, Bool isChroma );
+  Void extendBorderCoreFunction(Pel* pPel, Int stride, Bool* pbAvail, UInt width, UInt height, UInt extSize); //!< Extend slice boundary border  
+  Void copyRegion(std::vector<AlfLCUInfo*> &vpAlfLCU, Pel* pPicDst, Pel* pPicSrc, Int stride, Int formatShift = 0);
+  Void extendRegionBorder(std::vector<AlfLCUInfo*> &vpAlfLCU, Pel* pPelSrc, Int stride, Int formatShift = 0);
+  Void xPCMRestoration        (TComPic* pcPic);
+  Void xPCMCURestoration      (TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth);
+  Void xPCMSampleRestoration  (TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, TextType ttText);
+
+public: //public methods, interface functions
+
+  TComAdaptiveLoopFilter();
+  virtual ~TComAdaptiveLoopFilter() {}
+
+  Void create  ( Int iPicWidth, Int iPicHeight, UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxCUDepth );
+  Void destroy ();
+
+  Void ALFProcess          (TComPic* pcPic, ALFParam** alfParam, std::vector<Bool>* sliceAlfEnabled);
+  Int  getNumLCUInPicWidth ()  {return m_numLCUInPicWidth;}
+  Int  getNumLCUInPicHeight() {return m_numLCUInPicHeight;}
+
+  Int  getNumCUsInPic()  {return m_uiNumCUsInFrame;} //!< get number of LCU in picture for ALF process
+  Void createPicAlfInfo (TComPic* pcPic, Int numSlicesInPic = 1);
+  Void destroyPicAlfInfo();
+
+  Void PCMLFDisableProcess    ( TComPic* pcPic);                        ///< interface function for ALF process 
+
+};
+
+//! \}
+#endif
+
+#endif
Index: /trunk/source/Lib/TLibCommon/TComBitCounter.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComBitCounter.h	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComBitCounter.h	(revision 2)
@@ -0,0 +1,71 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComBitCounter.h
+    \brief    Class for counting bits (header)
+*/
+
+#ifndef __COMBITCOUNTER__
+#define __COMBITCOUNTER__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TComBitStream.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// class for counting bits
+class TComBitCounter : public TComBitIf
+{
+protected:
+  UInt  m_uiBitCounter;
+  
+public:
+  TComBitCounter()            {}
+  virtual ~TComBitCounter()   {}
+  
+  Void        write                 ( UInt uiBits, UInt uiNumberOfBits )  { m_uiBitCounter += uiNumberOfBits; }
+  Void        resetBits             ()                                    { m_uiBitCounter = 0;               }
+  UInt getNumberOfWrittenBits() const { return m_uiBitCounter; }
+};
+
+//! \}
+
+#endif
Index: /trunk/source/Lib/TLibCommon/TComBitStream.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComBitStream.cpp	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComBitStream.cpp	(revision 2)
@@ -0,0 +1,357 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComBitStream.cpp
+    \brief    class for handling bitstream
+*/
+
+#include <stdint.h>
+#include <vector>
+#include "TComBitStream.h"
+#include <string.h>
+#include <memory.h>
+
+using namespace std;
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TComOutputBitstream::TComOutputBitstream()
+{
+  m_fifo = new vector<uint8_t>;
+  clear();
+}
+
+TComOutputBitstream::~TComOutputBitstream()
+{
+  delete m_fifo;
+}
+
+TComInputBitstream::TComInputBitstream(std::vector<uint8_t>* buf)
+{
+  m_fifo = buf;
+  m_fifo_idx = 0;
+  m_held_bits = 0;
+  m_num_held_bits = 0;
+  m_numBitsRead = 0;
+}
+
+TComInputBitstream::~TComInputBitstream()
+{
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+char* TComOutputBitstream::getByteStream() const
+{
+  return (char*) &m_fifo->front();
+}
+
+unsigned int TComOutputBitstream::getByteStreamLength()
+{
+  return unsigned(m_fifo->size());
+}
+
+void TComOutputBitstream::clear()
+{
+  m_fifo->clear();
+  m_held_bits = 0;
+  m_num_held_bits = 0;
+}
+
+Void TComOutputBitstream::write   ( UInt uiBits, UInt uiNumberOfBits )
+{
+  assert( uiNumberOfBits <= 32 );
+
+  /* any modulo 8 remainder of num_total_bits cannot be written this time,
+   * and will be held until next time. */
+  unsigned num_total_bits = uiNumberOfBits + m_num_held_bits;
+  unsigned next_num_held_bits = num_total_bits % 8;
+
+  /* form a byte aligned word (write_bits), by concatenating any held bits
+   * with the new bits, discarding the bits that will form the next_held_bits.
+   * eg: H = held bits, V = n new bits        /---- next_held_bits
+   * len(H)=7, len(V)=1: ... ---- HHHH HHHV . 0000 0000, next_num_held_bits=0
+   * len(H)=7, len(V)=2: ... ---- HHHH HHHV . V000 0000, next_num_held_bits=1
+   * if total_bits < 8, the value of v_ is not used */
+  unsigned char next_held_bits = uiBits << (8 - next_num_held_bits);
+
+  if (!(num_total_bits >> 3))
+  {
+    /* insufficient bits accumulated to write out, append new_held_bits to
+     * current held_bits */
+    /* NB, this requires that v only contains 0 in bit positions {31..n} */
+    m_held_bits |= next_held_bits;
+    m_num_held_bits = next_num_held_bits;
+    return;
+  }
+
+  /* topword serves to justify held_bits to align with the msb of uiBits */
+  unsigned topword = (uiNumberOfBits - next_num_held_bits) & ~((1 << 3) -1);
+  unsigned int write_bits = (m_held_bits << topword) | (uiBits >> next_num_held_bits);
+
+  switch (num_total_bits >> 3)
+  {
+  case 4: m_fifo->push_back(write_bits >> 24);
+  case 3: m_fifo->push_back(write_bits >> 16);
+  case 2: m_fifo->push_back(write_bits >> 8);
+  case 1: m_fifo->push_back(write_bits);
+  }
+
+  m_held_bits = next_held_bits;
+  m_num_held_bits = next_num_held_bits;
+}
+
+Void TComOutputBitstream::writeAlignOne()
+{
+  unsigned int num_bits = getNumBitsUntilByteAligned();
+  write((1 << num_bits) - 1, num_bits);
+  return;
+}
+
+Void TComOutputBitstream::writeAlignZero()
+{
+  if (0 == m_num_held_bits)
+  {
+    return;
+  }
+  m_fifo->push_back(m_held_bits);
+  m_held_bits = 0;
+  m_num_held_bits = 0;
+}
+
+/**
+ - add substream to the end of the current bitstream
+ .
+ \param  pcSubstream  substream to be added
+ */
+Void   TComOutputBitstream::addSubstream( TComOutputBitstream* pcSubstream )
+{
+  UInt uiNumBits = pcSubstream->getNumberOfWrittenBits();
+
+  const vector<uint8_t>& rbsp = pcSubstream->getFIFO();
+  for (vector<uint8_t>::const_iterator it = rbsp.begin(); it != rbsp.end();)
+  {
+    write(*it++, 8);
+  }
+  if (uiNumBits&0x7)
+  {
+    write(pcSubstream->getHeldBits()>>(8-(uiNumBits&0x7)), uiNumBits&0x7);
+  }
+}
+#if BYTE_ALIGNMENT
+Void TComOutputBitstream::writeByteAlignment()
+{
+  write( 1, 1);
+  writeAlignZero();
+}
+#endif
+/**
+ * read #uiNumberOfBits# from bitstream without updating the bitstream
+ * state, storing the result in #ruiBits#.
+ *
+ * If reading #uiNumberOfBits# would overrun the bitstream buffer,
+ * the bitsream is effectively padded with sufficient zero-bits to
+ * avoid the overrun.
+ */
+Void TComInputBitstream::pseudoRead ( UInt uiNumberOfBits, UInt& ruiBits )
+{
+  unsigned int saved_num_held_bits = m_num_held_bits;
+  unsigned char saved_held_bits = m_held_bits;
+  unsigned int saved_fifo_idx = m_fifo_idx;
+
+  unsigned num_bits_to_read = min(uiNumberOfBits, getNumBitsLeft());
+  read(num_bits_to_read, ruiBits);
+  ruiBits <<= (uiNumberOfBits - num_bits_to_read);
+
+  m_fifo_idx = saved_fifo_idx;
+  m_held_bits = saved_held_bits;
+  m_num_held_bits = saved_num_held_bits;
+}
+
+
+Void TComInputBitstream::read (UInt uiNumberOfBits, UInt& ruiBits)
+{
+  assert( uiNumberOfBits <= 32 );
+  
+  m_numBitsRead += uiNumberOfBits;
+
+  /* NB, bits are extracted from the MSB of each byte. */
+  unsigned retval = 0;
+  if (uiNumberOfBits <= m_num_held_bits)
+  {
+    /* n=1, len(H)=7:   -VHH HHHH, shift_down=6, mask=0xfe
+     * n=3, len(H)=7:   -VVV HHHH, shift_down=4, mask=0xf8
+     */
+    retval = m_held_bits >> (m_num_held_bits - uiNumberOfBits);
+    retval &= ~(0xff << uiNumberOfBits);
+    m_num_held_bits -= uiNumberOfBits;
+    ruiBits = retval;
+    return;
+  }
+
+  /* all num_held_bits will go into retval
+   *   => need to mask leftover bits from previous extractions
+   *   => align retval with top of extracted word */
+  /* n=5, len(H)=3: ---- -VVV, mask=0x07, shift_up=5-3=2,
+   * n=9, len(H)=3: ---- -VVV, mask=0x07, shift_up=9-3=6 */
+  uiNumberOfBits -= m_num_held_bits;
+  retval = m_held_bits & ~(0xff << m_num_held_bits);
+  retval <<= uiNumberOfBits;
+
+  /* number of whole bytes that need to be loaded to form retval */
+  /* n=32, len(H)=0, load 4bytes, shift_down=0
+   * n=32, len(H)=1, load 4bytes, shift_down=1
+   * n=31, len(H)=1, load 4bytes, shift_down=1+1
+   * n=8,  len(H)=0, load 1byte,  shift_down=0
+   * n=8,  len(H)=3, load 1byte,  shift_down=3
+   * n=5,  len(H)=1, load 1byte,  shift_down=1+3
+   */
+  unsigned aligned_word = 0;
+  unsigned num_bytes_to_load = (uiNumberOfBits - 1) >> 3;
+  assert(m_fifo_idx + num_bytes_to_load < m_fifo->size());
+
+  switch (num_bytes_to_load)
+  {
+  case 3: aligned_word  = (*m_fifo)[m_fifo_idx++] << 24;
+  case 2: aligned_word |= (*m_fifo)[m_fifo_idx++] << 16;
+  case 1: aligned_word |= (*m_fifo)[m_fifo_idx++] <<  8;
+  case 0: aligned_word |= (*m_fifo)[m_fifo_idx++];
+  }
+
+  /* resolve remainder bits */
+  unsigned next_num_held_bits = (32 - uiNumberOfBits) % 8;
+
+  /* copy required part of aligned_word into retval */
+  retval |= aligned_word >> next_num_held_bits;
+
+  /* store held bits */
+  m_num_held_bits = next_num_held_bits;
+  m_held_bits = aligned_word;
+
+  ruiBits = retval;
+}
+
+/**
+ * insert the contents of the bytealigned (and flushed) bitstream src
+ * into this at byte position pos.
+ */
+void TComOutputBitstream::insertAt(const TComOutputBitstream& src, unsigned pos)
+{
+  unsigned src_bits = src.getNumberOfWrittenBits();
+  assert(0 == src_bits % 8);
+
+  vector<uint8_t>::iterator at = this->m_fifo->begin() + pos;
+  this->m_fifo->insert(at, src.m_fifo->begin(), src.m_fifo->end());
+}
+
+Void TComInputBitstream::readOutTrailingBits ()
+{
+  UInt uiBits = 0;
+
+  while ( ( getNumBitsLeft() > 0 ) && (getNumBitsUntilByteAligned()!=0) )
+  {
+    read ( 1, uiBits );
+  }
+}
+
+TComOutputBitstream& TComOutputBitstream::operator= (const TComOutputBitstream& src)
+{
+  vector<uint8_t>::iterator at = this->m_fifo->begin();
+  this->m_fifo->insert(at, src.m_fifo->begin(), src.m_fifo->end());
+
+  this->m_num_held_bits             = src.m_num_held_bits;
+  this->m_held_bits                 = src.m_held_bits;
+
+  return *this;
+}
+
+/**
+ - extract substream from the current bitstream
+ .
+ \param  pcBitstream  bitstream which contains substreams
+ \param  uiNumBits    number of bits to transfer
+ */
+TComInputBitstream *TComInputBitstream::extractSubstream( UInt uiNumBits )
+{
+  UInt uiNumBytes = uiNumBits/8;
+  std::vector<uint8_t>* buf = new std::vector<uint8_t>;
+  UInt uiByte;
+  for (UInt ui = 0; ui < uiNumBytes; ui++)
+  {
+    read(8, uiByte);
+    buf->push_back(uiByte);
+  }
+  if (uiNumBits&0x7)
+  {
+    uiByte = 0;
+    read(uiNumBits&0x7, uiByte);
+    uiByte <<= 8-(uiNumBits&0x7);
+    buf->push_back(uiByte);
+  }
+  return new TComInputBitstream(buf);
+}
+
+/**
+ - delete internal fifo
+ */
+Void TComInputBitstream::deleteFifo()
+{
+  delete m_fifo;
+  m_fifo = NULL;
+}
+
+#if BYTE_ALIGNMENT
+Void TComInputBitstream::readByteAlignment()
+{
+  UInt code = 0;
+  read( 1, code );
+  assert(code == 1);
+
+  UInt numBits = getNumBitsUntilByteAligned();
+  if(numBits)
+  {
+    assert(numBits <= getNumBitsLeft());
+    read( numBits, code );
+    assert(code == 0);
+  }
+}
+#endif
+
+//! \}
Index: /trunk/source/Lib/TLibCommon/TComBitStream.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComBitStream.h	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComBitStream.h	(revision 2)
@@ -0,0 +1,216 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComBitStream.h
+    \brief    class for handling bitstream (header)
+*/
+
+#ifndef __COMBITSTREAM__
+#define __COMBITSTREAM__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include <stdint.h>
+#include <vector>
+#include <stdio.h>
+#include <assert.h>
+#include "CommonDef.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// pure virtual class for basic bit handling
+class TComBitIf
+{
+public:
+  virtual Void        writeAlignOne         () {};
+  virtual Void        writeAlignZero        () {};
+  virtual Void        write                 ( UInt uiBits, UInt uiNumberOfBits )  = 0;
+  virtual Void        resetBits             ()                                    = 0;
+  virtual UInt getNumberOfWrittenBits() const = 0;
+  virtual ~TComBitIf() {}
+};
+
+/**
+ * Model of a writable bitstream that accumulates bits to produce a
+ * bytestream.
+ */
+class TComOutputBitstream : public TComBitIf
+{
+  /**
+   * FIFO for storage of bytes.  Use:
+   *  - fifo.push_back(x) to append words
+   *  - fifo.clear() to empty the FIFO
+   *  - &fifo.front() to get a pointer to the data array.
+   *    NB, this pointer is only valid until the next push_back()/clear()
+   */
+  std::vector<uint8_t> *m_fifo;
+
+  unsigned int m_num_held_bits; /// number of bits not flushed to bytestream.
+  unsigned char m_held_bits; /// the bits held and not flushed to bytestream.
+                             /// this value is always msb-aligned, bigendian.
+
+public:
+  // create / destroy
+  TComOutputBitstream();
+  ~TComOutputBitstream();
+
+  // interface for encoding
+  /**
+   * append uiNumberOfBits least significant bits of uiBits to
+   * the current bitstream
+   */
+  Void        write           ( UInt uiBits, UInt uiNumberOfBits );
+
+  /** insert one bits until the bitstream is byte-aligned */
+  Void        writeAlignOne   ();
+
+  /** insert zero bits until the bitstream is byte-aligned */
+  Void        writeAlignZero  ();
+
+  /** this function should never be called */
+  void resetBits() { assert(0); }
+
+  // utility functions
+
+  /**
+   * Return a pointer to the start of the byte-stream buffer.
+   * Pointer is valid until the next write/flush/reset call.
+   * NB, data is arranged such that subsequent bytes in the
+   * bytestream are stored in ascending addresses.
+   */
+  char* getByteStream() const;
+
+  /**
+   * Return the number of valid bytes available from  getByteStream()
+   */
+  unsigned int getByteStreamLength();
+
+  /**
+   * Reset all internal state.
+   */
+  Void clear();
+
+  /**
+   * returns the number of bits that need to be written to
+   * achieve byte alignment.
+   */
+  Int getNumBitsUntilByteAligned() { return (8 - m_num_held_bits) & 0x7; }
+
+  /**
+   * Return the number of bits that have been written since the last clear()
+   */
+  unsigned getNumberOfWrittenBits() const { return unsigned(m_fifo->size()) * 8 + m_num_held_bits; }
+
+  void insertAt(const TComOutputBitstream& src, unsigned pos);
+
+  /**
+   * Return a reference to the internal fifo
+   */
+  std::vector<uint8_t>& getFIFO() { return *m_fifo; }
+
+  UChar getHeldBits  ()          { return m_held_bits;          }
+
+  TComOutputBitstream& operator= (const TComOutputBitstream& src);
+  /** Return a reference to the internal fifo */
+  std::vector<uint8_t>& getFIFO() const { return *m_fifo; }
+
+  Void          addSubstream    ( TComOutputBitstream* pcSubstream );
+#if BYTE_ALIGNMENT
+  Void writeByteAlignment();
+#endif
+};
+
+/**
+ * Model of an input bitstream that extracts bits from a predefined
+ * bytestream.
+ */
+class TComInputBitstream
+{
+  std::vector<uint8_t> *m_fifo; /// FIFO for storage of complete bytes
+
+protected:
+  unsigned int m_fifo_idx; /// Read index into m_fifo
+
+  unsigned int m_num_held_bits;
+  unsigned char m_held_bits;
+  UInt  m_numBitsRead;
+
+public:
+  /**
+   * Create a new bitstream reader object that reads from #buf#.  Ownership
+   * of #buf# remains with the callee, although the constructed object
+   * will hold a reference to #buf#
+   */
+  TComInputBitstream(std::vector<uint8_t>* buf);
+  ~TComInputBitstream();
+
+  // interface for decoding
+  Void        pseudoRead      ( UInt uiNumberOfBits, UInt& ruiBits );
+  Void        read            ( UInt uiNumberOfBits, UInt& ruiBits );
+  Void        readByte        ( UInt &ruiBits )
+  {
+    assert(m_fifo_idx < m_fifo->size());
+    ruiBits = (*m_fifo)[m_fifo_idx++];
+  }
+
+  Void        readOutTrailingBits ();
+  UChar getHeldBits  ()          { return m_held_bits;          }
+  TComOutputBitstream& operator= (const TComOutputBitstream& src);
+  UInt  getByteLocation              ( )                     { return m_fifo_idx                    ; }
+
+  // Peek at bits in word-storage. Used in determining if we have completed reading of current bitstream and therefore slice in LCEC.
+  UInt        peekBits (UInt uiBits) { unsigned tmp; pseudoRead(uiBits, tmp); return tmp; }
+
+  // utility functions
+  unsigned read(unsigned numberOfBits) { UInt tmp; read(numberOfBits, tmp); return tmp; }
+  UInt     readByte() { UInt tmp; readByte( tmp ); return tmp; }
+  unsigned getNumBitsUntilByteAligned() { return m_num_held_bits & (0x7); }
+  unsigned getNumBitsLeft() { return 8*((unsigned)m_fifo->size() - m_fifo_idx) + m_num_held_bits; }
+  TComInputBitstream *extractSubstream( UInt uiNumBits ); // Read the nominated number of bits, and return as a bitstream.
+  Void                deleteFifo(); // Delete internal fifo of bitstream.
+  UInt  getNumBitsRead() { return m_numBitsRead; }
+#if BYTE_ALIGNMENT
+  Void readByteAlignment();
+#endif
+};
+
+//! \}
+
+#endif
Index: /trunk/source/Lib/TLibCommon/TComCABACTables.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComCABACTables.cpp	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComCABACTables.cpp	(revision 2)
@@ -0,0 +1,123 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComCABACTables.cpp
+ *  \brief    static class for CABAC tables
+ */
+
+#include "TComCABACTables.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+const UChar TComCABACTables::sm_aucLPSTable[64][4] =
+{
+  { 128, 176, 208, 240},
+  { 128, 167, 197, 227},
+  { 128, 158, 187, 216},
+  { 123, 150, 178, 205},
+  { 116, 142, 169, 195},
+  { 111, 135, 160, 185},
+  { 105, 128, 152, 175},
+  { 100, 122, 144, 166},
+  {  95, 116, 137, 158},
+  {  90, 110, 130, 150},
+  {  85, 104, 123, 142},
+  {  81,  99, 117, 135},
+  {  77,  94, 111, 128},
+  {  73,  89, 105, 122},
+  {  69,  85, 100, 116},
+  {  66,  80,  95, 110},
+  {  62,  76,  90, 104},
+  {  59,  72,  86,  99},
+  {  56,  69,  81,  94},
+  {  53,  65,  77,  89},
+  {  51,  62,  73,  85},
+  {  48,  59,  69,  80},
+  {  46,  56,  66,  76},
+  {  43,  53,  63,  72},
+  {  41,  50,  59,  69},
+  {  39,  48,  56,  65},
+  {  37,  45,  54,  62},
+  {  35,  43,  51,  59},
+  {  33,  41,  48,  56},
+  {  32,  39,  46,  53},
+  {  30,  37,  43,  50},
+  {  29,  35,  41,  48},
+  {  27,  33,  39,  45},
+  {  26,  31,  37,  43},
+  {  24,  30,  35,  41},
+  {  23,  28,  33,  39},
+  {  22,  27,  32,  37},
+  {  21,  26,  30,  35},
+  {  20,  24,  29,  33},
+  {  19,  23,  27,  31},
+  {  18,  22,  26,  30},
+  {  17,  21,  25,  28},
+  {  16,  20,  23,  27},
+  {  15,  19,  22,  25},
+  {  14,  18,  21,  24},
+  {  14,  17,  20,  23},
+  {  13,  16,  19,  22},
+  {  12,  15,  18,  21},
+  {  12,  14,  17,  20},
+  {  11,  14,  16,  19},
+  {  11,  13,  15,  18},
+  {  10,  12,  15,  17},
+  {  10,  12,  14,  16},
+  {   9,  11,  13,  15},
+  {   9,  11,  12,  14},
+  {   8,  10,  12,  14},
+  {   8,   9,  11,  13},
+  {   7,   9,  11,  12},
+  {   7,   9,  10,  12},
+  {   7,   8,  10,  11},
+  {   6,   8,   9,  11},
+  {   6,   7,   9,  10},
+  {   6,   7,   8,   9},
+  {   2,   2,   2,   2}
+};
+
+const UChar TComCABACTables::sm_aucRenormTable[32] =
+{
+  6,  5,  4,  4,
+  3,  3,  3,  3,
+  2,  2,  2,  2,
+  2,  2,  2,  2,
+  1,  1,  1,  1,
+  1,  1,  1,  1,
+  1,  1,  1,  1,
+  1,  1,  1,  1
+};
+
+//! \}
Index: /trunk/source/Lib/TLibCommon/TComCABACTables.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComCABACTables.h	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComCABACTables.h	(revision 2)
@@ -0,0 +1,60 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComCABACTables.h
+    \brief    static class for CABAC tables
+*/
+
+#ifndef __TCOM_CABAC_TABLES__
+#define __TCOM_CABAC_TABLES__
+
+#include "TLibCommon/CommonDef.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+/**
+ * \brief static class for CABAC tables
+ */
+
+class TComCABACTables
+{
+public:
+  const static UChar  sm_aucLPSTable[64][4];
+  const static UChar  sm_aucRenormTable[32];
+};
+
+
+//! \}
+
+#endif
Index: /trunk/source/Lib/TLibCommon/TComDataCU.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComDataCU.cpp	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComDataCU.cpp	(revision 2)
@@ -0,0 +1,4896 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComDataCU.cpp
+    \brief    CU data structure
+    \todo     not all entities are documented
+*/
+
+#include "TComDataCU.h"
+#include "TComPic.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+#if ADAPTIVE_QP_SELECTION
+Int * TComDataCU::m_pcGlbArlCoeffY  = NULL;
+Int * TComDataCU::m_pcGlbArlCoeffCb = NULL;
+Int * TComDataCU::m_pcGlbArlCoeffCr = NULL;
+#endif
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TComDataCU::TComDataCU()
+{
+  m_pcPic              = NULL;
+  m_pcSlice            = NULL;
+  m_puhDepth           = NULL;
+  
+#if SKIP_FLAG
+  m_skipFlag           = NULL;
+#endif
+
+  m_pePartSize         = NULL;
+  m_pePredMode         = NULL;
+  m_CUTransquantBypass = NULL;
+  m_puhWidth           = NULL;
+  m_puhHeight          = NULL;
+  m_phQP               = NULL;
+  m_pbMergeFlag        = NULL;
+  m_puhMergeIndex      = NULL;
+  m_puhLumaIntraDir    = NULL;
+  m_puhChromaIntraDir  = NULL;
+  m_puhInterDir        = NULL;
+  m_puhTrIdx           = NULL;
+#if !REMOVE_NSQT
+  m_nsqtPartIdx        = NULL;
+#endif
+  m_puhTransformSkip[0] = NULL;
+  m_puhTransformSkip[1] = NULL;
+  m_puhTransformSkip[2] = NULL;
+  m_puhCbf[0]          = NULL;
+  m_puhCbf[1]          = NULL;
+  m_puhCbf[2]          = NULL;
+  m_pcTrCoeffY         = NULL;
+  m_pcTrCoeffCb        = NULL;
+  m_pcTrCoeffCr        = NULL;
+#if ADAPTIVE_QP_SELECTION  
+  m_ArlCoeffIsAliasedAllocation = false;
+  m_pcArlCoeffY        = NULL;
+  m_pcArlCoeffCb       = NULL;
+  m_pcArlCoeffCr       = NULL;
+#endif
+  
+  m_pbIPCMFlag         = NULL;
+  m_pcIPCMSampleY      = NULL;
+  m_pcIPCMSampleCb     = NULL;
+  m_pcIPCMSampleCr     = NULL;
+
+  m_pcPattern          = NULL;
+  
+  m_pcCUAboveLeft      = NULL;
+  m_pcCUAboveRight     = NULL;
+  m_pcCUAbove          = NULL;
+  m_pcCULeft           = NULL;
+  
+  m_apcCUColocated[0]  = NULL;
+  m_apcCUColocated[1]  = NULL;
+  
+  m_apiMVPIdx[0]       = NULL;
+  m_apiMVPIdx[1]       = NULL;
+  m_apiMVPNum[0]       = NULL;
+  m_apiMVPNum[1]       = NULL;
+
+  m_lcuAlfEnabled[0]   = false;
+  m_lcuAlfEnabled[1]   = false;
+  m_lcuAlfEnabled[2]   = false;
+  m_bDecSubCu          = false;
+  m_uiSliceStartCU        = 0;
+  m_uiDependentSliceStartCU = 0;
+}
+
+TComDataCU::~TComDataCU()
+{
+}
+
+Void TComDataCU::create(UInt uiNumPartition, UInt uiWidth, UInt uiHeight, Bool bDecSubCu, Int unitSize
+#if ADAPTIVE_QP_SELECTION
+                        , Bool bGlobalRMARLBuffer
+#endif                                              
+                        )
+{
+  m_bDecSubCu = bDecSubCu;
+  
+  m_pcPic              = NULL;
+  m_pcSlice            = NULL;
+  m_uiNumPartition     = uiNumPartition;
+  m_unitSize = unitSize;
+  
+  if ( !bDecSubCu )
+  {
+    m_phQP               = (Char*     )xMalloc(Char,     uiNumPartition);
+    m_puhDepth           = (UChar*    )xMalloc(UChar,    uiNumPartition);
+    m_puhWidth           = (UChar*    )xMalloc(UChar,    uiNumPartition);
+    m_puhHeight          = (UChar*    )xMalloc(UChar,    uiNumPartition);
+
+#if SKIP_FLAG
+    m_skipFlag           = new Bool[ uiNumPartition ];
+#endif
+
+    m_pePartSize         = new Char[ uiNumPartition ];
+    memset( m_pePartSize, SIZE_NONE,uiNumPartition * sizeof( *m_pePartSize ) );
+    m_pePredMode         = new Char[ uiNumPartition ];
+    m_CUTransquantBypass = new Bool[ uiNumPartition ];
+    m_pbMergeFlag        = (Bool*  )xMalloc(Bool,   uiNumPartition);
+    m_puhMergeIndex      = (UChar* )xMalloc(UChar,  uiNumPartition);
+    m_puhLumaIntraDir    = (UChar* )xMalloc(UChar,  uiNumPartition);
+    m_puhChromaIntraDir  = (UChar* )xMalloc(UChar,  uiNumPartition);
+    m_puhInterDir        = (UChar* )xMalloc(UChar,  uiNumPartition);
+    
+    m_puhTrIdx           = (UChar* )xMalloc(UChar,  uiNumPartition);
+#if !REMOVE_NSQT
+    m_nsqtPartIdx        = (UChar* )xMalloc(UChar,  uiNumPartition);
+#endif
+    m_puhTransformSkip[0] = (UChar* )xMalloc(UChar,  uiNumPartition);
+    m_puhTransformSkip[1] = (UChar* )xMalloc(UChar,  uiNumPartition);
+    m_puhTransformSkip[2] = (UChar* )xMalloc(UChar,  uiNumPartition);
+
+    m_puhCbf[0]          = (UChar* )xMalloc(UChar,  uiNumPartition);
+    m_puhCbf[1]          = (UChar* )xMalloc(UChar,  uiNumPartition);
+    m_puhCbf[2]          = (UChar* )xMalloc(UChar,  uiNumPartition);
+    
+    m_apiMVPIdx[0]       = new Char[ uiNumPartition ];
+    m_apiMVPIdx[1]       = new Char[ uiNumPartition ];
+    m_apiMVPNum[0]       = new Char[ uiNumPartition ];
+    m_apiMVPNum[1]       = new Char[ uiNumPartition ];
+    memset( m_apiMVPIdx[0], -1,uiNumPartition * sizeof( Char ) );
+    memset( m_apiMVPIdx[1], -1,uiNumPartition * sizeof( Char ) );
+    
+    m_pcTrCoeffY         = (TCoeff*)xMalloc(TCoeff, uiWidth*uiHeight);
+    m_pcTrCoeffCb        = (TCoeff*)xMalloc(TCoeff, uiWidth*uiHeight/4);
+    m_pcTrCoeffCr        = (TCoeff*)xMalloc(TCoeff, uiWidth*uiHeight/4);
+    memset( m_pcTrCoeffY, 0,uiWidth*uiHeight * sizeof( TCoeff ) );
+    memset( m_pcTrCoeffCb, 0,uiWidth*uiHeight/4 * sizeof( TCoeff ) );
+    memset( m_pcTrCoeffCr, 0,uiWidth*uiHeight/4 * sizeof( TCoeff ) );
+#if ADAPTIVE_QP_SELECTION    
+    if( bGlobalRMARLBuffer )
+    {
+      if( m_pcGlbArlCoeffY == NULL )
+      {
+        m_pcGlbArlCoeffY   = (Int*)xMalloc(Int, uiWidth*uiHeight);
+        m_pcGlbArlCoeffCb  = (Int*)xMalloc(Int, uiWidth*uiHeight/4);
+        m_pcGlbArlCoeffCr  = (Int*)xMalloc(Int, uiWidth*uiHeight/4);
+      }
+      m_pcArlCoeffY        = m_pcGlbArlCoeffY;
+      m_pcArlCoeffCb       = m_pcGlbArlCoeffCb;
+      m_pcArlCoeffCr       = m_pcGlbArlCoeffCr;
+      m_ArlCoeffIsAliasedAllocation = true;
+    }
+    else
+    {
+      m_pcArlCoeffY        = (Int*)xMalloc(Int, uiWidth*uiHeight);
+      m_pcArlCoeffCb       = (Int*)xMalloc(Int, uiWidth*uiHeight/4);
+      m_pcArlCoeffCr       = (Int*)xMalloc(Int, uiWidth*uiHeight/4);
+    }
+#endif
+    
+    m_pbIPCMFlag         = (Bool*  )xMalloc(Bool, uiNumPartition);
+    m_pcIPCMSampleY      = (Pel*   )xMalloc(Pel , uiWidth*uiHeight);
+    m_pcIPCMSampleCb     = (Pel*   )xMalloc(Pel , uiWidth*uiHeight/4);
+    m_pcIPCMSampleCr     = (Pel*   )xMalloc(Pel , uiWidth*uiHeight/4);
+
+    m_acCUMvField[0].create( uiNumPartition );
+    m_acCUMvField[1].create( uiNumPartition );
+    
+  }
+  else
+  {
+    m_acCUMvField[0].setNumPartition(uiNumPartition );
+    m_acCUMvField[1].setNumPartition(uiNumPartition );
+  }
+  
+  m_uiSliceStartCU        = (UInt*  )xMalloc(UInt, uiNumPartition);
+  m_uiDependentSliceStartCU = (UInt*  )xMalloc(UInt, uiNumPartition);
+  
+  // create pattern memory
+  m_pcPattern            = (TComPattern*)xMalloc(TComPattern, 1);
+  
+  // create motion vector fields
+  
+  m_pcCUAboveLeft      = NULL;
+  m_pcCUAboveRight     = NULL;
+  m_pcCUAbove          = NULL;
+  m_pcCULeft           = NULL;
+  
+  m_apcCUColocated[0]  = NULL;
+  m_apcCUColocated[1]  = NULL;
+}
+
+Void TComDataCU::destroy()
+{
+  m_pcPic              = NULL;
+  m_pcSlice            = NULL;
+  
+  if ( m_pcPattern )
+  { 
+    xFree(m_pcPattern);
+    m_pcPattern = NULL;
+  }
+  
+  // encoder-side buffer free
+  if ( !m_bDecSubCu )
+  {
+    if ( m_phQP               ) { xFree(m_phQP);                m_phQP              = NULL; }
+    if ( m_puhDepth           ) { xFree(m_puhDepth);            m_puhDepth          = NULL; }
+    if ( m_puhWidth           ) { xFree(m_puhWidth);            m_puhWidth          = NULL; }
+    if ( m_puhHeight          ) { xFree(m_puhHeight);           m_puhHeight         = NULL; }
+
+#if SKIP_FLAG
+    if ( m_skipFlag           ) { delete[] m_skipFlag;          m_skipFlag          = NULL; }
+#endif
+
+    if ( m_pePartSize         ) { delete[] m_pePartSize;        m_pePartSize        = NULL; }
+    if ( m_pePredMode         ) { delete[] m_pePredMode;        m_pePredMode        = NULL; }
+    if ( m_CUTransquantBypass ) { delete[] m_CUTransquantBypass;m_CUTransquantBypass = NULL; }
+    if ( m_puhCbf[0]          ) { xFree(m_puhCbf[0]);           m_puhCbf[0]         = NULL; }
+    if ( m_puhCbf[1]          ) { xFree(m_puhCbf[1]);           m_puhCbf[1]         = NULL; }
+    if ( m_puhCbf[2]          ) { xFree(m_puhCbf[2]);           m_puhCbf[2]         = NULL; }
+    if ( m_puhInterDir        ) { xFree(m_puhInterDir);         m_puhInterDir       = NULL; }
+    if ( m_pbMergeFlag        ) { xFree(m_pbMergeFlag);         m_pbMergeFlag       = NULL; }
+    if ( m_puhMergeIndex      ) { xFree(m_puhMergeIndex);       m_puhMergeIndex     = NULL; }
+    if ( m_puhLumaIntraDir    ) { xFree(m_puhLumaIntraDir);     m_puhLumaIntraDir   = NULL; }
+    if ( m_puhChromaIntraDir  ) { xFree(m_puhChromaIntraDir);   m_puhChromaIntraDir = NULL; }
+    if ( m_puhTrIdx           ) { xFree(m_puhTrIdx);            m_puhTrIdx          = NULL; }
+#if !REMOVE_NSQT
+    if ( m_nsqtPartIdx        ) { xFree(m_nsqtPartIdx);         m_nsqtPartIdx       = NULL; }
+#endif
+    if ( m_puhTransformSkip[0]) { xFree(m_puhTransformSkip[0]); m_puhTransformSkip[0] = NULL; }
+    if ( m_puhTransformSkip[1]) { xFree(m_puhTransformSkip[1]); m_puhTransformSkip[1] = NULL; }
+    if ( m_puhTransformSkip[2]) { xFree(m_puhTransformSkip[2]); m_puhTransformSkip[2] = NULL; }
+    if ( m_pcTrCoeffY         ) { xFree(m_pcTrCoeffY);          m_pcTrCoeffY        = NULL; }
+    if ( m_pcTrCoeffCb        ) { xFree(m_pcTrCoeffCb);         m_pcTrCoeffCb       = NULL; }
+    if ( m_pcTrCoeffCr        ) { xFree(m_pcTrCoeffCr);         m_pcTrCoeffCr       = NULL; }
+#if ADAPTIVE_QP_SELECTION
+    if (!m_ArlCoeffIsAliasedAllocation)
+    {
+      xFree(m_pcArlCoeffY); m_pcArlCoeffY = 0;
+      xFree(m_pcArlCoeffCb); m_pcArlCoeffCb = 0;
+      xFree(m_pcArlCoeffCr); m_pcArlCoeffCr = 0;
+    }
+    if ( m_pcGlbArlCoeffY     ) { xFree(m_pcGlbArlCoeffY);      m_pcGlbArlCoeffY    = NULL; }
+    if ( m_pcGlbArlCoeffCb    ) { xFree(m_pcGlbArlCoeffCb);     m_pcGlbArlCoeffCb   = NULL; }
+    if ( m_pcGlbArlCoeffCr    ) { xFree(m_pcGlbArlCoeffCr);     m_pcGlbArlCoeffCr   = NULL; }
+#endif
+    if ( m_pbIPCMFlag         ) { xFree(m_pbIPCMFlag   );       m_pbIPCMFlag        = NULL; }
+    if ( m_pcIPCMSampleY      ) { xFree(m_pcIPCMSampleY);       m_pcIPCMSampleY     = NULL; }
+    if ( m_pcIPCMSampleCb     ) { xFree(m_pcIPCMSampleCb);      m_pcIPCMSampleCb    = NULL; }
+    if ( m_pcIPCMSampleCr     ) { xFree(m_pcIPCMSampleCr);      m_pcIPCMSampleCr    = NULL; }
+    if ( m_apiMVPIdx[0]       ) { delete[] m_apiMVPIdx[0];      m_apiMVPIdx[0]      = NULL; }
+    if ( m_apiMVPIdx[1]       ) { delete[] m_apiMVPIdx[1];      m_apiMVPIdx[1]      = NULL; }
+    if ( m_apiMVPNum[0]       ) { delete[] m_apiMVPNum[0];      m_apiMVPNum[0]      = NULL; }
+    if ( m_apiMVPNum[1]       ) { delete[] m_apiMVPNum[1];      m_apiMVPNum[1]      = NULL; }
+    
+    m_acCUMvField[0].destroy();
+    m_acCUMvField[1].destroy();
+    
+  }
+  
+  m_pcCUAboveLeft       = NULL;
+  m_pcCUAboveRight      = NULL;
+  m_pcCUAbove           = NULL;
+  m_pcCULeft            = NULL;
+  
+  m_apcCUColocated[0]   = NULL;
+  m_apcCUColocated[1]   = NULL;
+
+  if( m_uiSliceStartCU )
+  {
+    xFree(m_uiSliceStartCU);
+    m_uiSliceStartCU=NULL;
+  }
+  if(m_uiDependentSliceStartCU )
+  {
+    xFree(m_uiDependentSliceStartCU);
+    m_uiDependentSliceStartCU=NULL;
+  }
+}
+
+const NDBFBlockInfo& NDBFBlockInfo::operator= (const NDBFBlockInfo& src)
+{
+  this->tileID = src.tileID;
+  this->sliceID= src.sliceID;
+  this->startSU= src.startSU;
+  this->endSU  = src.endSU;
+  this->widthSU= src.widthSU;
+  this->heightSU=src.heightSU;
+  this->posX   = src.posX;
+  this->posY   = src.posY;
+  this->width  = src.width;
+  this->height = src.height;
+  ::memcpy(this->isBorderAvailable, src.isBorderAvailable, sizeof(Bool)*((Int)NUM_SGU_BORDER));
+  this->allBordersAvailable = src.allBordersAvailable;
+
+  return *this;
+}
+
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+// --------------------------------------------------------------------------------------------------------------------
+// Initialization
+// --------------------------------------------------------------------------------------------------------------------
+
+/**
+ - initialize top-level CU
+ - internal buffers are already created
+ - set values before encoding a CU
+ .
+ \param  pcPic     picture (TComPic) class pointer
+ \param  iCUAddr   CU address
+ */
+Void TComDataCU::initCU( TComPic* pcPic, UInt iCUAddr )
+{
+
+  m_pcPic              = pcPic;
+  m_pcSlice            = pcPic->getSlice(pcPic->getCurrSliceIdx());
+  m_uiCUAddr           = iCUAddr;
+  m_uiCUPelX           = ( iCUAddr % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth;
+  m_uiCUPelY           = ( iCUAddr / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight;
+  m_uiAbsIdxInLCU      = 0;
+  m_dTotalCost         = MAX_DOUBLE;
+  m_uiTotalDistortion  = 0;
+  m_uiTotalBits        = 0;
+  m_uiTotalBins        = 0;
+  m_uiNumPartition     = pcPic->getNumPartInCU();
+  m_numSucIPCM       = 0;
+  m_lastCUSucIPCMFlag   = false;
+
+#if SVC_EXTENSION
+  m_layerId          = pcPic->getLayerId();
+#endif 
+
+  for(int i=0; i<pcPic->getNumPartInCU(); i++) 
+  {
+    if(pcPic->getPicSym()->getInverseCUOrderMap(iCUAddr)*pcPic->getNumPartInCU()+i>=getSlice()->getSliceCurStartCUAddr())
+    {
+      m_uiSliceStartCU[i]=getSlice()->getSliceCurStartCUAddr();
+    }
+    else
+    {
+      m_uiSliceStartCU[i]=pcPic->getCU(getAddr())->m_uiSliceStartCU[i];
+    }
+  }
+  for(int i=0; i<pcPic->getNumPartInCU(); i++) 
+  {
+    if(pcPic->getPicSym()->getInverseCUOrderMap(iCUAddr)*pcPic->getNumPartInCU()+i>=getSlice()->getDependentSliceCurStartCUAddr())
+    {
+      m_uiDependentSliceStartCU[i]=getSlice()->getDependentSliceCurStartCUAddr();
+    }
+    else
+    {
+      m_uiDependentSliceStartCU[i]=pcPic->getCU(getAddr())->m_uiDependentSliceStartCU[i];
+    }
+  }
+
+  Int partStartIdx = getSlice()->getDependentSliceCurStartCUAddr() - pcPic->getPicSym()->getInverseCUOrderMap(iCUAddr) * pcPic->getNumPartInCU();
+
+  Int numElements = min<Int>( partStartIdx, m_uiNumPartition );
+  for ( Int ui = 0; ui < numElements; ui++ )
+  {
+    TComDataCU * pcFrom = pcPic->getCU(getAddr());
+#if SKIP_FLAG
+    m_skipFlag[ui]   = pcFrom->getSkipFlag(ui);
+#endif
+    m_pePartSize[ui] = pcFrom->getPartitionSize(ui);
+    m_pePredMode[ui] = pcFrom->getPredictionMode(ui);
+    m_CUTransquantBypass[ui] = pcFrom->getCUTransquantBypass(ui);
+    m_puhDepth[ui] = pcFrom->getDepth(ui);
+    m_puhWidth  [ui] = pcFrom->getWidth(ui);
+    m_puhHeight [ui] = pcFrom->getHeight(ui);
+    m_puhTrIdx  [ui] = pcFrom->getTransformIdx(ui);
+#if !REMOVE_NSQT
+    m_nsqtPartIdx[ui] = pcFrom->getNSQTPartIdx(ui);
+#endif
+    m_puhTransformSkip[0][ui] = pcFrom->getTransformSkip(ui,TEXT_LUMA);
+    m_puhTransformSkip[1][ui] = pcFrom->getTransformSkip(ui,TEXT_CHROMA_U);
+    m_puhTransformSkip[2][ui] = pcFrom->getTransformSkip(ui,TEXT_CHROMA_V);
+    m_apiMVPIdx[0][ui] = pcFrom->m_apiMVPIdx[0][ui];;
+    m_apiMVPIdx[1][ui] = pcFrom->m_apiMVPIdx[1][ui];
+    m_apiMVPNum[0][ui] = pcFrom->m_apiMVPNum[0][ui];
+    m_apiMVPNum[1][ui] = pcFrom->m_apiMVPNum[1][ui];
+    m_phQP[ui]=pcFrom->m_phQP[ui];
+    m_lcuAlfEnabled[0] = pcFrom->m_lcuAlfEnabled[0];
+    m_lcuAlfEnabled[1] = pcFrom->m_lcuAlfEnabled[1];
+    m_lcuAlfEnabled[2] = pcFrom->m_lcuAlfEnabled[2];
+    m_pbMergeFlag[ui]=pcFrom->m_pbMergeFlag[ui];
+    m_puhMergeIndex[ui]=pcFrom->m_puhMergeIndex[ui];
+    m_puhLumaIntraDir[ui]=pcFrom->m_puhLumaIntraDir[ui];
+    m_puhChromaIntraDir[ui]=pcFrom->m_puhChromaIntraDir[ui];
+    m_puhInterDir[ui]=pcFrom->m_puhInterDir[ui];
+    m_puhCbf[0][ui]=pcFrom->m_puhCbf[0][ui];
+    m_puhCbf[1][ui]=pcFrom->m_puhCbf[1][ui];
+    m_puhCbf[2][ui]=pcFrom->m_puhCbf[2][ui];
+    m_pbIPCMFlag[ui] = pcFrom->m_pbIPCMFlag[ui];
+  }
+  
+  Int firstElement = max<Int>( partStartIdx, 0 );
+  numElements = m_uiNumPartition - firstElement;
+  
+  if ( numElements > 0 )
+  {
+#if SKIP_FLAG
+    memset( m_skipFlag          + firstElement, false,                    numElements * sizeof( *m_skipFlag ) );
+#endif
+
+    memset( m_pePartSize        + firstElement, SIZE_NONE,                numElements * sizeof( *m_pePartSize ) );
+    memset( m_pePredMode        + firstElement, MODE_NONE,                numElements * sizeof( *m_pePredMode ) );
+    memset( m_CUTransquantBypass+ firstElement, false,                    numElements * sizeof( *m_CUTransquantBypass) );
+    memset( m_puhDepth          + firstElement, 0,                        numElements * sizeof( *m_puhDepth ) );
+    memset( m_puhTrIdx          + firstElement, 0,                        numElements * sizeof( *m_puhTrIdx ) );
+#if !REMOVE_NSQT
+    memset( m_nsqtPartIdx       + firstElement, 0,                        numElements * sizeof( *m_nsqtPartIdx) );
+#endif
+    memset( m_puhTransformSkip[0] + firstElement, 0,                      numElements * sizeof( *m_puhTransformSkip[0]) );
+    memset( m_puhTransformSkip[1] + firstElement, 0,                      numElements * sizeof( *m_puhTransformSkip[1]) );
+    memset( m_puhTransformSkip[2] + firstElement, 0,                      numElements * sizeof( *m_puhTransformSkip[2]) );
+    memset( m_puhWidth          + firstElement, g_uiMaxCUWidth,           numElements * sizeof( *m_puhWidth ) );
+    memset( m_puhHeight         + firstElement, g_uiMaxCUHeight,          numElements * sizeof( *m_puhHeight ) );
+    memset( m_apiMVPIdx[0]      + firstElement, -1,                       numElements * sizeof( *m_apiMVPIdx[0] ) );
+    memset( m_apiMVPIdx[1]      + firstElement, -1,                       numElements * sizeof( *m_apiMVPIdx[1] ) );
+    memset( m_apiMVPNum[0]      + firstElement, -1,                       numElements * sizeof( *m_apiMVPNum[0] ) );
+    memset( m_apiMVPNum[1]      + firstElement, -1,                       numElements * sizeof( *m_apiMVPNum[1] ) );
+    memset( m_phQP              + firstElement, getSlice()->getSliceQp(), numElements * sizeof( *m_phQP ) );
+    m_lcuAlfEnabled[0] = m_lcuAlfEnabled[1] = m_lcuAlfEnabled[2] = false;
+    memset( m_pbMergeFlag       + firstElement, false,                    numElements * sizeof( *m_pbMergeFlag ) );
+    memset( m_puhMergeIndex     + firstElement, 0,                        numElements * sizeof( *m_puhMergeIndex ) );
+    memset( m_puhLumaIntraDir   + firstElement, DC_IDX,                   numElements * sizeof( *m_puhLumaIntraDir ) );
+    memset( m_puhChromaIntraDir + firstElement, 0,                        numElements * sizeof( *m_puhChromaIntraDir ) );
+    memset( m_puhInterDir       + firstElement, 0,                        numElements * sizeof( *m_puhInterDir ) );
+    memset( m_puhCbf[0]         + firstElement, 0,                        numElements * sizeof( *m_puhCbf[0] ) );
+    memset( m_puhCbf[1]         + firstElement, 0,                        numElements * sizeof( *m_puhCbf[1] ) );
+    memset( m_puhCbf[2]         + firstElement, 0,                        numElements * sizeof( *m_puhCbf[2] ) );
+    memset( m_pbIPCMFlag        + firstElement, false,                    numElements * sizeof( *m_pbIPCMFlag ) );
+  }
+  
+  UInt uiTmp = g_uiMaxCUWidth*g_uiMaxCUHeight;
+  if ( 0 >= partStartIdx ) 
+  {
+    m_acCUMvField[0].clearMvField();
+    m_acCUMvField[1].clearMvField();
+    memset( m_pcTrCoeffY , 0, sizeof( TCoeff ) * uiTmp );
+#if ADAPTIVE_QP_SELECTION
+    memset( m_pcArlCoeffY , 0, sizeof( Int ) * uiTmp );  
+#endif
+    memset( m_pcIPCMSampleY , 0, sizeof( Pel ) * uiTmp );
+    uiTmp  >>= 2;
+    memset( m_pcTrCoeffCb, 0, sizeof( TCoeff ) * uiTmp );
+    memset( m_pcTrCoeffCr, 0, sizeof( TCoeff ) * uiTmp );
+#if ADAPTIVE_QP_SELECTION  
+    memset( m_pcArlCoeffCb, 0, sizeof( Int ) * uiTmp );
+    memset( m_pcArlCoeffCr, 0, sizeof( Int ) * uiTmp );
+#endif
+    memset( m_pcIPCMSampleCb , 0, sizeof( Pel ) * uiTmp );
+    memset( m_pcIPCMSampleCr , 0, sizeof( Pel ) * uiTmp );
+  }
+  else 
+  {
+    TComDataCU * pcFrom = pcPic->getCU(getAddr());
+    m_acCUMvField[0].copyFrom(&pcFrom->m_acCUMvField[0],m_uiNumPartition,0);
+    m_acCUMvField[1].copyFrom(&pcFrom->m_acCUMvField[1],m_uiNumPartition,0);
+    for(int i=0; i<uiTmp; i++) 
+    {
+      m_pcTrCoeffY[i]=pcFrom->m_pcTrCoeffY[i];
+#if ADAPTIVE_QP_SELECTION
+      m_pcArlCoeffY[i]=pcFrom->m_pcArlCoeffY[i];
+#endif
+      m_pcIPCMSampleY[i]=pcFrom->m_pcIPCMSampleY[i];
+    }
+    for(int i=0; i<(uiTmp>>2); i++) 
+    {
+      m_pcTrCoeffCb[i]=pcFrom->m_pcTrCoeffCb[i];
+      m_pcTrCoeffCr[i]=pcFrom->m_pcTrCoeffCr[i];
+#if ADAPTIVE_QP_SELECTION
+      m_pcArlCoeffCb[i]=pcFrom->m_pcArlCoeffCb[i];
+      m_pcArlCoeffCr[i]=pcFrom->m_pcArlCoeffCr[i];
+#endif
+      m_pcIPCMSampleCb[i]=pcFrom->m_pcIPCMSampleCb[i];
+      m_pcIPCMSampleCr[i]=pcFrom->m_pcIPCMSampleCr[i];
+    }
+  }
+
+  // Setting neighbor CU
+  m_pcCULeft        = NULL;
+  m_pcCUAbove       = NULL;
+  m_pcCUAboveLeft   = NULL;
+  m_pcCUAboveRight  = NULL;
+
+  m_apcCUColocated[0] = NULL;
+  m_apcCUColocated[1] = NULL;
+
+  UInt uiWidthInCU = pcPic->getFrameWidthInCU();
+  if ( m_uiCUAddr % uiWidthInCU )
+  {
+    m_pcCULeft = pcPic->getCU( m_uiCUAddr - 1 );
+  }
+
+  if ( m_uiCUAddr / uiWidthInCU )
+  {
+    m_pcCUAbove = pcPic->getCU( m_uiCUAddr - uiWidthInCU );
+  }
+
+  if ( m_pcCULeft && m_pcCUAbove )
+  {
+    m_pcCUAboveLeft = pcPic->getCU( m_uiCUAddr - uiWidthInCU - 1 );
+  }
+
+  if ( m_pcCUAbove && ( (m_uiCUAddr%uiWidthInCU) < (uiWidthInCU-1) )  )
+  {
+    m_pcCUAboveRight = pcPic->getCU( m_uiCUAddr - uiWidthInCU + 1 );
+  }
+
+  if ( getSlice()->getNumRefIdx( REF_PIC_LIST_0 ) > 0 )
+  {
+    m_apcCUColocated[0] = getSlice()->getRefPic( REF_PIC_LIST_0, 0)->getCU( m_uiCUAddr );
+  }
+
+  if ( getSlice()->getNumRefIdx( REF_PIC_LIST_1 ) > 0 )
+  {
+    m_apcCUColocated[1] = getSlice()->getRefPic( REF_PIC_LIST_1, 0)->getCU( m_uiCUAddr );
+  }
+}
+
+/** initialize prediction data with enabling sub-LCU-level delta QP
+*\param  uiDepth  depth of the current CU
+*\param  qp     qp for the current CU
+*- set CU width and CU height according to depth
+*- set qp value according to input qp 
+*- set last-coded qp value according to input last-coded qp 
+*/
+Void TComDataCU::initEstData( UInt uiDepth, Int qp )
+{
+  m_dTotalCost         = MAX_DOUBLE;
+  m_uiTotalDistortion  = 0;
+  m_uiTotalBits        = 0;
+  m_uiTotalBins        = 0;
+
+  UChar uhWidth  = g_uiMaxCUWidth  >> uiDepth;
+  UChar uhHeight = g_uiMaxCUHeight >> uiDepth;
+  m_lcuAlfEnabled[0] = m_lcuAlfEnabled[1] = m_lcuAlfEnabled[2] = false;
+
+  for (UInt ui = 0; ui < m_uiNumPartition; ui++)
+  {
+    if(getPic()->getPicSym()->getInverseCUOrderMap(getAddr())*m_pcPic->getNumPartInCU()+m_uiAbsIdxInLCU+ui >= getSlice()->getDependentSliceCurStartCUAddr())
+    {
+      m_apiMVPIdx[0][ui] = -1;
+      m_apiMVPIdx[1][ui] = -1;
+      m_apiMVPNum[0][ui] = -1;
+      m_apiMVPNum[1][ui] = -1;
+      m_puhDepth  [ui] = uiDepth;
+      m_puhWidth  [ui] = uhWidth;
+      m_puhHeight [ui] = uhHeight;
+      m_puhTrIdx  [ui] = 0;
+#if !REMOVE_NSQT
+      m_nsqtPartIdx[ui] = 0;
+#endif
+      m_puhTransformSkip[0][ui] = 0;
+      m_puhTransformSkip[1][ui] = 0;
+      m_puhTransformSkip[2][ui] = 0;
+#if SKIP_FLAG
+      m_skipFlag[ui]   = false;
+#endif
+      m_pePartSize[ui] = SIZE_NONE;
+      m_pePredMode[ui] = MODE_NONE;
+      m_CUTransquantBypass[ui] = false;
+      m_pbIPCMFlag[ui] = 0;
+      m_phQP[ui] = qp;
+      m_pbMergeFlag[ui] = 0;
+      m_puhMergeIndex[ui] = 0;
+      m_puhLumaIntraDir[ui] = DC_IDX;
+      m_puhChromaIntraDir[ui] = 0;
+      m_puhInterDir[ui] = 0;
+      m_puhCbf[0][ui] = 0;
+      m_puhCbf[1][ui] = 0;
+      m_puhCbf[2][ui] = 0;
+    }
+  }
+
+  UInt uiTmp = uhWidth*uhHeight;
+
+  if(getPic()->getPicSym()->getInverseCUOrderMap(getAddr())*m_pcPic->getNumPartInCU()+m_uiAbsIdxInLCU >= getSlice()->getDependentSliceCurStartCUAddr())
+  {
+    m_acCUMvField[0].clearMvField();
+    m_acCUMvField[1].clearMvField();
+    uiTmp = uhWidth*uhHeight;
+    
+    memset( m_pcTrCoeffY,    0, uiTmp * sizeof( *m_pcTrCoeffY    ) );
+#if ADAPTIVE_QP_SELECTION
+    memset( m_pcArlCoeffY ,  0, uiTmp * sizeof( *m_pcArlCoeffY   ) );
+#endif
+    memset( m_pcIPCMSampleY, 0, uiTmp * sizeof( *m_pcIPCMSampleY ) );
+
+    uiTmp>>=2;
+    memset( m_pcTrCoeffCb,    0, uiTmp * sizeof( *m_pcTrCoeffCb    ) );
+    memset( m_pcTrCoeffCr,    0, uiTmp * sizeof( *m_pcTrCoeffCr    ) );
+#if ADAPTIVE_QP_SELECTION  
+    memset( m_pcArlCoeffCb,   0, uiTmp * sizeof( *m_pcArlCoeffCb   ) );
+    memset( m_pcArlCoeffCr,   0, uiTmp * sizeof( *m_pcArlCoeffCr   ) );
+#endif
+    memset( m_pcIPCMSampleCb, 0, uiTmp * sizeof( *m_pcIPCMSampleCb ) );
+    memset( m_pcIPCMSampleCr, 0, uiTmp * sizeof( *m_pcIPCMSampleCr ) );
+  }
+}
+
+
+// initialize Sub partition
+Void TComDataCU::initSubCU( TComDataCU* pcCU, UInt uiPartUnitIdx, UInt uiDepth, Int qp )
+{
+  assert( uiPartUnitIdx<4 );
+
+  UInt uiPartOffset = ( pcCU->getTotalNumPart()>>2 )*uiPartUnitIdx;
+
+  m_pcPic              = pcCU->getPic();
+  m_pcSlice            = m_pcPic->getSlice(m_pcPic->getCurrSliceIdx());
+  m_uiCUAddr           = pcCU->getAddr();
+  m_uiAbsIdxInLCU      = pcCU->getZorderIdxInCU() + uiPartOffset;
+
+  m_uiCUPelX           = pcCU->getCUPelX() + ( g_uiMaxCUWidth>>uiDepth  )*( uiPartUnitIdx &  1 );
+  m_uiCUPelY           = pcCU->getCUPelY() + ( g_uiMaxCUHeight>>uiDepth  )*( uiPartUnitIdx >> 1 );
+
+  m_dTotalCost         = MAX_DOUBLE;
+  m_uiTotalDistortion  = 0;
+  m_uiTotalBits        = 0;
+  m_uiTotalBins        = 0;
+  m_uiNumPartition     = pcCU->getTotalNumPart() >> 2;
+
+  m_numSucIPCM       = 0;
+  m_lastCUSucIPCMFlag   = false;
+
+  Int iSizeInUchar = sizeof( UChar  ) * m_uiNumPartition;
+  Int iSizeInBool  = sizeof( Bool   ) * m_uiNumPartition;
+
+  Int sizeInChar = sizeof( Char  ) * m_uiNumPartition;
+  memset( m_phQP,              qp,  sizeInChar );
+
+  m_lcuAlfEnabled[0] = pcCU->m_lcuAlfEnabled[0];
+  m_lcuAlfEnabled[1] = pcCU->m_lcuAlfEnabled[1];
+  m_lcuAlfEnabled[2] = pcCU->m_lcuAlfEnabled[2];
+  memset( m_pbMergeFlag,        0, iSizeInBool  );
+  memset( m_puhMergeIndex,      0, iSizeInUchar );
+  memset( m_puhLumaIntraDir,    DC_IDX, iSizeInUchar );
+  memset( m_puhChromaIntraDir,  0, iSizeInUchar );
+  memset( m_puhInterDir,        0, iSizeInUchar );
+  memset( m_puhTrIdx,           0, iSizeInUchar );
+  memset( m_puhTransformSkip[0], 0, iSizeInUchar );
+  memset( m_puhTransformSkip[1], 0, iSizeInUchar );
+  memset( m_puhTransformSkip[2], 0, iSizeInUchar );
+  memset( m_puhCbf[0],          0, iSizeInUchar );
+  memset( m_puhCbf[1],          0, iSizeInUchar );
+  memset( m_puhCbf[2],          0, iSizeInUchar );
+  memset( m_puhDepth,     uiDepth, iSizeInUchar );
+
+  UChar uhWidth  = g_uiMaxCUWidth  >> uiDepth;
+  UChar uhHeight = g_uiMaxCUHeight >> uiDepth;
+  memset( m_puhWidth,          uhWidth,  iSizeInUchar );
+  memset( m_puhHeight,         uhHeight, iSizeInUchar );
+  memset( m_pbIPCMFlag,        0, iSizeInBool  );
+  for (UInt ui = 0; ui < m_uiNumPartition; ui++)
+  {
+#if SKIP_FLAG
+    m_skipFlag[ui]   = false;
+#endif
+    m_pePartSize[ui] = SIZE_NONE;
+    m_pePredMode[ui] = MODE_NONE;
+    m_CUTransquantBypass[ui] = false;
+    m_apiMVPIdx[0][ui] = -1;
+    m_apiMVPIdx[1][ui] = -1;
+    m_apiMVPNum[0][ui] = -1;
+    m_apiMVPNum[1][ui] = -1;
+    if(m_pcPic->getPicSym()->getInverseCUOrderMap(getAddr())*m_pcPic->getNumPartInCU()+m_uiAbsIdxInLCU+ui<getSlice()->getDependentSliceCurStartCUAddr())
+    {
+      m_apiMVPIdx[0][ui] = pcCU->m_apiMVPIdx[0][uiPartOffset+ui];
+      m_apiMVPIdx[1][ui] = pcCU->m_apiMVPIdx[1][uiPartOffset+ui];;
+      m_apiMVPNum[0][ui] = pcCU->m_apiMVPNum[0][uiPartOffset+ui];;
+      m_apiMVPNum[1][ui] = pcCU->m_apiMVPNum[1][uiPartOffset+ui];;
+      m_puhDepth  [ui] = pcCU->getDepth(uiPartOffset+ui);
+      m_puhWidth  [ui] = pcCU->getWidth(uiPartOffset+ui);
+      m_puhHeight  [ui] = pcCU->getHeight(uiPartOffset+ui);
+      m_puhTrIdx  [ui] = pcCU->getTransformIdx(uiPartOffset+ui);
+#if !REMOVE_NSQT
+      m_nsqtPartIdx[ui] = pcCU->getNSQTPartIdx(uiPartOffset+ui);
+#endif
+      m_puhTransformSkip[0][ui] = pcCU->getTransformSkip(uiPartOffset+ui,TEXT_LUMA);
+      m_puhTransformSkip[1][ui] = pcCU->getTransformSkip(uiPartOffset+ui,TEXT_CHROMA_U);
+      m_puhTransformSkip[2][ui] = pcCU->getTransformSkip(uiPartOffset+ui,TEXT_CHROMA_V);
+#if SKIP_FLAG
+      m_skipFlag[ui]   = pcCU->getSkipFlag(uiPartOffset+ui);
+#endif
+      m_pePartSize[ui] = pcCU->getPartitionSize(uiPartOffset+ui);
+      m_pePredMode[ui] = pcCU->getPredictionMode(uiPartOffset+ui);
+      m_CUTransquantBypass[ui] = pcCU->getCUTransquantBypass(uiPartOffset+ui);
+      m_pbIPCMFlag[ui]=pcCU->m_pbIPCMFlag[uiPartOffset+ui];
+      m_phQP[ui] = pcCU->m_phQP[uiPartOffset+ui];
+      m_pbMergeFlag[ui]=pcCU->m_pbMergeFlag[uiPartOffset+ui];
+      m_puhMergeIndex[ui]=pcCU->m_puhMergeIndex[uiPartOffset+ui];
+      m_puhLumaIntraDir[ui]=pcCU->m_puhLumaIntraDir[uiPartOffset+ui];
+      m_puhChromaIntraDir[ui]=pcCU->m_puhChromaIntraDir[uiPartOffset+ui];
+      m_puhInterDir[ui]=pcCU->m_puhInterDir[uiPartOffset+ui];
+      m_puhCbf[0][ui]=pcCU->m_puhCbf[0][uiPartOffset+ui];
+      m_puhCbf[1][ui]=pcCU->m_puhCbf[1][uiPartOffset+ui];
+      m_puhCbf[2][ui]=pcCU->m_puhCbf[2][uiPartOffset+ui];
+
+    }
+  }
+  UInt uiTmp = uhWidth*uhHeight;
+  memset( m_pcTrCoeffY , 0, sizeof(TCoeff)*uiTmp );
+#if ADAPTIVE_QP_SELECTION  
+  memset( m_pcArlCoeffY , 0, sizeof(Int)*uiTmp );
+#endif
+  memset( m_pcIPCMSampleY , 0, sizeof( Pel ) * uiTmp );
+  uiTmp >>= 2;
+  memset( m_pcTrCoeffCb, 0, sizeof(TCoeff)*uiTmp );
+  memset( m_pcTrCoeffCr, 0, sizeof(TCoeff)*uiTmp );
+#if ADAPTIVE_QP_SELECTION
+  memset( m_pcArlCoeffCb, 0, sizeof(Int)*uiTmp );
+  memset( m_pcArlCoeffCr, 0, sizeof(Int)*uiTmp );
+#endif
+  memset( m_pcIPCMSampleCb , 0, sizeof( Pel ) * uiTmp );
+  memset( m_pcIPCMSampleCr , 0, sizeof( Pel ) * uiTmp );
+  m_acCUMvField[0].clearMvField();
+  m_acCUMvField[1].clearMvField();
+
+  if(m_pcPic->getPicSym()->getInverseCUOrderMap(getAddr())*m_pcPic->getNumPartInCU()+m_uiAbsIdxInLCU<getSlice()->getDependentSliceCurStartCUAddr())
+  {
+    // Part of this CU contains data from an older slice. Now copy in that data.
+    UInt uiMaxCuWidth=pcCU->getSlice()->getSPS()->getMaxCUWidth();
+    UInt uiMaxCuHeight=pcCU->getSlice()->getSPS()->getMaxCUHeight();
+    TComDataCU * bigCU = getPic()->getCU(getAddr());
+    Int minui = uiPartOffset;
+    minui = -minui;
+    pcCU->m_acCUMvField[0].copyTo(&m_acCUMvField[0],minui,uiPartOffset,m_uiNumPartition);
+    pcCU->m_acCUMvField[1].copyTo(&m_acCUMvField[1],minui,uiPartOffset,m_uiNumPartition);
+    UInt uiCoffOffset = uiMaxCuWidth*uiMaxCuHeight*m_uiAbsIdxInLCU/pcCU->getPic()->getNumPartInCU();
+    uiTmp = uhWidth*uhHeight;
+    for(int i=0; i<uiTmp; i++) 
+    {
+      m_pcTrCoeffY[i]=bigCU->m_pcTrCoeffY[uiCoffOffset+i];
+#if ADAPTIVE_QP_SELECTION
+      m_pcArlCoeffY[i]=bigCU->m_pcArlCoeffY[uiCoffOffset+i];
+#endif
+      m_pcIPCMSampleY[i]=bigCU->m_pcIPCMSampleY[uiCoffOffset+i];
+    }
+    uiTmp>>=2;
+    uiCoffOffset>>=2;
+    for(int i=0; i<uiTmp; i++) 
+    {
+      m_pcTrCoeffCr[i]=bigCU->m_pcTrCoeffCr[uiCoffOffset+i];
+      m_pcTrCoeffCb[i]=bigCU->m_pcTrCoeffCb[uiCoffOffset+i];
+#if ADAPTIVE_QP_SELECTION
+      m_pcArlCoeffCr[i]=bigCU->m_pcArlCoeffCr[uiCoffOffset+i];
+      m_pcArlCoeffCb[i]=bigCU->m_pcArlCoeffCb[uiCoffOffset+i];
+#endif
+      m_pcIPCMSampleCb[i]=bigCU->m_pcIPCMSampleCb[uiCoffOffset+i];
+      m_pcIPCMSampleCr[i]=bigCU->m_pcIPCMSampleCr[uiCoffOffset+i];
+    }
+  }
+
+  m_pcCULeft        = pcCU->getCULeft();
+  m_pcCUAbove       = pcCU->getCUAbove();
+  m_pcCUAboveLeft   = pcCU->getCUAboveLeft();
+  m_pcCUAboveRight  = pcCU->getCUAboveRight();
+
+  m_apcCUColocated[0] = pcCU->getCUColocated(REF_PIC_LIST_0);
+  m_apcCUColocated[1] = pcCU->getCUColocated(REF_PIC_LIST_1);
+  memcpy(m_uiSliceStartCU,pcCU->m_uiSliceStartCU+uiPartOffset,sizeof(UInt)*m_uiNumPartition);
+  memcpy(m_uiDependentSliceStartCU,pcCU->m_uiDependentSliceStartCU+uiPartOffset,sizeof(UInt)*m_uiNumPartition);
+}
+
+Void TComDataCU::setOutsideCUPart( UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiNumPartition = m_uiNumPartition >> (uiDepth << 1);
+  UInt uiSizeInUchar = sizeof( UChar  ) * uiNumPartition;
+
+  UChar uhWidth  = g_uiMaxCUWidth  >> uiDepth;
+  UChar uhHeight = g_uiMaxCUHeight >> uiDepth;
+  memset( m_puhDepth    + uiAbsPartIdx,     uiDepth,  uiSizeInUchar );
+  memset( m_puhWidth    + uiAbsPartIdx,     uhWidth,  uiSizeInUchar );
+  memset( m_puhHeight   + uiAbsPartIdx,     uhHeight, uiSizeInUchar );
+}
+
+// --------------------------------------------------------------------------------------------------------------------
+// Copy
+// --------------------------------------------------------------------------------------------------------------------
+
+Void TComDataCU::copySubCU( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiPart = uiAbsPartIdx;
+  
+  m_pcPic              = pcCU->getPic();
+  m_pcSlice            = pcCU->getSlice();
+  m_uiCUAddr           = pcCU->getAddr();
+  m_uiAbsIdxInLCU      = uiAbsPartIdx;
+  
+  m_uiCUPelX           = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
+  m_uiCUPelY           = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
+  
+  UInt uiWidth         = g_uiMaxCUWidth  >> uiDepth;
+  UInt uiHeight        = g_uiMaxCUHeight >> uiDepth;
+  
+#if SKIP_FLAG
+  m_skipFlag=pcCU->getSkipFlag()          + uiPart;
+#endif
+
+  m_phQP=pcCU->getQP()                    + uiPart;
+  m_pePartSize = pcCU->getPartitionSize() + uiPart;
+  m_pePredMode=pcCU->getPredictionMode()  + uiPart;
+  m_CUTransquantBypass  = pcCU->getCUTransquantBypass()+uiPart;
+  
+  m_pbMergeFlag         = pcCU->getMergeFlag()        + uiPart;
+  m_puhMergeIndex       = pcCU->getMergeIndex()       + uiPart;
+
+  m_puhLumaIntraDir     = pcCU->getLumaIntraDir()     + uiPart;
+  m_puhChromaIntraDir   = pcCU->getChromaIntraDir()   + uiPart;
+  m_puhInterDir         = pcCU->getInterDir()         + uiPart;
+  m_puhTrIdx            = pcCU->getTransformIdx()     + uiPart;
+#if !REMOVE_NSQT
+  m_nsqtPartIdx         = pcCU->getNSQTPartIdx()      + uiPart;
+#endif
+  m_puhTransformSkip[0] = pcCU->getTransformSkip(TEXT_LUMA)     + uiPart;
+  m_puhTransformSkip[1] = pcCU->getTransformSkip(TEXT_CHROMA_U) + uiPart;
+  m_puhTransformSkip[2] = pcCU->getTransformSkip(TEXT_CHROMA_V) + uiPart;
+
+  m_puhCbf[0]= pcCU->getCbf(TEXT_LUMA)            + uiPart;
+  m_puhCbf[1]= pcCU->getCbf(TEXT_CHROMA_U)        + uiPart;
+  m_puhCbf[2]= pcCU->getCbf(TEXT_CHROMA_V)        + uiPart;
+  
+  m_puhDepth=pcCU->getDepth()                     + uiPart;
+  m_puhWidth=pcCU->getWidth()                     + uiPart;
+  m_puhHeight=pcCU->getHeight()                   + uiPart;
+  
+  m_apiMVPIdx[0]=pcCU->getMVPIdx(REF_PIC_LIST_0)  + uiPart;
+  m_apiMVPIdx[1]=pcCU->getMVPIdx(REF_PIC_LIST_1)  + uiPart;
+  m_apiMVPNum[0]=pcCU->getMVPNum(REF_PIC_LIST_0)  + uiPart;
+  m_apiMVPNum[1]=pcCU->getMVPNum(REF_PIC_LIST_1)  + uiPart;
+  
+  m_pbIPCMFlag         = pcCU->getIPCMFlag()        + uiPart;
+
+  m_pcCUAboveLeft      = pcCU->getCUAboveLeft();
+  m_pcCUAboveRight     = pcCU->getCUAboveRight();
+  m_pcCUAbove          = pcCU->getCUAbove();
+  m_pcCULeft           = pcCU->getCULeft();
+  
+  m_apcCUColocated[0] = pcCU->getCUColocated(REF_PIC_LIST_0);
+  m_apcCUColocated[1] = pcCU->getCUColocated(REF_PIC_LIST_1);
+  
+  UInt uiTmp = uiWidth*uiHeight;
+  UInt uiMaxCuWidth=pcCU->getSlice()->getSPS()->getMaxCUWidth();
+  UInt uiMaxCuHeight=pcCU->getSlice()->getSPS()->getMaxCUHeight();
+  
+  UInt uiCoffOffset = uiMaxCuWidth*uiMaxCuHeight*uiAbsPartIdx/pcCU->getPic()->getNumPartInCU();
+  
+  m_pcTrCoeffY = pcCU->getCoeffY() + uiCoffOffset;
+#if ADAPTIVE_QP_SELECTION
+  m_pcArlCoeffY= pcCU->getArlCoeffY() + uiCoffOffset;  
+#endif
+  m_pcIPCMSampleY = pcCU->getPCMSampleY() + uiCoffOffset;
+
+  uiTmp >>= 2;
+  uiCoffOffset >>=2;
+  m_pcTrCoeffCb=pcCU->getCoeffCb() + uiCoffOffset;
+  m_pcTrCoeffCr=pcCU->getCoeffCr() + uiCoffOffset;
+#if ADAPTIVE_QP_SELECTION  
+  m_pcArlCoeffCb=pcCU->getArlCoeffCb() + uiCoffOffset;
+  m_pcArlCoeffCr=pcCU->getArlCoeffCr() + uiCoffOffset;
+#endif
+  m_pcIPCMSampleCb = pcCU->getPCMSampleCb() + uiCoffOffset;
+  m_pcIPCMSampleCr = pcCU->getPCMSampleCr() + uiCoffOffset;
+
+  m_acCUMvField[0].linkToWithOffset( pcCU->getCUMvField(REF_PIC_LIST_0), uiPart );
+  m_acCUMvField[1].linkToWithOffset( pcCU->getCUMvField(REF_PIC_LIST_1), uiPart );
+  memcpy(m_uiSliceStartCU,pcCU->m_uiSliceStartCU+uiPart,sizeof(UInt)*m_uiNumPartition);
+  memcpy(m_uiDependentSliceStartCU,pcCU->m_uiDependentSliceStartCU+uiPart,sizeof(UInt)*m_uiNumPartition);
+}
+
+// Copy inter prediction info from the biggest CU
+Void TComDataCU::copyInterPredInfoFrom    ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefPicList )
+{
+  m_pcPic              = pcCU->getPic();
+  m_pcSlice            = pcCU->getSlice();
+  m_uiCUAddr           = pcCU->getAddr();
+  m_uiAbsIdxInLCU      = uiAbsPartIdx;
+  
+  Int iRastPartIdx     = g_auiZscanToRaster[uiAbsPartIdx];
+  m_uiCUPelX           = pcCU->getCUPelX() + m_pcPic->getMinCUWidth ()*( iRastPartIdx % m_pcPic->getNumPartInWidth() );
+  m_uiCUPelY           = pcCU->getCUPelY() + m_pcPic->getMinCUHeight()*( iRastPartIdx / m_pcPic->getNumPartInWidth() );
+  
+  m_pcCUAboveLeft      = pcCU->getCUAboveLeft();
+  m_pcCUAboveRight     = pcCU->getCUAboveRight();
+  m_pcCUAbove          = pcCU->getCUAbove();
+  m_pcCULeft           = pcCU->getCULeft();
+  
+  m_apcCUColocated[0]  = pcCU->getCUColocated(REF_PIC_LIST_0);
+  m_apcCUColocated[1]  = pcCU->getCUColocated(REF_PIC_LIST_1);
+  
+#if SKIP_FLAG
+  m_skipFlag           = pcCU->getSkipFlag ()             + uiAbsPartIdx;
+#endif
+
+  m_pePartSize         = pcCU->getPartitionSize ()        + uiAbsPartIdx;
+  m_pePredMode         = pcCU->getPredictionMode()        + uiAbsPartIdx;
+  m_CUTransquantBypass = pcCU->getCUTransquantBypass()    + uiAbsPartIdx;
+  m_puhInterDir        = pcCU->getInterDir      ()        + uiAbsPartIdx;
+  
+  m_puhDepth           = pcCU->getDepth ()                + uiAbsPartIdx;
+  m_puhWidth           = pcCU->getWidth ()                + uiAbsPartIdx;
+  m_puhHeight          = pcCU->getHeight()                + uiAbsPartIdx;
+  
+  m_pbMergeFlag        = pcCU->getMergeFlag()             + uiAbsPartIdx;
+  m_puhMergeIndex      = pcCU->getMergeIndex()            + uiAbsPartIdx;
+
+  m_apiMVPIdx[eRefPicList] = pcCU->getMVPIdx(eRefPicList) + uiAbsPartIdx;
+  m_apiMVPNum[eRefPicList] = pcCU->getMVPNum(eRefPicList) + uiAbsPartIdx;
+  
+  m_acCUMvField[ eRefPicList ].linkToWithOffset( pcCU->getCUMvField(eRefPicList), uiAbsPartIdx );
+
+  memcpy(m_uiSliceStartCU,pcCU->m_uiSliceStartCU+uiAbsPartIdx,sizeof(UInt)*m_uiNumPartition);
+  memcpy(m_uiDependentSliceStartCU,pcCU->m_uiDependentSliceStartCU+uiAbsPartIdx,sizeof(UInt)*m_uiNumPartition);
+}
+
+// Copy small CU to bigger CU.
+// One of quarter parts overwritten by predicted sub part.
+Void TComDataCU::copyPartFrom( TComDataCU* pcCU, UInt uiPartUnitIdx, UInt uiDepth )
+{
+  assert( uiPartUnitIdx<4 );
+  
+  m_dTotalCost         += pcCU->getTotalCost();
+  m_uiTotalDistortion  += pcCU->getTotalDistortion();
+  m_uiTotalBits        += pcCU->getTotalBits();
+  
+  UInt uiOffset         = pcCU->getTotalNumPart()*uiPartUnitIdx;
+  
+  UInt uiNumPartition = pcCU->getTotalNumPart();
+  Int iSizeInUchar  = sizeof( UChar ) * uiNumPartition;
+  Int iSizeInBool   = sizeof( Bool  ) * uiNumPartition;
+  
+  Int sizeInChar  = sizeof( Char ) * uiNumPartition;
+#if SKIP_FLAG
+  memcpy( m_skipFlag   + uiOffset, pcCU->getSkipFlag(),       sizeof( *m_skipFlag )   * uiNumPartition );
+#endif
+  memcpy( m_phQP       + uiOffset, pcCU->getQP(),             sizeInChar                        );
+  memcpy( m_pePartSize + uiOffset, pcCU->getPartitionSize(),  sizeof( *m_pePartSize ) * uiNumPartition );
+  memcpy( m_pePredMode + uiOffset, pcCU->getPredictionMode(), sizeof( *m_pePredMode ) * uiNumPartition );
+  memcpy( m_CUTransquantBypass + uiOffset, pcCU->getCUTransquantBypass(), sizeof( *m_CUTransquantBypass ) * uiNumPartition );
+  m_lcuAlfEnabled[0] = pcCU->m_lcuAlfEnabled[0];
+  m_lcuAlfEnabled[1] = pcCU->m_lcuAlfEnabled[1];
+  m_lcuAlfEnabled[2] = pcCU->m_lcuAlfEnabled[2];
+  memcpy( m_pbMergeFlag         + uiOffset, pcCU->getMergeFlag(),         iSizeInBool  );
+  memcpy( m_puhMergeIndex       + uiOffset, pcCU->getMergeIndex(),        iSizeInUchar );
+  memcpy( m_puhLumaIntraDir     + uiOffset, pcCU->getLumaIntraDir(),      iSizeInUchar );
+  memcpy( m_puhChromaIntraDir   + uiOffset, pcCU->getChromaIntraDir(),    iSizeInUchar );
+  memcpy( m_puhInterDir         + uiOffset, pcCU->getInterDir(),          iSizeInUchar );
+  memcpy( m_puhTrIdx            + uiOffset, pcCU->getTransformIdx(),      iSizeInUchar );
+#if !REMOVE_NSQT
+  memcpy( m_nsqtPartIdx         + uiOffset, pcCU->getNSQTPartIdx(),       iSizeInUchar );
+#endif
+  memcpy( m_puhTransformSkip[0] + uiOffset, pcCU->getTransformSkip(TEXT_LUMA),     iSizeInUchar );
+  memcpy( m_puhTransformSkip[1] + uiOffset, pcCU->getTransformSkip(TEXT_CHROMA_U), iSizeInUchar );
+  memcpy( m_puhTransformSkip[2] + uiOffset, pcCU->getTransformSkip(TEXT_CHROMA_V), iSizeInUchar );
+
+  memcpy( m_puhCbf[0] + uiOffset, pcCU->getCbf(TEXT_LUMA)    , iSizeInUchar );
+  memcpy( m_puhCbf[1] + uiOffset, pcCU->getCbf(TEXT_CHROMA_U), iSizeInUchar );
+  memcpy( m_puhCbf[2] + uiOffset, pcCU->getCbf(TEXT_CHROMA_V), iSizeInUchar );
+  
+  memcpy( m_puhDepth  + uiOffset, pcCU->getDepth(),  iSizeInUchar );
+  memcpy( m_puhWidth  + uiOffset, pcCU->getWidth(),  iSizeInUchar );
+  memcpy( m_puhHeight + uiOffset, pcCU->getHeight(), iSizeInUchar );
+  
+  memcpy( m_apiMVPIdx[0] + uiOffset, pcCU->getMVPIdx(REF_PIC_LIST_0), iSizeInUchar );
+  memcpy( m_apiMVPIdx[1] + uiOffset, pcCU->getMVPIdx(REF_PIC_LIST_1), iSizeInUchar );
+  memcpy( m_apiMVPNum[0] + uiOffset, pcCU->getMVPNum(REF_PIC_LIST_0), iSizeInUchar );
+  memcpy( m_apiMVPNum[1] + uiOffset, pcCU->getMVPNum(REF_PIC_LIST_1), iSizeInUchar );
+  
+  memcpy( m_pbIPCMFlag + uiOffset, pcCU->getIPCMFlag(), iSizeInBool );
+
+  m_pcCUAboveLeft      = pcCU->getCUAboveLeft();
+  m_pcCUAboveRight     = pcCU->getCUAboveRight();
+  m_pcCUAbove          = pcCU->getCUAbove();
+  m_pcCULeft           = pcCU->getCULeft();
+  
+  m_apcCUColocated[0] = pcCU->getCUColocated(REF_PIC_LIST_0);
+  m_apcCUColocated[1] = pcCU->getCUColocated(REF_PIC_LIST_1);
+  
+  m_acCUMvField[0].copyFrom( pcCU->getCUMvField( REF_PIC_LIST_0 ), pcCU->getTotalNumPart(), uiOffset );
+  m_acCUMvField[1].copyFrom( pcCU->getCUMvField( REF_PIC_LIST_1 ), pcCU->getTotalNumPart(), uiOffset );
+  
+  UInt uiTmp  = g_uiMaxCUWidth*g_uiMaxCUHeight >> (uiDepth<<1);
+  UInt uiTmp2 = uiPartUnitIdx*uiTmp;
+  memcpy( m_pcTrCoeffY  + uiTmp2, pcCU->getCoeffY(),  sizeof(TCoeff)*uiTmp );
+#if ADAPTIVE_QP_SELECTION
+  memcpy( m_pcArlCoeffY  + uiTmp2, pcCU->getArlCoeffY(),  sizeof(Int)*uiTmp );
+#endif
+  memcpy( m_pcIPCMSampleY + uiTmp2 , pcCU->getPCMSampleY(), sizeof(Pel) * uiTmp );
+
+  uiTmp >>= 2; uiTmp2>>= 2;
+  memcpy( m_pcTrCoeffCb + uiTmp2, pcCU->getCoeffCb(), sizeof(TCoeff)*uiTmp );
+  memcpy( m_pcTrCoeffCr + uiTmp2, pcCU->getCoeffCr(), sizeof(TCoeff)*uiTmp );
+#if ADAPTIVE_QP_SELECTION
+  memcpy( m_pcArlCoeffCb + uiTmp2, pcCU->getArlCoeffCb(), sizeof(Int)*uiTmp );
+  memcpy( m_pcArlCoeffCr + uiTmp2, pcCU->getArlCoeffCr(), sizeof(Int)*uiTmp );
+#endif
+  memcpy( m_pcIPCMSampleCb + uiTmp2 , pcCU->getPCMSampleCb(), sizeof(Pel) * uiTmp );
+  memcpy( m_pcIPCMSampleCr + uiTmp2 , pcCU->getPCMSampleCr(), sizeof(Pel) * uiTmp );
+  m_uiTotalBins += pcCU->getTotalBins();
+  memcpy( m_uiSliceStartCU        + uiOffset, pcCU->m_uiSliceStartCU,        sizeof( UInt ) * uiNumPartition  );
+  memcpy( m_uiDependentSliceStartCU + uiOffset, pcCU->m_uiDependentSliceStartCU, sizeof( UInt ) * uiNumPartition  );
+}
+
+// Copy current predicted part to a CU in picture.
+// It is used to predict for next part
+Void TComDataCU::copyToPic( UChar uhDepth )
+{
+  TComDataCU*& rpcCU = m_pcPic->getCU( m_uiCUAddr );
+  
+  rpcCU->getTotalCost()       = m_dTotalCost;
+  rpcCU->getTotalDistortion() = m_uiTotalDistortion;
+  rpcCU->getTotalBits()       = m_uiTotalBits;
+  
+  Int iSizeInUchar  = sizeof( UChar ) * m_uiNumPartition;
+  Int iSizeInBool   = sizeof( Bool  ) * m_uiNumPartition;
+  
+  Int sizeInChar  = sizeof( Char ) * m_uiNumPartition;
+
+#if SKIP_FLAG
+  memcpy( rpcCU->getSkipFlag() + m_uiAbsIdxInLCU, m_skipFlag, sizeof( *m_skipFlag ) * m_uiNumPartition );
+#endif
+
+  memcpy( rpcCU->getQP() + m_uiAbsIdxInLCU, m_phQP, sizeInChar  );
+
+  memcpy( rpcCU->getPartitionSize()  + m_uiAbsIdxInLCU, m_pePartSize, sizeof( *m_pePartSize ) * m_uiNumPartition );
+  memcpy( rpcCU->getPredictionMode() + m_uiAbsIdxInLCU, m_pePredMode, sizeof( *m_pePredMode ) * m_uiNumPartition );
+  memcpy( rpcCU->getCUTransquantBypass()+ m_uiAbsIdxInLCU, m_CUTransquantBypass, sizeof( *m_CUTransquantBypass ) * m_uiNumPartition );
+  rpcCU->m_lcuAlfEnabled[0] = m_lcuAlfEnabled[0];
+  rpcCU->m_lcuAlfEnabled[1] = m_lcuAlfEnabled[1];
+  rpcCU->m_lcuAlfEnabled[2] = m_lcuAlfEnabled[2];
+  memcpy( rpcCU->getMergeFlag()         + m_uiAbsIdxInLCU, m_pbMergeFlag,         iSizeInBool  );
+  memcpy( rpcCU->getMergeIndex()        + m_uiAbsIdxInLCU, m_puhMergeIndex,       iSizeInUchar );
+  memcpy( rpcCU->getLumaIntraDir()      + m_uiAbsIdxInLCU, m_puhLumaIntraDir,     iSizeInUchar );
+  memcpy( rpcCU->getChromaIntraDir()    + m_uiAbsIdxInLCU, m_puhChromaIntraDir,   iSizeInUchar );
+  memcpy( rpcCU->getInterDir()          + m_uiAbsIdxInLCU, m_puhInterDir,         iSizeInUchar );
+  memcpy( rpcCU->getTransformIdx()      + m_uiAbsIdxInLCU, m_puhTrIdx,            iSizeInUchar );
+#if !REMOVE_NSQT
+  memcpy( rpcCU->getNSQTPartIdx()       + m_uiAbsIdxInLCU, m_nsqtPartIdx,         iSizeInUchar );
+#endif
+  memcpy( rpcCU->getTransformSkip(TEXT_LUMA)     + m_uiAbsIdxInLCU, m_puhTransformSkip[0], iSizeInUchar );
+  memcpy( rpcCU->getTransformSkip(TEXT_CHROMA_U) + m_uiAbsIdxInLCU, m_puhTransformSkip[1], iSizeInUchar );
+  memcpy( rpcCU->getTransformSkip(TEXT_CHROMA_V) + m_uiAbsIdxInLCU, m_puhTransformSkip[2], iSizeInUchar );
+
+  memcpy( rpcCU->getCbf(TEXT_LUMA)     + m_uiAbsIdxInLCU, m_puhCbf[0], iSizeInUchar );
+  memcpy( rpcCU->getCbf(TEXT_CHROMA_U) + m_uiAbsIdxInLCU, m_puhCbf[1], iSizeInUchar );
+  memcpy( rpcCU->getCbf(TEXT_CHROMA_V) + m_uiAbsIdxInLCU, m_puhCbf[2], iSizeInUchar );
+  
+  memcpy( rpcCU->getDepth()  + m_uiAbsIdxInLCU, m_puhDepth,  iSizeInUchar );
+  memcpy( rpcCU->getWidth()  + m_uiAbsIdxInLCU, m_puhWidth,  iSizeInUchar );
+  memcpy( rpcCU->getHeight() + m_uiAbsIdxInLCU, m_puhHeight, iSizeInUchar );
+  
+  memcpy( rpcCU->getMVPIdx(REF_PIC_LIST_0) + m_uiAbsIdxInLCU, m_apiMVPIdx[0], iSizeInUchar );
+  memcpy( rpcCU->getMVPIdx(REF_PIC_LIST_1) + m_uiAbsIdxInLCU, m_apiMVPIdx[1], iSizeInUchar );
+  memcpy( rpcCU->getMVPNum(REF_PIC_LIST_0) + m_uiAbsIdxInLCU, m_apiMVPNum[0], iSizeInUchar );
+  memcpy( rpcCU->getMVPNum(REF_PIC_LIST_1) + m_uiAbsIdxInLCU, m_apiMVPNum[1], iSizeInUchar );
+  
+  m_acCUMvField[0].copyTo( rpcCU->getCUMvField( REF_PIC_LIST_0 ), m_uiAbsIdxInLCU );
+  m_acCUMvField[1].copyTo( rpcCU->getCUMvField( REF_PIC_LIST_1 ), m_uiAbsIdxInLCU );
+  
+  memcpy( rpcCU->getIPCMFlag() + m_uiAbsIdxInLCU, m_pbIPCMFlag,         iSizeInBool  );
+
+  UInt uiTmp  = (g_uiMaxCUWidth*g_uiMaxCUHeight)>>(uhDepth<<1);
+  UInt uiTmp2 = m_uiAbsIdxInLCU*m_pcPic->getMinCUWidth()*m_pcPic->getMinCUHeight();
+  memcpy( rpcCU->getCoeffY()  + uiTmp2, m_pcTrCoeffY,  sizeof(TCoeff)*uiTmp  );
+#if ADAPTIVE_QP_SELECTION  
+  memcpy( rpcCU->getArlCoeffY()  + uiTmp2, m_pcArlCoeffY,  sizeof(Int)*uiTmp  );
+#endif
+  memcpy( rpcCU->getPCMSampleY() + uiTmp2 , m_pcIPCMSampleY, sizeof(Pel)*uiTmp );
+
+  uiTmp >>= 2; uiTmp2 >>= 2;
+  memcpy( rpcCU->getCoeffCb() + uiTmp2, m_pcTrCoeffCb, sizeof(TCoeff)*uiTmp  );
+  memcpy( rpcCU->getCoeffCr() + uiTmp2, m_pcTrCoeffCr, sizeof(TCoeff)*uiTmp  );
+#if ADAPTIVE_QP_SELECTION
+  memcpy( rpcCU->getArlCoeffCb() + uiTmp2, m_pcArlCoeffCb, sizeof(Int)*uiTmp  );
+  memcpy( rpcCU->getArlCoeffCr() + uiTmp2, m_pcArlCoeffCr, sizeof(Int)*uiTmp  );
+#endif
+  memcpy( rpcCU->getPCMSampleCb() + uiTmp2 , m_pcIPCMSampleCb, sizeof( Pel ) * uiTmp );
+  memcpy( rpcCU->getPCMSampleCr() + uiTmp2 , m_pcIPCMSampleCr, sizeof( Pel ) * uiTmp );
+  rpcCU->getTotalBins() = m_uiTotalBins;
+  memcpy( rpcCU->m_uiSliceStartCU        + m_uiAbsIdxInLCU, m_uiSliceStartCU,        sizeof( UInt ) * m_uiNumPartition  );
+  memcpy( rpcCU->m_uiDependentSliceStartCU + m_uiAbsIdxInLCU, m_uiDependentSliceStartCU, sizeof( UInt ) * m_uiNumPartition  );
+}
+
+Void TComDataCU::copyToPic( UChar uhDepth, UInt uiPartIdx, UInt uiPartDepth )
+{
+  TComDataCU*&  rpcCU       = m_pcPic->getCU( m_uiCUAddr );
+  UInt          uiQNumPart  = m_uiNumPartition>>(uiPartDepth<<1);
+  
+  UInt uiPartStart          = uiPartIdx*uiQNumPart;
+  UInt uiPartOffset         = m_uiAbsIdxInLCU + uiPartStart;
+  
+  rpcCU->getTotalCost()       = m_dTotalCost;
+  rpcCU->getTotalDistortion() = m_uiTotalDistortion;
+  rpcCU->getTotalBits()       = m_uiTotalBits;
+  
+  Int iSizeInUchar  = sizeof( UChar  ) * uiQNumPart;
+  Int iSizeInBool   = sizeof( Bool   ) * uiQNumPart;
+  
+  Int sizeInChar  = sizeof( Char ) * uiQNumPart;
+#if SKIP_FLAG
+  memcpy( rpcCU->getSkipFlag()       + uiPartOffset, m_skipFlag,   sizeof( *m_skipFlag )   * uiQNumPart );
+#endif
+
+  memcpy( rpcCU->getQP() + uiPartOffset, m_phQP, sizeInChar );
+  memcpy( rpcCU->getPartitionSize()  + uiPartOffset, m_pePartSize, sizeof( *m_pePartSize ) * uiQNumPart );
+  memcpy( rpcCU->getPredictionMode() + uiPartOffset, m_pePredMode, sizeof( *m_pePredMode ) * uiQNumPart );
+  memcpy( rpcCU->getCUTransquantBypass()+ uiPartOffset, m_CUTransquantBypass, sizeof( *m_CUTransquantBypass ) * uiQNumPart );
+  rpcCU->m_lcuAlfEnabled[0] = m_lcuAlfEnabled[0];
+  rpcCU->m_lcuAlfEnabled[1] = m_lcuAlfEnabled[1];
+  rpcCU->m_lcuAlfEnabled[2] = m_lcuAlfEnabled[2];
+  memcpy( rpcCU->getMergeFlag()         + uiPartOffset, m_pbMergeFlag,         iSizeInBool  );
+  memcpy( rpcCU->getMergeIndex()        + uiPartOffset, m_puhMergeIndex,       iSizeInUchar );
+  memcpy( rpcCU->getLumaIntraDir()      + uiPartOffset, m_puhLumaIntraDir,     iSizeInUchar );
+  memcpy( rpcCU->getChromaIntraDir()    + uiPartOffset, m_puhChromaIntraDir,   iSizeInUchar );
+  memcpy( rpcCU->getInterDir()          + uiPartOffset, m_puhInterDir,         iSizeInUchar );
+  memcpy( rpcCU->getTransformIdx()      + uiPartOffset, m_puhTrIdx,            iSizeInUchar );
+#if !REMOVE_NSQT
+  memcpy( rpcCU->getNSQTPartIdx()       + uiPartOffset, m_nsqtPartIdx,         iSizeInUchar );
+#endif
+  memcpy( rpcCU->getTransformSkip(TEXT_LUMA)     + uiPartOffset, m_puhTransformSkip[0], iSizeInUchar );
+  memcpy( rpcCU->getTransformSkip(TEXT_CHROMA_U) + uiPartOffset, m_puhTransformSkip[1], iSizeInUchar );
+  memcpy( rpcCU->getTransformSkip(TEXT_CHROMA_V) + uiPartOffset, m_puhTransformSkip[2], iSizeInUchar );
+  memcpy( rpcCU->getCbf(TEXT_LUMA)     + uiPartOffset, m_puhCbf[0], iSizeInUchar );
+  memcpy( rpcCU->getCbf(TEXT_CHROMA_U) + uiPartOffset, m_puhCbf[1], iSizeInUchar );
+  memcpy( rpcCU->getCbf(TEXT_CHROMA_V) + uiPartOffset, m_puhCbf[2], iSizeInUchar );
+  
+  memcpy( rpcCU->getDepth()  + uiPartOffset, m_puhDepth,  iSizeInUchar );
+  memcpy( rpcCU->getWidth()  + uiPartOffset, m_puhWidth,  iSizeInUchar );
+  memcpy( rpcCU->getHeight() + uiPartOffset, m_puhHeight, iSizeInUchar );
+  
+  memcpy( rpcCU->getMVPIdx(REF_PIC_LIST_0) + uiPartOffset, m_apiMVPIdx[0], iSizeInUchar );
+  memcpy( rpcCU->getMVPIdx(REF_PIC_LIST_1) + uiPartOffset, m_apiMVPIdx[1], iSizeInUchar );
+  memcpy( rpcCU->getMVPNum(REF_PIC_LIST_0) + uiPartOffset, m_apiMVPNum[0], iSizeInUchar );
+  memcpy( rpcCU->getMVPNum(REF_PIC_LIST_1) + uiPartOffset, m_apiMVPNum[1], iSizeInUchar );
+  m_acCUMvField[0].copyTo( rpcCU->getCUMvField( REF_PIC_LIST_0 ), m_uiAbsIdxInLCU, uiPartStart, uiQNumPart );
+  m_acCUMvField[1].copyTo( rpcCU->getCUMvField( REF_PIC_LIST_1 ), m_uiAbsIdxInLCU, uiPartStart, uiQNumPart );
+  
+  memcpy( rpcCU->getIPCMFlag() + uiPartOffset, m_pbIPCMFlag,         iSizeInBool  );
+
+  UInt uiTmp  = (g_uiMaxCUWidth*g_uiMaxCUHeight)>>((uhDepth+uiPartDepth)<<1);
+  UInt uiTmp2 = uiPartOffset*m_pcPic->getMinCUWidth()*m_pcPic->getMinCUHeight();
+  memcpy( rpcCU->getCoeffY()  + uiTmp2, m_pcTrCoeffY,  sizeof(TCoeff)*uiTmp  );
+#if ADAPTIVE_QP_SELECTION
+  memcpy( rpcCU->getArlCoeffY()  + uiTmp2, m_pcArlCoeffY,  sizeof(Int)*uiTmp  );
+#endif
+ 
+  memcpy( rpcCU->getPCMSampleY() + uiTmp2 , m_pcIPCMSampleY, sizeof( Pel ) * uiTmp );
+
+  uiTmp >>= 2; uiTmp2 >>= 2;
+  memcpy( rpcCU->getCoeffCb() + uiTmp2, m_pcTrCoeffCb, sizeof(TCoeff)*uiTmp  );
+  memcpy( rpcCU->getCoeffCr() + uiTmp2, m_pcTrCoeffCr, sizeof(TCoeff)*uiTmp  );
+#if ADAPTIVE_QP_SELECTION
+  memcpy( rpcCU->getArlCoeffCb() + uiTmp2, m_pcArlCoeffCb, sizeof(Int)*uiTmp  );
+  memcpy( rpcCU->getArlCoeffCr() + uiTmp2, m_pcArlCoeffCr, sizeof(Int)*uiTmp  );
+#endif
+
+  memcpy( rpcCU->getPCMSampleCb() + uiTmp2 , m_pcIPCMSampleCb, sizeof( Pel ) * uiTmp );
+  memcpy( rpcCU->getPCMSampleCr() + uiTmp2 , m_pcIPCMSampleCr, sizeof( Pel ) * uiTmp );
+  rpcCU->getTotalBins() = m_uiTotalBins;
+  memcpy( rpcCU->m_uiSliceStartCU        + uiPartOffset, m_uiSliceStartCU,        sizeof( UInt ) * uiQNumPart  );
+  memcpy( rpcCU->m_uiDependentSliceStartCU + uiPartOffset, m_uiDependentSliceStartCU, sizeof( UInt ) * uiQNumPart  );
+}
+
+// --------------------------------------------------------------------------------------------------------------------
+// Other public functions
+// --------------------------------------------------------------------------------------------------------------------
+
+TComDataCU* TComDataCU::getPULeft( UInt& uiLPartUnitIdx, 
+                                   UInt uiCurrPartUnitIdx, 
+                                   Bool bEnforceSliceRestriction, 
+                                   Bool bEnforceDependentSliceRestriction,
+                                   Bool bEnforceTileRestriction )
+{
+  UInt uiAbsPartIdx       = g_auiZscanToRaster[uiCurrPartUnitIdx];
+  UInt uiAbsZorderCUIdx   = g_auiZscanToRaster[m_uiAbsIdxInLCU];
+  UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
+  
+  if ( !RasterAddress::isZeroCol( uiAbsPartIdx, uiNumPartInCUWidth ) )
+  {
+    uiLPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx - 1 ];
+    if ( RasterAddress::isEqualCol( uiAbsPartIdx, uiAbsZorderCUIdx, uiNumPartInCUWidth ) )
+    {
+#if !REMOVE_FGS
+      TComDataCU* pcTempReconCU = m_pcPic->getCU( getAddr() );
+      if ((bEnforceSliceRestriction        && (pcTempReconCU==NULL || pcTempReconCU->getSlice() == NULL || pcTempReconCU->getSCUAddr()+uiLPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU       (uiCurrPartUnitIdx)))
+        ||(bEnforceDependentSliceRestriction && (pcTempReconCU==NULL || pcTempReconCU->getSlice() == NULL || pcTempReconCU->getSCUAddr()+uiLPartUnitIdx < m_pcPic->getCU( getAddr() )->getDependentSliceStartCU(uiCurrPartUnitIdx))))
+      {
+        return NULL;
+      }
+#endif
+      return m_pcPic->getCU( getAddr() );
+    }
+    else
+    {
+      uiLPartUnitIdx -= m_uiAbsIdxInLCU;
+#if !REMOVE_FGS
+      if ((bEnforceSliceRestriction        && (this->getSCUAddr()+uiLPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU       (uiCurrPartUnitIdx) || m_pcSlice==NULL))
+        ||(bEnforceDependentSliceRestriction && (this->getSCUAddr()+uiLPartUnitIdx < m_pcPic->getCU( getAddr() )->getDependentSliceStartCU(uiCurrPartUnitIdx) || m_pcSlice==NULL)))
+      {
+        return NULL;
+      }
+#endif
+      return this;
+    }
+  }
+  
+  uiLPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx + uiNumPartInCUWidth - 1 ];
+
+
+  if ( (bEnforceSliceRestriction && (m_pcCULeft==NULL || m_pcCULeft->getSlice()==NULL || m_pcCULeft->getSCUAddr()+uiLPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx)))
+      ||
+       (bEnforceDependentSliceRestriction && (m_pcCULeft==NULL || m_pcCULeft->getSlice()==NULL || m_pcCULeft->getSCUAddr()+uiLPartUnitIdx < m_pcPic->getCU( getAddr() )->getDependentSliceStartCU(uiCurrPartUnitIdx)))
+      ||
+       (bEnforceTileRestriction && ( m_pcCULeft==NULL || m_pcCULeft->getSlice()==NULL || (m_pcPic->getPicSym()->getTileIdxMap( m_pcCULeft->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))  )  )
+      )
+  {
+    return NULL;
+  }
+  return m_pcCULeft;
+}
+
+
+TComDataCU* TComDataCU::getPUAbove( UInt& uiAPartUnitIdx, 
+                                    UInt uiCurrPartUnitIdx, 
+                                    Bool bEnforceSliceRestriction, 
+                                    Bool bEnforceDependentSliceRestriction, 
+                                    Bool MotionDataCompresssion,
+                                    Bool planarAtLCUBoundary ,
+                                    Bool bEnforceTileRestriction )
+{
+  UInt uiAbsPartIdx       = g_auiZscanToRaster[uiCurrPartUnitIdx];
+  UInt uiAbsZorderCUIdx   = g_auiZscanToRaster[m_uiAbsIdxInLCU];
+  UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
+  
+  if ( !RasterAddress::isZeroRow( uiAbsPartIdx, uiNumPartInCUWidth ) )
+  {
+    uiAPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx - uiNumPartInCUWidth ];
+    if ( RasterAddress::isEqualRow( uiAbsPartIdx, uiAbsZorderCUIdx, uiNumPartInCUWidth ) )
+    {
+#if !REMOVE_FGS
+      TComDataCU* pcTempReconCU = m_pcPic->getCU( getAddr() );
+      if ((bEnforceSliceRestriction        && (pcTempReconCU==NULL || pcTempReconCU->getSlice() == NULL || pcTempReconCU->getSCUAddr()+uiAPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU       (uiCurrPartUnitIdx)))
+        ||(bEnforceDependentSliceRestriction && (pcTempReconCU==NULL || pcTempReconCU->getSlice() == NULL || pcTempReconCU->getSCUAddr()+uiAPartUnitIdx < m_pcPic->getCU( getAddr() )->getDependentSliceStartCU(uiCurrPartUnitIdx))))
+      {
+        return NULL;
+      }
+#endif
+      return m_pcPic->getCU( getAddr() );
+    }
+    else
+    {
+      uiAPartUnitIdx -= m_uiAbsIdxInLCU;
+#if !REMOVE_FGS
+      if ((bEnforceSliceRestriction        && (this->getSCUAddr()+uiAPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU       (uiCurrPartUnitIdx) || m_pcSlice==NULL))
+        ||(bEnforceDependentSliceRestriction && (this->getSCUAddr()+uiAPartUnitIdx < m_pcPic->getCU( getAddr() )->getDependentSliceStartCU(uiCurrPartUnitIdx) || m_pcSlice==NULL)))
+      {
+        return NULL;
+      }
+#endif
+      return this;
+    }
+  }
+
+  if(planarAtLCUBoundary)
+  {
+    return NULL;
+  }
+  
+  uiAPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx + m_pcPic->getNumPartInCU() - uiNumPartInCUWidth ];
+  if(MotionDataCompresssion)
+  {
+    uiAPartUnitIdx = g_motionRefer[uiAPartUnitIdx];
+  }
+
+  if ( (bEnforceSliceRestriction && (m_pcCUAbove==NULL || m_pcCUAbove->getSlice()==NULL || m_pcCUAbove->getSCUAddr()+uiAPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx)))
+      ||
+       (bEnforceDependentSliceRestriction && (m_pcCUAbove==NULL || m_pcCUAbove->getSlice()==NULL || m_pcCUAbove->getSCUAddr()+uiAPartUnitIdx < m_pcPic->getCU( getAddr() )->getDependentSliceStartCU(uiCurrPartUnitIdx)))
+      ||
+       (bEnforceTileRestriction &&(m_pcCUAbove==NULL || m_pcCUAbove->getSlice()==NULL || (m_pcPic->getPicSym()->getTileIdxMap( m_pcCUAbove->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))))
+      )
+  {
+    return NULL;
+  }
+  return m_pcCUAbove;
+}
+
+TComDataCU* TComDataCU::getPUAboveLeft( UInt& uiALPartUnitIdx, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction, Bool bEnforceDependentSliceRestriction, Bool MotionDataCompresssion )
+{
+  UInt uiAbsPartIdx       = g_auiZscanToRaster[uiCurrPartUnitIdx];
+  UInt uiAbsZorderCUIdx   = g_auiZscanToRaster[m_uiAbsIdxInLCU];
+  UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
+  
+  if ( !RasterAddress::isZeroCol( uiAbsPartIdx, uiNumPartInCUWidth ) )
+  {
+    if ( !RasterAddress::isZeroRow( uiAbsPartIdx, uiNumPartInCUWidth ) )
+    {
+      uiALPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx - uiNumPartInCUWidth - 1 ];
+      if ( RasterAddress::isEqualRowOrCol( uiAbsPartIdx, uiAbsZorderCUIdx, uiNumPartInCUWidth ) )
+      {
+#if !REMOVE_FGS
+        TComDataCU* pcTempReconCU = m_pcPic->getCU( getAddr() );
+        if ((bEnforceSliceRestriction        && (pcTempReconCU==NULL || pcTempReconCU->getSlice() == NULL || pcTempReconCU->getSCUAddr()+uiALPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU       (uiCurrPartUnitIdx)))
+          ||(bEnforceDependentSliceRestriction && (pcTempReconCU==NULL || pcTempReconCU->getSlice() == NULL || pcTempReconCU->getSCUAddr()+uiALPartUnitIdx < m_pcPic->getCU( getAddr() )->getDependentSliceStartCU(uiCurrPartUnitIdx)))) 
+        {
+          return NULL;
+        }
+#endif
+        return m_pcPic->getCU( getAddr() );
+      }
+      else
+      {
+        uiALPartUnitIdx -= m_uiAbsIdxInLCU;
+#if !REMOVE_FGS
+        if ((bEnforceSliceRestriction        && (this->getSCUAddr()+uiALPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU       (uiCurrPartUnitIdx) || m_pcSlice==NULL))
+          ||(bEnforceDependentSliceRestriction && (this->getSCUAddr()+uiALPartUnitIdx < m_pcPic->getCU( getAddr() )->getDependentSliceStartCU(uiCurrPartUnitIdx) || m_pcSlice==NULL)))
+        {
+          return NULL;
+        }
+#endif
+        return this;
+      }
+    }
+    uiALPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx + getPic()->getNumPartInCU() - uiNumPartInCUWidth - 1 ];
+    if(MotionDataCompresssion)
+    {
+      uiALPartUnitIdx = g_motionRefer[uiALPartUnitIdx];
+    }
+    if ( (bEnforceSliceRestriction && (m_pcCUAbove==NULL || m_pcCUAbove->getSlice()==NULL ||
+       m_pcCUAbove->getSCUAddr()+uiALPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx)||
+       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCUAbove->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
+       ))||
+       (bEnforceDependentSliceRestriction && (m_pcCUAbove==NULL || m_pcCUAbove->getSlice()==NULL || 
+       m_pcCUAbove->getSCUAddr()+uiALPartUnitIdx < m_pcPic->getCU( getAddr() )->getDependentSliceStartCU(uiCurrPartUnitIdx)||
+       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCUAbove->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
+       ))
+     )
+    {
+      return NULL;
+    }
+    return m_pcCUAbove;
+  }
+  
+  if ( !RasterAddress::isZeroRow( uiAbsPartIdx, uiNumPartInCUWidth ) )
+  {
+    uiALPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx - 1 ];
+    if ( (bEnforceSliceRestriction && (m_pcCULeft==NULL || m_pcCULeft->getSlice()==NULL || 
+       m_pcCULeft->getSCUAddr()+uiALPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx)||
+       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCULeft->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
+       ))||
+       (bEnforceDependentSliceRestriction && (m_pcCULeft==NULL || m_pcCULeft->getSlice()==NULL || 
+       m_pcCULeft->getSCUAddr()+uiALPartUnitIdx < m_pcPic->getCU( getAddr() )->getDependentSliceStartCU(uiCurrPartUnitIdx)||
+       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCULeft->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
+       ))
+     )
+    {
+      return NULL;
+    }
+    return m_pcCULeft;
+  }
+  
+  uiALPartUnitIdx = g_auiRasterToZscan[ m_pcPic->getNumPartInCU() - 1 ];
+  if(MotionDataCompresssion)
+  {
+    uiALPartUnitIdx = g_motionRefer[uiALPartUnitIdx];
+  }
+  if ( (bEnforceSliceRestriction && (m_pcCUAboveLeft==NULL || m_pcCUAboveLeft->getSlice()==NULL || 
+       m_pcCUAboveLeft->getSCUAddr()+uiALPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx)||
+       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCUAboveLeft->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
+       ))||
+       (bEnforceDependentSliceRestriction && (m_pcCUAboveLeft==NULL || m_pcCUAboveLeft->getSlice()==NULL || 
+       m_pcCUAboveLeft->getSCUAddr()+uiALPartUnitIdx < m_pcPic->getCU( getAddr() )->getDependentSliceStartCU(uiCurrPartUnitIdx)||
+       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCUAboveLeft->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
+       ))
+     )
+  {
+    return NULL;
+  }
+  return m_pcCUAboveLeft;
+}
+
+TComDataCU* TComDataCU::getPUAboveRight( UInt& uiARPartUnitIdx, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction, Bool bEnforceDependentSliceRestriction, Bool MotionDataCompresssion )
+{
+  UInt uiAbsPartIdxRT     = g_auiZscanToRaster[uiCurrPartUnitIdx];
+  UInt uiAbsZorderCUIdx   = g_auiZscanToRaster[ m_uiAbsIdxInLCU ] + m_puhWidth[0] / m_pcPic->getMinCUWidth() - 1;
+  UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
+  
+  if( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelX() + g_auiRasterToPelX[uiAbsPartIdxRT] + m_pcPic->getMinCUWidth() ) >= m_pcSlice->getSPS()->getPicWidthInLumaSamples() )
+  {
+    uiARPartUnitIdx = MAX_UINT;
+    return NULL;
+  }
+  
+  if ( RasterAddress::lessThanCol( uiAbsPartIdxRT, uiNumPartInCUWidth - 1, uiNumPartInCUWidth ) )
+  {
+    if ( !RasterAddress::isZeroRow( uiAbsPartIdxRT, uiNumPartInCUWidth ) )
+    {
+      if ( uiCurrPartUnitIdx > g_auiRasterToZscan[ uiAbsPartIdxRT - uiNumPartInCUWidth + 1 ] )
+      {
+        uiARPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxRT - uiNumPartInCUWidth + 1 ];
+        if ( RasterAddress::isEqualRowOrCol( uiAbsPartIdxRT, uiAbsZorderCUIdx, uiNumPartInCUWidth ) )
+        {
+#if !REMOVE_FGS
+          TComDataCU* pcTempReconCU = m_pcPic->getCU( getAddr() );
+          if ((bEnforceSliceRestriction        && (pcTempReconCU==NULL || pcTempReconCU->getSlice() == NULL || pcTempReconCU->getSCUAddr()+uiARPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU       (uiCurrPartUnitIdx)))
+            ||(bEnforceDependentSliceRestriction && (pcTempReconCU==NULL || pcTempReconCU->getSlice() == NULL || pcTempReconCU->getSCUAddr()+uiARPartUnitIdx < m_pcPic->getCU( getAddr() )->getDependentSliceStartCU(uiCurrPartUnitIdx))))
+          {
+            return NULL;
+          }
+#endif
+          return m_pcPic->getCU( getAddr() );
+        }
+        else
+        {
+          uiARPartUnitIdx -= m_uiAbsIdxInLCU;
+#if !REMOVE_FGS
+          if ((bEnforceSliceRestriction        && (this->getSCUAddr()+uiARPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU       (uiCurrPartUnitIdx) || m_pcSlice==NULL))
+            ||(bEnforceDependentSliceRestriction && (this->getSCUAddr()+uiARPartUnitIdx < m_pcPic->getCU( getAddr() )->getDependentSliceStartCU(uiCurrPartUnitIdx) || m_pcSlice==NULL)))
+          {
+            return NULL;
+          }
+#endif
+          return this;
+        }
+      }
+      uiARPartUnitIdx = MAX_UINT;
+      return NULL;
+    }
+    uiARPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxRT + m_pcPic->getNumPartInCU() - uiNumPartInCUWidth + 1 ];
+    if(MotionDataCompresssion)
+    {
+      uiARPartUnitIdx = g_motionRefer[uiARPartUnitIdx];
+    }
+
+    if ( (bEnforceSliceRestriction && (m_pcCUAbove==NULL || m_pcCUAbove->getSlice()==NULL || 
+       m_pcCUAbove->getSCUAddr()+uiARPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx)||
+       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCUAbove->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
+       ))||
+       (bEnforceDependentSliceRestriction && (m_pcCUAbove==NULL || m_pcCUAbove->getSlice()==NULL || 
+       m_pcCUAbove->getSCUAddr()+uiARPartUnitIdx < m_pcPic->getCU( getAddr() )->getDependentSliceStartCU(uiCurrPartUnitIdx)||
+       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCUAbove->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
+       ))
+     )
+    {
+      return NULL;
+    }
+    return m_pcCUAbove;
+  }
+  
+  if ( !RasterAddress::isZeroRow( uiAbsPartIdxRT, uiNumPartInCUWidth ) )
+  {
+    uiARPartUnitIdx = MAX_UINT;
+    return NULL;
+  }
+  
+  uiARPartUnitIdx = g_auiRasterToZscan[ m_pcPic->getNumPartInCU() - uiNumPartInCUWidth ];
+  if(MotionDataCompresssion)
+  {
+    uiARPartUnitIdx = g_motionRefer[uiARPartUnitIdx];
+  }
+  if ( (bEnforceSliceRestriction && (m_pcCUAboveRight==NULL || m_pcCUAboveRight->getSlice()==NULL ||
+       m_pcPic->getPicSym()->getInverseCUOrderMap( m_pcCUAboveRight->getAddr()) > m_pcPic->getPicSym()->getInverseCUOrderMap( getAddr()) ||
+       m_pcCUAboveRight->getSCUAddr()+uiARPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx)||
+       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCUAboveRight->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
+       ))||
+       (bEnforceDependentSliceRestriction && (m_pcCUAboveRight==NULL || m_pcCUAboveRight->getSlice()==NULL || 
+       m_pcPic->getPicSym()->getInverseCUOrderMap( m_pcCUAboveRight->getAddr()) > m_pcPic->getPicSym()->getInverseCUOrderMap( getAddr()) ||
+       m_pcCUAboveRight->getSCUAddr()+uiARPartUnitIdx < m_pcPic->getCU( getAddr() )->getDependentSliceStartCU(uiCurrPartUnitIdx)||
+       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCUAboveRight->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
+       ))
+     )
+  {
+    return NULL;
+  }
+  return m_pcCUAboveRight;
+}
+
+TComDataCU* TComDataCU::getPUBelowLeft( UInt& uiBLPartUnitIdx, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction, Bool bEnforceDependentSliceRestriction )
+{
+  UInt uiAbsPartIdxLB     = g_auiZscanToRaster[uiCurrPartUnitIdx];
+  UInt uiAbsZorderCUIdxLB = g_auiZscanToRaster[ m_uiAbsIdxInLCU ] + (m_puhHeight[0] / m_pcPic->getMinCUHeight() - 1)*m_pcPic->getNumPartInWidth();
+  UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
+  
+  if( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelY() + g_auiRasterToPelY[uiAbsPartIdxLB] + m_pcPic->getMinCUHeight() ) >= m_pcSlice->getSPS()->getPicHeightInLumaSamples() )
+  {
+    uiBLPartUnitIdx = MAX_UINT;
+    return NULL;
+  }
+  
+  if ( RasterAddress::lessThanRow( uiAbsPartIdxLB, m_pcPic->getNumPartInHeight() - 1, uiNumPartInCUWidth ) )
+  {
+    if ( !RasterAddress::isZeroCol( uiAbsPartIdxLB, uiNumPartInCUWidth ) )
+    {
+      if ( uiCurrPartUnitIdx > g_auiRasterToZscan[ uiAbsPartIdxLB + uiNumPartInCUWidth - 1 ] )
+      {
+        uiBLPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxLB + uiNumPartInCUWidth - 1 ];
+        if ( RasterAddress::isEqualRowOrCol( uiAbsPartIdxLB, uiAbsZorderCUIdxLB, uiNumPartInCUWidth ) )
+        {
+#if !REMOVE_FGS
+          TComDataCU* pcTempReconCU = m_pcPic->getCU( getAddr() );
+          if ((bEnforceSliceRestriction        && (pcTempReconCU==NULL || pcTempReconCU->getSlice() == NULL || pcTempReconCU->getSCUAddr()+uiBLPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU       (uiCurrPartUnitIdx)))
+            ||(bEnforceDependentSliceRestriction && (pcTempReconCU==NULL || pcTempReconCU->getSlice() == NULL || pcTempReconCU->getSCUAddr()+uiBLPartUnitIdx < m_pcPic->getCU( getAddr() )->getDependentSliceStartCU(uiCurrPartUnitIdx))))
+          {
+            return NULL;
+          }
+#endif
+          return m_pcPic->getCU( getAddr() );
+        }
+        else
+        {
+          uiBLPartUnitIdx -= m_uiAbsIdxInLCU;
+#if !REMOVE_FGS
+          if ((bEnforceSliceRestriction        && (this->getSCUAddr()+uiBLPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU       (uiCurrPartUnitIdx) || m_pcSlice==NULL))
+            ||(bEnforceDependentSliceRestriction && (this->getSCUAddr()+uiBLPartUnitIdx < m_pcPic->getCU( getAddr() )->getDependentSliceStartCU(uiCurrPartUnitIdx) || m_pcSlice==NULL)))
+          {
+            return NULL;
+          }
+#endif
+          return this;
+        }
+      }
+      uiBLPartUnitIdx = MAX_UINT;
+      return NULL;
+    }
+    uiBLPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxLB + uiNumPartInCUWidth*2 - 1 ];
+    if ( (bEnforceSliceRestriction && (m_pcCULeft==NULL || m_pcCULeft->getSlice()==NULL || 
+       m_pcCULeft->getSCUAddr()+uiBLPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx)||
+       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCULeft->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
+       ))||
+       (bEnforceDependentSliceRestriction && (m_pcCULeft==NULL || m_pcCULeft->getSlice()==NULL || 
+       m_pcCULeft->getSCUAddr()+uiBLPartUnitIdx < m_pcPic->getCU( getAddr() )->getDependentSliceStartCU(uiCurrPartUnitIdx)||
+       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCULeft->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
+       ))
+     )
+    {
+      return NULL;
+    }
+    return m_pcCULeft;
+  }
+  
+  uiBLPartUnitIdx = MAX_UINT;
+  return NULL;
+}
+
+TComDataCU* TComDataCU::getPUBelowLeftAdi(UInt& uiBLPartUnitIdx, UInt uiPuHeight,  UInt uiCurrPartUnitIdx, UInt uiPartUnitOffset, Bool bEnforceSliceRestriction, Bool bEnforceDependentSliceRestriction )
+{
+  UInt uiAbsPartIdxLB     = g_auiZscanToRaster[uiCurrPartUnitIdx];
+  UInt uiAbsZorderCUIdxLB = g_auiZscanToRaster[ m_uiAbsIdxInLCU ] + ((m_puhHeight[0] / m_pcPic->getMinCUHeight()) - 1)*m_pcPic->getNumPartInWidth();
+  UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
+  
+  if( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelY() + g_auiRasterToPelY[uiAbsPartIdxLB] + (m_pcPic->getPicSym()->getMinCUHeight() * uiPartUnitOffset)) >= m_pcSlice->getSPS()->getPicHeightInLumaSamples())
+  {
+    uiBLPartUnitIdx = MAX_UINT;
+    return NULL;
+  }
+  
+  if ( RasterAddress::lessThanRow( uiAbsPartIdxLB, m_pcPic->getNumPartInHeight() - uiPartUnitOffset, uiNumPartInCUWidth ) )
+  {
+    if ( !RasterAddress::isZeroCol( uiAbsPartIdxLB, uiNumPartInCUWidth ) )
+    {
+      if ( uiCurrPartUnitIdx > g_auiRasterToZscan[ uiAbsPartIdxLB + uiPartUnitOffset * uiNumPartInCUWidth - 1 ] )
+      {
+        uiBLPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxLB + uiPartUnitOffset * uiNumPartInCUWidth - 1 ];
+        if ( RasterAddress::isEqualRowOrCol( uiAbsPartIdxLB, uiAbsZorderCUIdxLB, uiNumPartInCUWidth ) )
+        {
+#if !REMOVE_FGS
+          TComDataCU* pcTempReconCU = m_pcPic->getCU( getAddr() );
+          if ((bEnforceSliceRestriction        && (pcTempReconCU==NULL || pcTempReconCU->getSlice() == NULL || pcTempReconCU->getSCUAddr()+uiBLPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU       (uiCurrPartUnitIdx)))
+            ||(bEnforceDependentSliceRestriction && (pcTempReconCU==NULL || pcTempReconCU->getSlice() == NULL || pcTempReconCU->getSCUAddr()+uiBLPartUnitIdx < m_pcPic->getCU( getAddr() )->getDependentSliceStartCU(uiCurrPartUnitIdx))))
+          {
+            return NULL;
+          }
+#endif
+          return m_pcPic->getCU( getAddr() );
+        }
+        else
+        {
+          uiBLPartUnitIdx -= m_uiAbsIdxInLCU;
+#if !REMOVE_FGS
+          if ((bEnforceSliceRestriction        && (this->getSCUAddr()+uiBLPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU       (uiCurrPartUnitIdx) || m_pcSlice==NULL))
+            ||(bEnforceDependentSliceRestriction && (this->getSCUAddr()+uiBLPartUnitIdx < m_pcPic->getCU( getAddr() )->getDependentSliceStartCU(uiCurrPartUnitIdx) || m_pcSlice==NULL)))
+          {
+            return NULL;
+          }
+#endif
+          return this;
+        }
+      }
+      uiBLPartUnitIdx = MAX_UINT;
+      return NULL;
+    }
+    uiBLPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxLB + (1+uiPartUnitOffset) * uiNumPartInCUWidth - 1 ];
+    if ( (bEnforceSliceRestriction && (m_pcCULeft==NULL || m_pcCULeft->getSlice()==NULL || 
+       m_pcCULeft->getSCUAddr()+uiBLPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx)||
+       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCULeft->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
+       ))||
+       (bEnforceDependentSliceRestriction && (m_pcCULeft==NULL || m_pcCULeft->getSlice()==NULL || 
+       m_pcCULeft->getSCUAddr()+uiBLPartUnitIdx < m_pcPic->getCU( getAddr() )->getDependentSliceStartCU(uiCurrPartUnitIdx)||
+       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCULeft->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
+       ))
+     )
+    {
+      return NULL;
+    }
+    return m_pcCULeft;
+  }
+  
+  uiBLPartUnitIdx = MAX_UINT;
+  return NULL;
+}
+
+TComDataCU* TComDataCU::getPUAboveRightAdi(UInt&  uiARPartUnitIdx, UInt uiPuWidth, UInt uiCurrPartUnitIdx, UInt uiPartUnitOffset, Bool bEnforceSliceRestriction, Bool bEnforceDependentSliceRestriction )
+{
+  UInt uiAbsPartIdxRT     = g_auiZscanToRaster[uiCurrPartUnitIdx];
+  UInt uiAbsZorderCUIdx   = g_auiZscanToRaster[ m_uiAbsIdxInLCU ] + (m_puhWidth[0] / m_pcPic->getMinCUWidth()) - 1;
+  UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
+  
+  if( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelX() + g_auiRasterToPelX[uiAbsPartIdxRT] + (m_pcPic->getPicSym()->getMinCUHeight() * uiPartUnitOffset)) >= m_pcSlice->getSPS()->getPicWidthInLumaSamples() )
+  {
+    uiARPartUnitIdx = MAX_UINT;
+    return NULL;
+  }
+  
+  if ( RasterAddress::lessThanCol( uiAbsPartIdxRT, uiNumPartInCUWidth - uiPartUnitOffset, uiNumPartInCUWidth ) )
+  {
+    if ( !RasterAddress::isZeroRow( uiAbsPartIdxRT, uiNumPartInCUWidth ) )
+    {
+      if ( uiCurrPartUnitIdx > g_auiRasterToZscan[ uiAbsPartIdxRT - uiNumPartInCUWidth + uiPartUnitOffset ] )
+      {
+        uiARPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxRT - uiNumPartInCUWidth + uiPartUnitOffset ];
+        if ( RasterAddress::isEqualRowOrCol( uiAbsPartIdxRT, uiAbsZorderCUIdx, uiNumPartInCUWidth ) )
+        {
+#if !REMOVE_FGS
+          TComDataCU* pcTempReconCU = m_pcPic->getCU( getAddr() );
+          if ((bEnforceSliceRestriction && (pcTempReconCU==NULL || pcTempReconCU->getSlice() == NULL || pcTempReconCU->getSCUAddr()+uiARPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx)))
+           ||( bEnforceDependentSliceRestriction && (pcTempReconCU==NULL || pcTempReconCU->getSlice() == NULL || pcTempReconCU->getSCUAddr()+uiARPartUnitIdx < m_pcPic->getCU( getAddr() )->getDependentSliceStartCU(uiCurrPartUnitIdx))))
+
+          {
+            return NULL;
+          }
+#endif
+          return m_pcPic->getCU( getAddr() );
+        }
+        else
+        {
+          uiARPartUnitIdx -= m_uiAbsIdxInLCU;
+#if !REMOVE_FGS
+          if ((bEnforceSliceRestriction && (this->getSCUAddr()+uiARPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx) || m_pcSlice==NULL))
+            ||(bEnforceDependentSliceRestriction && (this->getSCUAddr()+uiARPartUnitIdx < m_pcPic->getCU( getAddr() )->getDependentSliceStartCU(uiCurrPartUnitIdx) || m_pcSlice==NULL)))
+          {
+            return NULL;
+          }
+#endif
+          return this;
+        }
+      }
+      uiARPartUnitIdx = MAX_UINT;
+      return NULL;
+    }
+    uiARPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxRT + m_pcPic->getNumPartInCU() - uiNumPartInCUWidth + uiPartUnitOffset ];
+    if ( (bEnforceSliceRestriction && (m_pcCUAbove==NULL || m_pcCUAbove->getSlice()==NULL || 
+       m_pcCUAbove->getSCUAddr()+uiARPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx)||
+       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCUAbove->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
+       ))||
+       (bEnforceDependentSliceRestriction && (m_pcCUAbove==NULL || m_pcCUAbove->getSlice()==NULL || 
+       m_pcCUAbove->getSCUAddr()+uiARPartUnitIdx < m_pcPic->getCU( getAddr() )->getDependentSliceStartCU(uiCurrPartUnitIdx)||
+       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCUAbove->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
+       ))
+     )
+    {
+      return NULL;
+    }
+    return m_pcCUAbove;
+  }
+  
+  if ( !RasterAddress::isZeroRow( uiAbsPartIdxRT, uiNumPartInCUWidth ) )
+  {
+    uiARPartUnitIdx = MAX_UINT;
+    return NULL;
+  }
+  
+  uiARPartUnitIdx = g_auiRasterToZscan[ m_pcPic->getNumPartInCU() - uiNumPartInCUWidth + uiPartUnitOffset-1 ];
+  if ( (bEnforceSliceRestriction && (m_pcCUAboveRight==NULL || m_pcCUAboveRight->getSlice()==NULL ||
+       m_pcPic->getPicSym()->getInverseCUOrderMap( m_pcCUAboveRight->getAddr()) > m_pcPic->getPicSym()->getInverseCUOrderMap( getAddr()) ||
+       m_pcCUAboveRight->getSCUAddr()+uiARPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx)||
+       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCUAboveRight->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
+       ))||
+       (bEnforceDependentSliceRestriction && (m_pcCUAboveRight==NULL || m_pcCUAboveRight->getSlice()==NULL || 
+       m_pcPic->getPicSym()->getInverseCUOrderMap( m_pcCUAboveRight->getAddr()) > m_pcPic->getPicSym()->getInverseCUOrderMap( getAddr()) ||
+       m_pcCUAboveRight->getSCUAddr()+uiARPartUnitIdx < m_pcPic->getCU( getAddr() )->getDependentSliceStartCU(uiCurrPartUnitIdx)||
+       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCUAboveRight->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
+       ))
+     )
+  {
+    return NULL;
+  }
+  return m_pcCUAboveRight;
+}
+
+/** Get left QpMinCu
+*\param   uiLPartUnitIdx
+*\param   uiCurrAbsIdxInLCU
+*\param   bEnforceSliceRestriction
+*\param   bEnforceDependentSliceRestriction
+*\returns TComDataCU*   point of TComDataCU of left QpMinCu
+*/
+TComDataCU* TComDataCU::getQpMinCuLeft( UInt& uiLPartUnitIdx, UInt uiCurrAbsIdxInLCU, Bool bEnforceSliceRestriction, Bool bEnforceDependentSliceRestriction)
+{
+  UInt numPartInCUWidth = m_pcPic->getNumPartInWidth();
+  UInt absZorderQpMinCUIdx = (uiCurrAbsIdxInLCU>>((g_uiMaxCUDepth - getSlice()->getPPS()->getMaxCuDQPDepth())<<1))<<((g_uiMaxCUDepth -getSlice()->getPPS()->getMaxCuDQPDepth())<<1);
+  UInt absRorderQpMinCUIdx = g_auiZscanToRaster[absZorderQpMinCUIdx];
+
+  // check for left LCU boundary
+  if ( RasterAddress::isZeroCol(absRorderQpMinCUIdx, numPartInCUWidth) )
+  {
+    return NULL;
+  }
+
+  // get index of left-CU relative to top-left corner of current quantization group
+  uiLPartUnitIdx = g_auiRasterToZscan[absRorderQpMinCUIdx - 1];
+
+#if !REMOVE_FGS
+  // check for fine-grain slice boundaries
+  if ((bEnforceSliceRestriction        && (m_pcPic->getCU( getAddr() )->getSCUAddr()+uiLPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU       (absZorderQpMinCUIdx)))
+    ||(bEnforceDependentSliceRestriction && (m_pcPic->getCU( getAddr() )->getSCUAddr()+uiLPartUnitIdx < m_pcPic->getCU( getAddr() )->getDependentSliceStartCU(absZorderQpMinCUIdx))))
+  {
+    return NULL;
+  }
+#endif
+  
+  // return pointer to current LCU
+  return m_pcPic->getCU( getAddr() );
+}
+
+/** Get Above QpMinCu
+*\param   aPartUnitIdx
+*\param   currAbsIdxInLCU
+*\param   enforceSliceRestriction
+*\param   enforceDependentSliceRestriction
+*\returns TComDataCU*   point of TComDataCU of above QpMinCu
+*/
+TComDataCU* TComDataCU::getQpMinCuAbove( UInt& aPartUnitIdx, UInt currAbsIdxInLCU, Bool enforceSliceRestriction, Bool enforceDependentSliceRestriction )
+{
+  UInt numPartInCUWidth = m_pcPic->getNumPartInWidth();
+  UInt absZorderQpMinCUIdx = (currAbsIdxInLCU>>((g_uiMaxCUDepth - getSlice()->getPPS()->getMaxCuDQPDepth())<<1))<<((g_uiMaxCUDepth - getSlice()->getPPS()->getMaxCuDQPDepth())<<1);
+  UInt absRorderQpMinCUIdx = g_auiZscanToRaster[absZorderQpMinCUIdx];
+
+  // check for top LCU boundary
+  if ( RasterAddress::isZeroRow( absRorderQpMinCUIdx, numPartInCUWidth) )
+  {
+    return NULL;
+  }
+
+  // get index of top-CU relative to top-left corner of current quantization group
+  aPartUnitIdx = g_auiRasterToZscan[absRorderQpMinCUIdx - numPartInCUWidth];
+
+#if !REMOVE_FGS
+  // check for fine-grain slice boundaries
+  if ((enforceSliceRestriction        && (m_pcPic->getCU( getAddr() )->getSCUAddr()+aPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU       (absZorderQpMinCUIdx)))
+    ||(enforceDependentSliceRestriction && (m_pcPic->getCU( getAddr() )->getSCUAddr()+aPartUnitIdx < m_pcPic->getCU( getAddr() )->getDependentSliceStartCU(absZorderQpMinCUIdx))))
+  {
+    return NULL;
+  }
+#endif
+  
+  // return pointer to current LCU
+  return m_pcPic->getCU( getAddr() );
+}
+
+/** Get reference QP from left QpMinCu or latest coded QP
+*\param   uiCurrAbsIdxInLCU
+*\returns Char   reference QP value
+*/
+Char TComDataCU::getRefQP( UInt uiCurrAbsIdxInLCU )
+{
+  UInt        lPartIdx = 0, aPartIdx = 0;
+  TComDataCU* cULeft  = getQpMinCuLeft ( lPartIdx, m_uiAbsIdxInLCU + uiCurrAbsIdxInLCU );
+  TComDataCU* cUAbove = getQpMinCuAbove( aPartIdx, m_uiAbsIdxInLCU + uiCurrAbsIdxInLCU );
+  return (((cULeft? cULeft->getQP( lPartIdx ): getLastCodedQP( uiCurrAbsIdxInLCU )) + (cUAbove? cUAbove->getQP( aPartIdx ): getLastCodedQP( uiCurrAbsIdxInLCU )) + 1) >> 1);
+}
+
+Int TComDataCU::getLastValidPartIdx( Int iAbsPartIdx )
+{
+  Int iLastValidPartIdx = iAbsPartIdx-1;
+  while ( iLastValidPartIdx >= 0
+       && getPredictionMode( iLastValidPartIdx ) == MODE_NONE )
+  {
+    UInt uiDepth = getDepth( iLastValidPartIdx );
+    iLastValidPartIdx -= m_uiNumPartition>>(uiDepth<<1);
+  }
+  return iLastValidPartIdx;
+}
+
+Char TComDataCU::getLastCodedQP( UInt uiAbsPartIdx )
+{
+  UInt uiQUPartIdxMask = ~((1<<((g_uiMaxCUDepth - getSlice()->getPPS()->getMaxCuDQPDepth())<<1))-1);
+  Int iLastValidPartIdx = getLastValidPartIdx( uiAbsPartIdx&uiQUPartIdxMask );
+  if ( uiAbsPartIdx < m_uiNumPartition
+    && (getSCUAddr()+iLastValidPartIdx < getSliceStartCU(m_uiAbsIdxInLCU+uiAbsPartIdx) || getSCUAddr()+iLastValidPartIdx < getDependentSliceStartCU(m_uiAbsIdxInLCU+uiAbsPartIdx) ))
+  {
+    return getSlice()->getSliceQp();
+  }
+  else
+  if ( iLastValidPartIdx >= 0 )
+  {
+    return getQP( iLastValidPartIdx );
+  }
+  else
+  {
+    if ( getZorderIdxInCU() > 0 )
+    {
+      return getPic()->getCU( getAddr() )->getLastCodedQP( getZorderIdxInCU() );
+    }
+    else if ( getPic()->getPicSym()->getInverseCUOrderMap(getAddr()) > 0
+      && getPic()->getPicSym()->getTileIdxMap(getAddr()) == getPic()->getPicSym()->getTileIdxMap(getPic()->getPicSym()->getCUOrderMap(getPic()->getPicSym()->getInverseCUOrderMap(getAddr())-1))
+#if TILES_WPP_ENTROPYSLICES_FLAGS
+      && !( getSlice()->getPPS()->getEntropyCodingSyncEnabledFlag() && getAddr() % getPic()->getFrameWidthInCU() == 0 ) )
+#else
+      && !( getSlice()->getPPS()->getTilesOrEntropyCodingSyncIdc() == 2 && getAddr() % getPic()->getFrameWidthInCU() == 0 ) )
+#endif
+    {
+      return getPic()->getCU( getPic()->getPicSym()->getCUOrderMap(getPic()->getPicSym()->getInverseCUOrderMap(getAddr())-1) )->getLastCodedQP( getPic()->getNumPartInCU() );
+    }
+    else
+    {
+      return getSlice()->getSliceQp();
+    }
+  }
+}
+/** Check whether the CU is coded in lossless coding mode
+ * \param   uiAbsPartIdx
+ * \returns true if the CU is coded in lossless coding mode; false if otherwise 
+ */
+Bool TComDataCU::isLosslessCoded(UInt absPartIdx)
+{
+  return (getSlice()->getPPS()->getTransquantBypassEnableFlag() && getCUTransquantBypass (absPartIdx));
+}
+
+/** Get allowed chroma intra modes
+*\param   uiAbsPartIdx
+*\param   uiModeList  pointer to chroma intra modes array
+*\returns 
+*- fill uiModeList with chroma intra modes
+*/
+Void TComDataCU::getAllowedChromaDir( UInt uiAbsPartIdx, UInt* uiModeList )
+{
+  uiModeList[0] = PLANAR_IDX;
+  uiModeList[1] = VER_IDX;
+  uiModeList[2] = HOR_IDX;
+  uiModeList[3] = DC_IDX;
+#if !REMOVE_LMCHROMA
+  uiModeList[4] = LM_CHROMA_IDX;
+  uiModeList[5] = DM_CHROMA_IDX;
+#else
+  uiModeList[4] = DM_CHROMA_IDX;
+#endif
+
+  UInt uiLumaMode = getLumaIntraDir( uiAbsPartIdx );
+
+#if REMOVE_LMCHROMA
+  for( Int i = 0; i < NUM_CHROMA_MODE - 1; i++ )
+#else
+  for( Int i = 0; i < NUM_CHROMA_MODE - 2; i++ )
+#endif
+  {
+    if( uiLumaMode == uiModeList[i] )
+    {
+      uiModeList[i] = 34; // VER+8 mode
+      break;
+    }
+  }
+}
+
+/** Get most probable intra modes
+*\param   uiAbsPartIdx
+*\param   uiIntraDirPred  pointer to the array for MPM storage
+*\param   piMode          it is set with MPM mode in case both MPM are equal. It is used to restrict RD search at encode side.
+*\returns Number of MPM
+*/
+Int TComDataCU::getIntraDirLumaPredictor( UInt uiAbsPartIdx, Int* uiIntraDirPred, Int* piMode  )
+{
+  TComDataCU* pcTempCU;
+  UInt        uiTempPartIdx;
+  Int         iLeftIntraDir, iAboveIntraDir;
+  Int         uiPredNum = 0;
+  
+  // Get intra direction of left PU
+#if DEPENDENT_SLICES
+  Bool bDepSliceRestriction = ( !m_pcSlice->getPPS()->getDependentSliceEnabledFlag());
+  pcTempCU = getPULeft( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx, true, bDepSliceRestriction );
+#else
+  pcTempCU = getPULeft( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+#endif
+  
+#if INTRA_BL
+  iLeftIntraDir  = pcTempCU ? ( pcTempCU->isIntra( uiTempPartIdx ) && ( !pcTempCU->isIntraBL( uiTempPartIdx ) ) ? pcTempCU->getLumaIntraDir( uiTempPartIdx ) : DC_IDX ) : DC_IDX;
+#else
+  iLeftIntraDir  = pcTempCU ? ( pcTempCU->isIntra( uiTempPartIdx ) ? pcTempCU->getLumaIntraDir( uiTempPartIdx ) : DC_IDX ) : DC_IDX;
+#endif
+  
+  // Get intra direction of above PU
+#if DEPENDENT_SLICES
+  pcTempCU = getPUAbove( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx, true, bDepSliceRestriction, false, true );
+#else
+  pcTempCU = getPUAbove( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx, true, true, false, true );
+#endif
+  
+#if INTRA_BL
+  iAboveIntraDir = pcTempCU ? ( pcTempCU->isIntra( uiTempPartIdx ) && ( !pcTempCU->isIntraBL( uiTempPartIdx ) ) ? pcTempCU->getLumaIntraDir( uiTempPartIdx ) : DC_IDX ) : DC_IDX;
+#else
+  iAboveIntraDir = pcTempCU ? ( pcTempCU->isIntra( uiTempPartIdx ) ? pcTempCU->getLumaIntraDir( uiTempPartIdx ) : DC_IDX ) : DC_IDX;
+#endif 
+  
+#if SVC_BL_CAND_INTRA
+  if(m_layerId > 0)
+  {
+    UInt uiCUAddrBase, uiAbsPartAddrBase;
+    pcTempCU = getBaseColCU( uiAbsPartIdx, uiCUAddrBase, uiAbsPartAddrBase );
+
+    if(pcTempCU->getPredictionMode( uiAbsPartAddrBase ) == MODE_INTRA )
+    {
+      Int iColBaseDir = pcTempCU->getLumaIntraDir( uiAbsPartAddrBase );
+      if( iColBaseDir != iAboveIntraDir && iColBaseDir != iLeftIntraDir && iAboveIntraDir != iLeftIntraDir)
+      {
+        uiIntraDirPred[0] = iColBaseDir;
+        uiIntraDirPred[1] = iLeftIntraDir;
+        uiIntraDirPred[2] = iAboveIntraDir;
+        if( piMode )
+        {
+          *piMode = 2;
+        }
+        uiPredNum = 3;
+        return uiPredNum;
+      }
+      else 
+      {
+        iAboveIntraDir = (iColBaseDir == iLeftIntraDir) ? iAboveIntraDir : iLeftIntraDir;
+        iLeftIntraDir  = iColBaseDir;
+      }
+    }
+  }
+#endif
+  
+  uiPredNum = 3;
+  if(iLeftIntraDir == iAboveIntraDir)
+  {
+    if( piMode )
+    {
+      *piMode = 1;
+    }
+    
+    if (iLeftIntraDir > 1) // angular modes
+    {
+      uiIntraDirPred[0] = iLeftIntraDir;
+      uiIntraDirPred[1] = ((iLeftIntraDir + 29) % 32) + 2;
+      uiIntraDirPred[2] = ((iLeftIntraDir - 1 ) % 32) + 2;
+    }
+    else //non-angular
+    {
+      uiIntraDirPred[0] = PLANAR_IDX;
+      uiIntraDirPred[1] = DC_IDX;
+      uiIntraDirPred[2] = VER_IDX; 
+    }
+  }
+  else
+  {
+    if( piMode )
+    {
+      *piMode = 2;
+    }
+    uiIntraDirPred[0] = iLeftIntraDir;
+    uiIntraDirPred[1] = iAboveIntraDir;
+    
+    if (iLeftIntraDir && iAboveIntraDir ) //both modes are non-planar
+    {
+      uiIntraDirPred[2] = PLANAR_IDX;
+    }
+    else
+    {
+      uiIntraDirPred[2] =  (iLeftIntraDir+iAboveIntraDir)<2? VER_IDX : DC_IDX;
+    }
+  }
+
+  return uiPredNum;
+}
+
+UInt TComDataCU::getCtxSplitFlag( UInt uiAbsPartIdx, UInt uiDepth )
+{
+  TComDataCU* pcTempCU;
+  UInt        uiTempPartIdx;
+  UInt        uiCtx;
+  // Get left split flag
+#if DEPENDENT_SLICES
+  Bool bDepSliceRestriction = ( !m_pcSlice->getPPS()->getDependentSliceEnabledFlag());
+  pcTempCU = getPULeft( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx, true, bDepSliceRestriction );
+#else
+  pcTempCU = getPULeft( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+#endif
+  uiCtx  = ( pcTempCU ) ? ( ( pcTempCU->getDepth( uiTempPartIdx ) > uiDepth ) ? 1 : 0 ) : 0;
+  
+  // Get above split flag
+#if DEPENDENT_SLICES
+  pcTempCU = getPUAbove( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx, true, bDepSliceRestriction );
+#else
+  pcTempCU = getPUAbove( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+#endif
+  uiCtx += ( pcTempCU ) ? ( ( pcTempCU->getDepth( uiTempPartIdx ) > uiDepth ) ? 1 : 0 ) : 0;
+  
+  return uiCtx;
+}
+
+UInt TComDataCU::getCtxQtCbf( UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth )
+{
+  if( eType )
+  {
+    return uiTrDepth;
+  }
+  else
+  {
+#if SIMPLE_LUMA_CBF_CTX_DERIVATION
+    const UInt uiCtx = ( uiTrDepth == 0 ? 1 : 0 );
+#else
+    const UInt uiDepth = getDepth( uiAbsPartIdx );
+    const UInt uiLog2TrafoSize = g_aucConvertToBit[ getSlice()->getSPS()->getMaxCUWidth() ] + 2 - uiDepth - uiTrDepth;
+    const UInt uiCtx = uiTrDepth == 0 || uiLog2TrafoSize == getSlice()->getSPS()->getQuadtreeTULog2MaxSize() ? 1 : 0;
+#endif
+    return uiCtx;
+  }
+}
+
+UInt TComDataCU::getQuadtreeTULog2MinSizeInCU( UInt absPartIdx )
+{
+  UInt log2CbSize = g_aucConvertToBit[getWidth( absPartIdx )] + 2;
+  PartSize  partSize  = getPartitionSize( absPartIdx );
+#if INTRA_BL
+  UInt quadtreeTUMaxDepth = isIntra( absPartIdx ) ? m_pcSlice->getSPS()->getQuadtreeTUMaxDepthIntra() : m_pcSlice->getSPS()->getQuadtreeTUMaxDepthInter(); 
+#else
+  UInt quadtreeTUMaxDepth = getPredictionMode( absPartIdx ) == MODE_INTRA ? m_pcSlice->getSPS()->getQuadtreeTUMaxDepthIntra() : m_pcSlice->getSPS()->getQuadtreeTUMaxDepthInter(); 
+#endif
+  Int intraSplitFlag = ( getPredictionMode( absPartIdx ) == MODE_INTRA && partSize == SIZE_NxN ) ? 1 : 0;
+  Int interSplitFlag = ((quadtreeTUMaxDepth == 1) && (getPredictionMode( absPartIdx ) == MODE_INTER) && (partSize != SIZE_2Nx2N) );
+  
+  UInt log2MinTUSizeInCU = 0;
+  if (log2CbSize < (m_pcSlice->getSPS()->getQuadtreeTULog2MinSize() + quadtreeTUMaxDepth - 1 + interSplitFlag + intraSplitFlag) ) 
+  {
+    // when fully making use of signaled TUMaxDepth + inter/intraSplitFlag, resulting luma TB size is < QuadtreeTULog2MinSize
+    log2MinTUSizeInCU = m_pcSlice->getSPS()->getQuadtreeTULog2MinSize();
+  }
+  else
+  {
+    // when fully making use of signaled TUMaxDepth + inter/intraSplitFlag, resulting luma TB size is still >= QuadtreeTULog2MinSize
+    log2MinTUSizeInCU = log2CbSize - ( quadtreeTUMaxDepth - 1 + interSplitFlag + intraSplitFlag); // stop when trafoDepth == hierarchy_depth = splitFlag
+    if ( log2MinTUSizeInCU > m_pcSlice->getSPS()->getQuadtreeTULog2MaxSize())
+    {
+      // when fully making use of signaled TUMaxDepth + inter/intraSplitFlag, resulting luma TB size is still > QuadtreeTULog2MaxSize
+      log2MinTUSizeInCU = m_pcSlice->getSPS()->getQuadtreeTULog2MaxSize();
+    }  
+  }
+  return log2MinTUSizeInCU;
+}
+
+#if INTRA_BL
+UInt TComDataCU::getCtxIntraBLFlag( UInt uiAbsPartIdx )
+{
+  TComDataCU* pcTempCU;
+  UInt        uiTempPartIdx;
+  UInt        uiCtx = 0;
+  
+  // Get BCBP of left PU
+#if DEPENDENT_SLICES
+  Bool bDepSliceRestriction = ( !m_pcSlice->getPPS()->getDependentSliceEnabledFlag());
+  pcTempCU = getPULeft( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx, true, bDepSliceRestriction );
+#else
+  pcTempCU = getPULeft( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+#endif  
+  uiCtx    = ( pcTempCU ) ? pcTempCU->isIntraBL( uiTempPartIdx ) : 0;
+  
+  // Get BCBP of above PU
+#if DEPENDENT_SLICES
+  pcTempCU = getPUAbove( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx, true, bDepSliceRestriction );
+#else
+  pcTempCU = getPUAbove( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+#endif  
+  uiCtx   += ( pcTempCU ) ? pcTempCU->isIntraBL( uiTempPartIdx ) : 0;
+  
+  return uiCtx;
+}
+#endif
+
+UInt TComDataCU::getCtxSkipFlag( UInt uiAbsPartIdx )
+{
+  TComDataCU* pcTempCU;
+  UInt        uiTempPartIdx;
+  UInt        uiCtx = 0;
+  
+  // Get BCBP of left PU
+#if DEPENDENT_SLICES
+  Bool bDepSliceRestriction = ( !m_pcSlice->getPPS()->getDependentSliceEnabledFlag());
+  pcTempCU = getPULeft( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx, true, bDepSliceRestriction );
+#else
+  pcTempCU = getPULeft( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+#endif
+  uiCtx    = ( pcTempCU ) ? pcTempCU->isSkipped( uiTempPartIdx ) : 0;
+  
+  // Get BCBP of above PU
+#if DEPENDENT_SLICES
+  pcTempCU = getPUAbove( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx, true, bDepSliceRestriction );
+#else
+  pcTempCU = getPUAbove( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+#endif
+  uiCtx   += ( pcTempCU ) ? pcTempCU->isSkipped( uiTempPartIdx ) : 0;
+  
+  return uiCtx;
+}
+
+UInt TComDataCU::getCtxInterDir( UInt uiAbsPartIdx )
+{
+  return getDepth( uiAbsPartIdx );
+}
+
+Void TComDataCU::setCbfSubParts( UInt uiCbfY, UInt uiCbfU, UInt uiCbfV, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+  memset( m_puhCbf[0] + uiAbsPartIdx, uiCbfY, sizeof( UChar ) * uiCurrPartNumb );
+  memset( m_puhCbf[1] + uiAbsPartIdx, uiCbfU, sizeof( UChar ) * uiCurrPartNumb );
+  memset( m_puhCbf[2] + uiAbsPartIdx, uiCbfV, sizeof( UChar ) * uiCurrPartNumb );
+}
+
+Void TComDataCU::setCbfSubParts( UInt uiCbf, TextType eTType, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+  memset( m_puhCbf[g_aucConvertTxtTypeToIdx[eTType]] + uiAbsPartIdx, uiCbf, sizeof( UChar ) * uiCurrPartNumb );
+}
+
+/** Sets a coded block flag for all sub-partitions of a partition
+ * \param uiCbf The value of the coded block flag to be set
+ * \param eTType
+ * \param uiAbsPartIdx
+ * \param uiPartIdx
+ * \param uiDepth
+ * \returns Void
+ */
+Void TComDataCU::setCbfSubParts ( UInt uiCbf, TextType eTType, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+  setSubPart<UChar>( uiCbf, m_puhCbf[g_aucConvertTxtTypeToIdx[eTType]], uiAbsPartIdx, uiDepth, uiPartIdx );
+}
+
+Void TComDataCU::setDepthSubParts( UInt uiDepth, UInt uiAbsPartIdx )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+  memset( m_puhDepth + uiAbsPartIdx, uiDepth, sizeof(UChar)*uiCurrPartNumb );
+}
+
+Bool TComDataCU::isFirstAbsZorderIdxInDepth (UInt uiAbsPartIdx, UInt uiDepth)
+{
+  UInt uiPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+  return (((m_uiAbsIdxInLCU + uiAbsPartIdx)% uiPartNumb) == 0);
+}
+
+Void TComDataCU::setPartSizeSubParts( PartSize eMode, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert( sizeof( *m_pePartSize) == 1 );
+  memset( m_pePartSize + uiAbsPartIdx, eMode, m_pcPic->getNumPartInCU() >> ( 2 * uiDepth ) );
+}
+
+Void TComDataCU::setCUTransquantBypassSubParts( bool flag, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  memset( m_CUTransquantBypass + uiAbsPartIdx, flag, m_pcPic->getNumPartInCU() >> ( 2 * uiDepth ) );
+}
+
+#if SKIP_FLAG
+Void TComDataCU::setSkipFlagSubParts( Bool skip, UInt absPartIdx, UInt depth )
+{
+  assert( sizeof( *m_skipFlag) == 1 );
+  memset( m_skipFlag + absPartIdx, skip, m_pcPic->getNumPartInCU() >> ( 2 * depth ) );
+}
+#endif
+
+Void TComDataCU::setPredModeSubParts( PredMode eMode, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert( sizeof( *m_pePredMode) == 1 );
+  memset( m_pePredMode + uiAbsPartIdx, eMode, m_pcPic->getNumPartInCU() >> ( 2 * uiDepth ) );
+}
+
+Void TComDataCU::setQPSubCUs( Int qp, TComDataCU* pcCU, UInt absPartIdx, UInt depth, Bool &foundNonZeroCbf )
+{
+  UInt currPartNumb = m_pcPic->getNumPartInCU() >> (depth << 1);
+  UInt currPartNumQ = currPartNumb >> 2;
+
+  if(!foundNonZeroCbf)
+  {
+    if(pcCU->getDepth(absPartIdx) > depth)
+    {
+      for ( UInt partUnitIdx = 0; partUnitIdx < 4; partUnitIdx++ )
+      {
+        pcCU->setQPSubCUs( qp, pcCU, absPartIdx+partUnitIdx*currPartNumQ, depth+1, foundNonZeroCbf );
+      }
+    }
+    else
+    {
+      if(pcCU->getCbf( absPartIdx, TEXT_LUMA ) || pcCU->getCbf( absPartIdx, TEXT_CHROMA_U ) || pcCU->getCbf( absPartIdx, TEXT_CHROMA_V ) )
+      {
+        foundNonZeroCbf = true;
+      }
+      else
+      {
+        setQPSubParts(qp, absPartIdx, depth);
+      }
+    }
+  }
+}
+
+Void TComDataCU::setQPSubParts( Int qp, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+  TComSlice * pcSlice = getPic()->getSlice(getPic()->getCurrSliceIdx());
+
+  for(UInt uiSCUIdx = uiAbsPartIdx; uiSCUIdx < uiAbsPartIdx+uiCurrPartNumb; uiSCUIdx++)
+  {
+    if( m_pcPic->getCU( getAddr() )->getDependentSliceStartCU(uiSCUIdx+getZorderIdxInCU()) == pcSlice->getDependentSliceCurStartCUAddr() )
+    {
+      m_phQP[uiSCUIdx] = qp;
+    }
+  }
+}
+
+Void TComDataCU::setLumaIntraDirSubParts( UInt uiDir, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+  
+  memset( m_puhLumaIntraDir + uiAbsPartIdx, uiDir, sizeof(UChar)*uiCurrPartNumb );
+}
+
+template<typename T>
+Void TComDataCU::setSubPart( T uiParameter, T* puhBaseLCU, UInt uiCUAddr, UInt uiCUDepth, UInt uiPUIdx )
+{
+  assert( sizeof(T) == 1 ); // Using memset() works only for types of size 1
+  
+  UInt uiCurrPartNumQ = (m_pcPic->getNumPartInCU() >> (2 * uiCUDepth)) >> 2;
+  switch ( m_pePartSize[ uiCUAddr ] )
+  {
+    case SIZE_2Nx2N:
+      memset( puhBaseLCU + uiCUAddr, uiParameter, 4 * uiCurrPartNumQ );
+      break;
+    case SIZE_2NxN:
+      memset( puhBaseLCU + uiCUAddr, uiParameter, 2 * uiCurrPartNumQ );
+      break;
+    case SIZE_Nx2N:
+      memset( puhBaseLCU + uiCUAddr, uiParameter, uiCurrPartNumQ );
+      memset( puhBaseLCU + uiCUAddr + 2 * uiCurrPartNumQ, uiParameter, uiCurrPartNumQ );
+      break;
+    case SIZE_NxN:
+      memset( puhBaseLCU + uiCUAddr, uiParameter, uiCurrPartNumQ ); 
+      break;
+    case SIZE_2NxnU:
+      if ( uiPUIdx == 0 )
+      {
+        memset( puhBaseLCU + uiCUAddr, uiParameter, (uiCurrPartNumQ >> 1) );                      
+        memset( puhBaseLCU + uiCUAddr + uiCurrPartNumQ, uiParameter, (uiCurrPartNumQ >> 1) );                      
+      }
+      else if ( uiPUIdx == 1 )
+      {
+        memset( puhBaseLCU + uiCUAddr, uiParameter, (uiCurrPartNumQ >> 1) );                      
+        memset( puhBaseLCU + uiCUAddr + uiCurrPartNumQ, uiParameter, ((uiCurrPartNumQ >> 1) + (uiCurrPartNumQ << 1)) );                      
+      }
+      else
+      {
+        assert(0);
+      }
+      break;
+    case SIZE_2NxnD:
+      if ( uiPUIdx == 0 )
+      {
+        memset( puhBaseLCU + uiCUAddr, uiParameter, ((uiCurrPartNumQ << 1) + (uiCurrPartNumQ >> 1)) );                      
+        memset( puhBaseLCU + uiCUAddr + (uiCurrPartNumQ << 1) + uiCurrPartNumQ, uiParameter, (uiCurrPartNumQ >> 1) );                      
+      }
+      else if ( uiPUIdx == 1 )
+      {
+        memset( puhBaseLCU + uiCUAddr, uiParameter, (uiCurrPartNumQ >> 1) );                      
+        memset( puhBaseLCU + uiCUAddr + uiCurrPartNumQ, uiParameter, (uiCurrPartNumQ >> 1) );                      
+      }
+      else
+      {
+        assert(0);
+      }
+      break;
+    case SIZE_nLx2N:
+      if ( uiPUIdx == 0 )
+      {
+        memset( puhBaseLCU + uiCUAddr, uiParameter, (uiCurrPartNumQ >> 2) );
+        memset( puhBaseLCU + uiCUAddr + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ >> 2) ); 
+        memset( puhBaseLCU + uiCUAddr + (uiCurrPartNumQ << 1), uiParameter, (uiCurrPartNumQ >> 2) ); 
+        memset( puhBaseLCU + uiCUAddr + (uiCurrPartNumQ << 1) + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ >> 2) ); 
+      }
+      else if ( uiPUIdx == 1 )
+      {
+        memset( puhBaseLCU + uiCUAddr, uiParameter, (uiCurrPartNumQ >> 2) );
+        memset( puhBaseLCU + uiCUAddr + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ + (uiCurrPartNumQ >> 2)) ); 
+        memset( puhBaseLCU + uiCUAddr + (uiCurrPartNumQ << 1), uiParameter, (uiCurrPartNumQ >> 2) ); 
+        memset( puhBaseLCU + uiCUAddr + (uiCurrPartNumQ << 1) + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ + (uiCurrPartNumQ >> 2)) ); 
+      }
+      else
+      {
+        assert(0);
+      }
+      break;
+    case SIZE_nRx2N:
+      if ( uiPUIdx == 0 )
+      {      
+        memset( puhBaseLCU + uiCUAddr, uiParameter, (uiCurrPartNumQ + (uiCurrPartNumQ >> 2)) );                           
+        memset( puhBaseLCU + uiCUAddr + uiCurrPartNumQ + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ >> 2) );                           
+        memset( puhBaseLCU + uiCUAddr + (uiCurrPartNumQ << 1), uiParameter, (uiCurrPartNumQ + (uiCurrPartNumQ >> 2)) );                           
+        memset( puhBaseLCU + uiCUAddr + (uiCurrPartNumQ << 1) + uiCurrPartNumQ + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ >> 2) );                           
+      }
+      else if ( uiPUIdx == 1 )
+      {
+        memset( puhBaseLCU + uiCUAddr, uiParameter, (uiCurrPartNumQ >> 2) );                           
+        memset( puhBaseLCU + uiCUAddr + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ >> 2) );                           
+        memset( puhBaseLCU + uiCUAddr + (uiCurrPartNumQ << 1), uiParameter, (uiCurrPartNumQ >> 2) );                           
+        memset( puhBaseLCU + uiCUAddr + (uiCurrPartNumQ << 1) + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ >> 2) );                          
+      }
+      else
+      {
+        assert(0);
+      }
+      break;
+    default:
+      assert( 0 );
+  }
+}
+
+Void TComDataCU::setMergeFlagSubParts ( Bool bMergeFlag, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+  setSubPart( bMergeFlag, m_pbMergeFlag, uiAbsPartIdx, uiDepth, uiPartIdx );
+}
+
+Void TComDataCU::setMergeIndexSubParts ( UInt uiMergeIndex, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+  setSubPart<UChar>( uiMergeIndex, m_puhMergeIndex, uiAbsPartIdx, uiDepth, uiPartIdx );
+}
+
+Void TComDataCU::setChromIntraDirSubParts( UInt uiDir, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+  
+  memset( m_puhChromaIntraDir + uiAbsPartIdx, uiDir, sizeof(UChar)*uiCurrPartNumb );
+}
+
+Void TComDataCU::setInterDirSubParts( UInt uiDir, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+  setSubPart<UChar>( uiDir, m_puhInterDir, uiAbsPartIdx, uiDepth, uiPartIdx );
+}
+
+Void TComDataCU::setMVPIdxSubParts( Int iMVPIdx, RefPicList eRefPicList, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+  setSubPart<Char>( 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 );
+}
+
+
+Void TComDataCU::setTrIdxSubParts( UInt uiTrIdx, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+  
+  memset( m_puhTrIdx + uiAbsPartIdx, uiTrIdx, sizeof(UChar)*uiCurrPartNumb );
+}
+
+Void TComDataCU::setTransformSkipSubParts( UInt useTransformSkipY, UInt useTransformSkipU, UInt useTransformSkipV, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+
+  memset( m_puhTransformSkip[0] + uiAbsPartIdx, useTransformSkipY, sizeof( UChar ) * uiCurrPartNumb );
+  memset( m_puhTransformSkip[1] + uiAbsPartIdx, useTransformSkipU, sizeof( UChar ) * uiCurrPartNumb );
+  memset( m_puhTransformSkip[2] + uiAbsPartIdx, useTransformSkipV, sizeof( UChar ) * uiCurrPartNumb );
+}
+
+Void TComDataCU::setTransformSkipSubParts( UInt useTransformSkip, TextType eType, UInt uiAbsPartIdx, UInt uiDepth)
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+
+  memset( m_puhTransformSkip[g_aucConvertTxtTypeToIdx[eType]] + uiAbsPartIdx, useTransformSkip, sizeof( UChar ) * uiCurrPartNumb );
+}
+
+#if !REMOVE_NSQT
+Void TComDataCU::setNSQTIdxSubParts( UInt absPartIdx, UInt depth )
+{
+  UInt currPartNumb = m_pcPic->getNumPartInCU() >> (depth << 1);
+  
+  memset( m_nsqtPartIdx + absPartIdx, absPartIdx, sizeof(UChar)*currPartNumb );
+}
+
+Void  TComDataCU::setNSQTIdxSubParts( UInt log2TrafoSize, UInt absPartIdx, UInt absTUPartIdx, UInt trMode )
+{
+  UInt trWidth, trHeight;
+  UInt nsTUWidthInBaseUnits, nsTUHeightInBaseUnits;
+  UInt lcuWidthInBaseUnits = getPic()->getNumPartInWidth();
+
+  UInt minTuSize = ( 1 << getSlice()->getSPS()->getQuadtreeTULog2MinSize() );
+
+  trWidth = trHeight = ( 1 << log2TrafoSize );
+
+  if ( useNonSquareTrans( trMode, absPartIdx ) && ( trWidth > minTuSize ) )
+  {
+    trWidth  = ( m_pePartSize[absPartIdx] == SIZE_Nx2N || m_pePartSize[absPartIdx] == SIZE_nLx2N || m_pePartSize[absPartIdx] == SIZE_nRx2N )? trWidth >> 1  : trWidth << 1;
+    trHeight = ( m_pePartSize[absPartIdx] == SIZE_Nx2N || m_pePartSize[absPartIdx] == SIZE_nLx2N || m_pePartSize[absPartIdx] == SIZE_nRx2N )? trHeight << 1 : trHeight >> 1;
+  }
+  
+  nsTUWidthInBaseUnits  = trWidth / getPic()->getMinCUWidth();
+  nsTUHeightInBaseUnits = trHeight / getPic()->getMinCUHeight();
+  
+  if ( nsTUWidthInBaseUnits > nsTUHeightInBaseUnits )
+  {
+    UInt currPartNumb = nsTUHeightInBaseUnits*nsTUHeightInBaseUnits;
+    memset( m_nsqtPartIdx + absTUPartIdx                                                                , absPartIdx, sizeof(UChar)*(currPartNumb) );
+    memset( m_nsqtPartIdx + g_auiRasterToZscan[g_auiZscanToRaster[absTUPartIdx]+  nsTUHeightInBaseUnits], absPartIdx, sizeof(UChar)*(currPartNumb) );
+    memset( m_nsqtPartIdx + g_auiRasterToZscan[g_auiZscanToRaster[absTUPartIdx]+2*nsTUHeightInBaseUnits], absPartIdx, sizeof(UChar)*(currPartNumb) );
+    memset( m_nsqtPartIdx + g_auiRasterToZscan[g_auiZscanToRaster[absTUPartIdx]+3*nsTUHeightInBaseUnits], absPartIdx, sizeof(UChar)*(currPartNumb) );
+  }
+  else if ( nsTUWidthInBaseUnits < nsTUHeightInBaseUnits )
+  {
+    UInt currPartNumb = nsTUWidthInBaseUnits*nsTUWidthInBaseUnits;
+    memset( m_nsqtPartIdx + absTUPartIdx                                                                                   , absPartIdx, sizeof(UChar)*(currPartNumb) );
+    memset( m_nsqtPartIdx + g_auiRasterToZscan[g_auiZscanToRaster[absTUPartIdx]+  nsTUWidthInBaseUnits*lcuWidthInBaseUnits], absPartIdx, sizeof(UChar)*(currPartNumb) );
+    memset( m_nsqtPartIdx + g_auiRasterToZscan[g_auiZscanToRaster[absTUPartIdx]+2*nsTUWidthInBaseUnits*lcuWidthInBaseUnits], absPartIdx, sizeof(UChar)*(currPartNumb) );
+    memset( m_nsqtPartIdx + g_auiRasterToZscan[g_auiZscanToRaster[absTUPartIdx]+3*nsTUWidthInBaseUnits*lcuWidthInBaseUnits], absPartIdx, sizeof(UChar)*(currPartNumb) );
+  }
+  else
+  {
+    UInt currPartNumb = nsTUWidthInBaseUnits*nsTUHeightInBaseUnits;
+    memset( m_nsqtPartIdx + absTUPartIdx, absPartIdx, sizeof(UChar)*(currPartNumb) );
+  }
+}
+#endif
+
+Void TComDataCU::setSizeSubParts( UInt uiWidth, UInt uiHeight, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+  
+  memset( m_puhWidth  + uiAbsPartIdx, uiWidth,  sizeof(UChar)*uiCurrPartNumb );
+  memset( m_puhHeight + uiAbsPartIdx, uiHeight, sizeof(UChar)*uiCurrPartNumb );
+}
+
+UChar TComDataCU::getNumPartInter()
+{
+  UChar iNumPart = 0;
+  
+  switch ( m_pePartSize[0] )
+  {
+    case SIZE_2Nx2N:    iNumPart = 1; break;
+    case SIZE_2NxN:     iNumPart = 2; break;
+    case SIZE_Nx2N:     iNumPart = 2; break;
+    case SIZE_NxN:      iNumPart = 4; break;
+    case SIZE_2NxnU:    iNumPart = 2; break;
+    case SIZE_2NxnD:    iNumPart = 2; break;
+    case SIZE_nLx2N:    iNumPart = 2; break;
+    case SIZE_nRx2N:    iNumPart = 2; break;
+    default:            assert (0);   break;
+  }
+  
+  return  iNumPart;
+}
+
+Void TComDataCU::getPartIndexAndSize( UInt uiPartIdx, UInt& ruiPartAddr, Int& riWidth, Int& riHeight )
+{
+  switch ( m_pePartSize[0] )
+  {
+    case SIZE_2NxN:
+      riWidth = getWidth(0);      riHeight = getHeight(0) >> 1; ruiPartAddr = ( uiPartIdx == 0 )? 0 : m_uiNumPartition >> 1;
+      break;
+    case SIZE_Nx2N:
+      riWidth = getWidth(0) >> 1; riHeight = getHeight(0);      ruiPartAddr = ( uiPartIdx == 0 )? 0 : m_uiNumPartition >> 2;
+      break;
+    case SIZE_NxN:
+      riWidth = getWidth(0) >> 1; riHeight = getHeight(0) >> 1; ruiPartAddr = ( m_uiNumPartition >> 2 ) * uiPartIdx;
+      break;
+    case SIZE_2NxnU:
+      riWidth     = getWidth(0);
+      riHeight    = ( uiPartIdx == 0 ) ?  getHeight(0) >> 2 : ( getHeight(0) >> 2 ) + ( getHeight(0) >> 1 );
+      ruiPartAddr = ( uiPartIdx == 0 ) ? 0 : m_uiNumPartition >> 3;
+      break;
+    case SIZE_2NxnD:
+      riWidth     = getWidth(0);
+      riHeight    = ( uiPartIdx == 0 ) ?  ( getHeight(0) >> 2 ) + ( getHeight(0) >> 1 ) : getHeight(0) >> 2;
+      ruiPartAddr = ( uiPartIdx == 0 ) ? 0 : (m_uiNumPartition >> 1) + (m_uiNumPartition >> 3);
+      break;
+    case SIZE_nLx2N:
+      riWidth     = ( uiPartIdx == 0 ) ? getWidth(0) >> 2 : ( getWidth(0) >> 2 ) + ( getWidth(0) >> 1 );
+      riHeight    = getHeight(0);
+      ruiPartAddr = ( uiPartIdx == 0 ) ? 0 : m_uiNumPartition >> 4;
+      break;
+    case SIZE_nRx2N:
+      riWidth     = ( uiPartIdx == 0 ) ? ( getWidth(0) >> 2 ) + ( getWidth(0) >> 1 ) : getWidth(0) >> 2;
+      riHeight    = getHeight(0);
+      ruiPartAddr = ( uiPartIdx == 0 ) ? 0 : (m_uiNumPartition >> 2) + (m_uiNumPartition >> 4);
+      break;
+    default:
+      assert ( m_pePartSize[0] == SIZE_2Nx2N );
+      riWidth = getWidth(0);      riHeight = getHeight(0);      ruiPartAddr = 0;
+      break;
+  }
+}
+
+
+Void TComDataCU::getMvField ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefPicList, TComMvField& rcMvField )
+{
+  if ( pcCU == NULL )  // OUT OF BOUNDARY
+  {
+    TComMv  cZeroMv;
+    rcMvField.setMvField( cZeroMv, NOT_VALID );
+    return;
+  }
+  
+  TComCUMvField*  pcCUMvField = pcCU->getCUMvField( eRefPicList );
+  rcMvField.setMvField( pcCUMvField->getMv( uiAbsPartIdx ), pcCUMvField->getRefIdx( uiAbsPartIdx ) );
+}
+
+Void TComDataCU::deriveLeftRightTopIdxGeneral ( PartSize eCUMode, UInt uiAbsPartIdx, UInt uiPartIdx, UInt& ruiPartIdxLT, UInt& ruiPartIdxRT )
+{
+  ruiPartIdxLT = m_uiAbsIdxInLCU + uiAbsPartIdx;
+  UInt uiPUWidth = 0;
+  
+  switch ( m_pePartSize[uiAbsPartIdx] )
+  {
+    case SIZE_2Nx2N: uiPUWidth = m_puhWidth[uiAbsPartIdx];  break;
+    case SIZE_2NxN:  uiPUWidth = m_puhWidth[uiAbsPartIdx];   break;
+    case SIZE_Nx2N:  uiPUWidth = m_puhWidth[uiAbsPartIdx]  >> 1;  break;
+    case SIZE_NxN:   uiPUWidth = m_puhWidth[uiAbsPartIdx]  >> 1; break;
+    case SIZE_2NxnU:   uiPUWidth = m_puhWidth[uiAbsPartIdx]; break;
+    case SIZE_2NxnD:   uiPUWidth = m_puhWidth[uiAbsPartIdx]; break;
+    case SIZE_nLx2N:   
+      if ( uiPartIdx == 0 )
+      {
+        uiPUWidth = m_puhWidth[uiAbsPartIdx]  >> 2; 
+      }
+      else if ( uiPartIdx == 1 )
+      {
+        uiPUWidth = (m_puhWidth[uiAbsPartIdx]  >> 1) + (m_puhWidth[uiAbsPartIdx]  >> 2); 
+      }
+      else
+      {
+        assert(0);
+      }
+      break;
+    case SIZE_nRx2N:   
+      if ( uiPartIdx == 0 )
+      {
+        uiPUWidth = (m_puhWidth[uiAbsPartIdx]  >> 1) + (m_puhWidth[uiAbsPartIdx]  >> 2); 
+      }
+      else if ( uiPartIdx == 1 )
+      {
+        uiPUWidth = m_puhWidth[uiAbsPartIdx]  >> 2; 
+      }
+      else
+      {
+        assert(0);
+      }
+      break;
+    default:
+      assert (0);
+      break;
+  }
+  
+  ruiPartIdxRT = g_auiRasterToZscan [g_auiZscanToRaster[ ruiPartIdxLT ] + uiPUWidth / m_pcPic->getMinCUWidth() - 1 ];
+}
+
+Void TComDataCU::deriveLeftBottomIdxGeneral( PartSize eCUMode, UInt uiAbsPartIdx, UInt uiPartIdx, UInt& ruiPartIdxLB )
+{
+  UInt uiPUHeight = 0;
+  switch ( m_pePartSize[uiAbsPartIdx] )
+  {
+    case SIZE_2Nx2N: uiPUHeight = m_puhHeight[uiAbsPartIdx];    break;
+    case SIZE_2NxN:  uiPUHeight = m_puhHeight[uiAbsPartIdx] >> 1;    break;
+    case SIZE_Nx2N:  uiPUHeight = m_puhHeight[uiAbsPartIdx];  break;
+    case SIZE_NxN:   uiPUHeight = m_puhHeight[uiAbsPartIdx] >> 1;    break;
+    case SIZE_2NxnU: 
+      if ( uiPartIdx == 0 )
+      {
+        uiPUHeight = m_puhHeight[uiAbsPartIdx] >> 2;    
+      }
+      else if ( uiPartIdx == 1 )
+      {
+        uiPUHeight = (m_puhHeight[uiAbsPartIdx] >> 1) + (m_puhHeight[uiAbsPartIdx] >> 2);    
+      }
+      else
+      {
+        assert(0);
+      }
+      break;
+    case SIZE_2NxnD: 
+      if ( uiPartIdx == 0 )
+      {
+        uiPUHeight = (m_puhHeight[uiAbsPartIdx] >> 1) + (m_puhHeight[uiAbsPartIdx] >> 2);    
+      }
+      else if ( uiPartIdx == 1 )
+      {
+        uiPUHeight = m_puhHeight[uiAbsPartIdx] >> 2;    
+      }
+      else
+      {
+        assert(0);
+      }
+      break;
+    case SIZE_nLx2N: uiPUHeight = m_puhHeight[uiAbsPartIdx];  break;
+    case SIZE_nRx2N: uiPUHeight = m_puhHeight[uiAbsPartIdx];  break;
+    default:
+      assert (0);
+      break;
+  }
+  
+  ruiPartIdxLB      = g_auiRasterToZscan [g_auiZscanToRaster[ m_uiAbsIdxInLCU + uiAbsPartIdx ] + ((uiPUHeight / m_pcPic->getMinCUHeight()) - 1)*m_pcPic->getNumPartInWidth()];
+}
+
+Void TComDataCU::deriveLeftRightTopIdx ( PartSize eCUMode, UInt uiPartIdx, UInt& ruiPartIdxLT, UInt& ruiPartIdxRT )
+{
+  ruiPartIdxLT = m_uiAbsIdxInLCU;
+  ruiPartIdxRT = g_auiRasterToZscan [g_auiZscanToRaster[ ruiPartIdxLT ] + m_puhWidth[0] / m_pcPic->getMinCUWidth() - 1 ];
+  
+  switch ( m_pePartSize[0] )
+  {
+    case SIZE_2Nx2N:                                                                                                                                break;
+    case SIZE_2NxN:
+      ruiPartIdxLT += ( uiPartIdx == 0 )? 0 : m_uiNumPartition >> 1; ruiPartIdxRT += ( uiPartIdx == 0 )? 0 : m_uiNumPartition >> 1;
+      break;
+    case SIZE_Nx2N:
+      ruiPartIdxLT += ( uiPartIdx == 0 )? 0 : m_uiNumPartition >> 2; ruiPartIdxRT -= ( uiPartIdx == 1 )? 0 : m_uiNumPartition >> 2;
+      break;
+    case SIZE_NxN:
+      ruiPartIdxLT += ( m_uiNumPartition >> 2 ) * uiPartIdx;         ruiPartIdxRT +=  ( m_uiNumPartition >> 2 ) * ( uiPartIdx - 1 );
+      break;
+    case SIZE_2NxnU:
+      ruiPartIdxLT += ( uiPartIdx == 0 )? 0 : m_uiNumPartition >> 3;
+      ruiPartIdxRT += ( uiPartIdx == 0 )? 0 : m_uiNumPartition >> 3;
+      break;
+    case SIZE_2NxnD:
+      ruiPartIdxLT += ( uiPartIdx == 0 )? 0 : ( m_uiNumPartition >> 1 ) + ( m_uiNumPartition >> 3 );
+      ruiPartIdxRT += ( uiPartIdx == 0 )? 0 : ( m_uiNumPartition >> 1 ) + ( m_uiNumPartition >> 3 );
+      break;
+    case SIZE_nLx2N:
+      ruiPartIdxLT += ( uiPartIdx == 0 )? 0 : m_uiNumPartition >> 4;
+      ruiPartIdxRT -= ( uiPartIdx == 1 )? 0 : ( m_uiNumPartition >> 2 ) + ( m_uiNumPartition >> 4 );
+      break;
+    case SIZE_nRx2N:
+      ruiPartIdxLT += ( uiPartIdx == 0 )? 0 : ( m_uiNumPartition >> 2 ) + ( m_uiNumPartition >> 4 );
+      ruiPartIdxRT -= ( uiPartIdx == 1 )? 0 : m_uiNumPartition >> 4;
+      break;
+    default:
+      assert (0);
+      break;
+  }
+  
+}
+
+Void TComDataCU::deriveLeftBottomIdx( PartSize      eCUMode,   UInt  uiPartIdx,      UInt&      ruiPartIdxLB )
+{
+  ruiPartIdxLB      = g_auiRasterToZscan [g_auiZscanToRaster[ m_uiAbsIdxInLCU ] + ( ((m_puhHeight[0] / m_pcPic->getMinCUHeight())>>1) - 1)*m_pcPic->getNumPartInWidth()];
+  
+  switch ( m_pePartSize[0] )
+  {
+    case SIZE_2Nx2N:
+      ruiPartIdxLB += m_uiNumPartition >> 1;
+      break;
+    case SIZE_2NxN:
+      ruiPartIdxLB += ( uiPartIdx == 0 )? 0 : m_uiNumPartition >> 1;
+      break;
+    case SIZE_Nx2N:
+      ruiPartIdxLB += ( uiPartIdx == 0 )? m_uiNumPartition >> 1 : (m_uiNumPartition >> 2)*3;
+      break;
+    case SIZE_NxN:
+      ruiPartIdxLB += ( m_uiNumPartition >> 2 ) * uiPartIdx;
+      break;
+    case SIZE_2NxnU:
+      ruiPartIdxLB += ( uiPartIdx == 0 ) ? -((Int)m_uiNumPartition >> 3) : m_uiNumPartition >> 1;
+      break;
+    case SIZE_2NxnD:
+      ruiPartIdxLB += ( uiPartIdx == 0 ) ? (m_uiNumPartition >> 2) + (m_uiNumPartition >> 3): m_uiNumPartition >> 1;
+      break;
+    case SIZE_nLx2N:
+      ruiPartIdxLB += ( uiPartIdx == 0 ) ? m_uiNumPartition >> 1 : (m_uiNumPartition >> 1) + (m_uiNumPartition >> 4);
+      break;
+    case SIZE_nRx2N:
+      ruiPartIdxLB += ( uiPartIdx == 0 ) ? m_uiNumPartition >> 1 : (m_uiNumPartition >> 1) + (m_uiNumPartition >> 2) + (m_uiNumPartition >> 4);
+      break;
+    default:
+      assert (0);
+      break;
+  }
+}
+
+/** Derives the partition index of neighbouring bottom right block
+ * \param [in]  eCUMode
+ * \param [in]  uiPartIdx 
+ * \param [out] ruiPartIdxRB 
+ */
+Void TComDataCU::deriveRightBottomIdx( PartSize      eCUMode,   UInt  uiPartIdx,      UInt&      ruiPartIdxRB )
+{
+  ruiPartIdxRB      = g_auiRasterToZscan [g_auiZscanToRaster[ m_uiAbsIdxInLCU ] + ( ((m_puhHeight[0] / m_pcPic->getMinCUHeight())>>1) - 1)*m_pcPic->getNumPartInWidth() +  m_puhWidth[0] / m_pcPic->getMinCUWidth() - 1];
+
+  switch ( m_pePartSize[0] )
+  {
+    case SIZE_2Nx2N:  
+      ruiPartIdxRB += m_uiNumPartition >> 1;    
+      break;
+    case SIZE_2NxN:  
+      ruiPartIdxRB += ( uiPartIdx == 0 )? 0 : m_uiNumPartition >> 1;   
+      break;
+    case SIZE_Nx2N:  
+      ruiPartIdxRB += ( uiPartIdx == 0 )? m_uiNumPartition >> 2 : (m_uiNumPartition >> 1);   
+      break;
+    case SIZE_NxN:   
+      ruiPartIdxRB += ( m_uiNumPartition >> 2 ) * ( uiPartIdx - 1 );   
+      break;
+    case SIZE_2NxnU:
+      ruiPartIdxRB += ( uiPartIdx == 0 ) ? -((Int)m_uiNumPartition >> 3) : m_uiNumPartition >> 1;
+      break;
+    case SIZE_2NxnD:
+      ruiPartIdxRB += ( uiPartIdx == 0 ) ? (m_uiNumPartition >> 2) + (m_uiNumPartition >> 3): m_uiNumPartition >> 1;
+      break;
+    case SIZE_nLx2N:
+      ruiPartIdxRB += ( uiPartIdx == 0 ) ? (m_uiNumPartition >> 3) + (m_uiNumPartition >> 4): m_uiNumPartition >> 1;
+      break;
+    case SIZE_nRx2N:
+      ruiPartIdxRB += ( uiPartIdx == 0 ) ? (m_uiNumPartition >> 2) + (m_uiNumPartition >> 3) + (m_uiNumPartition >> 4) : m_uiNumPartition >> 1;
+      break;
+    default:
+      assert (0);
+      break;
+  }
+}
+
+Void TComDataCU::deriveLeftRightTopIdxAdi ( UInt& ruiPartIdxLT, UInt& ruiPartIdxRT, UInt uiPartOffset, UInt uiPartDepth )
+{
+  UInt uiNumPartInWidth = (m_puhWidth[0]/m_pcPic->getMinCUWidth())>>uiPartDepth;
+  ruiPartIdxLT = m_uiAbsIdxInLCU + uiPartOffset;
+  ruiPartIdxRT = g_auiRasterToZscan[ g_auiZscanToRaster[ ruiPartIdxLT ] + uiNumPartInWidth - 1 ];
+}
+
+Void TComDataCU::deriveLeftBottomIdxAdi( UInt& ruiPartIdxLB, UInt uiPartOffset, UInt uiPartDepth )
+{
+  UInt uiAbsIdx;
+  UInt uiMinCuWidth, uiWidthInMinCus;
+  
+  uiMinCuWidth    = getPic()->getMinCUWidth();
+  uiWidthInMinCus = (getWidth(0)/uiMinCuWidth)>>uiPartDepth;
+  uiAbsIdx        = getZorderIdxInCU()+uiPartOffset+(m_uiNumPartition>>(uiPartDepth<<1))-1;
+  uiAbsIdx        = g_auiZscanToRaster[uiAbsIdx]-(uiWidthInMinCus-1);
+  ruiPartIdxLB    = g_auiRasterToZscan[uiAbsIdx];
+}
+
+Bool TComDataCU::hasEqualMotion( UInt uiAbsPartIdx, TComDataCU* pcCandCU, UInt uiCandAbsPartIdx )
+{
+
+  if ( getInterDir( uiAbsPartIdx ) != pcCandCU->getInterDir( uiCandAbsPartIdx ) )
+  {
+    return false;
+  }
+
+  for ( UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )
+  {
+    if ( getInterDir( uiAbsPartIdx ) & ( 1 << uiRefListIdx ) )
+    {
+      if ( getCUMvField( RefPicList( uiRefListIdx ) )->getMv( uiAbsPartIdx )     != pcCandCU->getCUMvField( RefPicList( uiRefListIdx ) )->getMv( uiCandAbsPartIdx ) || 
+        getCUMvField( RefPicList( uiRefListIdx ) )->getRefIdx( uiAbsPartIdx ) != pcCandCU->getCUMvField( RefPicList( uiRefListIdx ) )->getRefIdx( uiCandAbsPartIdx ) )
+      {
+        return false;
+      }
+    }
+  }
+
+  return true;
+}
+
+/** Constructs a list of merging candidates
+ * \param uiAbsPartIdx
+ * \param uiPUIdx 
+ * \param uiDepth
+ * \param pcMvFieldNeighbours
+ * \param puhInterDirNeighbours
+ * \param numValidMergeCand
+ */
+Void TComDataCU::getInterMergeCandidates( UInt uiAbsPartIdx, UInt uiPUIdx, UInt uiDepth, TComMvField* pcMvFieldNeighbours, UChar* puhInterDirNeighbours, Int& numValidMergeCand, Int mrgCandIdx )
+{
+  UInt uiAbsPartAddr = m_uiAbsIdxInLCU + uiAbsPartIdx;
+  UInt uiIdx = 1;
+  bool abCandIsInter[ MRG_MAX_NUM_CANDS ];
+  for( UInt ui = 0; ui < getSlice()->getMaxNumMergeCand(); ++ui )
+  {
+    abCandIsInter[ui] = false;
+  }
+  numValidMergeCand = getSlice()->getMaxNumMergeCand();
+  // compute the location of the current PU
+  Int xP, yP, nPSW, nPSH;
+  this->getPartPosition(uiPUIdx, xP, yP, nPSW, nPSH);
+
+  Int iCount = 0;
+
+  UInt uiPartIdxLT, uiPartIdxRT, uiPartIdxLB;
+  PartSize cCurPS = getPartitionSize( uiAbsPartIdx );
+  deriveLeftRightTopIdxGeneral( cCurPS, uiAbsPartIdx, uiPUIdx, uiPartIdxLT, uiPartIdxRT );
+  deriveLeftBottomIdxGeneral( cCurPS, uiAbsPartIdx, uiPUIdx, uiPartIdxLB );
+
+#if SVC_MVP
+  // BL collocated
+  TComDataCU *pcColCU = 0;
+  UInt uiCUAddrBase, uiAbsPartAddrBase ;
+  TComMvField cMvFieldBaseColCU[2];
+  if(m_layerId)  
+  {
+    UInt uiPartIdxCenter;
+    xDeriveCenterIdx( cCurPS, uiPUIdx, uiPartIdxCenter );
+    uiPartIdxCenter -= m_uiAbsIdxInLCU;
+    pcColCU = getBaseColCU( uiPartIdxCenter, uiCUAddrBase, uiAbsPartAddrBase );
+    
+#if INTRA_BL
+    if( pcColCU && pcColCU->isIntraBL( uiAbsPartAddrBase ) )
+    {
+      pcColCU = NULL;
+    }
+#endif
+    
+    if(pcColCU && !pcColCU->isIntra( uiAbsPartAddrBase ) )
+    {
+      abCandIsInter[iCount] = true;
+
+      // get interDir
+      puhInterDirNeighbours[iCount] = pcColCU->getInterDir( uiAbsPartAddrBase );
+
+      pcMvFieldNeighbours[(iCount << 1)].setMvField( TComMv(0,0), -1);
+      pcMvFieldNeighbours[(iCount << 1) + 1].setMvField( TComMv(0,0), -1);
+
+      if( puhInterDirNeighbours[iCount] & 1 )
+      {
+        pcColCU->getMvField( pcColCU, uiAbsPartAddrBase, REF_PIC_LIST_0, cMvFieldBaseColCU[0]);
+        scaleBaseMV( pcMvFieldNeighbours[iCount<<1], cMvFieldBaseColCU[0] );
+      }
+
+      if ( getSlice()->isInterB() && puhInterDirNeighbours[iCount] & 2 )
+      {
+        pcColCU->getMvField( pcColCU, uiAbsPartAddrBase, REF_PIC_LIST_1, cMvFieldBaseColCU[1] );
+        scaleBaseMV( pcMvFieldNeighbours[(iCount<<1)+1], cMvFieldBaseColCU[1] );
+      }
+
+      if( puhInterDirNeighbours[iCount] > 0 )
+      {
+        if ( mrgCandIdx == iCount )
+        {
+          return;
+        }
+        iCount ++;
+      }
+    }
+  }
+#endif
+
+  //left
+  UInt uiLeftPartIdx = 0;
+  TComDataCU* pcCULeft = 0;
+  pcCULeft = getPULeft( uiLeftPartIdx, uiPartIdxLB, true, false );
+#if INTRA_BL
+  if( pcCULeft && pcCULeft->isIntraBL( uiLeftPartIdx ) )
+  {
+    pcCULeft = NULL;
+  }
+#endif
+  if (pcCULeft) 
+  {
+    if (!pcCULeft->isDiffMER(xP -1, yP+nPSH-1, xP, yP))
+    {
+      pcCULeft = NULL;
+    }
+  }
+  PartSize partSize = getPartitionSize( uiAbsPartIdx );
+  if (!(uiPUIdx == 1 && (partSize == SIZE_Nx2N || partSize == SIZE_nLx2N || partSize == SIZE_nRx2N)))
+  {
+#if SVC_MVP
+  if ( pcCULeft && !pcCULeft->isIntra( uiLeftPartIdx ) && ( !pcColCU || pcColCU->isIntra( uiAbsPartAddrBase ) || !pcCULeft->hasEqualMotion( uiLeftPartIdx, puhInterDirNeighbours[0], &pcMvFieldNeighbours[0])))
+#else
+  if ( pcCULeft && !pcCULeft->isIntra( uiLeftPartIdx ) )
+#endif
+  {
+    abCandIsInter[iCount] = true;
+    // get Inter Dir
+    puhInterDirNeighbours[iCount] = pcCULeft->getInterDir( uiLeftPartIdx );
+    // get Mv from Left
+    pcCULeft->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] );
+    }
+    if ( mrgCandIdx == iCount )
+    {
+      return;
+    }
+    iCount ++;
+  }
+  }
+
+  // early termination
+  if (iCount == getSlice()->getMaxNumMergeCand()) 
+  {
+    return;
+  }
+  // above
+  UInt uiAbovePartIdx = 0;
+  TComDataCU* pcCUAbove = 0;
+  pcCUAbove = getPUAbove( uiAbovePartIdx, uiPartIdxRT, true, false, true );
+#if INTRA_BL
+  if( pcCUAbove && pcCUAbove->isIntraBL( uiAbovePartIdx ) )
+  {
+    pcCUAbove = NULL;
+  }
+#endif
+  if (pcCUAbove) 
+  {
+    if (!pcCUAbove->isDiffMER(xP+nPSW-1, yP-1, xP, yP))
+    {
+      pcCUAbove = NULL;
+    }
+  }
+#if SVC_MVP
+  if ( pcCUAbove && !pcCUAbove->isIntra( uiAbovePartIdx ) 
+    && !(uiPUIdx == 1 && (cCurPS == SIZE_2NxN || cCurPS == SIZE_2NxnU || cCurPS == SIZE_2NxnD))
+    && ( !pcCULeft || pcCULeft->isIntra( uiLeftPartIdx ) || !pcCULeft->hasEqualMotion( uiLeftPartIdx, pcCUAbove, uiAbovePartIdx ) ) 
+    && ( !pcColCU || pcColCU->isIntra( uiAbsPartAddrBase ) || !pcCUAbove->hasEqualMotion( uiAbovePartIdx, puhInterDirNeighbours[0], &pcMvFieldNeighbours[0] )) )
+#else
+  if ( pcCUAbove && !pcCUAbove->isIntra( uiAbovePartIdx ) 
+    && !(uiPUIdx == 1 && (cCurPS == SIZE_2NxN || cCurPS == SIZE_2NxnU || cCurPS == SIZE_2NxnD))
+    && ( !pcCULeft || pcCULeft->isIntra( uiLeftPartIdx ) || !pcCULeft->hasEqualMotion( uiLeftPartIdx, pcCUAbove, uiAbovePartIdx ) ) )
+#endif
+  {
+    abCandIsInter[iCount] = true;
+    // get Inter Dir
+    puhInterDirNeighbours[iCount] = pcCUAbove->getInterDir( uiAbovePartIdx );
+    // get Mv from Left
+    pcCUAbove->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] );
+    }
+    if ( mrgCandIdx == iCount )
+    {
+      return;
+    }
+    iCount ++;
+  }
+  // early termination
+  if (iCount == getSlice()->getMaxNumMergeCand()) 
+  {
+    return;
+  }
+
+  // above right
+  UInt uiAboveRightPartIdx = 0;
+  TComDataCU* pcCUAboveRight = 0;
+  pcCUAboveRight = getPUAboveRight( uiAboveRightPartIdx, uiPartIdxRT, true, false, true );
+  if (pcCUAboveRight) 
+  {
+    if (!pcCUAboveRight->isDiffMER(xP+nPSW, yP-1, xP, yP))
+    {
+      pcCUAboveRight = NULL;
+    }
+  }
+#if SVC_MVP
+  if ( pcCUAboveRight && !pcCUAboveRight->isIntra( uiAboveRightPartIdx ) && ( !pcCUAbove || pcCUAbove->isIntra( uiAbovePartIdx ) || !pcCUAbove->hasEqualMotion( uiAbovePartIdx, pcCUAboveRight, uiAboveRightPartIdx ) ) 
+                                                                         && ( !pcColCU || pcColCU->isIntra( uiAbsPartAddrBase ) || !pcCUAboveRight->hasEqualMotion( uiAboveRightPartIdx, puhInterDirNeighbours[0], &pcMvFieldNeighbours[0] )) )
+#else
+  if ( pcCUAboveRight && !pcCUAboveRight->isIntra( uiAboveRightPartIdx ) && ( !pcCUAbove || pcCUAbove->isIntra( uiAbovePartIdx ) || !pcCUAbove->hasEqualMotion( uiAbovePartIdx, pcCUAboveRight, uiAboveRightPartIdx ) ) )
+#endif
+  {
+    abCandIsInter[iCount] = true;
+    // get Inter Dir
+    puhInterDirNeighbours[iCount] = pcCUAboveRight->getInterDir( uiAboveRightPartIdx );
+    // get Mv from Left
+    pcCUAboveRight->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] );
+    }
+    if ( mrgCandIdx == iCount )
+    {
+      return;
+    }
+    iCount ++;
+  }
+  // early termination
+  if (iCount == getSlice()->getMaxNumMergeCand()) 
+  {
+    return;
+  }
+
+  //left bottom
+#if SVC_MVP
+  if( iCount < 4 )
+  {
+#endif
+  UInt uiLeftBottomPartIdx = 0;
+  TComDataCU* pcCULeftBottom = 0;
+  pcCULeftBottom = this->getPUBelowLeft( uiLeftBottomPartIdx, uiPartIdxLB, true, false );
+  if (pcCULeftBottom)
+  {
+    if (!pcCULeftBottom->isDiffMER(xP-1, yP+nPSH, xP, yP))
+    {
+      pcCULeftBottom = NULL;
+    }
+  }
+#if SVC_MVP
+  if ( pcCULeftBottom && !pcCULeftBottom->isIntra( uiLeftBottomPartIdx ) && ( !pcCULeft || pcCULeft->isIntra( uiLeftPartIdx ) || !pcCULeft->hasEqualMotion( uiLeftPartIdx, pcCULeftBottom, uiLeftBottomPartIdx ) ) 
+                                                                         && ( !pcColCU || pcColCU->isIntra( uiAbsPartAddrBase ) || !pcCULeftBottom->hasEqualMotion( uiLeftBottomPartIdx, puhInterDirNeighbours[0], &pcMvFieldNeighbours[0])) )
+#else
+  if ( pcCULeftBottom && !pcCULeftBottom->isIntra( uiLeftBottomPartIdx ) && ( !pcCULeft || pcCULeft->isIntra( uiLeftPartIdx ) || !pcCULeft->hasEqualMotion( uiLeftPartIdx, pcCULeftBottom, uiLeftBottomPartIdx ) ) )
+#endif
+  {
+    abCandIsInter[iCount] = true;
+    // get Inter Dir
+    puhInterDirNeighbours[iCount] = pcCULeftBottom->getInterDir( uiLeftBottomPartIdx );
+    // get Mv from Left
+    pcCULeftBottom->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] );
+    }
+    if ( mrgCandIdx == iCount )
+    {
+      return;
+    }
+    iCount ++;
+  }
+  // early termination
+  if (iCount == getSlice()->getMaxNumMergeCand()) 
+  {
+    return;
+  }
+#if SVC_MVP
+  }
+#endif
+
+  // above left 
+  if( iCount < 4 )
+  {
+    UInt uiAboveLeftPartIdx = 0;
+    TComDataCU* pcCUAboveLeft = 0;
+    pcCUAboveLeft = getPUAboveLeft( uiAboveLeftPartIdx, uiAbsPartAddr, true, false, true );
+    if (pcCUAboveLeft) 
+    {
+      if (!pcCUAboveLeft->isDiffMER(xP-1, yP-1, xP, yP))
+      {
+        pcCUAboveLeft = NULL;
+      }
+    }
+#if SVC_MVP
+    if( pcCUAboveLeft && !pcCUAboveLeft->isIntra( uiAboveLeftPartIdx )
+     && ( !pcCULeft || pcCULeft->isIntra( uiLeftPartIdx ) || !pcCULeft->hasEqualMotion( uiLeftPartIdx, pcCUAboveLeft, uiAboveLeftPartIdx ) )
+     && ( !pcCUAbove || pcCUAbove->isIntra( uiAbovePartIdx ) || !pcCUAbove->hasEqualMotion( uiAbovePartIdx, pcCUAboveLeft, uiAboveLeftPartIdx ) )
+     && ( !pcColCU || pcColCU->isIntra( uiAbsPartAddrBase ) || !pcCUAboveLeft->hasEqualMotion( uiAboveLeftPartIdx, puhInterDirNeighbours[0], &pcMvFieldNeighbours[0] )) 
+     )
+#else
+    if( pcCUAboveLeft && !pcCUAboveLeft->isIntra( uiAboveLeftPartIdx )
+     && ( !pcCULeft || pcCULeft->isIntra( uiLeftPartIdx ) || !pcCULeft->hasEqualMotion( uiLeftPartIdx, pcCUAboveLeft, uiAboveLeftPartIdx ) )
+     && ( !pcCUAbove || pcCUAbove->isIntra( uiAbovePartIdx ) || !pcCUAbove->hasEqualMotion( uiAbovePartIdx, pcCUAboveLeft, uiAboveLeftPartIdx ) )
+     )
+#endif
+    {
+      abCandIsInter[iCount] = true;
+      // get Inter Dir
+      puhInterDirNeighbours[iCount] = pcCUAboveLeft->getInterDir( uiAboveLeftPartIdx );
+      // get Mv from Left
+      pcCUAboveLeft->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] );
+      }
+      if ( mrgCandIdx == iCount )
+      {
+        return;
+      }
+      iCount ++;
+    }
+  }
+  // early termination
+  if (iCount == getSlice()->getMaxNumMergeCand()) 
+  {
+    return;
+  }
+  if ( getSlice()->getEnableTMVPFlag())
+  {
+    //>> MTK colocated-RightBottom
+    UInt uiPartIdxRB;
+    Int uiLCUIdx = getAddr();
+    PartSize eCUMode = getPartitionSize( 0 );
+
+    deriveRightBottomIdx( eCUMode, uiPUIdx, uiPartIdxRB );  
+
+    UInt uiAbsPartIdxTmp = g_auiZscanToRaster[uiPartIdxRB];
+    UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
+
+    TComMv cColMv;
+    Int iRefIdx;
+
+    if      ( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelX() + g_auiRasterToPelX[uiAbsPartIdxTmp] + m_pcPic->getMinCUWidth() ) >= m_pcSlice->getSPS()->getPicWidthInLumaSamples() )  // image boundary check
+    {
+      uiLCUIdx = -1;
+    }
+    else if ( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelY() + g_auiRasterToPelY[uiAbsPartIdxTmp] + m_pcPic->getMinCUHeight() ) >= m_pcSlice->getSPS()->getPicHeightInLumaSamples() )
+    {
+      uiLCUIdx = -1;
+    }
+    else
+    {
+      if ( ( uiAbsPartIdxTmp % uiNumPartInCUWidth < uiNumPartInCUWidth - 1 ) &&           // is not at the last column of LCU 
+        ( uiAbsPartIdxTmp / uiNumPartInCUWidth < m_pcPic->getNumPartInHeight() - 1 ) ) // is not at the last row    of LCU
+      {
+        uiAbsPartAddr = g_auiRasterToZscan[ uiAbsPartIdxTmp + uiNumPartInCUWidth + 1 ];
+        uiLCUIdx = getAddr();
+      }
+      else if ( uiAbsPartIdxTmp % uiNumPartInCUWidth < uiNumPartInCUWidth - 1 )           // is not at the last column of LCU But is last row of LCU
+      {
+        uiAbsPartAddr = g_auiRasterToZscan[ (uiAbsPartIdxTmp + uiNumPartInCUWidth + 1) % m_pcPic->getNumPartInCU() ];
+        uiLCUIdx = -1 ; 
+      }
+      else if ( uiAbsPartIdxTmp / uiNumPartInCUWidth < m_pcPic->getNumPartInHeight() - 1 ) // is not at the last row of LCU But is last column of LCU
+      {
+        uiAbsPartAddr = g_auiRasterToZscan[ uiAbsPartIdxTmp + 1 ];
+        uiLCUIdx = getAddr() + 1;
+      }
+      else //is the right bottom corner of LCU                       
+      {
+        uiAbsPartAddr = 0;
+        uiLCUIdx = -1 ; 
+      }
+    }
+    iRefIdx = 0;
+
+    Bool bExistMV = false;
+    UInt uiPartIdxCenter;
+    UInt uiCurLCUIdx = getAddr();
+    xDeriveCenterIdx( eCUMode, uiPUIdx, uiPartIdxCenter );
+    bExistMV = uiLCUIdx >= 0 && xGetColMVP( REF_PIC_LIST_0, uiLCUIdx, uiAbsPartAddr, cColMv, iRefIdx );
+    if( bExistMV == false )
+    {
+      bExistMV = xGetColMVP( REF_PIC_LIST_0, uiCurLCUIdx, uiPartIdxCenter,  cColMv, iRefIdx );
+    }
+    if( bExistMV )
+    {
+      UInt uiArrayAddr = iCount;
+      abCandIsInter[uiArrayAddr] = true;
+      pcMvFieldNeighbours[uiArrayAddr << 1].setMvField( cColMv, iRefIdx );
+
+      if ( getSlice()->isInterB() )
+      {       
+        iRefIdx = 0;
+        bExistMV = uiLCUIdx >= 0 && xGetColMVP( REF_PIC_LIST_1, uiLCUIdx, uiAbsPartAddr, cColMv, iRefIdx);
+        if( bExistMV == false )
+        {
+          bExistMV = xGetColMVP( REF_PIC_LIST_1, uiCurLCUIdx, uiPartIdxCenter,  cColMv, iRefIdx );
+        }
+        if( bExistMV )
+        {
+          pcMvFieldNeighbours[ ( uiArrayAddr << 1 ) + 1 ].setMvField( cColMv, iRefIdx );
+          puhInterDirNeighbours[uiArrayAddr] = 3;
+        }
+        else
+        {
+          puhInterDirNeighbours[uiArrayAddr] = 1;
+        }
+      }
+      else
+      {
+        puhInterDirNeighbours[uiArrayAddr] = 1;
+      }
+      if ( mrgCandIdx == iCount )
+      {
+        return;
+      }
+      iCount++;
+    }
+    uiIdx++;
+
+  }
+  // early termination
+  if (iCount == getSlice()->getMaxNumMergeCand()) 
+  {
+    return;
+  }
+  UInt uiArrayAddr = iCount;
+  UInt uiCutoff = uiArrayAddr;
+    
+  if ( getSlice()->isInterB())
+  {
+    UInt uiPriorityList0[12] = {0 , 1, 0, 2, 1, 2, 0, 3, 1, 3, 2, 3};
+    UInt uiPriorityList1[12] = {1 , 0, 2, 0, 2, 1, 3, 0, 3, 1, 3, 2};
+
+    for (Int idx=0; idx<uiCutoff*(uiCutoff-1) && uiArrayAddr!= getSlice()->getMaxNumMergeCand(); idx++)
+    {
+      Int i = uiPriorityList0[idx]; Int j = uiPriorityList1[idx];
+      if (abCandIsInter[i] && abCandIsInter[j]&& (puhInterDirNeighbours[i]&0x1)&&(puhInterDirNeighbours[j]&0x2))
+      {
+        abCandIsInter[uiArrayAddr] = true;
+        puhInterDirNeighbours[uiArrayAddr] = 3;
+
+        // get Mv from cand[i] and cand[j]
+        pcMvFieldNeighbours[uiArrayAddr << 1].setMvField(pcMvFieldNeighbours[i<<1].getMv(), pcMvFieldNeighbours[i<<1].getRefIdx());
+        pcMvFieldNeighbours[( uiArrayAddr << 1 ) + 1].setMvField(pcMvFieldNeighbours[(j<<1)+1].getMv(), pcMvFieldNeighbours[(j<<1)+1].getRefIdx());
+
+        Int iRefPOCL0 = m_pcSlice->getRefPOC( REF_PIC_LIST_0, pcMvFieldNeighbours[(uiArrayAddr<<1)].getRefIdx() );
+        Int iRefPOCL1 = m_pcSlice->getRefPOC( REF_PIC_LIST_1, pcMvFieldNeighbours[(uiArrayAddr<<1)+1].getRefIdx() );
+        if (iRefPOCL0 == iRefPOCL1 && pcMvFieldNeighbours[(uiArrayAddr<<1)].getMv() == pcMvFieldNeighbours[(uiArrayAddr<<1)+1].getMv())
+        {
+          abCandIsInter[uiArrayAddr] = false;
+        }
+        else
+        {
+          uiArrayAddr++;
+        }
+      }
+    }
+  }
+  // early termination
+  if (uiArrayAddr == getSlice()->getMaxNumMergeCand()) 
+  {
+    return;
+  }
+  Int iNumRefIdx = (getSlice()->isInterB()) ? min(m_pcSlice->getNumRefIdx(REF_PIC_LIST_0), m_pcSlice->getNumRefIdx(REF_PIC_LIST_1)) : m_pcSlice->getNumRefIdx(REF_PIC_LIST_0);
+  Int r = 0;
+  Int refcnt = 0;
+  while (uiArrayAddr < getSlice()->getMaxNumMergeCand())
+  {
+    abCandIsInter[uiArrayAddr] = true;
+    puhInterDirNeighbours[uiArrayAddr] = 1;
+    pcMvFieldNeighbours[uiArrayAddr << 1].setMvField( TComMv(0, 0), r);
+
+    if ( getSlice()->isInterB() )
+    {
+      puhInterDirNeighbours[uiArrayAddr] = 3;
+      pcMvFieldNeighbours[(uiArrayAddr << 1) + 1].setMvField(TComMv(0, 0), r);
+    }
+    uiArrayAddr++;
+    if ( refcnt == iNumRefIdx - 1 )
+    {
+      r = 0;
+    }
+    else
+    {
+      ++r;
+      ++refcnt;
+    }
+  }
+
+  numValidMergeCand = uiArrayAddr;
+}
+
+/** Check whether the current PU and a spatial neighboring PU are in a same ME region.
+ * \param xN, xN   location of the upper-left corner pixel of a neighboring PU
+ * \param xP, yP   location of the upper-left corner pixel of the current PU
+ * \returns Bool
+ */
+Bool TComDataCU::isDiffMER(Int xN, Int yN, Int xP, Int yP)
+{
+
+  UInt plevel = this->getSlice()->getPPS()->getLog2ParallelMergeLevelMinus2() + 2;
+  if ((xN>>plevel)!= (xP>>plevel))
+  {
+    return true;
+  }
+  if ((yN>>plevel)!= (yP>>plevel))
+  {
+    return true;
+  }
+  return false;
+}
+/** calculate the location of upper-left corner pixel and size of the current PU.
+ * \param partIdx  PU index within a CU
+ * \param xP, yP   location of the upper-left corner pixel of the current PU
+ * \param PSW, nPSH    size of the curren PU
+ * \returns Void
+ */
+Void TComDataCU::getPartPosition( UInt partIdx, Int& xP, Int& yP, Int& nPSW, Int& nPSH)
+{
+  UInt col = m_uiCUPelX;
+  UInt row = m_uiCUPelY;
+
+  switch ( m_pePartSize[0] )
+  {
+  case SIZE_2NxN:
+    nPSW = getWidth(0);      
+    nPSH = getHeight(0) >> 1; 
+    xP   = col;
+    yP   = (partIdx ==0)? row: row + nPSH;
+    break;
+  case SIZE_Nx2N:
+    nPSW = getWidth(0) >> 1; 
+    nPSH = getHeight(0);      
+    xP   = (partIdx ==0)? col: col + nPSW;
+    yP   = row;
+    break;
+  case SIZE_NxN:
+    nPSW = getWidth(0) >> 1; 
+    nPSH = getHeight(0) >> 1; 
+    xP   = col + (partIdx&0x1)*nPSW;
+    yP   = row + (partIdx>>1)*nPSH;
+    break;
+  case SIZE_2NxnU:
+    nPSW = getWidth(0);
+    nPSH = ( partIdx == 0 ) ?  getHeight(0) >> 2 : ( getHeight(0) >> 2 ) + ( getHeight(0) >> 1 );
+    xP   = col;
+    yP   = (partIdx ==0)? row: row + getHeight(0) - nPSH;
+
+    break;
+  case SIZE_2NxnD:
+    nPSW = getWidth(0);
+    nPSH = ( partIdx == 0 ) ?  ( getHeight(0) >> 2 ) + ( getHeight(0) >> 1 ) : getHeight(0) >> 2;
+    xP   = col;
+    yP   = (partIdx ==0)? row: row + getHeight(0) - nPSH;
+    break;
+  case SIZE_nLx2N:
+    nPSW = ( partIdx == 0 ) ? getWidth(0) >> 2 : ( getWidth(0) >> 2 ) + ( getWidth(0) >> 1 );
+    nPSH = getHeight(0);
+    xP   = (partIdx ==0)? col: col + getWidth(0) - nPSW;
+    yP   = row;
+    break;
+  case SIZE_nRx2N:
+    nPSW = ( partIdx == 0 ) ? ( getWidth(0) >> 2 ) + ( getWidth(0) >> 1 ) : getWidth(0) >> 2;
+    nPSH = getHeight(0);
+    xP   = (partIdx ==0)? col: col + getWidth(0) - nPSW;
+    yP   = row;
+    break;
+  default:
+    assert ( m_pePartSize[0] == SIZE_2Nx2N );
+    nPSW = getWidth(0);      
+    nPSH = getHeight(0);      
+    xP   = col ;
+    yP   = row ;
+
+    break;
+  }
+}
+
+#if !SPS_AMVP_CLEANUP
+AMVP_MODE TComDataCU::getAMVPMode(UInt uiIdx)
+{
+  return m_pcSlice->getSPS()->getAMVPMode(m_puhDepth[uiIdx]);
+}
+#endif
+
+/** Constructs a list of candidates for AMVP
+ * \param uiPartIdx
+ * \param uiPartAddr 
+ * \param eRefPicList
+ * \param iRefIdx
+ * \param pInfo
+ */
+Void TComDataCU::fillMvpCand ( UInt uiPartIdx, UInt uiPartAddr, RefPicList eRefPicList, Int iRefIdx, AMVPInfo* pInfo )
+{
+  PartSize eCUMode = getPartitionSize( 0 );
+  
+  TComMv cMvPred;
+  Bool bAddedSmvp = false;
+
+  pInfo->iN = 0;  
+  if (iRefIdx < 0)
+  {
+    return;
+  }
+  
+  //-- Get Spatial MV
+  UInt uiPartIdxLT, uiPartIdxRT, uiPartIdxLB;
+  UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
+  Bool bAdded = false;
+  
+  deriveLeftRightTopIdx( eCUMode, uiPartIdx, uiPartIdxLT, uiPartIdxRT );
+  deriveLeftBottomIdx( eCUMode, uiPartIdx, uiPartIdxLB );
+  
+  TComDataCU* tmpCU = NULL;
+  UInt idx;
+  tmpCU = getPUBelowLeft(idx, uiPartIdxLB, true, false);
+#if INTRA_BL
+  bAddedSmvp = (tmpCU != NULL) && (!tmpCU->isIntra(idx));
+#else
+  bAddedSmvp = (tmpCU != NULL) && (tmpCU->getPredictionMode(idx) != MODE_INTRA);
+#endif
+
+  if (!bAddedSmvp)
+  {
+    tmpCU = getPULeft(idx, uiPartIdxLB, true, false);
+#if INTRA_BL
+    bAddedSmvp = (tmpCU != NULL) && (!tmpCU->isIntra(idx));
+#else
+    bAddedSmvp = (tmpCU != NULL) && (tmpCU->getPredictionMode(idx) != MODE_INTRA);
+#endif
+  }
+
+  // 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 (!bAdded) 
+    {
+      bAdded = xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxLB, 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)
+  {
+    bAdded = xAddMVPCand( pInfo, eRefPicList, iRefIdx, uiPartIdxLT, MD_ABOVE_LEFT);
+  }
+  bAdded = bAddedSmvp;
+  if (pInfo->iN==2) bAdded = true;
+
+  if(!bAdded)
+  {
+    bAdded = xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxRT, MD_ABOVE_RIGHT);
+    if (!bAdded) 
+    {
+      bAdded = xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxRT, MD_ABOVE);
+    }
+
+    if(!bAdded)
+    {
+      bAdded = xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxLT, MD_ABOVE_LEFT);
+    }
+  }
+  
+#if !SPS_AMVP_CLEANUP
+  if (getAMVPMode(uiPartAddr) == AM_NONE)  //Should be optimized later for special cases
+  {
+    assert(pInfo->iN > 0);
+    pInfo->iN = 1;
+    return;
+  }
+#endif
+
+  if ( pInfo->iN == 2 )
+  {
+    if ( pInfo->m_acMvCand[ 0 ] == pInfo->m_acMvCand[ 1 ] )
+    {
+      pInfo->iN = 1;
+    }
+  }
+
+  if ( getSlice()->getEnableTMVPFlag() )
+  {
+    // Get Temporal Motion Predictor
+    int iRefIdx_Col = iRefIdx;
+    TComMv cColMv;
+    UInt uiPartIdxRB;
+    UInt uiAbsPartIdx;  
+    UInt uiAbsPartAddr;
+    int uiLCUIdx = getAddr();
+
+    deriveRightBottomIdx( eCUMode, uiPartIdx, uiPartIdxRB );
+    uiAbsPartAddr = m_uiAbsIdxInLCU + uiPartAddr;
+
+    //----  co-located RightBottom Temporal Predictor (H) ---//
+    uiAbsPartIdx = g_auiZscanToRaster[uiPartIdxRB];
+    if ( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelX() + g_auiRasterToPelX[uiAbsPartIdx] + m_pcPic->getMinCUWidth() ) >= m_pcSlice->getSPS()->getPicWidthInLumaSamples() )  // image boundary check
+    {
+      uiLCUIdx = -1;
+    }
+    else if ( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelY() + g_auiRasterToPelY[uiAbsPartIdx] + m_pcPic->getMinCUHeight() ) >= m_pcSlice->getSPS()->getPicHeightInLumaSamples() )
+    {
+      uiLCUIdx = -1;
+    }
+    else
+    {
+      if ( ( uiAbsPartIdx % uiNumPartInCUWidth < uiNumPartInCUWidth - 1 ) &&           // is not at the last column of LCU 
+        ( uiAbsPartIdx / uiNumPartInCUWidth < m_pcPic->getNumPartInHeight() - 1 ) ) // is not at the last row    of LCU
+      {
+        uiAbsPartAddr = g_auiRasterToZscan[ uiAbsPartIdx + uiNumPartInCUWidth + 1 ];
+        uiLCUIdx = getAddr();
+      }
+      else if ( uiAbsPartIdx % uiNumPartInCUWidth < uiNumPartInCUWidth - 1 )           // is not at the last column of LCU But is last row of LCU
+      {
+        uiAbsPartAddr = g_auiRasterToZscan[ (uiAbsPartIdx + uiNumPartInCUWidth + 1) % m_pcPic->getNumPartInCU() ];
+        uiLCUIdx      = -1 ; 
+      }
+      else if ( uiAbsPartIdx / uiNumPartInCUWidth < m_pcPic->getNumPartInHeight() - 1 ) // is not at the last row of LCU But is last column of LCU
+      {
+        uiAbsPartAddr = g_auiRasterToZscan[ uiAbsPartIdx + 1 ];
+        uiLCUIdx = getAddr() + 1;
+      }
+      else //is the right bottom corner of LCU                       
+      {
+        uiAbsPartAddr = 0;
+        uiLCUIdx      = -1 ; 
+      }
+    }
+    if ( uiLCUIdx >= 0 && xGetColMVP( eRefPicList, uiLCUIdx, uiAbsPartAddr, cColMv, iRefIdx_Col ) )
+    {
+      pInfo->m_acMvCand[pInfo->iN++] = cColMv;
+    }
+    else 
+    {
+      UInt uiPartIdxCenter;
+      UInt uiCurLCUIdx = getAddr();
+      xDeriveCenterIdx( eCUMode, uiPartIdx, uiPartIdxCenter );
+      if (xGetColMVP( eRefPicList, uiCurLCUIdx, uiPartIdxCenter,  cColMv, iRefIdx_Col ))
+      {
+        pInfo->m_acMvCand[pInfo->iN++] = cColMv;
+      }
+    }
+    //----  co-located RightBottom Temporal Predictor  ---//
+  }
+
+  if (pInfo->iN > AMVP_MAX_NUM_CANDS)
+  {
+    pInfo->iN = AMVP_MAX_NUM_CANDS;
+  }
+  while (pInfo->iN < AMVP_MAX_NUM_CANDS)
+  {
+      pInfo->m_acMvCand[pInfo->iN].set(0,0);
+      pInfo->iN++;
+  }
+  return ;
+}
+
+Bool TComDataCU::isBipredRestriction(UInt puIdx)
+{
+  Int width = 0;
+  Int height = 0;
+  UInt partAddr;
+
+  getPartIndexAndSize( puIdx, partAddr, width, height );
+  if ( getWidth(0) == 8 && (width < 8 || height < 8) )
+  {
+    return true;
+  }
+  return false;
+}
+
+Void TComDataCU::clipMv    (TComMv&  rcMv)
+{
+  Int  iMvShift = 2;
+  Int iOffset = 8;
+  Int iHorMax = ( m_pcSlice->getSPS()->getPicWidthInLumaSamples() + iOffset - m_uiCUPelX - 1 ) << iMvShift;
+  Int iHorMin = (       -(Int)g_uiMaxCUWidth - iOffset - (Int)m_uiCUPelX + 1 ) << iMvShift;
+  
+  Int iVerMax = ( m_pcSlice->getSPS()->getPicHeightInLumaSamples() + iOffset - m_uiCUPelY - 1 ) << iMvShift;
+  Int iVerMin = (       -(Int)g_uiMaxCUHeight - iOffset - (Int)m_uiCUPelY + 1 ) << iMvShift;
+  
+  rcMv.setHor( min (iHorMax, max (iHorMin, rcMv.getHor())) );
+  rcMv.setVer( min (iVerMax, max (iVerMin, rcMv.getVer())) );
+}
+
+
+Void TComDataCU::convertTransIdx( UInt uiAbsPartIdx, UInt uiTrIdx, UInt& ruiLumaTrMode, UInt& ruiChromaTrMode )
+{
+  ruiLumaTrMode   = uiTrIdx;
+  ruiChromaTrMode = uiTrIdx;
+  return;
+}
+
+UInt TComDataCU::getIntraSizeIdx(UInt uiAbsPartIdx)
+{
+  UInt uiShift = ( (m_puhTrIdx[uiAbsPartIdx]==0) && (m_pePartSize[uiAbsPartIdx]==SIZE_NxN) ) ? m_puhTrIdx[uiAbsPartIdx]+1 : m_puhTrIdx[uiAbsPartIdx];
+  uiShift = ( m_pePartSize[uiAbsPartIdx]==SIZE_NxN ? 1 : 0 );
+  
+  UChar uiWidth = m_puhWidth[uiAbsPartIdx]>>uiShift;
+  UInt  uiCnt = 0;
+  while( uiWidth )
+  {
+    uiCnt++;
+    uiWidth>>=1;
+  }
+  uiCnt-=2;
+  return uiCnt > 6 ? 6 : uiCnt;
+}
+
+Void TComDataCU::clearCbf( UInt uiIdx, TextType eType, UInt uiNumParts )
+{
+  ::memset( &m_puhCbf[g_aucConvertTxtTypeToIdx[eType]][uiIdx], 0, sizeof(UChar)*uiNumParts);
+}
+
+/** Set a I_PCM flag for all sub-partitions of a partition.
+ * \param bIpcmFlag I_PCM flag
+ * \param uiAbsPartIdx patition index
+ * \param uiDepth CU depth
+ * \returns Void
+ */
+Void TComDataCU::setIPCMFlagSubParts  (Bool bIpcmFlag, UInt uiAbsPartIdx, UInt uiDepth)
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+
+  memset(m_pbIPCMFlag + uiAbsPartIdx, bIpcmFlag, sizeof(Bool)*uiCurrPartNumb );
+}
+
+/** Test whether the current block is skipped
+ * \param uiPartIdx Block index
+ * \returns Flag indicating whether the block is skipped
+ */
+Bool TComDataCU::isSkipped( UInt uiPartIdx )
+{
+#if SKIP_FLAG
+  return ( getSkipFlag( uiPartIdx ) );
+#else
+  if ( m_pcSlice->isIntra () )
+  {
+    return false;
+  }
+  return ( getMergeFlag( uiPartIdx ) && getPartitionSize( uiPartIdx ) == SIZE_2Nx2N && !getQtRootCbf( uiPartIdx ) );
+#endif
+}
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+Bool TComDataCU::xAddMVPCand( AMVPInfo* pInfo, RefPicList eRefPicList, Int iRefIdx, UInt uiPartUnitIdx, MVP_DIR eDir )
+{
+  TComDataCU* pcTmpCU = NULL;
+  UInt uiIdx;
+  switch( eDir )
+  {
+    case MD_LEFT:
+    {
+      pcTmpCU = getPULeft(uiIdx, uiPartUnitIdx, true, false);
+      break;
+    }
+    case MD_ABOVE:
+    {
+      pcTmpCU = getPUAbove(uiIdx, uiPartUnitIdx, true, false, true);
+      break;
+    }
+    case MD_ABOVE_RIGHT:
+    {
+      pcTmpCU = getPUAboveRight(uiIdx, uiPartUnitIdx, true, false, true);
+      break;
+    }
+    case MD_BELOW_LEFT:
+    {
+      pcTmpCU = getPUBelowLeft(uiIdx, uiPartUnitIdx, true, false);
+      break;
+    }
+    case MD_ABOVE_LEFT:
+    {
+      pcTmpCU = getPUAboveLeft(uiIdx, uiPartUnitIdx, true, false, true);
+      break;
+    }
+    default:
+    {
+      break;
+    }
+  }
+ 
+  if ( pcTmpCU != NULL && m_pcSlice->isEqualRef(eRefPicList, pcTmpCU->getCUMvField(eRefPicList)->getRefIdx(uiIdx), iRefIdx) )
+  {
+    TComMv cMvPred = pcTmpCU->getCUMvField(eRefPicList)->getMv(uiIdx);
+    
+    pInfo->m_acMvCand[ pInfo->iN++] = cMvPred;
+    return true;
+  }
+
+  if ( pcTmpCU == 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 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;
+      return true;
+    }
+  }
+  return false;
+}
+
+/** 
+ * \param pInfo
+ * \param eRefPicList 
+ * \param iRefIdx
+ * \param uiPartUnitIdx
+ * \param eDir
+ * \returns Bool
+ */
+Bool TComDataCU::xAddMVPCandOrder( AMVPInfo* pInfo, RefPicList eRefPicList, Int iRefIdx, UInt uiPartUnitIdx, MVP_DIR eDir )
+{
+  TComDataCU* pcTmpCU = NULL;
+  UInt uiIdx;
+  switch( eDir )
+  {
+  case MD_LEFT:
+    {
+      pcTmpCU = getPULeft(uiIdx, uiPartUnitIdx, true, false);
+      break;
+    }
+  case MD_ABOVE:
+    {
+      pcTmpCU = getPUAbove(uiIdx, uiPartUnitIdx, true, false, true);
+      break;
+    }
+  case MD_ABOVE_RIGHT:
+    {
+      pcTmpCU = getPUAboveRight(uiIdx, uiPartUnitIdx, true, false, true);
+      break;
+    }
+  case MD_BELOW_LEFT:
+    {
+      pcTmpCU = getPUBelowLeft(uiIdx, uiPartUnitIdx, true, false);
+      break;
+    }
+  case MD_ABOVE_LEFT:
+    {
+      pcTmpCU = getPUAboveLeft(uiIdx, uiPartUnitIdx, true, false, true);
+      break;
+    }
+  default:
+    {
+      break;
+    }
+  }
+
+  if ( pcTmpCU == 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 NO_MV_PRED_IF_DIFFERENT_TERM
+    if ( bIsCurrRefLongTerm == bIsNeibRefLongTerm ) 
+    {
+#endif
+    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;
+#if NO_MV_PRED_IF_DIFFERENT_TERM
+    }
+#endif
+  }
+  //---------------------- 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 NO_MV_PRED_IF_DIFFERENT_TERM
+    if ( bIsCurrRefLongTerm == bIsNeibRefLongTerm ) 
+    {
+#endif
+    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;
+#if NO_MV_PRED_IF_DIFFERENT_TERM
+    }
+#endif
+  }
+  //---------------------- V3(END) --------------------//
+  return false;
+}
+
+/** 
+ * \param eRefPicList
+ * \param uiCUAddr 
+ * \param uiPartUnitIdx
+ * \param riRefIdx
+ * \returns Bool
+ */
+Bool TComDataCU::xGetColMVP( RefPicList eRefPicList, Int uiCUAddr, Int uiPartUnitIdx, TComMv& rcMv, Int& riRefIdx )
+{
+  UInt uiAbsPartAddr = uiPartUnitIdx;
+
+  RefPicList  eColRefPicList;
+  Int iColPOC, iColRefPOC, iCurrPOC, iCurrRefPOC, iScale;
+  TComMv cColMv;
+
+  // use coldir.
+  TComPic *pColPic = getSlice()->getRefPic( RefPicList(getSlice()->isInterB() ? 1-getSlice()->getColFromL0Flag() : 0), getSlice()->getColRefIdx());
+  TComDataCU *pColCU = pColPic->getCU( uiCUAddr );
+  if(pColCU->getPic()==0||pColCU->getPartitionSize(uiPartUnitIdx)==SIZE_NONE)
+  {
+    return false;
+  }
+  iCurrPOC = m_pcSlice->getPOC();    
+  iCurrRefPOC = m_pcSlice->getRefPic(eRefPicList, riRefIdx)->getPOC();
+  iColPOC = pColCU->getSlice()->getPOC();  
+
+  if (pColCU->isIntra(uiAbsPartAddr))
+  {
+    return false;
+  }
+  eColRefPicList = getSlice()->getCheckLDC() ? eRefPicList : RefPicList(getSlice()->getColFromL0Flag());
+
+  Int iColRefIdx = pColCU->getCUMvField(RefPicList(eColRefPicList))->getRefIdx(uiAbsPartAddr);
+
+  if (iColRefIdx < 0 )
+  {
+    eColRefPicList = RefPicList(1 - eColRefPicList);
+    iColRefIdx = pColCU->getCUMvField(RefPicList(eColRefPicList))->getRefIdx(uiAbsPartAddr);
+
+    if (iColRefIdx < 0 )
+    {
+      return false;
+    }
+  }
+
+  // Scale the vector.
+  iColRefPOC = pColCU->getSlice()->getRefPOC(eColRefPicList, iColRefIdx);
+  cColMv = pColCU->getCUMvField(eColRefPicList)->getMv(uiAbsPartAddr);
+
+  iCurrRefPOC = m_pcSlice->getRefPic(eRefPicList, riRefIdx)->getPOC();
+  Bool bIsCurrRefLongTerm = m_pcSlice->getRefPic(eRefPicList, riRefIdx)->getIsLongTerm();
+  Bool bIsColRefLongTerm = pColCU->getSlice()->getRefPic(eColRefPicList, iColRefIdx)->getIsUsedAsLongTerm();
+
+#if NO_MV_PRED_IF_DIFFERENT_TERM
+  if ( bIsCurrRefLongTerm != bIsColRefLongTerm ) 
+  {
+    return false;
+  }
+#endif
+
+  if ( bIsCurrRefLongTerm || bIsColRefLongTerm )
+  {
+    rcMv = cColMv;
+  }
+  else
+  {
+    iScale = xGetDistScaleFactor(iCurrPOC, iCurrRefPOC, iColPOC, iColRefPOC);
+    if ( iScale == 4096 )
+    {
+      rcMv = cColMv;
+    }
+    else
+    {
+      rcMv = cColMv.scaleMv( iScale );
+    }
+  }
+  return true;
+}
+
+UInt TComDataCU::xGetMvdBits(TComMv cMvd)
+{
+  return ( xGetComponentBits(cMvd.getHor()) + xGetComponentBits(cMvd.getVer()) );
+}
+
+UInt TComDataCU::xGetComponentBits(Int iVal)
+{
+  UInt uiLength = 1;
+  UInt uiTemp   = ( iVal <= 0) ? (-iVal<<1)+1: (iVal<<1);
+  
+  assert ( uiTemp );
+  
+  while ( 1 != uiTemp )
+  {
+    uiTemp >>= 1;
+    uiLength += 2;
+  }
+  
+  return uiLength;
+}
+
+
+Int TComDataCU::xGetDistScaleFactor(Int iCurrPOC, Int iCurrRefPOC, Int iColPOC, Int iColRefPOC)
+{
+  Int iDiffPocD = iColPOC - iColRefPOC;
+  Int iDiffPocB = iCurrPOC - iCurrRefPOC;
+  
+  if( iDiffPocD == iDiffPocB )
+  {
+    return 4096;
+  }
+  else
+  {
+    Int iTDB      = Clip3( -128, 127, iDiffPocB );
+    Int iTDD      = Clip3( -128, 127, iDiffPocD );
+    Int iX        = (0x4000 + abs(iTDD/2)) / iTDD;
+    Int iScale    = Clip3( -4096, 4095, (iTDB * iX + 32) >> 6 );
+    return iScale;
+  }
+}
+
+/** 
+ * \param eCUMode
+ * \param uiPartIdx 
+ * \param ruiPartIdxCenter
+ * \returns Void
+ */
+Void TComDataCU::xDeriveCenterIdx( PartSize eCUMode, UInt uiPartIdx, UInt& ruiPartIdxCenter )
+{
+  UInt uiPartAddr;
+  Int  iPartWidth;
+  Int  iPartHeight;
+  getPartIndexAndSize( uiPartIdx, uiPartAddr, iPartWidth, iPartHeight);
+  
+  ruiPartIdxCenter = m_uiAbsIdxInLCU+uiPartAddr; // partition origin.
+  ruiPartIdxCenter = g_auiRasterToZscan[ g_auiZscanToRaster[ ruiPartIdxCenter ]
+                                        + ( iPartHeight/m_pcPic->getMinCUHeight()  )/2*m_pcPic->getNumPartInWidth()
+                                        + ( iPartWidth/m_pcPic->getMinCUWidth()  )/2];
+}
+
+/** 
+ * \param uiPartIdx
+ * \param eRefPicList 
+ * \param iRefIdx
+ * \param pcMv
+ * \returns Bool
+ */
+Bool TComDataCU::xGetCenterCol( UInt uiPartIdx, RefPicList eRefPicList, int iRefIdx, TComMv *pcMv )
+{
+  PartSize eCUMode = getPartitionSize( 0 );
+  
+  Int iCurrPOC = m_pcSlice->getPOC();
+  
+  // use coldir.
+  TComPic *pColPic = getSlice()->getRefPic( RefPicList(getSlice()->isInterB() ? 1-getSlice()->getColFromL0Flag() : 0), getSlice()->getColRefIdx());
+  TComDataCU *pColCU = pColPic->getCU( m_uiCUAddr );
+  
+  Int iColPOC = pColCU->getSlice()->getPOC();
+  UInt uiPartIdxCenter;
+  xDeriveCenterIdx( eCUMode, uiPartIdx, uiPartIdxCenter );
+  
+  if (pColCU->isIntra(uiPartIdxCenter))
+  {
+    return false;
+  }
+  
+  // Prefer a vector crossing us.  Prefer shortest.
+  RefPicList eColRefPicList = REF_PIC_LIST_0;
+  bool bFirstCrosses = false;
+  Int  iFirstColDist = -1;
+  for (Int l = 0; l < 2; l++)
+  {
+    bool bSaveIt = false;
+    int iColRefIdx = pColCU->getCUMvField(RefPicList(l))->getRefIdx(uiPartIdxCenter);
+    if (iColRefIdx < 0)
+    {
+      continue;
+    }
+    int iColRefPOC = pColCU->getSlice()->getRefPOC(RefPicList(l), iColRefIdx);
+    int iColDist = abs(iColRefPOC - iColPOC);
+    bool bCrosses = iColPOC < iCurrPOC ? iColRefPOC > iCurrPOC : iColRefPOC < iCurrPOC;
+    if (iFirstColDist < 0)
+    {
+      bSaveIt = true;
+    }
+    else if (bCrosses && !bFirstCrosses)
+    {
+      bSaveIt = true;
+    }
+    else if (bCrosses == bFirstCrosses && l == eRefPicList)
+    {
+      bSaveIt = true;
+    }
+    
+    if (bSaveIt)
+    {
+      bFirstCrosses = bCrosses;
+      iFirstColDist = iColDist;
+      eColRefPicList = RefPicList(l);
+    }
+  }
+  
+  // Scale the vector.
+  Int iColRefPOC = pColCU->getSlice()->getRefPOC(eColRefPicList, pColCU->getCUMvField(eColRefPicList)->getRefIdx(uiPartIdxCenter));
+  TComMv cColMv = pColCU->getCUMvField(eColRefPicList)->getMv(uiPartIdxCenter);
+  
+  Int iCurrRefPOC = m_pcSlice->getRefPic(eRefPicList, iRefIdx)->getPOC();
+  Bool bIsCurrRefLongTerm = m_pcSlice->getRefPic(eRefPicList, iRefIdx)->getIsLongTerm();
+  Bool bIsColRefLongTerm = pColCU->getSlice()->getRefPic(eColRefPicList, pColCU->getCUMvField(eColRefPicList)->getRefIdx(uiPartIdxCenter))->getIsUsedAsLongTerm();
+
+#if NO_MV_PRED_IF_DIFFERENT_TERM
+  if ( bIsCurrRefLongTerm != bIsColRefLongTerm ) 
+  {
+    return false;
+  }
+#endif
+
+  if ( bIsCurrRefLongTerm || bIsColRefLongTerm )
+  {
+    pcMv[0] = cColMv;
+  }
+  else
+  {
+    Int iScale = xGetDistScaleFactor(iCurrPOC, iCurrRefPOC, iColPOC, iColRefPOC);
+    if ( iScale == 4096 )
+    {
+      pcMv[0] = cColMv;
+    }
+    else
+    {
+      pcMv[0] = cColMv.scaleMv( iScale );
+    }
+  }
+  return true;
+}
+
+Void TComDataCU::compressMV()
+{
+  Int scaleFactor = 4 * AMVP_DECIMATION_FACTOR / m_unitSize;
+  if (scaleFactor > 0)
+  {
+#if SVC_MVP
+    m_acCUMvField[0].compress(m_pePredMode, m_puhInterDir, scaleFactor);
+    m_acCUMvField[1].compress(m_pePredMode, m_puhInterDir, scaleFactor);    
+#else
+    m_acCUMvField[0].compress(m_pePredMode, scaleFactor);
+    m_acCUMvField[1].compress(m_pePredMode, scaleFactor);    
+#endif
+  }
+}
+
+UInt TComDataCU::getCoefScanIdx(UInt uiAbsPartIdx, UInt uiWidth, Bool bIsLuma, Bool bIsIntra)
+{
+  UInt uiCTXIdx;
+  UInt uiScanIdx;
+  UInt uiDirMode;
+
+  if ( !bIsIntra ) 
+  {
+    uiScanIdx = SCAN_ZIGZAG;
+    return uiScanIdx;
+  }
+
+  switch(uiWidth)
+  {
+    case  2: uiCTXIdx = 6; break;
+    case  4: uiCTXIdx = 5; break;
+    case  8: uiCTXIdx = 4; break;
+    case 16: uiCTXIdx = 3; break;
+    case 32: uiCTXIdx = 2; break;
+    case 64: uiCTXIdx = 1; break;
+    default: uiCTXIdx = 0; break;
+  }
+
+  if ( bIsLuma )
+  {
+    uiDirMode = getLumaIntraDir(uiAbsPartIdx);
+    uiScanIdx = SCAN_ZIGZAG;
+    if (uiCTXIdx >3 && uiCTXIdx < 6) //if multiple scans supported for transform size
+    {
+      uiScanIdx = abs((Int) uiDirMode - VER_IDX) < 5 ? 1 : (abs((Int)uiDirMode - HOR_IDX) < 5 ? 2 : 0);
+    }
+  }
+  else
+  {
+    uiDirMode = getChromaIntraDir(uiAbsPartIdx);
+    if( uiDirMode == DM_CHROMA_IDX )
+    {
+      // get number of partitions in current CU
+      UInt depth = getDepth(uiAbsPartIdx);
+      UInt numParts = getPic()->getNumPartInCU() >> (2 * depth);
+      
+      // get luma mode from upper-left corner of current CU
+      uiDirMode = getLumaIntraDir((uiAbsPartIdx/numParts)*numParts);
+    }
+    uiScanIdx = SCAN_ZIGZAG;
+    if (uiCTXIdx >4 && uiCTXIdx < 7) //if multiple scans supported for transform size
+    {
+      uiScanIdx = abs((Int) uiDirMode - VER_IDX) < 5 ? 1 : (abs((Int)uiDirMode - HOR_IDX) < 5 ? 2 : 0);
+    }
+  }
+
+  return uiScanIdx;
+}
+
+#if !REMOVE_NSQT
+Bool TComDataCU::useNonSquareTrans(UInt uiTrMode, Int absPartIdx)
+{
+  UInt minTuSize = ( 1 << ( getSlice()->getSPS()->getQuadtreeTULog2MinSize() + 1 ) );
+  const UInt uiLog2TrSize = g_aucConvertToBit[ getSlice()->getSPS()->getMaxCUWidth() >> ( m_puhDepth[ absPartIdx ] + uiTrMode ) ] + 2;
+  if ( uiTrMode && uiLog2TrSize < getSlice()->getSPS()->getQuadtreeTULog2MaxSize() && ( getWidth( absPartIdx ) > minTuSize ) &&
+      ( m_pePartSize[absPartIdx] == SIZE_Nx2N || m_pePartSize[absPartIdx] == SIZE_2NxN || ( m_pePartSize[absPartIdx] >= SIZE_2NxnU && m_pePartSize[absPartIdx] <= SIZE_nRx2N ) ) )
+  {
+    return getSlice()->getSPS()->getUseNSQT();
+  }
+  else
+  {
+    return false;
+  }
+}
+
+Void TComDataCU::getNSQTSize(Int trMode, Int absPartIdx, Int &trWidth, Int &trHeight)
+{
+  UInt minTuSize = ( 1 << getSlice()->getSPS()->getQuadtreeTULog2MinSize() );
+  if ( useNonSquareTrans( trMode, absPartIdx ) && ( trWidth > minTuSize ) )
+  {
+    trWidth  = ( m_pePartSize[absPartIdx] == SIZE_Nx2N || m_pePartSize[absPartIdx] == SIZE_nLx2N || m_pePartSize[absPartIdx] == SIZE_nRx2N )? trWidth >> 1 : trWidth << 1;
+    trHeight = ( m_pePartSize[absPartIdx] == SIZE_Nx2N || m_pePartSize[absPartIdx] == SIZE_nLx2N || m_pePartSize[absPartIdx] == SIZE_nRx2N )? trHeight << 1 : trHeight >> 1;
+  }
+}
+
+Bool TComDataCU::useNonSquarePU(UInt absPartIdx)
+{
+  if ( ( m_pePartSize[absPartIdx] == SIZE_Nx2N ) || ( m_pePartSize[absPartIdx] == SIZE_2NxN ) || ( m_pePartSize[absPartIdx] >= SIZE_2NxnU && m_pePartSize[absPartIdx] <= SIZE_nRx2N ) )
+  {
+    return true;
+  }
+  else
+  {
+    return false;
+  }
+}
+
+UInt TComDataCU::getInterTUSplitDirection( Int trWidth, Int trHeight, Int trLastWidth, Int trLastHeight )
+{
+  UInt interTUSplitDirection = 2;
+  if ( ( trWidth == trLastWidth ) && ( trHeight < trLastHeight ) )
+  {
+    interTUSplitDirection = 0;
+  }
+  else if ( ( trWidth < trLastWidth ) && ( trHeight == trLastHeight ) )
+  {
+    interTUSplitDirection = 1;
+  }    
+
+  return interTUSplitDirection;
+}
+
+UInt TComDataCU::getNSAbsPartIdx ( UInt log2TrafoSize, UInt absPartIdx, UInt absTUPartIdx, UInt innerQuadIdx, UInt trMode )
+{
+  Int trWidth, trHeight, trLastWidth, trLastHeight;
+  UInt lcuWidthInBaseUnits = getPic()->getNumPartInWidth();
+  UInt nsTUWidthInBaseUnits, nsTUHeightInBaseUnits;
+  UInt interTUSplitDirection;
+  
+  if( isIntra(absPartIdx) )
+  {
+    return absPartIdx;
+  }
+
+  trWidth = trHeight = ( 1 << log2TrafoSize );
+  trLastWidth = trWidth << 1, trLastHeight = trHeight << 1;  
+
+  getNSQTSize( trMode,     absPartIdx, trWidth,     trHeight );
+  getNSQTSize( trMode - 1, absPartIdx, trLastWidth, trLastHeight );
+  interTUSplitDirection = getInterTUSplitDirection ( trWidth, trHeight, trLastWidth, trLastHeight );
+
+  nsTUWidthInBaseUnits  = trWidth / getPic()->getMinCUWidth();
+  nsTUHeightInBaseUnits = trHeight / getPic()->getMinCUHeight();    
+
+  if ( interTUSplitDirection != 2 )  
+  {
+    UInt uiNSTUBaseUnits = nsTUWidthInBaseUnits < nsTUHeightInBaseUnits ? nsTUWidthInBaseUnits : nsTUHeightInBaseUnits;
+    absTUPartIdx = g_auiRasterToZscan[ g_auiZscanToRaster[absTUPartIdx] + innerQuadIdx * uiNSTUBaseUnits * lcuWidthInBaseUnits * ( 1 - interTUSplitDirection ) + innerQuadIdx * uiNSTUBaseUnits * interTUSplitDirection ];
+  }
+  else  
+  {
+    absTUPartIdx = g_auiRasterToZscan[ g_auiZscanToRaster[absTUPartIdx] + (innerQuadIdx & 0x01) * nsTUWidthInBaseUnits + ( ( innerQuadIdx >> 1 ) & 0x01 ) * nsTUHeightInBaseUnits * lcuWidthInBaseUnits ]; 
+  }
+
+  return absTUPartIdx;  
+}
+
+UInt TComDataCU::getNSAddrChroma( UInt uiLog2TrSizeC, UInt uiTrModeC, UInt uiQuadrant, UInt absTUPartIdx )
+{  
+  if( uiLog2TrSizeC != getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+  {
+    return absTUPartIdx;
+  }
+
+  UInt lcuWidthInBaseUnits = getPic()->getNumPartInWidth();
+  Int trWidth  = ( 1 << ( uiLog2TrSizeC + 1 ) );
+  Int trHeight = ( 1 << ( uiLog2TrSizeC + 1 ) );
+  Int trLastWidth = trWidth << 1, trLastHeight = trHeight << 1;
+
+  getNSQTSize ( uiTrModeC - 1, absTUPartIdx, trLastWidth, trLastHeight );
+  getNSQTSize ( uiTrModeC,     absTUPartIdx, trWidth,     trHeight );
+
+  UInt interTUSplitDirection = getInterTUSplitDirection ( trWidth, trHeight, trLastWidth, trLastHeight );
+  UInt nsTUWidthInBaseUnits  = trWidth / getPic()->getMinCUWidth();
+  UInt nsTUHeightInBaseUnits = trHeight / getPic()->getMinCUHeight();
+  UInt firstTURasterIdx = 0, absTUPartIdxC = 0; 
+
+  if(interTUSplitDirection != 2)
+  {
+    UInt uiNSTUBaseUnits = nsTUWidthInBaseUnits < nsTUHeightInBaseUnits ? 1 : lcuWidthInBaseUnits;
+    firstTURasterIdx   = g_auiZscanToRaster[absTUPartIdx] - uiQuadrant * uiNSTUBaseUnits;
+    absTUPartIdxC      = g_auiRasterToZscan[firstTURasterIdx] + uiQuadrant * nsTUWidthInBaseUnits * nsTUHeightInBaseUnits;
+  }
+  else
+  {
+    UInt uiNSTUBaseUnits = nsTUWidthInBaseUnits < nsTUHeightInBaseUnits ? 2 * lcuWidthInBaseUnits : 2;
+    firstTURasterIdx   = g_auiZscanToRaster[absTUPartIdx] - ( ( uiQuadrant >> 1 ) & 0x01 ) * nsTUHeightInBaseUnits * lcuWidthInBaseUnits - ( uiQuadrant & 0x01 ) * nsTUWidthInBaseUnits;
+    absTUPartIdxC      = g_auiRasterToZscan[firstTURasterIdx + uiQuadrant * uiNSTUBaseUnits];
+  }
+
+  return absTUPartIdxC;
+}
+#endif
+
+UInt TComDataCU::getSCUAddr()
+{ 
+  return getPic()->getPicSym()->getInverseCUOrderMap(m_uiCUAddr)*(1<<(m_pcSlice->getSPS()->getMaxCUDepth()<<1))+m_uiAbsIdxInLCU; 
+}
+
+/** Set neighboring blocks availabilities for non-deblocked filtering 
+ * \param numLCUInPicWidth number of LCUs in picture width
+ * \param numLCUInPicHeight number of LCUs in picture height
+ * \param numSUInLCUWidth number of SUs in LCU width
+ * \param numSUInLCUHeight number of SUs in LCU height
+ * \param picWidth picture width
+ * \param picHeight picture height
+ * \param bIndependentSliceBoundaryEnabled true for independent slice boundary enabled
+ * \param bTopTileBoundary true means that top boundary coincides tile boundary
+ * \param bDownTileBoundary true means that bottom boundary coincides tile boundary
+ * \param bLeftTileBoundary true means that left boundary coincides tile boundary
+ * \param bRightTileBoundary true means that right boundary coincides tile boundary
+ * \param bIndependentTileBoundaryEnabled true for independent tile boundary enabled
+ */
+Void TComDataCU::setNDBFilterBlockBorderAvailability(UInt numLCUInPicWidth, UInt numLCUInPicHeight, UInt numSUInLCUWidth, UInt numSUInLCUHeight, UInt picWidth, UInt picHeight
+                                                    ,std::vector<Bool>& LFCrossSliceBoundary
+                                                    ,Bool bTopTileBoundary, Bool bDownTileBoundary, Bool bLeftTileBoundary, Bool bRightTileBoundary
+                                                    ,Bool bIndependentTileBoundaryEnabled)
+{
+  UInt numSUInLCU = numSUInLCUWidth*numSUInLCUHeight;
+  Int* pSliceIDMapLCU = m_piSliceSUMap;
+#if MODIFIED_CROSS_SLICE
+  Bool onlyOneSliceInPic = ((Int)LFCrossSliceBoundary.size() == 1);
+#endif
+  UInt uiLPelX, uiTPelY;
+  UInt width, height;
+  Bool bPicRBoundary, bPicBBoundary, bPicTBoundary, bPicLBoundary;
+  Bool bLCURBoundary= false, bLCUBBoundary= false, bLCUTBoundary= false, bLCULBoundary= false;
+  Bool* pbAvailBorder;
+  Bool* pbAvail;
+  UInt rTLSU, rBRSU, widthSU, heightSU;
+  UInt zRefSU;
+  Int* pRefID;
+  Int* pRefMapLCU;
+  UInt rTRefSU= 0, rBRefSU= 0, rLRefSU= 0, rRRefSU= 0;
+  Int* pRRefMapLCU= NULL;
+  Int* pLRefMapLCU= NULL;
+  Int* pTRefMapLCU= NULL;
+  Int* pBRefMapLCU= NULL;
+  Int  sliceID;
+  UInt numSGU = (UInt)m_vNDFBlock.size();
+
+  for(Int i=0; i< numSGU; i++)
+  {
+    NDBFBlockInfo& rSGU = m_vNDFBlock[i];
+
+    sliceID = rSGU.sliceID;
+    uiLPelX = rSGU.posX;
+    uiTPelY = rSGU.posY;
+    width   = rSGU.width;
+    height  = rSGU.height;
+#if !MODIFIED_CROSS_SLICE
+    Bool bIndependentSliceBoundaryEnabled = !(LFCrossSliceBoundary[sliceID]);
+#endif
+    rTLSU     = g_auiZscanToRaster[ rSGU.startSU ];
+    rBRSU     = g_auiZscanToRaster[ rSGU.endSU   ];
+    widthSU   = rSGU.widthSU;
+    heightSU  = rSGU.heightSU;
+
+    pbAvailBorder = rSGU.isBorderAvailable;
+
+    bPicTBoundary= (uiTPelY == 0                       )?(true):(false);
+    bPicLBoundary= (uiLPelX == 0                       )?(true):(false);
+    bPicRBoundary= (!(uiLPelX+ width < picWidth )  )?(true):(false);
+    bPicBBoundary= (!(uiTPelY + height < picHeight))?(true):(false);
+
+    bLCULBoundary = (rTLSU % numSUInLCUWidth == 0)?(true):(false);
+    bLCURBoundary = ( (rTLSU+ widthSU) % numSUInLCUWidth == 0)?(true):(false);
+    bLCUTBoundary = ( (UInt)(rTLSU / numSUInLCUWidth)== 0)?(true):(false);
+    bLCUBBoundary = ( (UInt)(rBRSU / numSUInLCUWidth) == (numSUInLCUHeight-1) )?(true):(false);
+
+    //       SGU_L
+    pbAvail = &(pbAvailBorder[SGU_L]);
+    if(bPicLBoundary)
+    {
+      *pbAvail = false;
+    }
+#if MODIFIED_CROSS_SLICE
+    else if (onlyOneSliceInPic)
+#else
+    else if (!bIndependentSliceBoundaryEnabled)
+#endif
+    {
+      *pbAvail = true;
+    }
+    else
+    {
+      //      bLCULBoundary = (rTLSU % uiNumSUInLCUWidth == 0)?(true):(false);
+      if(bLCULBoundary)
+      {
+        rLRefSU     = rTLSU + numSUInLCUWidth -1;
+        zRefSU      = g_auiRasterToZscan[rLRefSU];
+        pRefMapLCU = pLRefMapLCU= (pSliceIDMapLCU - numSUInLCU);
+      }
+      else
+      {
+        zRefSU   = g_auiRasterToZscan[rTLSU - 1];
+        pRefMapLCU  = pSliceIDMapLCU;
+      }
+      pRefID = pRefMapLCU + zRefSU;
+#if MODIFIED_CROSS_SLICE
+      *pbAvail = (*pRefID == sliceID)?(true):((*pRefID > sliceID)?(LFCrossSliceBoundary[*pRefID]):(LFCrossSliceBoundary[sliceID]));
+#else
+      *pbAvail = (*pRefID == sliceID)?(true):(false);
+#endif
+    }
+
+    //       SGU_R
+    pbAvail = &(pbAvailBorder[SGU_R]);
+    if(bPicRBoundary)
+    {
+      *pbAvail = false;
+    }
+#if MODIFIED_CROSS_SLICE
+    else if (onlyOneSliceInPic)
+#else
+    else if (!bIndependentSliceBoundaryEnabled)
+#endif
+    {
+      *pbAvail = true;
+    }
+    else
+    {
+      //       bLCURBoundary = ( (rTLSU+ uiWidthSU) % uiNumSUInLCUWidth == 0)?(true):(false);
+      if(bLCURBoundary)
+      {
+        rRRefSU      = rTLSU + widthSU - numSUInLCUWidth;
+        zRefSU       = g_auiRasterToZscan[rRRefSU];
+        pRefMapLCU  = pRRefMapLCU= (pSliceIDMapLCU + numSUInLCU);
+      }
+      else
+      {
+        zRefSU       = g_auiRasterToZscan[rTLSU + widthSU];
+        pRefMapLCU  = pSliceIDMapLCU;
+      }
+      pRefID = pRefMapLCU + zRefSU;
+#if MODIFIED_CROSS_SLICE
+      *pbAvail = (*pRefID == sliceID)?(true):((*pRefID > sliceID)?(LFCrossSliceBoundary[*pRefID]):(LFCrossSliceBoundary[sliceID]));
+#else
+      *pbAvail = (*pRefID == sliceID)?(true):(false);
+#endif
+    }
+
+    //       SGU_T
+    pbAvail = &(pbAvailBorder[SGU_T]);
+    if(bPicTBoundary)
+    {
+      *pbAvail = false;
+    }
+#if MODIFIED_CROSS_SLICE
+    else if (onlyOneSliceInPic)
+#else
+    else if (!bIndependentSliceBoundaryEnabled)
+#endif
+    {
+      *pbAvail = true;
+    }
+    else
+    {
+      //      bLCUTBoundary = ( (UInt)(rTLSU / uiNumSUInLCUWidth)== 0)?(true):(false);
+      if(bLCUTBoundary)
+      {
+        rTRefSU      = numSUInLCU - (numSUInLCUWidth - rTLSU);
+        zRefSU       = g_auiRasterToZscan[rTRefSU];
+        pRefMapLCU  = pTRefMapLCU= (pSliceIDMapLCU - (numLCUInPicWidth*numSUInLCU));
+      }
+      else
+      {
+        zRefSU       = g_auiRasterToZscan[rTLSU - numSUInLCUWidth];
+        pRefMapLCU  = pSliceIDMapLCU;
+      }
+      pRefID = pRefMapLCU + zRefSU;
+#if MODIFIED_CROSS_SLICE
+      *pbAvail = (*pRefID == sliceID)?(true):((*pRefID > sliceID)?(LFCrossSliceBoundary[*pRefID]):(LFCrossSliceBoundary[sliceID]));
+#else
+      *pbAvail = (*pRefID == sliceID)?(true):(false);
+#endif
+    }
+
+    //       SGU_B
+    pbAvail = &(pbAvailBorder[SGU_B]);
+    if(bPicBBoundary)
+    {
+      *pbAvail = false;
+    }
+#if MODIFIED_CROSS_SLICE
+    else if (onlyOneSliceInPic)
+#else
+    else if (!bIndependentSliceBoundaryEnabled)
+#endif
+    {
+      *pbAvail = true;
+    }
+    else
+    {
+      //      bLCUBBoundary = ( (UInt)(rBRSU / uiNumSUInLCUWidth) == (uiNumSUInLCUHeight-1) )?(true):(false);
+      if(bLCUBBoundary)
+      {
+        rBRefSU      = rTLSU % numSUInLCUWidth;
+        zRefSU       = g_auiRasterToZscan[rBRefSU];
+        pRefMapLCU  = pBRefMapLCU= (pSliceIDMapLCU + (numLCUInPicWidth*numSUInLCU));
+      }
+      else
+      {
+        zRefSU       = g_auiRasterToZscan[rTLSU + (heightSU*numSUInLCUWidth)];
+        pRefMapLCU  = pSliceIDMapLCU;
+      }
+      pRefID = pRefMapLCU + zRefSU;
+#if MODIFIED_CROSS_SLICE
+      *pbAvail = (*pRefID == sliceID)?(true):((*pRefID > sliceID)?(LFCrossSliceBoundary[*pRefID]):(LFCrossSliceBoundary[sliceID]));
+#else
+      *pbAvail = (*pRefID == sliceID)?(true):(false);
+#endif
+    }
+
+    //       SGU_TL
+    pbAvail = &(pbAvailBorder[SGU_TL]);
+    if(bPicTBoundary || bPicLBoundary)
+    {
+      *pbAvail = false;
+    }
+#if MODIFIED_CROSS_SLICE
+    else if (onlyOneSliceInPic)
+#else
+    else if (!bIndependentSliceBoundaryEnabled)
+#endif
+    {
+      *pbAvail = true;
+    }
+    else
+    {
+      if(bLCUTBoundary && bLCULBoundary)
+      {
+        zRefSU       = numSUInLCU -1;
+        pRefMapLCU  = pSliceIDMapLCU - ( (numLCUInPicWidth+1)*numSUInLCU);
+      }
+      else if(bLCUTBoundary)
+      {
+        zRefSU       = g_auiRasterToZscan[ rTRefSU- 1];
+        pRefMapLCU  = pTRefMapLCU;
+      }
+      else if(bLCULBoundary)
+      {
+        zRefSU       = g_auiRasterToZscan[ rLRefSU- numSUInLCUWidth ];
+        pRefMapLCU  = pLRefMapLCU;
+      }
+      else //inside LCU
+      {
+        zRefSU       = g_auiRasterToZscan[ rTLSU - numSUInLCUWidth -1];
+        pRefMapLCU  = pSliceIDMapLCU;
+      }
+      pRefID = pRefMapLCU + zRefSU;
+#if MODIFIED_CROSS_SLICE
+      *pbAvail = (*pRefID == sliceID)?(true):((*pRefID > sliceID)?(LFCrossSliceBoundary[*pRefID]):(LFCrossSliceBoundary[sliceID]));
+#else
+      *pbAvail = (*pRefID == sliceID)?(true):(false);
+#endif
+    }
+
+    //       SGU_TR
+    pbAvail = &(pbAvailBorder[SGU_TR]);
+    if(bPicTBoundary || bPicRBoundary)
+    {
+      *pbAvail = false;
+    }
+#if MODIFIED_CROSS_SLICE
+    else if (onlyOneSliceInPic)
+#else
+    else if (!bIndependentSliceBoundaryEnabled)
+#endif
+    {
+      *pbAvail = true;
+    }
+    else
+    {
+      if(bLCUTBoundary && bLCURBoundary)
+      {
+        zRefSU      = g_auiRasterToZscan[numSUInLCU - numSUInLCUWidth];
+        pRefMapLCU  = pSliceIDMapLCU - ( (numLCUInPicWidth-1)*numSUInLCU);        
+      }
+      else if(bLCUTBoundary)
+      {
+        zRefSU       = g_auiRasterToZscan[ rTRefSU+ widthSU];
+        pRefMapLCU  = pTRefMapLCU;
+      }
+      else if(bLCURBoundary)
+      {
+        zRefSU       = g_auiRasterToZscan[ rRRefSU- numSUInLCUWidth ];
+        pRefMapLCU  = pRRefMapLCU;
+      }
+      else //inside LCU
+      {
+        zRefSU       = g_auiRasterToZscan[ rTLSU - numSUInLCUWidth +widthSU];
+        pRefMapLCU  = pSliceIDMapLCU;
+      }
+      pRefID = pRefMapLCU + zRefSU;
+#if MODIFIED_CROSS_SLICE
+      *pbAvail = (*pRefID == sliceID)?(true):((*pRefID > sliceID)?(LFCrossSliceBoundary[*pRefID]):(LFCrossSliceBoundary[sliceID]));
+#else
+      *pbAvail = (*pRefID == sliceID)?(true):(false);
+#endif
+    }
+
+    //       SGU_BL
+    pbAvail = &(pbAvailBorder[SGU_BL]);
+    if(bPicBBoundary || bPicLBoundary)
+    {
+      *pbAvail = false;
+    }
+#if MODIFIED_CROSS_SLICE
+    else if (onlyOneSliceInPic)
+#else
+    else if (!bIndependentSliceBoundaryEnabled)
+#endif
+    {
+      *pbAvail = true;
+    }
+    else
+    {
+      if(bLCUBBoundary && bLCULBoundary)
+      {
+        zRefSU      = g_auiRasterToZscan[numSUInLCUWidth - 1];
+        pRefMapLCU  = pSliceIDMapLCU + ( (numLCUInPicWidth-1)*numSUInLCU);        
+      }
+      else if(bLCUBBoundary)
+      {
+        zRefSU       = g_auiRasterToZscan[ rBRefSU - 1];
+        pRefMapLCU  = pBRefMapLCU;
+      }
+      else if(bLCULBoundary)
+      {
+        zRefSU       = g_auiRasterToZscan[ rLRefSU+ heightSU*numSUInLCUWidth ];
+        pRefMapLCU  = pLRefMapLCU;
+      }
+      else //inside LCU
+      {
+        zRefSU       = g_auiRasterToZscan[ rTLSU + heightSU*numSUInLCUWidth -1];
+        pRefMapLCU  = pSliceIDMapLCU;
+      }
+      pRefID = pRefMapLCU + zRefSU;
+#if MODIFIED_CROSS_SLICE
+      *pbAvail = (*pRefID == sliceID)?(true):((*pRefID > sliceID)?(LFCrossSliceBoundary[*pRefID]):(LFCrossSliceBoundary[sliceID]));
+#else
+      *pbAvail = (*pRefID == sliceID)?(true):(false);
+#endif
+    }
+
+    //       SGU_BR
+    pbAvail = &(pbAvailBorder[SGU_BR]);
+    if(bPicBBoundary || bPicRBoundary)
+    {
+      *pbAvail = false;
+    }
+#if MODIFIED_CROSS_SLICE
+    else if (onlyOneSliceInPic)
+#else
+    else if (!bIndependentSliceBoundaryEnabled)
+#endif
+    {
+      *pbAvail = true;
+    }
+    else
+    {
+      if(bLCUBBoundary && bLCURBoundary)
+      {
+        zRefSU = 0;
+        pRefMapLCU = pSliceIDMapLCU+ ( (numLCUInPicWidth+1)*numSUInLCU);
+      }
+      else if(bLCUBBoundary)
+      {
+        zRefSU      = g_auiRasterToZscan[ rBRefSU + widthSU];
+        pRefMapLCU = pBRefMapLCU;
+      }
+      else if(bLCURBoundary)
+      {
+        zRefSU      = g_auiRasterToZscan[ rRRefSU + (heightSU*numSUInLCUWidth)];
+        pRefMapLCU = pRRefMapLCU;
+      }
+      else //inside LCU
+      {
+        zRefSU      = g_auiRasterToZscan[ rTLSU + (heightSU*numSUInLCUWidth)+ widthSU];
+        pRefMapLCU = pSliceIDMapLCU;
+      }
+      pRefID = pRefMapLCU + zRefSU;
+#if MODIFIED_CROSS_SLICE
+      *pbAvail = (*pRefID == sliceID)?(true):((*pRefID > sliceID)?(LFCrossSliceBoundary[*pRefID]):(LFCrossSliceBoundary[sliceID]));
+#else
+      *pbAvail = (*pRefID == sliceID)?(true):(false);
+#endif
+    }
+
+    if(bIndependentTileBoundaryEnabled)
+    {
+      //left LCU boundary
+      if(!bPicLBoundary && bLCULBoundary)
+      {
+        if(bLeftTileBoundary)
+        {
+          pbAvailBorder[SGU_L] = pbAvailBorder[SGU_TL] = pbAvailBorder[SGU_BL] = false;
+        }
+      }
+      //right LCU boundary
+      if(!bPicRBoundary && bLCURBoundary)
+      {
+        if(bRightTileBoundary)
+        {
+          pbAvailBorder[SGU_R] = pbAvailBorder[SGU_TR] = pbAvailBorder[SGU_BR] = false;
+        }
+      }
+      //top LCU boundary
+      if(!bPicTBoundary && bLCUTBoundary)
+      {
+        if(bTopTileBoundary)
+        {
+          pbAvailBorder[SGU_T] = pbAvailBorder[SGU_TL] = pbAvailBorder[SGU_TR] = false;
+        }
+      }
+      //down LCU boundary
+      if(!bPicBBoundary && bLCUBBoundary)
+      {
+        if(bDownTileBoundary)
+        {
+          pbAvailBorder[SGU_B] = pbAvailBorder[SGU_BL] = pbAvailBorder[SGU_BR] = false;
+        }
+      }
+    }
+    rSGU.allBordersAvailable = true;
+    for(Int b=0; b< NUM_SGU_BORDER; b++)
+    {
+      if(pbAvailBorder[b] == false)
+      {
+        rSGU.allBordersAvailable = false;
+        break;
+      }
+    }
+  }
+}
+
+#if INTRA_BL 
+Void TComDataCU::getBaseLumaBlk ( UInt uiWidth, UInt uiHeight, UInt uiAbsPartIdx, Pel* piPred, UInt uiStride )
+{
+  TComPicYuv* pcBaseRec = getSlice()->getFullPelBaseRec();
+  UInt uiStrideBase = pcBaseRec->getStride();
+  Pel* piBase = pcBaseRec->getLumaAddr( getAddr(), getZorderIdxInCU() + uiAbsPartIdx );
+  
+  for ( UInt y = 0; y < uiHeight; y ++ )
+  {
+    memcpy( piPred + y * uiStride, piBase + y * uiStrideBase, uiWidth * sizeof( Pel ) );
+  }
+}
+
+Void TComDataCU::getBaseChromaBlk ( UInt uiWidth, UInt uiHeight, UInt uiAbsPartIdx, Pel* piPred, UInt uiStride, UInt uiChromaId )
+{
+  TComPicYuv* pcBaseRec = getSlice()->getFullPelBaseRec();
+
+  UInt uiStrideBase = pcBaseRec->getCStride();
+  Pel* piBase;
+  
+  if( uiChromaId == 0 )
+  {
+    piBase = pcBaseRec->getCbAddr( getAddr(), getZorderIdxInCU() + uiAbsPartIdx );
+  }
+  else
+  {
+    piBase = pcBaseRec->getCrAddr( getAddr(), getZorderIdxInCU() + uiAbsPartIdx );
+  }
+  
+  for ( UInt y = 0; y < uiHeight; y ++ )
+  {
+    memcpy( piPred + y * uiStride, piBase + y * uiStrideBase, uiWidth * sizeof( Pel ) );
+  }
+}
+
+#endif
+
+#if SVC_COL_BLK
+TComDataCU*  TComDataCU::getBaseColCU( UInt uiCuAbsPartIdx, UInt &uiCUAddrBase, UInt &uiAbsPartIdxBase )
+{
+  TComPic* cBaseColPic = m_pcSlice->getBaseColPic();
+
+#if SVC_UPSAMPLING
+  Int iBWidth   = cBaseColPic->getPicYuvRec()->getWidth () - cBaseColPic->getPicYuvRec()->getPicCropLeftOffset() - cBaseColPic->getPicYuvRec()->getPicCropRightOffset();
+  Int iBHeight  = cBaseColPic->getPicYuvRec()->getHeight() - cBaseColPic->getPicYuvRec()->getPicCropTopOffset() - cBaseColPic->getPicYuvRec()->getPicCropBottomOffset();
+
+  Int iEWidth   = m_pcPic->getPicYuvRec()->getWidth() - m_pcPic->getPicYuvRec()->getPicCropLeftOffset() - m_pcPic->getPicYuvRec()->getPicCropRightOffset();
+  Int iEHeight  = m_pcPic->getPicYuvRec()->getHeight() - m_pcPic->getPicYuvRec()->getPicCropTopOffset() - m_pcPic->getPicYuvRec()->getPicCropBottomOffset();
+#else
+  Int iBWidth   = cBaseColPic->getPicYuvRec()->getWidth();
+  Int iBHeight  = cBaseColPic->getPicYuvRec()->getHeight();
+
+  Int iEWidth   = m_pcPic->getPicYuvRec()->getWidth();
+  Int iEHeight  = m_pcPic->getPicYuvRec()->getHeight();
+#endif
+
+  if (iBWidth == iEWidth && iEHeight == iBHeight)
+  {
+    uiAbsPartIdxBase = uiCuAbsPartIdx + m_uiAbsIdxInLCU;
+    uiCUAddrBase = m_uiCUAddr;
+  }
+  else
+  {
+    UInt uiMinUnitSize = m_pcPic->getMinCUWidth();
+    UInt uiRasterAddr  = g_auiZscanToRaster[uiCuAbsPartIdx];
+    UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
+
+    Int iEX = m_uiCUPelX + uiMinUnitSize*(uiRasterAddr%uiNumPartInCUWidth);
+    Int iEY = m_uiCUPelY + uiMinUnitSize*(uiRasterAddr/uiNumPartInCUWidth);
+
+    Int iBX = (iEX*iBWidth + iEWidth/2)/iEWidth;
+    Int iBY = (iEY*iBHeight+ iEHeight/2)/iEHeight;
+
+    uiCUAddrBase = (iBY/g_uiMaxCUHeight)*cBaseColPic->getFrameWidthInCU() + (iBX/g_uiMaxCUWidth);
+
+    assert(uiCUAddrBase < cBaseColPic->getNumCUsInFrame());
+    
+    UInt uiRasterAddrBase = (iBY - (iBY/g_uiMaxCUHeight)*g_uiMaxCUHeight)/uiMinUnitSize*cBaseColPic->getNumPartInWidth()
+                          + (iBX - (iBX/g_uiMaxCUWidth)*g_uiMaxCUWidth)/uiMinUnitSize;
+
+    uiAbsPartIdxBase = g_auiRasterToZscan[uiRasterAddrBase];
+  }
+
+  return cBaseColPic->getCU(uiCUAddrBase);
+}
+
+Void TComDataCU::scaleBaseMV( TComMvField& rcMvFieldEnhance, TComMvField& rcMvFieldBase )
+{
+   TComMvField cMvFieldBase;
+   TComMv cMv;
+
+   Int iBWidth   = m_pcSlice->getBaseColPic()->getPicYuvRec()->getWidth();
+   Int iBHeight  = m_pcSlice->getBaseColPic()->getPicYuvRec()->getHeight();
+
+   Int iEWidth   = m_pcPic->getPicYuvRec()->getWidth();
+   Int iEHeight  = m_pcPic->getPicYuvRec()->getHeight();
+
+   Int iMvX = (rcMvFieldBase.getHor()*iEWidth + (iBWidth/2 -1) * (rcMvFieldBase.getHor() > 0 ? 1: -1) )/iBWidth;
+   Int iMvY = (rcMvFieldBase.getVer()*iEHeight + (iBHeight/2 -1) * (rcMvFieldBase.getVer() > 0 ? 1: -1) )/iBHeight;
+
+   cMv.set(iMvX, iMvY);
+
+   rcMvFieldEnhance.setMvField( cMv, rcMvFieldBase.getRefIdx() );
+}
+#endif
+
+#if SVC_MVP
+Bool TComDataCU::hasEqualMotion( UInt uiAbsPartIdx, UChar uchInterDir, TComMvField* pcMvField  )
+{
+  if ( getInterDir( uiAbsPartIdx ) != uchInterDir )
+  {
+    return false;
+  }
+
+  for ( UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )
+  {
+    if ( getInterDir( uiAbsPartIdx ) & ( 1 << uiRefListIdx ) )
+    {
+      if ( getCUMvField( RefPicList( uiRefListIdx ) )->getMv( uiAbsPartIdx )  != pcMvField[uiRefListIdx].getMv() || 
+        getCUMvField( RefPicList( uiRefListIdx ) )->getRefIdx( uiAbsPartIdx ) != pcMvField[uiRefListIdx].getRefIdx() )
+      {
+        return false;
+      }
+    }
+  }
+
+  return true;
+}
+#endif
+
+//! \}
Index: /trunk/source/Lib/TLibCommon/TComDataCU.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComDataCU.h	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComDataCU.h	(revision 2)
@@ -0,0 +1,680 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComDataCU.h
+    \brief    CU data structure (header)
+    \todo     not all entities are documented
+*/
+
+#ifndef _TCOMDATACU_
+#define _TCOMDATACU_
+
+#include <assert.h>
+
+// Include files
+#include "CommonDef.h"
+#include "TComMotionInfo.h"
+#include "TComSlice.h"
+#include "TComRdCost.h"
+#include "TComPattern.h"
+
+#include <algorithm>
+#include <vector>
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Non-deblocking in-loop filter processing block data structure
+// ====================================================================================================================
+
+/// Non-deblocking filter processing block border tag
+enum NDBFBlockBorderTag
+{
+  SGU_L = 0,
+  SGU_R,
+  SGU_T,
+  SGU_B,
+  SGU_TL,
+  SGU_TR,
+  SGU_BL,
+  SGU_BR,
+  NUM_SGU_BORDER
+};
+
+/// Non-deblocking filter processing block information
+struct NDBFBlockInfo
+{
+  Int   tileID;   //!< tile ID
+  Int   sliceID;  //!< slice ID
+  UInt  startSU;  //!< starting SU z-scan address in LCU
+  UInt  endSU;    //!< ending SU z-scan address in LCU
+  UInt  widthSU;  //!< number of SUs in width
+  UInt  heightSU; //!< number of SUs in height
+  UInt  posX;     //!< top-left X coordinate in picture
+  UInt  posY;     //!< top-left Y coordinate in picture
+  UInt  width;    //!< number of pixels in width
+  UInt  height;   //!< number of pixels in height
+  Bool  isBorderAvailable[NUM_SGU_BORDER];  //!< the border availabilities
+  Bool  allBordersAvailable;
+
+  NDBFBlockInfo():tileID(0), sliceID(0), startSU(0), endSU(0) {} //!< constructor
+  const NDBFBlockInfo& operator= (const NDBFBlockInfo& src);  //!< "=" operator
+};
+
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// CU data structure class
+class TComDataCU
+{
+private:
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // class pointers
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  TComPic*      m_pcPic;              ///< picture class pointer
+  TComSlice*    m_pcSlice;            ///< slice header pointer
+  TComPattern*  m_pcPattern;          ///< neighbour access class pointer
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // CU description
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  UInt          m_uiCUAddr;           ///< CU address in a slice
+  UInt          m_uiAbsIdxInLCU;      ///< absolute address in a CU. It's Z scan order
+  UInt          m_uiCUPelX;           ///< CU position in a pixel (X)
+  UInt          m_uiCUPelY;           ///< CU position in a pixel (Y)
+  UInt          m_uiNumPartition;     ///< total number of minimum partitions in a CU
+  UChar*        m_puhWidth;           ///< array of widths
+  UChar*        m_puhHeight;          ///< array of heights
+  UChar*        m_puhDepth;           ///< array of depths
+  Int           m_unitSize;           ///< size of a "minimum partition"
+  
+#if SVC_EXTENSION
+  UInt          m_layerId;          ///< layer id
+#endif
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // CU data
+  // -------------------------------------------------------------------------------------------------------------------
+#if SKIP_FLAG
+  Bool*         m_skipFlag;           ///< array of skip flags
+#endif
+  Char*         m_pePartSize;         ///< array of partition sizes
+  Char*         m_pePredMode;         ///< array of prediction modes
+  Bool*         m_CUTransquantBypass;   ///< array of cu_transquant_bypass flags
+  Char*         m_phQP;               ///< array of QP values
+  UChar*        m_puhTrIdx;           ///< array of transform indices
+  UChar*        m_puhTransformSkip[3];///< array of transform skipping flags
+#if !REMOVE_NSQT
+  UChar*        m_nsqtPartIdx;        ///< array of absPartIdx mapping table, map zigzag to NSQT
+#endif
+  UChar*        m_puhCbf[3];          ///< array of coded block flags (CBF)
+  TComCUMvField m_acCUMvField[2];     ///< array of motion vectors
+  TCoeff*       m_pcTrCoeffY;         ///< transformed coefficient buffer (Y)
+  TCoeff*       m_pcTrCoeffCb;        ///< transformed coefficient buffer (Cb)
+  TCoeff*       m_pcTrCoeffCr;        ///< transformed coefficient buffer (Cr)
+#if ADAPTIVE_QP_SELECTION
+  Int*          m_pcArlCoeffY;        ///< ARL coefficient buffer (Y)
+  Int*          m_pcArlCoeffCb;       ///< ARL coefficient buffer (Cb)
+  Int*          m_pcArlCoeffCr;       ///< ARL coefficient buffer (Cr)
+  bool          m_ArlCoeffIsAliasedAllocation; ///< ARL coefficient buffer is an alias of the global buffer and must not be free()'d
+
+  static Int*   m_pcGlbArlCoeffY;     ///< ARL coefficient buffer (Y)
+  static Int*   m_pcGlbArlCoeffCb;    ///< ARL coefficient buffer (Cb)
+  static Int*   m_pcGlbArlCoeffCr;    ///< ARL coefficient buffer (Cr)
+#endif
+  
+  Pel*          m_pcIPCMSampleY;      ///< PCM sample buffer (Y)
+  Pel*          m_pcIPCMSampleCb;     ///< PCM sample buffer (Cb)
+  Pel*          m_pcIPCMSampleCr;     ///< PCM sample buffer (Cr)
+
+  Int*          m_piSliceSUMap;       ///< pointer of slice ID map
+  std::vector<NDBFBlockInfo> m_vNDFBlock;
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // neighbour access variables
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  TComDataCU*   m_pcCUAboveLeft;      ///< pointer of above-left CU
+  TComDataCU*   m_pcCUAboveRight;     ///< pointer of above-right CU
+  TComDataCU*   m_pcCUAbove;          ///< pointer of above CU
+  TComDataCU*   m_pcCULeft;           ///< pointer of left CU
+  TComDataCU*   m_apcCUColocated[2];  ///< pointer of temporally colocated CU's for both directions
+  TComMvField   m_cMvFieldA;          ///< motion vector of position A
+  TComMvField   m_cMvFieldB;          ///< motion vector of position B
+  TComMvField   m_cMvFieldC;          ///< motion vector of position C
+  TComMv        m_cMvPred;            ///< motion vector predictor
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // coding tool information
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Bool*         m_pbMergeFlag;        ///< array of merge flags
+  UChar*        m_puhMergeIndex;      ///< array of merge candidate indices
+#if AMP_MRG
+  Bool          m_bIsMergeAMP;
+#endif
+  UChar*        m_puhLumaIntraDir;    ///< array of intra directions (luma)
+  UChar*        m_puhChromaIntraDir;  ///< array of intra directions (chroma)
+  UChar*        m_puhInterDir;        ///< array of inter directions
+  Char*         m_apiMVPIdx[2];       ///< array of motion vector predictor candidates
+  Char*         m_apiMVPNum[2];       ///< array of number of possible motion vectors predictors
+  Bool          m_lcuAlfEnabled[3];
+  Bool*         m_pbIPCMFlag;         ///< array of intra_pcm flags
+
+  Int           m_numSucIPCM;         ///< the number of succesive IPCM blocks associated with the current log2CUSize
+  Bool          m_lastCUSucIPCMFlag;  ///< True indicates that the last CU is IPCM and shares the same root as the current CU.  
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // misc. variables
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Bool          m_bDecSubCu;          ///< indicates decoder-mode
+  Double        m_dTotalCost;         ///< sum of partition RD costs
+  UInt          m_uiTotalDistortion;  ///< sum of partition distortion
+  UInt          m_uiTotalBits;        ///< sum of partition bits
+  UInt          m_uiTotalBins;       ///< sum of partition bins
+  UInt*         m_uiSliceStartCU;    ///< Start CU address of current slice
+  UInt*         m_uiDependentSliceStartCU; ///< Start CU address of current slice
+  Char          m_codedQP;
+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 );
+
+  Void          deriveRightBottomIdx        ( PartSize eCUMode, UInt uiPartIdx, UInt& ruiPartIdxRB );
+  Bool          xGetColMVP( RefPicList eRefPicList, Int uiCUAddr, Int uiPartUnitIdx, TComMv& rcMv, Int& riRefIdx );
+  
+  /// compute required bits to encode MVD (used in AMVP)
+  UInt          xGetMvdBits           ( TComMv cMvd );
+  UInt          xGetComponentBits     ( Int iVal );
+  
+  /// compute scaling factor from POC difference
+  Int           xGetDistScaleFactor   ( Int iCurrPOC, Int iCurrRefPOC, Int iColPOC, Int iColRefPOC );
+  
+  Void xDeriveCenterIdx( PartSize eCUMode, UInt uiPartIdx, UInt& ruiPartIdxCenter );
+  Bool xGetCenterCol( UInt uiPartIdx, RefPicList eRefPicList, int iRefIdx, TComMv *pcMv );
+
+public:
+  TComDataCU();
+  virtual ~TComDataCU();
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // create / destroy / initialize / copy
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Void          create                ( UInt uiNumPartition, UInt uiWidth, UInt uiHeight, Bool bDecSubCu, Int unitSize
+#if ADAPTIVE_QP_SELECTION
+    , Bool bGlobalRMARLBuffer = false
+#endif  
+    );
+  Void          destroy               ();
+  
+  Void          initCU                ( TComPic* pcPic, UInt uiCUAddr );
+  Void          initEstData           ( UInt uiDepth, Int qp );
+  Void          initSubCU             ( TComDataCU* pcCU, UInt uiPartUnitIdx, UInt uiDepth, Int qp );
+  Void          setOutsideCUPart      ( UInt uiAbsPartIdx, UInt uiDepth );
+
+  Void          copySubCU             ( TComDataCU* pcCU, UInt uiPartUnitIdx, UInt uiDepth );
+  Void          copyInterPredInfoFrom ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefPicList );
+  Void          copyPartFrom          ( TComDataCU* pcCU, UInt uiPartUnitIdx, UInt uiDepth );
+  
+  Void          copyToPic             ( UChar uiDepth );
+  Void          copyToPic             ( UChar uiDepth, UInt uiPartIdx, UInt uiPartDepth );
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // member functions for CU description
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  TComPic*      getPic                ()                        { return m_pcPic;           }
+  TComSlice*    getSlice              ()                        { return m_pcSlice;         }
+  UInt&         getAddr               ()                        { return m_uiCUAddr;        }
+  UInt&         getZorderIdxInCU      ()                        { return m_uiAbsIdxInLCU; }
+  UInt          getSCUAddr            ();
+  UInt          getCUPelX             ()                        { return m_uiCUPelX;        }
+  UInt          getCUPelY             ()                        { return m_uiCUPelY;        }
+  TComPattern*  getPattern            ()                        { return m_pcPattern;       }
+  
+  UChar*        getDepth              ()                        { return m_puhDepth;        }
+  UChar         getDepth              ( UInt uiIdx )            { return m_puhDepth[uiIdx]; }
+  Void          setDepth              ( UInt uiIdx, UChar  uh ) { m_puhDepth[uiIdx] = uh;   }
+  
+  Void          setDepthSubParts      ( UInt uiDepth, UInt uiAbsPartIdx );
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // member functions for CU data
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Char*         getPartitionSize      ()                        { return m_pePartSize;        }
+  PartSize      getPartitionSize      ( UInt uiIdx )            { 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 );
+  Void          setCUTransquantBypassSubParts( bool flag, UInt uiAbsPartIdx, UInt uiDepth );
+  
+#if SKIP_FLAG
+  Bool*        getSkipFlag            ()                        { return m_skipFlag;          }
+  Bool         getSkipFlag            (UInt idx)                { return m_skipFlag[idx];     }
+  Void         setSkipFlag           ( UInt idx, Bool skip)     { m_skipFlag[idx] = skip;   }
+  Void         setSkipFlagSubParts   ( Bool skip, UInt absPartIdx, UInt depth );
+#endif
+
+  Char*         getPredictionMode     ()                        { return m_pePredMode;        }
+  PredMode      getPredictionMode     ( UInt uiIdx )            { return static_cast<PredMode>( m_pePredMode[uiIdx] ); }
+  Bool*         getCUTransquantBypass ()                        { return m_CUTransquantBypass;        }
+  Bool          getCUTransquantBypass( UInt uiIdx )             { return m_CUTransquantBypass[uiIdx]; }
+  Void          setPredictionMode     ( UInt uiIdx, PredMode uh){ m_pePredMode[uiIdx] = uh;   }
+  Void          setPredModeSubParts   ( PredMode eMode, UInt uiAbsPartIdx, UInt uiDepth );
+  
+  UChar*        getWidth              ()                        { return m_puhWidth;          }
+  UChar         getWidth              ( UInt uiIdx )            { 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];  }
+  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 )            { return m_phQP[uiIdx];       }
+  Void          setQP                 ( UInt uiIdx, Char value ){ m_phQP[uiIdx] =  value;     }
+  Void          setQPSubParts         ( Int qp,   UInt uiAbsPartIdx, UInt uiDepth );
+  Int           getLastValidPartIdx   ( Int iAbsPartIdx );
+  Char          getLastCodedQP        ( UInt uiAbsPartIdx );
+  Void          setQPSubCUs           ( Int qp, TComDataCU* pcCU, UInt absPartIdx, UInt depth, Bool &foundNonZeroCbf );
+  Void          setCodedQP            ( Char qp )               { m_codedQP = qp;             }
+  Char          getCodedQP            ()                        { return m_codedQP;           }
+
+  Bool          isLosslessCoded(UInt absPartIdx);
+#if !REMOVE_NSQT
+  UChar*        getNSQTPartIdx        ()                        { return m_nsqtPartIdx;        }
+  UChar         getNSQTPartIdx        ( UInt idx )              { return m_nsqtPartIdx[idx];   }
+  Void          setNSQTIdxSubParts    ( UInt absPartIdx, UInt depth );
+  Void          setNSQTIdxSubParts    ( UInt log2TrafoSize, UInt absPartIdx, UInt absTUPartIdx, UInt trMode );
+#endif
+  
+  UChar*        getTransformIdx       ()                        { return m_puhTrIdx;          }
+  UChar         getTransformIdx       ( UInt uiIdx )            { return m_puhTrIdx[uiIdx];   }
+  Void          setTrIdxSubParts      ( UInt uiTrIdx, UInt uiAbsPartIdx, UInt uiDepth );
+
+  UChar*        getTransformSkip      ( TextType eType)    { return m_puhTransformSkip[g_aucConvertTxtTypeToIdx[eType]];}
+  UChar         getTransformSkip      ( UInt uiIdx,TextType eType)    { return m_puhTransformSkip[g_aucConvertTxtTypeToIdx[eType]][uiIdx];}
+  Void          setTransformSkipSubParts  ( UInt useTransformSkip, TextType eType, UInt uiAbsPartIdx, UInt uiDepth); 
+  Void          setTransformSkipSubParts  ( UInt useTransformSkipY, UInt useTransformSkipU, UInt useTransformSkipV, UInt uiAbsPartIdx, UInt uiDepth );
+
+  UInt          getQuadtreeTULog2MinSizeInCU( UInt absPartIdx );
+  
+  TComCUMvField* getCUMvField         ( RefPicList e )          { return  &m_acCUMvField[e];  }
+  
+  TCoeff*&      getCoeffY             ()                        { return m_pcTrCoeffY;        }
+  TCoeff*&      getCoeffCb            ()                        { return m_pcTrCoeffCb;       }
+  TCoeff*&      getCoeffCr            ()                        { return m_pcTrCoeffCr;       }
+#if ADAPTIVE_QP_SELECTION
+  Int*&         getArlCoeffY          ()                        { return m_pcArlCoeffY;       }
+  Int*&         getArlCoeffCb         ()                        { return m_pcArlCoeffCb;      }
+  Int*&         getArlCoeffCr         ()                        { return m_pcArlCoeffCr;      }
+#endif
+  
+  Pel*&         getPCMSampleY         ()                        { return m_pcIPCMSampleY;     }
+  Pel*&         getPCMSampleCb        ()                        { return m_pcIPCMSampleCb;    }
+  Pel*&         getPCMSampleCr        ()                        { return m_pcIPCMSampleCr;    }
+
+  UChar         getCbf    ( UInt uiIdx, TextType eType )                  { return m_puhCbf[g_aucConvertTxtTypeToIdx[eType]][uiIdx];  }
+  UChar*        getCbf    ( TextType eType )                              { return m_puhCbf[g_aucConvertTxtTypeToIdx[eType]];         }
+  UChar         getCbf    ( UInt uiIdx, TextType eType, UInt uiTrDepth )  { return ( ( getCbf( uiIdx, eType ) >> uiTrDepth ) & 0x1 ); }
+  Void          setCbf    ( UInt uiIdx, TextType eType, UChar uh )        { m_puhCbf[g_aucConvertTxtTypeToIdx[eType]][uiIdx] = uh;    }
+  Void          clearCbf  ( UInt uiIdx, TextType eType, UInt uiNumParts );
+  UChar         getQtRootCbf          ( UInt uiIdx )                      { return getCbf( uiIdx, TEXT_LUMA, 0 ) || getCbf( uiIdx, TEXT_CHROMA_U, 0 ) || getCbf( uiIdx, TEXT_CHROMA_V, 0 ); }
+  
+  Void          setCbfSubParts        ( UInt uiCbfY, UInt uiCbfU, UInt uiCbfV, UInt uiAbsPartIdx, UInt uiDepth          );
+  Void          setCbfSubParts        ( UInt uiCbf, TextType eTType, UInt uiAbsPartIdx, UInt uiDepth                    );
+  Void          setCbfSubParts        ( UInt uiCbf, TextType eTType, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth    );
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // member functions for coding tool information
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Bool*         getMergeFlag          ()                        { return m_pbMergeFlag;               }
+  Bool          getMergeFlag          ( UInt uiIdx )            { 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];                  }
+  Void          setMergeIndex         ( UInt uiIdx, UInt uiMergeIndex ) { m_puhMergeIndex[uiIdx] = uiMergeIndex;  }
+  Void          setMergeIndexSubParts ( UInt uiMergeIndex, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
+  template <typename T>
+  Void          setSubPart            ( T bParameter, T* pbBaseLCU, UInt uiCUAddr, UInt uiCUDepth, UInt uiPUIdx );
+
+#if AMP_MRG
+  Void          setMergeAMP( Bool b )      { m_bIsMergeAMP = b; }
+  Bool          getMergeAMP( )             { return m_bIsMergeAMP; }
+#endif
+
+  UChar*        getLumaIntraDir       ()                        { return m_puhLumaIntraDir;           }
+  UChar         getLumaIntraDir       ( UInt uiIdx )            { return m_puhLumaIntraDir[uiIdx];    }
+  Void          setLumaIntraDir       ( UInt uiIdx, UChar  uh ) { m_puhLumaIntraDir[uiIdx] = uh;      }
+  Void          setLumaIntraDirSubParts( UInt uiDir,  UInt uiAbsPartIdx, UInt uiDepth );
+  
+  UChar*        getChromaIntraDir     ()                        { return m_puhChromaIntraDir;         }
+  UChar         getChromaIntraDir     ( UInt uiIdx )            { return m_puhChromaIntraDir[uiIdx];  }
+  Void          setChromaIntraDir     ( UInt uiIdx, UChar  uh ) { m_puhChromaIntraDir[uiIdx] = uh;    }
+  Void          setChromIntraDirSubParts( UInt uiDir,  UInt uiAbsPartIdx, UInt uiDepth );
+  
+  UChar*        getInterDir           ()                        { return m_puhInterDir;               }
+  UChar         getInterDir           ( UInt uiIdx )            { 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          getAlfLCUEnabled      (Int compIdx)             {return m_lcuAlfEnabled[compIdx];     }
+  Void          setAlfLCUEnabled      (Bool b, Int compIdx)     {m_lcuAlfEnabled[compIdx] = b;        }
+  Bool*         getIPCMFlag           ()                        { return m_pbIPCMFlag;               }
+  Bool          getIPCMFlag           (UInt uiIdx )             { return m_pbIPCMFlag[uiIdx];        }
+  Void          setIPCMFlag           (UInt uiIdx, Bool b )     { m_pbIPCMFlag[uiIdx] = b;           }
+  Void          setIPCMFlagSubParts   (Bool bIpcmFlag, UInt uiAbsPartIdx, UInt uiDepth);
+
+  Int           getNumSucIPCM         ()                        { return m_numSucIPCM;             }
+  Void          setNumSucIPCM         ( Int num )               { m_numSucIPCM = num;              }
+  Bool          getLastCUSucIPCMFlag  ()                        { return m_lastCUSucIPCMFlag;        }
+  Void          setLastCUSucIPCMFlag  ( Bool flg )              { m_lastCUSucIPCMFlag = flg;         }
+
+  /// get slice ID for SU
+  Int           getSUSliceID          (UInt uiIdx)              {return m_piSliceSUMap[uiIdx];      } 
+
+  /// get the pointer of slice ID map
+  Int*          getSliceSUMap         ()                        {return m_piSliceSUMap;             }
+
+  /// set the pointer of slice ID map
+  Void          setSliceSUMap         (Int *pi)                 {m_piSliceSUMap = pi;               }
+
+  std::vector<NDBFBlockInfo>* getNDBFilterBlocks()      {return &m_vNDFBlock;}
+  Void setNDBFilterBlockBorderAvailability(UInt numLCUInPicWidth, UInt numLCUInPicHeight, UInt numSUInLCUWidth, UInt numSUInLCUHeight, UInt picWidth, UInt picHeight
+                                          ,std::vector<Bool>& LFCrossSliceBoundary
+                                          ,Bool bTopTileBoundary, Bool bDownTileBoundary, Bool bLeftTileBoundary, Bool bRightTileBoundary
+                                          ,Bool bIndependentTileBoundaryEnabled );
+  // -------------------------------------------------------------------------------------------------------------------
+  // member functions for accessing partition information
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Void          getPartIndexAndSize   ( UInt uiPartIdx, UInt& ruiPartAddr, Int& riWidth, Int& riHeight );
+  UChar         getNumPartInter       ();
+  Bool          isFirstAbsZorderIdxInDepth (UInt uiAbsPartIdx, UInt uiDepth);
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // member functions for motion vector
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Void          getMvField            ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefPicList, TComMvField& rcMvField );
+  
+#if !SPS_AMVP_CLEANUP
+  AMVP_MODE     getAMVPMode           ( UInt uiIdx );
+#endif
+  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);
+  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];            }
+
+  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];            }
+  
+  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          getMvPredLeft         ( TComMv&     rcMvPred )   { rcMvPred = m_cMvFieldA.getMv(); }
+  Void          getMvPredAbove        ( TComMv&     rcMvPred )   { rcMvPred = m_cMvFieldB.getMv(); }
+  Void          getMvPredAboveRight   ( TComMv&     rcMvPred )   { rcMvPred = m_cMvFieldC.getMv(); }
+  
+  Void          compressMV            ();
+
+#if SVC_EXTENSION
+  Void          setLayerId (UInt layerId) { m_layerId = layerId; }
+  UInt          getLayerId ()               { return m_layerId; }
+#endif
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // utility functions for neighbouring information
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  TComDataCU*   getCULeft                   () { return m_pcCULeft;       }
+  TComDataCU*   getCUAbove                  () { return m_pcCUAbove;      }
+  TComDataCU*   getCUAboveLeft              () { return m_pcCUAboveLeft;  }
+  TComDataCU*   getCUAboveRight             () { return m_pcCUAboveRight; }
+  TComDataCU*   getCUColocated              ( RefPicList eRefPicList ) { return m_apcCUColocated[eRefPicList]; }
+
+
+  TComDataCU*   getPULeft                   ( UInt&  uiLPartUnitIdx, 
+                                              UInt uiCurrPartUnitIdx, 
+                                              Bool bEnforceSliceRestriction=true, 
+                                              Bool bEnforceDependentSliceRestriction=true,
+                                              Bool bEnforceTileRestriction=true );
+
+  TComDataCU*   getPUAbove                  ( UInt&  uiAPartUnitIdx, 
+                                              UInt uiCurrPartUnitIdx, 
+                                              Bool bEnforceSliceRestriction=true, 
+                                              Bool bEnforceDependentSliceRestriction=true, 
+                                              Bool MotionDataCompresssion = false,
+                                              Bool planarAtLCUBoundary = false,
+                                              Bool bEnforceTileRestriction=true );
+
+  TComDataCU*   getPUAboveLeft              ( UInt&  uiALPartUnitIdx, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction=true, Bool bEnforceDependentSliceRestriction=true, Bool MotionDataCompresssion = false );
+  TComDataCU*   getPUAboveRight             ( UInt&  uiARPartUnitIdx, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction=true, Bool bEnforceDependentSliceRestriction=true, Bool MotionDataCompresssion = false );
+  TComDataCU*   getPUBelowLeft              ( UInt&  uiBLPartUnitIdx, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction=true, Bool bEnforceDependentSliceRestriction=true );
+
+  TComDataCU*   getQpMinCuLeft              ( UInt&  uiLPartUnitIdx , UInt uiCurrAbsIdxInLCU, Bool bEnforceSliceRestriction=true, Bool bEnforceDependentSliceRestriction=true );
+  TComDataCU*   getQpMinCuAbove             ( UInt&  aPartUnitIdx , UInt currAbsIdxInLCU, Bool enforceSliceRestriction=true, Bool enforceDependentSliceRestriction=true );
+  Char          getRefQP                    ( UInt   uiCurrAbsIdxInLCU                       );
+
+  TComDataCU*   getPUAboveRightAdi          ( UInt&  uiARPartUnitIdx, UInt uiPuWidth, UInt uiCurrPartUnitIdx, UInt uiPartUnitOffset = 1, Bool bEnforceSliceRestriction=true, Bool bEnforceDependentSliceRestriction=true );
+  TComDataCU*   getPUBelowLeftAdi           ( UInt&  uiBLPartUnitIdx, UInt uiPuHeight, UInt uiCurrPartUnitIdx, UInt uiPartUnitOffset = 1, Bool bEnforceSliceRestriction=true, Bool bEnforceDependentSliceRestriction=true );
+  
+  Void          deriveLeftRightTopIdx       ( PartSize eCUMode, UInt uiPartIdx, UInt& ruiPartIdxLT, UInt& ruiPartIdxRT );
+  Void          deriveLeftBottomIdx         ( PartSize eCUMode, UInt uiPartIdx, UInt& ruiPartIdxLB );
+  
+  Void          deriveLeftRightTopIdxAdi    ( UInt& ruiPartIdxLT, UInt& ruiPartIdxRT, UInt uiPartOffset, UInt uiPartDepth );
+  Void          deriveLeftBottomIdxAdi      ( UInt& ruiPartIdxLB, UInt  uiPartOffset, UInt uiPartDepth );
+  
+  Bool          hasEqualMotion              ( UInt uiAbsPartIdx, TComDataCU* pcCandCU, UInt uiCandAbsPartIdx );
+  Void          getInterMergeCandidates       ( UInt uiAbsPartIdx, UInt uiPUIdx, UInt uiDepth, TComMvField* pcMFieldNeighbours, UChar* puhInterDirNeighbours, Int& numValidMergeCand, Int mrgCandIdx = -1 );
+  Void          deriveLeftRightTopIdxGeneral  ( PartSize eCUMode, UInt uiAbsPartIdx, UInt uiPartIdx, UInt& ruiPartIdxLT, UInt& ruiPartIdxRT );
+  Void          deriveLeftBottomIdxGeneral    ( PartSize eCUMode, UInt uiAbsPartIdx, UInt uiPartIdx, UInt& ruiPartIdxLB );
+  
+#if SVC_MVP
+  Bool          hasEqualMotion              ( UInt uiAbsPartIdx, UChar uchInterDir, TComMvField* pcMvField  );
+#endif
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // member functions for modes
+  // -------------------------------------------------------------------------------------------------------------------
+  
+#if INTRA_BL
+  Void          getBaseLumaBlk   ( UInt uiWidth, UInt uiHeight, UInt uiAbsPartIdx, Pel* piPred, UInt uiStride );
+  Void          getBaseChromaBlk ( UInt uiWidth, UInt uiHeight, UInt uiAbsPartIdx, Pel* piPred, UInt uiStride, UInt uiChromaId );
+#endif
+#if INTRA_BL
+  Bool          isIntraBL ( UInt uiPartIdx )  { return m_pePredMode[ uiPartIdx ] == MODE_INTRA_BL; }
+  Bool          isIntra   ( UInt uiPartIdx )  { return m_pePredMode[ uiPartIdx ] == MODE_INTRA || m_pePredMode[ uiPartIdx ] == MODE_INTRA_BL; }
+#else
+  Bool          isIntra   ( UInt uiPartIdx )  { return m_pePredMode[ uiPartIdx ] == MODE_INTRA; }
+#endif 
+  Bool          isSkipped ( UInt uiPartIdx );                                                     ///< SKIP (no residual)
+  Bool          isBipredRestriction( UInt puIdx );
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // member functions for symbol prediction (most probable / mode conversion)
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  UInt          getIntraSizeIdx                 ( UInt uiAbsPartIdx                                       );
+  Void          convertTransIdx                 ( UInt uiAbsPartIdx, UInt uiTrIdx, UInt& ruiLumaTrMode, UInt& ruiChromaTrMode );
+  
+  Void          getAllowedChromaDir             ( UInt uiAbsPartIdx, UInt* uiModeList );
+  Int           getIntraDirLumaPredictor        ( UInt uiAbsPartIdx, Int* uiIntraDirPred, Int* piMode = NULL );
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // member functions for SBAC context
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  UInt          getCtxSplitFlag                 ( UInt   uiAbsPartIdx, UInt uiDepth                   );
+  UInt          getCtxQtCbf                     ( UInt   uiAbsPartIdx, TextType eType, UInt uiTrDepth );
+
+  UInt          getCtxSkipFlag                  ( UInt   uiAbsPartIdx                                 );
+  UInt          getCtxInterDir                  ( UInt   uiAbsPartIdx                                 );
+
+#if INTRA_BL
+  UInt          getCtxIntraBLFlag               ( UInt   uiAbsPartIdx                                 );
+#endif  
+  
+  UInt          getSliceStartCU         ( UInt pos )                  { return m_uiSliceStartCU[pos-m_uiAbsIdxInLCU];                                                                                          }
+  UInt          getDependentSliceStartCU  ( UInt pos )                  { return m_uiDependentSliceStartCU[pos-m_uiAbsIdxInLCU];                                                                                   }
+  UInt&         getTotalBins            ()                            { return m_uiTotalBins;                                                                                                  }
+  // -------------------------------------------------------------------------------------------------------------------
+  // member functions for RD cost storage
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Double&       getTotalCost()                  { return m_dTotalCost;        }
+  UInt&         getTotalDistortion()            { return m_uiTotalDistortion; }
+  UInt&         getTotalBits()                  { return m_uiTotalBits;       }
+  UInt&         getTotalNumPart()               { return m_uiNumPartition;    }
+
+  UInt          getCoefScanIdx(UInt uiAbsPartIdx, UInt uiWidth, Bool bIsLuma, Bool bIsIntra);
+
+#if !REMOVE_NSQT
+  Bool          useNonSquareTrans( UInt uiTrMode, Int absPartIdx );
+  Void          getNSQTSize(Int trMode, Int absPartIdx, Int &trWidth, Int &trHeight);
+  Bool          useNonSquarePU   ( UInt absPartIdx);
+  UInt          getInterTUSplitDirection ( Int width, Int height, Int trLastWidth, Int trLastHeight );
+  UInt          getNSAbsPartIdx  ( UInt log2TrafoSize, UInt absPartIdx, UInt absTUPartIdx, UInt innerQuadIdx, UInt trMode );
+  UInt          getNSAddrChroma   ( UInt uiLog2TrSizeC, UInt uiTrModeC, UInt uiQuadrant, UInt absTUPartIdx );
+#endif
+
+#if SVC_COL_BLK 
+  TComDataCU*   getBaseColCU( UInt uiCuAbsPartIdx, UInt &uiCUAddrBase, UInt &uiAbsPartIdxBase );
+  Void          scaleBaseMV( TComMvField& rcMvFieldEnhance, TComMvField& rcMvFieldBase );
+#endif
+};
+
+namespace RasterAddress
+{
+  /** Check whether 2 addresses point to the same column
+   * \param addrA          First address in raster scan order
+   * \param addrB          Second address in raters scan order
+   * \param numUnitsPerRow Number of units in a row
+   * \return Result of test
+   */
+  static inline Bool isEqualCol( Int addrA, Int addrB, Int numUnitsPerRow )
+  {
+    // addrA % numUnitsPerRow == addrB % numUnitsPerRow
+    return (( addrA ^ addrB ) &  ( numUnitsPerRow - 1 ) ) == 0;
+  }
+  
+  /** Check whether 2 addresses point to the same row
+   * \param addrA          First address in raster scan order
+   * \param addrB          Second address in raters scan order
+   * \param numUnitsPerRow Number of units in a row
+   * \return Result of test
+   */
+  static inline Bool isEqualRow( Int addrA, Int addrB, Int numUnitsPerRow )
+  {
+    // addrA / numUnitsPerRow == addrB / numUnitsPerRow
+    return (( addrA ^ addrB ) &~ ( numUnitsPerRow - 1 ) ) == 0;
+  }
+  
+  /** Check whether 2 addresses point to the same row or column
+   * \param addrA          First address in raster scan order
+   * \param addrB          Second address in raters scan order
+   * \param numUnitsPerRow Number of units in a row
+   * \return Result of test
+   */
+  static inline Bool isEqualRowOrCol( Int addrA, Int addrB, Int numUnitsPerRow )
+  {
+    return isEqualCol( addrA, addrB, numUnitsPerRow ) | isEqualRow( addrA, addrB, numUnitsPerRow );
+  }
+  
+  /** Check whether one address points to the first column
+   * \param addr           Address in raster scan order
+   * \param numUnitsPerRow Number of units in a row
+   * \return Result of test
+   */
+  static inline Bool isZeroCol( Int addr, Int numUnitsPerRow )
+  {
+    // addr % numUnitsPerRow == 0
+    return ( addr & ( numUnitsPerRow - 1 ) ) == 0;
+  }
+  
+  /** Check whether one address points to the first row
+   * \param addr           Address in raster scan order
+   * \param numUnitsPerRow Number of units in a row
+   * \return Result of test
+   */
+  static inline Bool isZeroRow( Int addr, Int numUnitsPerRow )
+  {
+    // addr / numUnitsPerRow == 0
+    return ( addr &~ ( numUnitsPerRow - 1 ) ) == 0;
+  }
+  
+  /** Check whether one address points to a column whose index is smaller than a given value
+   * \param addr           Address in raster scan order
+   * \param val            Given column index value
+   * \param numUnitsPerRow Number of units in a row
+   * \return Result of test
+   */
+  static inline Bool lessThanCol( Int addr, Int val, Int numUnitsPerRow )
+  {
+    // addr % numUnitsPerRow < val
+    return ( addr & ( numUnitsPerRow - 1 ) ) < val;
+  }
+  
+  /** Check whether one address points to a row whose index is smaller than a given value
+   * \param addr           Address in raster scan order
+   * \param val            Given row index value
+   * \param numUnitsPerRow Number of units in a row
+   * \return Result of test
+   */
+  static inline Bool lessThanRow( Int addr, Int val, Int numUnitsPerRow )
+  {
+    // addr / numUnitsPerRow < val
+    return addr < val * numUnitsPerRow;
+  }
+};
+
+//! \}
+
+#endif
Index: /trunk/source/Lib/TLibCommon/TComInterpolationFilter.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComInterpolationFilter.cpp	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComInterpolationFilter.cpp	(revision 2)
@@ -0,0 +1,417 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * \file
+ * \brief Implementation of TComInterpolationFilter class
+ */
+
+// ====================================================================================================================
+// Includes
+// ====================================================================================================================
+
+#include "TComRom.h"
+#include "TComInterpolationFilter.h"
+#include <assert.h>
+
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Tables
+// ====================================================================================================================
+
+const Short TComInterpolationFilter::m_lumaFilter[4][NTAPS_LUMA] =
+{
+  {  0, 0,   0, 64,  0,   0, 0,  0 },
+  { -1, 4, -10, 58, 17,  -5, 1,  0 },
+  { -1, 4, -11, 40, 40, -11, 4, -1 },
+  {  0, 1,  -5, 17, 58, -10, 4, -1 }
+};
+
+const Short TComInterpolationFilter::m_chromaFilter[8][NTAPS_CHROMA] =
+{
+  {  0, 64,  0,  0 },
+  { -2, 58, 10, -2 },
+  { -4, 54, 16, -2 },
+  { -6, 46, 28, -4 },
+  { -4, 36, 36, -4 },
+  { -4, 28, 46, -6 },
+  { -2, 16, 54, -4 },
+  { -2, 10, 58, -2 }
+};
+
+// ====================================================================================================================
+// Private member functions
+// ====================================================================================================================
+
+/**
+ * \brief Apply unit FIR filter to a block of samples
+ *
+ * \param src        Pointer to source samples
+ * \param srcStride  Stride of source samples
+ * \param dst        Pointer to destination samples
+ * \param dstStride  Stride of destination samples
+ * \param width      Width of block
+ * \param height     Height of block
+ * \param isFirst    Flag indicating whether it is the first filtering operation
+ * \param isLast     Flag indicating whether it is the last filtering operation
+ */
+Void TComInterpolationFilter::filterCopy(const Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Bool isFirst, Bool isLast)
+{
+  Int row, col;
+  
+  if ( isFirst == isLast )
+  {
+    for (row = 0; row < height; row++)
+    {
+      for (col = 0; col < width; col++)
+      {
+        dst[col] = src[col];
+      }
+      
+      src += srcStride;
+      dst += dstStride;
+    }              
+  }
+  else if ( isFirst )
+  {
+    Int shift = IF_INTERNAL_PREC - ( g_uiBitDepth + g_uiBitIncrement );
+    
+    for (row = 0; row < height; row++)
+    {
+      for (col = 0; col < width; col++)
+      {
+        Short val = src[col] << shift;
+        dst[col] = val - (Short)IF_INTERNAL_OFFS;
+      }
+      
+      src += srcStride;
+      dst += dstStride;
+    }          
+  }
+  else
+  {
+    Int shift = IF_INTERNAL_PREC - ( g_uiBitDepth + g_uiBitIncrement );
+    Short offset = IF_INTERNAL_OFFS;
+    offset += shift?(1 << (shift - 1)):0;
+    Short maxVal = g_uiIBDI_MAX;
+    Short minVal = 0;
+    for (row = 0; row < height; row++)
+    {
+      for (col = 0; col < width; col++)
+      {
+        Short val = src[ col ];
+        val = ( val + offset ) >> shift;
+        if (val < minVal) val = minVal;
+        if (val > maxVal) val = maxVal;
+        dst[col] = val;
+      }
+      
+      src += srcStride;
+      dst += dstStride;
+    }              
+  }
+}
+
+/**
+ * \brief Apply FIR filter to a block of samples
+ *
+ * \tparam N          Number of taps
+ * \tparam isVertical Flag indicating filtering along vertical direction
+ * \tparam isFirst    Flag indicating whether it is the first filtering operation
+ * \tparam isLast     Flag indicating whether it is the last filtering operation
+ * \param  src        Pointer to source samples
+ * \param  srcStride  Stride of source samples
+ * \param  dst        Pointer to destination samples
+ * \param  dstStride  Stride of destination samples
+ * \param  width      Width of block
+ * \param  height     Height of block
+ * \param  coeff      Pointer to filter taps
+ */
+template<int N, bool isVertical, bool isFirst, bool isLast>
+Void TComInterpolationFilter::filter(Short const *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Short const *coeff)
+{
+  Int row, col;
+  
+  Short c[8];
+  c[0] = coeff[0];
+  c[1] = coeff[1];
+  if ( N >= 4 )
+  {
+    c[2] = coeff[2];
+    c[3] = coeff[3];
+  }
+  if ( N >= 6 )
+  {
+    c[4] = coeff[4];
+    c[5] = coeff[5];
+  }
+  if ( N == 8 )
+  {
+    c[6] = coeff[6];
+    c[7] = coeff[7];
+  }
+  
+  Int cStride = ( isVertical ) ? srcStride : 1;
+  src -= ( N/2 - 1 ) * cStride;
+
+  Int offset;
+  Short maxVal;
+  Int headRoom = IF_INTERNAL_PREC - (g_uiBitDepth + g_uiBitIncrement);
+  Int shift = IF_FILTER_PREC;
+  if ( isLast )
+  {
+    shift += (isFirst) ? 0 : headRoom;
+    offset = 1 << (shift - 1);
+    offset += (isFirst) ? 0 : IF_INTERNAL_OFFS << IF_FILTER_PREC;
+    maxVal = g_uiIBDI_MAX;
+  }
+  else
+  {
+    shift -= (isFirst) ? headRoom : 0;
+    offset = (isFirst) ? -IF_INTERNAL_OFFS << shift : 0;
+    maxVal = 0;
+  }
+  
+  for (row = 0; row < height; row++)
+  {
+    for (col = 0; col < width; col++)
+    {
+      Int sum;
+      
+      sum  = src[ col + 0 * cStride] * c[0];
+      sum += src[ col + 1 * cStride] * c[1];
+      if ( N >= 4 )
+      {
+        sum += src[ col + 2 * cStride] * c[2];
+        sum += src[ col + 3 * cStride] * c[3];
+      }
+      if ( N >= 6 )
+      {
+        sum += src[ col + 4 * cStride] * c[4];
+        sum += src[ col + 5 * cStride] * c[5];
+      }
+      if ( N == 8 )
+      {
+        sum += src[ col + 6 * cStride] * c[6];
+        sum += src[ col + 7 * cStride] * c[7];        
+      }
+      
+      Short val = ( sum + offset ) >> shift;
+      if ( isLast )
+      {
+        val = ( val < 0 ) ? 0 : val;
+        val = ( val > maxVal ) ? maxVal : val;        
+      }
+      dst[col] = val;
+    }
+    
+    src += srcStride;
+    dst += dstStride;
+  }    
+}
+
+/**
+ * \brief Filter a block of samples (horizontal)
+ *
+ * \tparam N          Number of taps
+ * \param  src        Pointer to source samples
+ * \param  srcStride  Stride of source samples
+ * \param  dst        Pointer to destination samples
+ * \param  dstStride  Stride of destination samples
+ * \param  width      Width of block
+ * \param  height     Height of block
+ * \param  isLast     Flag indicating whether it is the last filtering operation
+ * \param  coeff      Pointer to filter taps
+ */
+template<int N>
+Void TComInterpolationFilter::filterHor(Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Bool isLast, Short const *coeff)
+{
+  if ( isLast )
+  {
+    filter<N, false, true, true>(src, srcStride, dst, dstStride, width, height, coeff);
+  }
+  else
+  {
+    filter<N, false, true, false>(src, srcStride, dst, dstStride, width, height, coeff);
+  }
+}
+
+/**
+ * \brief Filter a block of samples (vertical)
+ *
+ * \tparam N          Number of taps
+ * \param  src        Pointer to source samples
+ * \param  srcStride  Stride of source samples
+ * \param  dst        Pointer to destination samples
+ * \param  dstStride  Stride of destination samples
+ * \param  width      Width of block
+ * \param  height     Height of block
+ * \param  isFirst    Flag indicating whether it is the first filtering operation
+ * \param  isLast     Flag indicating whether it is the last filtering operation
+ * \param  coeff      Pointer to filter taps
+ */
+template<int N>
+Void TComInterpolationFilter::filterVer(Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Bool isFirst, Bool isLast, Short const *coeff)
+{
+  if ( isFirst && isLast )
+  {
+    filter<N, true, true, true>(src, srcStride, dst, dstStride, width, height, coeff);
+  }
+  else if ( isFirst && !isLast )
+  {
+    filter<N, true, true, false>(src, srcStride, dst, dstStride, width, height, coeff);
+  }
+  else if ( !isFirst && isLast )
+  {
+    filter<N, true, false, true>(src, srcStride, dst, dstStride, width, height, coeff);
+  }
+  else
+  {
+    filter<N, true, false, false>(src, srcStride, dst, dstStride, width, height, coeff);    
+  }      
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/**
+ * \brief Filter a block of luma samples (horizontal)
+ *
+ * \param  src        Pointer to source samples
+ * \param  srcStride  Stride of source samples
+ * \param  dst        Pointer to destination samples
+ * \param  dstStride  Stride of destination samples
+ * \param  width      Width of block
+ * \param  height     Height of block
+ * \param  frac       Fractional sample offset
+ * \param  isLast     Flag indicating whether it is the last filtering operation
+ */
+Void TComInterpolationFilter::filterHorLuma(Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Int frac, Bool isLast )
+{
+  assert(frac >= 0 && frac < 4);
+  
+  if ( frac == 0 )
+  {
+    filterCopy( src, srcStride, dst, dstStride, width, height, true, isLast );
+  }
+  else
+  {
+    filterHor<NTAPS_LUMA>(src, srcStride, dst, dstStride, width, height, isLast, m_lumaFilter[frac]);
+  }
+}
+
+/**
+ * \brief Filter a block of luma samples (vertical)
+ *
+ * \param  src        Pointer to source samples
+ * \param  srcStride  Stride of source samples
+ * \param  dst        Pointer to destination samples
+ * \param  dstStride  Stride of destination samples
+ * \param  width      Width of block
+ * \param  height     Height of block
+ * \param  frac       Fractional sample offset
+ * \param  isFirst    Flag indicating whether it is the first filtering operation
+ * \param  isLast     Flag indicating whether it is the last filtering operation
+ */
+Void TComInterpolationFilter::filterVerLuma(Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Int frac, Bool isFirst, Bool isLast )
+{
+  assert(frac >= 0 && frac < 4);
+  
+  if ( frac == 0 )
+  {
+    filterCopy( src, srcStride, dst, dstStride, width, height, isFirst, isLast );
+  }
+  else
+  {
+    filterVer<NTAPS_LUMA>(src, srcStride, dst, dstStride, width, height, isFirst, isLast, m_lumaFilter[frac]);    
+  }
+}
+
+/**
+ * \brief Filter a block of chroma samples (horizontal)
+ *
+ * \param  src        Pointer to source samples
+ * \param  srcStride  Stride of source samples
+ * \param  dst        Pointer to destination samples
+ * \param  dstStride  Stride of destination samples
+ * \param  width      Width of block
+ * \param  height     Height of block
+ * \param  frac       Fractional sample offset
+ * \param  isLast     Flag indicating whether it is the last filtering operation
+ */
+Void TComInterpolationFilter::filterHorChroma(Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Int frac, Bool isLast )
+{
+  assert(frac >= 0 && frac < 8);
+  
+  if ( frac == 0 )
+  {
+    filterCopy( src, srcStride, dst, dstStride, width, height, true, isLast );
+  }
+  else
+  {
+    filterHor<NTAPS_CHROMA>(src, srcStride, dst, dstStride, width, height, isLast, m_chromaFilter[frac]);
+  }
+}
+
+/**
+ * \brief Filter a block of chroma samples (vertical)
+ *
+ * \param  src        Pointer to source samples
+ * \param  srcStride  Stride of source samples
+ * \param  dst        Pointer to destination samples
+ * \param  dstStride  Stride of destination samples
+ * \param  width      Width of block
+ * \param  height     Height of block
+ * \param  frac       Fractional sample offset
+ * \param  isFirst    Flag indicating whether it is the first filtering operation
+ * \param  isLast     Flag indicating whether it is the last filtering operation
+ */
+Void TComInterpolationFilter::filterVerChroma(Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Int frac, Bool isFirst, Bool isLast )
+{
+  assert(frac >= 0 && frac < 8);
+  
+  if ( frac == 0 )
+  {
+    filterCopy( src, srcStride, dst, dstStride, width, height, isFirst, isLast );
+  }
+  else
+  {
+    filterVer<NTAPS_CHROMA>(src, srcStride, dst, dstStride, width, height, isFirst, isLast, m_chromaFilter[frac]);    
+  }
+}
+
+//! \}
Index: /trunk/source/Lib/TLibCommon/TComInterpolationFilter.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComInterpolationFilter.h	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComInterpolationFilter.h	(revision 2)
@@ -0,0 +1,83 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * \file
+ * \brief Declaration of TComInterpolationFilter class
+ */
+
+#ifndef __HM_TCOMINTERPOLATIONFILTER_H__
+#define __HM_TCOMINTERPOLATIONFILTER_H__
+
+#include "TypeDef.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+#define NTAPS_LUMA        8 ///< Number of taps for luma
+#define NTAPS_CHROMA      4 ///< Number of taps for chroma
+#define IF_INTERNAL_PREC 14 ///< Number of bits for internal precision
+#define IF_FILTER_PREC    6 ///< Log2 of sum of filter taps
+#define IF_INTERNAL_OFFS (1<<(IF_INTERNAL_PREC-1)) ///< Offset used internally
+
+/**
+ * \brief Interpolation filter class
+ */
+class TComInterpolationFilter
+{
+  static const Short m_lumaFilter[4][NTAPS_LUMA];     ///< Luma filter taps
+  static const Short m_chromaFilter[8][NTAPS_CHROMA]; ///< Chroma filter taps
+  
+  static Void filterCopy(const Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Bool isFirst, Bool isLast);
+  
+  template<int N, bool isVertical, bool isFirst, bool isLast>
+  static Void filter(Pel const *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Short const *coeff);
+
+  template<int N>
+  static Void filterHor(Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height,               Bool isLast, Short const *coeff);
+  template<int N>
+  static Void filterVer(Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Bool isFirst, Bool isLast, Short const *coeff);
+
+public:
+  TComInterpolationFilter() {}
+  ~TComInterpolationFilter() {}
+
+  Void filterHorLuma  (Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Int frac,               Bool isLast );
+  Void filterVerLuma  (Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Int frac, Bool isFirst, Bool isLast );
+  Void filterHorChroma(Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Int frac,               Bool isLast );
+  Void filterVerChroma(Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Int frac, Bool isFirst, Bool isLast );
+};
+
+//! \}
+
+#endif
Index: /trunk/source/Lib/TLibCommon/TComList.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComList.h	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComList.h	(revision 2)
@@ -0,0 +1,115 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComList.h
+    \brief    general list class (header)
+*/
+
+#ifndef _TCOMLIST_
+#define _TCOMLIST_
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include <list>
+#include <assert.h>
+#include "CommonDef.h"
+
+#include <cstdlib>
+using namespace std;
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// list template
+template< class C >
+class TComList : public std::list< C >
+{
+public:
+  typedef typename std::list<C>::iterator TComIterator;
+  
+  TComList& operator += ( const TComList& rcTComList)
+  {
+    if( ! rcTComList.empty() )
+    {
+      insert( this->end(), rcTComList.begin(), rcTComList.end());
+    }
+    return *this;
+  } // leszek
+  
+  C popBack()
+  {
+    C cT = this->back();
+    this->pop_back();
+    return cT;
+  }
+  
+  C popFront()
+  {
+    C cT = this->front();
+    this->pop_front();
+    return cT;
+  }
+  
+  Void pushBack( const C& rcT )
+  {
+    /*assert( sizeof(C) == 4);*/
+    if( rcT != NULL )
+    {
+      this->push_back( rcT);
+    }
+  }
+  
+  Void pushFront( const C& rcT )
+  {
+    /*assert( sizeof(C) == 4);*/
+    if( rcT != NULL )
+    {
+      this->push_front( rcT);
+    }
+  }
+  
+  TComIterator find( const C& rcT ) // leszek
+  {
+    return find( this->begin(), this->end(), rcT );
+  }
+};
+
+//! \}
+
+#endif
Index: /trunk/source/Lib/TLibCommon/TComLoopFilter.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComLoopFilter.cpp	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComLoopFilter.cpp	(revision 2)
@@ -0,0 +1,925 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComLoopFilter.cpp
+    \brief    deblocking filter
+*/
+
+#include "TComLoopFilter.h"
+#include "TComSlice.h"
+#include "TComMv.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+#define   EDGE_VER    0
+#define   EDGE_HOR    1
+#define   QpUV(iQpY)  ( g_aucChromaScale[ max( min( (iQpY), MAX_QP ), MIN_QP ) ] )
+
+#define DEFAULT_INTRA_TC_OFFSET 2 ///< Default intra TC offset
+
+// ====================================================================================================================
+// Tables
+// ====================================================================================================================
+
+const UChar tctable_8x8[54] =
+{
+  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,5,5,6,6,7,8,9,10,11,13,14,16,18,20,22,24
+};
+
+const UChar betatable_8x8[52] =
+{
+  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,6,7,8,9,10,11,12,13,14,15,16,17,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64
+};
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TComLoopFilter::TComLoopFilter()
+: m_disableDeblockingFilterFlag(false)
+, m_betaOffsetDiv2(0)
+, m_tcOffsetDiv2(0)
+, m_uiNumPartitions(0)
+, m_bLFCrossTileBoundary(true)
+{
+  for( UInt uiDir = 0; uiDir < 2; uiDir++ )
+  {
+    m_aapucBS       [uiDir] = NULL;
+    for( UInt uiPlane = 0; uiPlane < 3; uiPlane++ )
+    {
+      m_aapbEdgeFilter[uiDir][uiPlane] = NULL;
+    }
+  }
+}
+
+TComLoopFilter::~TComLoopFilter()
+{
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+Void TComLoopFilter::setCfg( Bool deblockingFilterControlPresentFlag, Bool disableDeblockingFilterFlag, Int betaOffsetDiv2, Int tcOffsetDiv2, Bool bLFCrossTileBoundary )
+{
+  m_bLFCrossTileBoundary = bLFCrossTileBoundary;
+
+  if (deblockingFilterControlPresentFlag)
+  {
+    m_disableDeblockingFilterFlag  = disableDeblockingFilterFlag;
+    m_betaOffsetDiv2 = betaOffsetDiv2;
+    m_tcOffsetDiv2 = tcOffsetDiv2;
+  } 
+  else // use default values
+  {
+    m_disableDeblockingFilterFlag = false;
+    m_betaOffsetDiv2 = 0;
+    m_tcOffsetDiv2 = 0;
+  }
+}
+
+Void TComLoopFilter::create( UInt uiMaxCUDepth )
+{
+  destroy();
+  m_uiNumPartitions = 1 << ( uiMaxCUDepth<<1 );
+  for( UInt uiDir = 0; uiDir < 2; uiDir++ )
+  {
+    m_aapucBS       [uiDir] = new UChar[m_uiNumPartitions];
+    for( UInt uiPlane = 0; uiPlane < 3; uiPlane++ )
+    {
+      m_aapbEdgeFilter[uiDir][uiPlane] = new Bool [m_uiNumPartitions];
+    }
+  }
+}
+
+Void TComLoopFilter::destroy()
+{
+  for( UInt uiDir = 0; uiDir < 2; uiDir++ )
+  {
+    if (m_aapucBS)
+    {
+      delete [] m_aapucBS       [uiDir];
+      m_aapucBS [uiDir] = NULL;
+    }
+    for( UInt uiPlane = 0; uiPlane < 3; uiPlane++ )
+    {
+      if (m_aapbEdgeFilter[uiDir][uiPlane])
+      {
+        delete [] m_aapbEdgeFilter[uiDir][uiPlane];
+        m_aapbEdgeFilter[uiDir][uiPlane] = NULL;
+      }
+    }
+  }
+}
+
+/**
+ - call deblocking function for every CU
+ .
+ \param  pcPic   picture class (TComPic) pointer
+ */
+Void TComLoopFilter::loopFilterPic( TComPic* pcPic )
+{
+  if ( m_disableDeblockingFilterFlag )
+  {
+    return;
+  }
+  
+  // Horizontal filtering
+  for ( UInt uiCUAddr = 0; uiCUAddr < pcPic->getNumCUsInFrame(); uiCUAddr++ )
+  {
+    TComDataCU* pcCU = pcPic->getCU( uiCUAddr );
+
+    ::memset( m_aapucBS       [EDGE_VER], 0, sizeof( UChar ) * m_uiNumPartitions );
+    for( Int iPlane = 0; iPlane < 3; iPlane++ )
+    {
+      ::memset( m_aapbEdgeFilter[EDGE_VER][iPlane], 0, sizeof( bool  ) * m_uiNumPartitions );
+    }
+
+    // CU-based deblocking
+    xDeblockCU( pcCU, 0, 0, EDGE_VER );
+  }
+
+  // Vertical filtering
+  for ( UInt uiCUAddr = 0; uiCUAddr < pcPic->getNumCUsInFrame(); uiCUAddr++ )
+  {
+    TComDataCU* pcCU = pcPic->getCU( uiCUAddr );
+
+    ::memset( m_aapucBS       [EDGE_HOR], 0, sizeof( UChar ) * m_uiNumPartitions );
+    
+    for( Int iPlane = 0; iPlane < 3; iPlane++ )
+    {
+      ::memset( m_aapbEdgeFilter[EDGE_HOR][iPlane], 0, sizeof( bool  ) * m_uiNumPartitions );
+    }
+
+    // CU-based deblocking
+    xDeblockCU( pcCU, 0, 0, EDGE_HOR );
+  }
+}
+
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+/**
+ - Deblocking filter process in CU-based (the same function as conventional's)
+ .
+ \param Edge          the direction of the edge in block boundary (horizonta/vertical), which is added newly
+*/
+Void TComLoopFilter::xDeblockCU( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, Int Edge )
+{
+  if(pcCU->getPic()==0||pcCU->getPartitionSize(uiAbsZorderIdx)==SIZE_NONE)
+  {
+    return;
+  }
+  TComPic* pcPic     = pcCU->getPic();
+  UInt uiCurNumParts = pcPic->getNumPartInCU() >> (uiDepth<<1);
+  UInt uiQNumParts   = uiCurNumParts>>2;
+  
+  if( pcCU->getDepth(uiAbsZorderIdx) > uiDepth )
+  {
+    for ( UInt uiPartIdx = 0; uiPartIdx < 4; uiPartIdx++, uiAbsZorderIdx+=uiQNumParts )
+    {
+      UInt uiLPelX   = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsZorderIdx] ];
+      UInt uiTPelY   = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsZorderIdx] ];
+      if( ( uiLPelX < pcCU->getSlice()->getSPS()->getPicWidthInLumaSamples() ) && ( uiTPelY < pcCU->getSlice()->getSPS()->getPicHeightInLumaSamples() ) )
+      {
+        xDeblockCU( pcCU, uiAbsZorderIdx, uiDepth+1, Edge );
+      }
+    }
+    return;
+  }
+  
+  xSetLoopfilterParam( pcCU, uiAbsZorderIdx );
+  
+  xSetEdgefilterTU   ( pcCU, uiAbsZorderIdx , uiAbsZorderIdx, uiDepth );
+  xSetEdgefilterPU   ( pcCU, uiAbsZorderIdx );
+  
+  Int iDir = Edge;
+  for( UInt uiPartIdx = uiAbsZorderIdx; uiPartIdx < uiAbsZorderIdx + uiCurNumParts; uiPartIdx++ )
+  {
+    UInt uiBSCheck;
+    if( (g_uiMaxCUWidth >> g_uiMaxCUDepth) == 4 ) 
+    {
+      uiBSCheck = (iDir == EDGE_VER && uiPartIdx%2 == 0) || (iDir == EDGE_HOR && (uiPartIdx-((uiPartIdx>>2)<<2))/2 == 0);
+    }
+    else
+    {
+      uiBSCheck = 1;
+    }
+    
+    if ( m_aapbEdgeFilter[iDir][0][uiPartIdx] && uiBSCheck )
+    {
+      xGetBoundaryStrengthSingle ( pcCU, uiAbsZorderIdx, iDir, uiPartIdx );
+    }
+  }
+  
+  UInt uiPelsInPart = g_uiMaxCUWidth >> g_uiMaxCUDepth;
+  UInt PartIdxIncr = DEBLOCK_SMALLEST_BLOCK / uiPelsInPart ? DEBLOCK_SMALLEST_BLOCK / uiPelsInPart : 1 ;
+  
+  UInt uiSizeInPU = pcPic->getNumPartInWidth()>>(uiDepth);
+  
+  for ( UInt iEdge = 0; iEdge < uiSizeInPU ; iEdge+=PartIdxIncr)
+  {
+    xEdgeFilterLuma     ( pcCU, uiAbsZorderIdx, uiDepth, iDir, iEdge );
+    if ( (uiPelsInPart>DEBLOCK_SMALLEST_BLOCK) || (iEdge % ( (DEBLOCK_SMALLEST_BLOCK<<1)/uiPelsInPart ) ) == 0 )
+    {
+      xEdgeFilterChroma   ( pcCU, uiAbsZorderIdx, uiDepth, iDir, iEdge );
+    }
+  }
+}
+
+Void TComLoopFilter::xSetEdgefilterMultiple( TComDataCU* pcCU, UInt uiScanIdx, UInt uiDepth, Int iDir, Int iEdgeIdx, Bool bValue,UInt uiWidthInBaseUnits, UInt uiHeightInBaseUnits, Bool nonSquare )
+{  
+  if ( uiWidthInBaseUnits == 0 )
+  {
+    uiWidthInBaseUnits  = pcCU->getPic()->getNumPartInWidth () >> uiDepth;
+  }
+  if ( uiHeightInBaseUnits == 0 )
+  {
+    uiHeightInBaseUnits = pcCU->getPic()->getNumPartInHeight() >> uiDepth;
+  }
+  const UInt uiNumElem = iDir == 0 ? uiHeightInBaseUnits : uiWidthInBaseUnits;
+  assert( uiNumElem > 0 );
+  assert( uiWidthInBaseUnits > 0 );
+  assert( uiHeightInBaseUnits > 0 );
+  for( UInt ui = 0; ui < uiNumElem; ui++ )
+  {
+    const UInt uiBsIdx = xCalcBsIdx( pcCU, uiScanIdx, iDir, iEdgeIdx, ui );
+    m_aapbEdgeFilter[iDir][0][uiBsIdx] = bValue;
+    m_aapbEdgeFilter[iDir][1][uiBsIdx] = bValue;
+    m_aapbEdgeFilter[iDir][2][uiBsIdx] = bValue;
+    if (iEdgeIdx == 0)
+    {
+      m_aapucBS[iDir][uiBsIdx] = bValue;
+    }
+  }
+}
+
+Void TComLoopFilter::xSetEdgefilterTU( TComDataCU* pcCU, UInt absTUPartIdx, UInt uiAbsZorderIdx, UInt uiDepth )
+{
+  if( pcCU->getTransformIdx( uiAbsZorderIdx ) + pcCU->getDepth( uiAbsZorderIdx) > uiDepth )
+  {
+    const UInt uiCurNumParts = pcCU->getPic()->getNumPartInCU() >> (uiDepth<<1);
+    const UInt uiQNumParts   = uiCurNumParts>>2;
+#if !REMOVE_NSQT
+    const UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiDepth ] + 2;
+#endif
+    for ( UInt uiPartIdx = 0; uiPartIdx < 4; uiPartIdx++, uiAbsZorderIdx+=uiQNumParts )
+    {
+#if REMOVE_NSQT
+      UInt nsAddr = uiAbsZorderIdx;
+#else
+      UInt nsAddr = 0;
+      nsAddr = pcCU->getNSAbsPartIdx( uiLog2TrSize - 1, uiAbsZorderIdx, absTUPartIdx, uiPartIdx, uiDepth + 1 - pcCU->getDepth( uiAbsZorderIdx ) );
+#endif
+      xSetEdgefilterTU( pcCU,nsAddr, uiAbsZorderIdx, uiDepth + 1 );
+    }
+    return;
+  }
+
+  Int trWidth  = pcCU->getWidth( uiAbsZorderIdx ) >> pcCU->getTransformIdx( uiAbsZorderIdx );
+  Int trHeight = pcCU->getHeight( uiAbsZorderIdx ) >> pcCU->getTransformIdx( uiAbsZorderIdx );
+#if !REMOVE_NSQT
+  pcCU->getNSQTSize( uiDepth - pcCU->getDepth( uiAbsZorderIdx ), uiAbsZorderIdx, trWidth, trHeight );
+#endif
+  
+  UInt uiWidthInBaseUnits  = trWidth / (g_uiMaxCUWidth >> g_uiMaxCUDepth);
+  UInt uiHeightInBaseUnits = trHeight / (g_uiMaxCUWidth >> g_uiMaxCUDepth);
+
+  xSetEdgefilterMultiple( pcCU, absTUPartIdx, uiDepth, EDGE_VER, 0, m_stLFCUParam.bInternalEdge, uiWidthInBaseUnits, uiHeightInBaseUnits );
+  xSetEdgefilterMultiple( pcCU, absTUPartIdx, uiDepth, EDGE_HOR, 0, m_stLFCUParam.bInternalEdge, uiWidthInBaseUnits, uiHeightInBaseUnits );
+}
+
+Void TComLoopFilter::xSetEdgefilterPU( TComDataCU* pcCU, UInt uiAbsZorderIdx )
+{
+  const UInt uiDepth = pcCU->getDepth( uiAbsZorderIdx );
+  const UInt uiWidthInBaseUnits  = pcCU->getPic()->getNumPartInWidth () >> uiDepth;
+  const UInt uiHeightInBaseUnits = pcCU->getPic()->getNumPartInHeight() >> uiDepth;
+  const UInt uiHWidthInBaseUnits  = uiWidthInBaseUnits  >> 1;
+  const UInt uiHHeightInBaseUnits = uiHeightInBaseUnits >> 1;
+  const UInt uiQWidthInBaseUnits  = uiWidthInBaseUnits  >> 2;
+  const UInt uiQHeightInBaseUnits = uiHeightInBaseUnits >> 2;
+  
+  xSetEdgefilterMultiple( pcCU, uiAbsZorderIdx, uiDepth, EDGE_VER, 0, m_stLFCUParam.bLeftEdge );
+  xSetEdgefilterMultiple( pcCU, uiAbsZorderIdx, uiDepth, EDGE_HOR, 0, m_stLFCUParam.bTopEdge );
+  
+  switch ( pcCU->getPartitionSize( uiAbsZorderIdx ) )
+  {
+    case SIZE_2Nx2N:
+    {
+      break;
+    }
+    case SIZE_2NxN:
+    {
+      xSetEdgefilterMultiple( pcCU, uiAbsZorderIdx, uiDepth, EDGE_HOR, uiHHeightInBaseUnits, m_stLFCUParam.bInternalEdge );
+      break;
+    }
+    case SIZE_Nx2N:
+    {
+      xSetEdgefilterMultiple( pcCU, uiAbsZorderIdx, uiDepth, EDGE_VER, uiHWidthInBaseUnits, m_stLFCUParam.bInternalEdge );
+      break;
+    }
+    case SIZE_NxN:
+    {
+      xSetEdgefilterMultiple( pcCU, uiAbsZorderIdx, uiDepth, EDGE_VER, uiHWidthInBaseUnits, m_stLFCUParam.bInternalEdge );
+      xSetEdgefilterMultiple( pcCU, uiAbsZorderIdx, uiDepth, EDGE_HOR, uiHHeightInBaseUnits, m_stLFCUParam.bInternalEdge );
+      break;
+    }
+    case SIZE_2NxnU:
+    {
+      xSetEdgefilterMultiple( pcCU, uiAbsZorderIdx, uiDepth, EDGE_HOR, uiQHeightInBaseUnits, m_stLFCUParam.bInternalEdge );
+      break;
+    }
+    case SIZE_2NxnD:
+    {
+      xSetEdgefilterMultiple( pcCU, uiAbsZorderIdx, uiDepth, EDGE_HOR, uiHeightInBaseUnits - uiQHeightInBaseUnits, m_stLFCUParam.bInternalEdge );
+      break;
+    }
+    case SIZE_nLx2N:
+    {
+      xSetEdgefilterMultiple( pcCU, uiAbsZorderIdx, uiDepth, EDGE_VER, uiQWidthInBaseUnits, m_stLFCUParam.bInternalEdge );
+      break;
+    }
+    case SIZE_nRx2N:
+    {
+      xSetEdgefilterMultiple( pcCU, uiAbsZorderIdx, uiDepth, EDGE_VER, uiWidthInBaseUnits - uiQWidthInBaseUnits, m_stLFCUParam.bInternalEdge );
+      break;
+    }
+    default:
+    {
+      break;
+    }
+  }
+}
+
+
+Void TComLoopFilter::xSetLoopfilterParam( TComDataCU* pcCU, UInt uiAbsZorderIdx )
+{
+  UInt uiX           = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[ uiAbsZorderIdx ] ];
+  UInt uiY           = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[ uiAbsZorderIdx ] ];
+  
+  TComDataCU* pcTempCU;
+  UInt        uiTempPartIdx;
+
+  m_stLFCUParam.bInternalEdge = !m_disableDeblockingFilterFlag;
+  
+  if ( (uiX == 0) || m_disableDeblockingFilterFlag )
+  {
+    m_stLFCUParam.bLeftEdge = false;
+  }
+  else
+  {
+    m_stLFCUParam.bLeftEdge = true;
+  }
+  if ( m_stLFCUParam.bLeftEdge )
+  {
+    pcTempCU = pcCU->getPULeft( uiTempPartIdx, uiAbsZorderIdx, !pcCU->getSlice()->getLFCrossSliceBoundaryFlag(), false, !m_bLFCrossTileBoundary);
+    if ( pcTempCU )
+    {
+      m_stLFCUParam.bLeftEdge = true;
+    }
+    else
+    {
+      m_stLFCUParam.bLeftEdge = false;
+    }
+  }
+  
+  if ( (uiY == 0 ) || m_disableDeblockingFilterFlag )
+  {
+    m_stLFCUParam.bTopEdge = false;
+  }
+  else
+  {
+    m_stLFCUParam.bTopEdge = true;
+  }
+  if ( m_stLFCUParam.bTopEdge )
+  {
+    pcTempCU = pcCU->getPUAbove( uiTempPartIdx, uiAbsZorderIdx, !pcCU->getSlice()->getLFCrossSliceBoundaryFlag(), false , false, false, !m_bLFCrossTileBoundary);
+    if ( pcTempCU )
+    {
+      m_stLFCUParam.bTopEdge = true;
+    }
+    else
+    {
+      m_stLFCUParam.bTopEdge = false;
+    }
+  }
+}
+
+Void TComLoopFilter::xGetBoundaryStrengthSingle ( TComDataCU* pcCU, UInt uiAbsZorderIdx, Int iDir, UInt uiAbsPartIdx )
+{
+  TComSlice* const pcSlice = pcCU->getSlice();
+  
+  const UInt uiPartQ = uiAbsPartIdx;
+  TComDataCU* const pcCUQ = pcCU;
+  
+  UInt uiPartP;
+  TComDataCU* pcCUP;
+  UInt uiBs = 0;
+  
+  //-- Calculate Block Index
+  if (iDir == EDGE_VER)
+  {
+    pcCUP = pcCUQ->getPULeft(uiPartP, uiPartQ, !pcCU->getSlice()->getLFCrossSliceBoundaryFlag(), false, !m_bLFCrossTileBoundary);
+  }
+  else  // (iDir == EDGE_HOR)
+  {
+    pcCUP = pcCUQ->getPUAbove(uiPartP, uiPartQ, !pcCU->getSlice()->getLFCrossSliceBoundaryFlag(), false, false, false, !m_bLFCrossTileBoundary);
+  }
+  
+  //-- Set BS for Intra MB : BS = 4 or 3
+  if ( pcCUP->isIntra(uiPartP) || pcCUQ->isIntra(uiPartQ) )
+  {
+    uiBs = 2;
+  }
+  
+  //-- Set BS for not Intra MB : BS = 2 or 1 or 0
+  if ( !pcCUP->isIntra(uiPartP) && !pcCUQ->isIntra(uiPartQ) )
+  {
+    UInt nsPartQ = uiPartQ;
+    UInt nsPartP = uiPartP;
+#if !REMOVE_NSQT
+    if(pcCUQ->getPredictionMode(uiPartQ) == MODE_INTER && pcCUQ->useNonSquarePU(uiPartQ))
+    {
+      nsPartQ = pcCUQ->getNSQTPartIdx( uiAbsPartIdx );
+    }
+    if(pcCUP->getPredictionMode(uiPartP) == MODE_INTER && pcCUP->useNonSquarePU(uiPartP))
+    {
+      nsPartP = pcCUP->getNSQTPartIdx( uiPartP );
+    }
+#endif
+    
+    if ( m_aapucBS[iDir][uiAbsPartIdx] && (pcCUQ->getCbf( nsPartQ, TEXT_LUMA, pcCUQ->getTransformIdx(nsPartQ)) != 0 || pcCUP->getCbf( nsPartP, TEXT_LUMA, pcCUP->getTransformIdx(nsPartP) ) != 0) )
+    {
+      uiBs = 1;
+    }
+    else
+    {
+      if (iDir == EDGE_HOR)
+      {
+        pcCUP = pcCUQ->getPUAbove(uiPartP, uiPartQ, !pcCU->getSlice()->getLFCrossSliceBoundaryFlag(), false, true, false, !m_bLFCrossTileBoundary);
+      }
+      if (pcSlice->isInterB())
+      {
+        Int iRefIdx;
+        Int *piRefP0, *piRefP1, *piRefQ0, *piRefQ1;
+        iRefIdx = pcCUP->getCUMvField(REF_PIC_LIST_0)->getRefIdx(uiPartP);
+        piRefP0 = (iRefIdx < 0) ? NULL :  (Int*) pcSlice->getRefPic(REF_PIC_LIST_0, iRefIdx);
+        iRefIdx = pcCUP->getCUMvField(REF_PIC_LIST_1)->getRefIdx(uiPartP);
+        piRefP1 = (iRefIdx < 0) ? NULL :  (Int*) pcSlice->getRefPic(REF_PIC_LIST_1, iRefIdx);
+        iRefIdx = pcCUQ->getCUMvField(REF_PIC_LIST_0)->getRefIdx(uiPartQ);
+        piRefQ0 = (iRefIdx < 0) ? NULL :  (Int*) pcSlice->getRefPic(REF_PIC_LIST_0, iRefIdx);
+        iRefIdx = pcCUQ->getCUMvField(REF_PIC_LIST_1)->getRefIdx(uiPartQ);
+        piRefQ1 = (iRefIdx < 0) ? NULL :  (Int*) pcSlice->getRefPic(REF_PIC_LIST_1, iRefIdx);
+        
+        
+        TComMv pcMvP0 = pcCUP->getCUMvField(REF_PIC_LIST_0)->getMv(uiPartP);
+        TComMv pcMvP1 = pcCUP->getCUMvField(REF_PIC_LIST_1)->getMv(uiPartP);
+        TComMv pcMvQ0 = pcCUQ->getCUMvField(REF_PIC_LIST_0)->getMv(uiPartQ);
+        TComMv pcMvQ1 = pcCUQ->getCUMvField(REF_PIC_LIST_1)->getMv(uiPartQ);
+        
+        if ( ((piRefP0==piRefQ0)&&(piRefP1==piRefQ1)) || ((piRefP0==piRefQ1)&&(piRefP1==piRefQ0)) )
+        {
+          uiBs = 0;
+          if ( piRefP0 != piRefP1 )   // Different L0 & L1
+          {
+            if ( piRefP0 == piRefQ0 )
+            {
+              pcMvP0 -= pcMvQ0;   pcMvP1 -= pcMvQ1;
+              uiBs = (pcMvP0.getAbsHor() >= 4) | (pcMvP0.getAbsVer() >= 4) |
+              (pcMvP1.getAbsHor() >= 4) | (pcMvP1.getAbsVer() >= 4);
+            }
+            else
+            {
+              pcMvP0 -= pcMvQ1;   pcMvP1 -= pcMvQ0;
+              uiBs = (pcMvP0.getAbsHor() >= 4) | (pcMvP0.getAbsVer() >= 4) |
+              (pcMvP1.getAbsHor() >= 4) | (pcMvP1.getAbsVer() >= 4);
+            }
+          }
+          else    // Same L0 & L1
+          {
+            TComMv pcMvSub0 = pcMvP0 - pcMvQ0;
+            TComMv pcMvSub1 = pcMvP1 - pcMvQ1;
+            pcMvP0 -= pcMvQ1;   pcMvP1 -= pcMvQ0;
+            uiBs = ( (pcMvP0.getAbsHor() >= 4) | (pcMvP0.getAbsVer() >= 4) |
+                    (pcMvP1.getAbsHor() >= 4) | (pcMvP1.getAbsVer() >= 4) ) &&
+            ( (pcMvSub0.getAbsHor() >= 4) | (pcMvSub0.getAbsVer() >= 4) |
+             (pcMvSub1.getAbsHor() >= 4) | (pcMvSub1.getAbsVer() >= 4) );
+          }
+        }
+        else // for all different Ref_Idx
+        {
+          uiBs = 1;
+        }
+      }
+      else  // pcSlice->isInterP()
+      {
+        Int iRefIdx;
+        Int *piRefP0, *piRefQ0;
+        iRefIdx = pcCUP->getCUMvField(REF_PIC_LIST_0)->getRefIdx(uiPartP);
+        piRefP0 = (iRefIdx < 0) ? NULL :  (Int*) pcSlice->getRefPic(REF_PIC_LIST_0, iRefIdx);
+        iRefIdx = pcCUQ->getCUMvField(REF_PIC_LIST_0)->getRefIdx(uiPartQ);
+        piRefQ0 = (iRefIdx < 0) ? NULL :  (Int*) 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);
+        
+        pcMvP0 -= pcMvQ0;
+        uiBs = (piRefP0 != piRefQ0) | (pcMvP0.getAbsHor() >= 4) | (pcMvP0.getAbsVer() >= 4);
+      }
+    }   // enf of "if( one of BCBP == 0 )"
+  }   // enf of "if( not Intra )"
+  
+  m_aapucBS[iDir][uiAbsPartIdx] = uiBs;
+}
+
+
+Void TComLoopFilter::xEdgeFilterLuma( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, Int iDir, Int iEdge  )
+{
+  TComPicYuv* pcPicYuvRec = pcCU->getPic()->getPicYuvRec();
+  Pel* piSrc    = pcPicYuvRec->getLumaAddr( pcCU->getAddr(), uiAbsZorderIdx );
+  Pel* piTmpSrc = piSrc;
+  
+  Int  iStride = pcPicYuvRec->getStride();
+  Int iQP = 0;
+  Int iQP_P = 0;
+  Int iQP_Q = 0;
+  UInt uiNumParts = pcCU->getPic()->getNumPartInWidth()>>uiDepth;
+  
+  UInt  uiPelsInPart = g_uiMaxCUWidth >> g_uiMaxCUDepth;
+  UInt  uiBsAbsIdx = 0, uiBs = 0;
+  Int   iOffset, iSrcStep;
+  
+  Bool  bPCMFilter = (pcCU->getSlice()->getSPS()->getUsePCM() && pcCU->getSlice()->getSPS()->getPCMFilterDisableFlag())? true : false;
+  Bool  bPartPNoFilter = false;
+  Bool  bPartQNoFilter = false; 
+  UInt  uiPartPIdx = 0;
+  UInt  uiPartQIdx = 0;
+  TComDataCU* pcCUP = pcCU; 
+  TComDataCU* pcCUQ = pcCU;
+  
+  if (iDir == EDGE_VER)
+  {
+    iOffset = 1;
+    iSrcStep = iStride;
+    piTmpSrc += iEdge*uiPelsInPart;
+  }
+  else  // (iDir == EDGE_HOR)
+  {
+    iOffset = iStride;
+    iSrcStep = 1;
+    piTmpSrc += iEdge*uiPelsInPart*iStride;
+  }
+  
+  for ( UInt iIdx = 0; iIdx < uiNumParts; iIdx++ )
+  {
+    uiBsAbsIdx = xCalcBsIdx( pcCU, uiAbsZorderIdx, iDir, iEdge, iIdx);
+    uiBs = m_aapucBS[iDir][uiBsAbsIdx];
+    if ( uiBs )
+    {
+      iQP_Q = pcCU->getQP( uiBsAbsIdx );
+      uiPartQIdx = uiBsAbsIdx;
+      // Derive neighboring PU index
+      if (iDir == EDGE_VER)
+      {
+        pcCUP = pcCUQ->getPULeft (uiPartPIdx, uiPartQIdx,!pcCU->getSlice()->getLFCrossSliceBoundaryFlag(), false, !m_bLFCrossTileBoundary);
+      }
+      else  // (iDir == EDGE_HOR)
+      {
+        pcCUP = pcCUQ->getPUAbove(uiPartPIdx, uiPartQIdx,!pcCU->getSlice()->getLFCrossSliceBoundaryFlag(), false, false, false, !m_bLFCrossTileBoundary);
+      }
+
+      iQP_P = pcCUP->getQP(uiPartPIdx);
+      iQP = (iQP_P + iQP_Q + 1) >> 1;
+      Int iBitdepthScale = (1<<(g_uiBitIncrement+g_uiBitDepth-8));
+      
+      Int iIndexTC = Clip3(0, MAX_QP+DEFAULT_INTRA_TC_OFFSET, Int(iQP + DEFAULT_INTRA_TC_OFFSET*(uiBs-1) + (m_tcOffsetDiv2 << 1)));
+      Int iIndexB = Clip3(0, MAX_QP, iQP + (m_betaOffsetDiv2 << 1));
+      
+      Int iTc =  tctable_8x8[iIndexTC]*iBitdepthScale;
+      Int iBeta = betatable_8x8[iIndexB]*iBitdepthScale;
+      Int iSideThreshold = (iBeta+(iBeta>>1))>>3;
+      Int iThrCut = iTc*10;
+
+      UInt  uiBlocksInPart = uiPelsInPart / 4 ? uiPelsInPart / 4 : 1;
+      for (UInt iBlkIdx = 0; iBlkIdx<uiBlocksInPart; iBlkIdx ++)
+      {
+        Int dp0 = xCalcDP( piTmpSrc+iSrcStep*(iIdx*uiPelsInPart+iBlkIdx*4+0), iOffset);
+        Int dq0 = xCalcDQ( piTmpSrc+iSrcStep*(iIdx*uiPelsInPart+iBlkIdx*4+0), iOffset);
+        Int dp3 = xCalcDP( piTmpSrc+iSrcStep*(iIdx*uiPelsInPart+iBlkIdx*4+3), iOffset);
+        Int dq3 = xCalcDQ( piTmpSrc+iSrcStep*(iIdx*uiPelsInPart+iBlkIdx*4+3), iOffset);
+        Int d0 = dp0 + dq0;
+        Int d3 = dp3 + dq3;
+        
+        Int dp = dp0 + dp3;
+        Int dq = dq0 + dq3;
+        Int d =  d0 + d3;
+        
+        if (bPCMFilter || pcCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
+        {
+          // Check if each of PUs is I_PCM with LF disabling
+          bPartPNoFilter = (bPCMFilter && pcCUP->getIPCMFlag(uiPartPIdx));
+          bPartQNoFilter = (bPCMFilter && pcCUQ->getIPCMFlag(uiPartQIdx));
+
+          // check if each of PUs is lossless coded
+          bPartPNoFilter = bPartPNoFilter || (pcCUP->isLosslessCoded(uiPartPIdx) );
+          bPartQNoFilter = bPartQNoFilter || (pcCUQ->isLosslessCoded(uiPartQIdx) );
+        }
+
+        if (d < iBeta)
+        { 
+          Bool bFilterP = (dp < iSideThreshold);
+          Bool bFilterQ = (dq < iSideThreshold);
+          
+          Bool sw =  xUseStrongFiltering( iOffset, 2*d0, iBeta, iTc, piTmpSrc+iSrcStep*(iIdx*uiPelsInPart+iBlkIdx*4+0))
+          && xUseStrongFiltering( iOffset, 2*d3, iBeta, iTc, piTmpSrc+iSrcStep*(iIdx*uiPelsInPart+iBlkIdx*4+3));
+          
+          for ( Int i = 0; i < DEBLOCK_SMALLEST_BLOCK/2; i++)
+          {
+            xPelFilterLuma( piTmpSrc+iSrcStep*(iIdx*uiPelsInPart+iBlkIdx*4+i), iOffset, d, iBeta, iTc, sw, bPartPNoFilter, bPartQNoFilter, iThrCut, bFilterP, bFilterQ);
+          }
+        }
+      }
+    }
+  }
+}
+
+
+Void TComLoopFilter::xEdgeFilterChroma( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, Int iDir, Int iEdge )
+{
+  TComPicYuv* pcPicYuvRec = pcCU->getPic()->getPicYuvRec();
+  Int         iStride     = pcPicYuvRec->getCStride();
+  Pel*        piSrcCb     = pcPicYuvRec->getCbAddr( pcCU->getAddr(), uiAbsZorderIdx );
+  Pel*        piSrcCr     = pcPicYuvRec->getCrAddr( pcCU->getAddr(), uiAbsZorderIdx );
+  Int iQP = 0;
+  Int iQP_P = 0;
+  Int iQP_Q = 0;
+  
+  UInt  uiPelsInPartChroma = g_uiMaxCUWidth >> (g_uiMaxCUDepth+1);
+  
+  Int   iOffset, iSrcStep;
+  
+  const UInt uiLCUWidthInBaseUnits = pcCU->getPic()->getNumPartInWidth();
+  
+  Bool  bPCMFilter = (pcCU->getSlice()->getSPS()->getUsePCM() && pcCU->getSlice()->getSPS()->getPCMFilterDisableFlag())? true : false;
+  Bool  bPartPNoFilter = false;
+  Bool  bPartQNoFilter = false; 
+  UInt  uiPartPIdx;
+  UInt  uiPartQIdx;
+  TComDataCU* pcCUP; 
+  TComDataCU* pcCUQ = pcCU;
+  
+  // Vertical Position
+  UInt uiEdgeNumInLCUVert = g_auiZscanToRaster[uiAbsZorderIdx]%uiLCUWidthInBaseUnits + iEdge;
+  UInt uiEdgeNumInLCUHor = g_auiZscanToRaster[uiAbsZorderIdx]/uiLCUWidthInBaseUnits + iEdge;
+  
+  if ( (uiPelsInPartChroma < DEBLOCK_SMALLEST_BLOCK) && (( (uiEdgeNumInLCUVert%(DEBLOCK_SMALLEST_BLOCK/uiPelsInPartChroma))&&(iDir==0) ) || ( (uiEdgeNumInLCUHor%(DEBLOCK_SMALLEST_BLOCK/uiPelsInPartChroma))&& iDir ) ))
+  {
+    return;
+  }
+  
+  UInt  uiNumParts = pcCU->getPic()->getNumPartInWidth()>>uiDepth;
+  
+  UInt  uiBsAbsIdx;
+  UChar ucBs;
+  
+  Pel* piTmpSrcCb = piSrcCb;
+  Pel* piTmpSrcCr = piSrcCr;
+  
+  
+  if (iDir == EDGE_VER)
+  {
+    iOffset   = 1;
+    iSrcStep  = iStride;
+    piTmpSrcCb += iEdge*uiPelsInPartChroma;
+    piTmpSrcCr += iEdge*uiPelsInPartChroma;
+  }
+  else  // (iDir == EDGE_HOR)
+  {
+    iOffset   = iStride;
+    iSrcStep  = 1;
+    piTmpSrcCb += iEdge*iStride*uiPelsInPartChroma;
+    piTmpSrcCr += iEdge*iStride*uiPelsInPartChroma;
+  }
+  
+  for ( UInt iIdx = 0; iIdx < uiNumParts; iIdx++ )
+  {
+    ucBs = 0;
+    
+    uiBsAbsIdx = xCalcBsIdx( pcCU, uiAbsZorderIdx, iDir, iEdge, iIdx);
+    ucBs = m_aapucBS[iDir][uiBsAbsIdx];
+    
+    if ( ucBs > 1)
+    {
+      iQP_Q = pcCU->getQP( uiBsAbsIdx );
+      uiPartQIdx = uiBsAbsIdx;
+      // Derive neighboring PU index
+      if (iDir == EDGE_VER)
+      {
+        pcCUP = pcCUQ->getPULeft (uiPartPIdx, uiPartQIdx,!pcCU->getSlice()->getLFCrossSliceBoundaryFlag(), false, !m_bLFCrossTileBoundary);
+      }
+      else  // (iDir == EDGE_HOR)
+      {
+        pcCUP = pcCUQ->getPUAbove(uiPartPIdx, uiPartQIdx,!pcCU->getSlice()->getLFCrossSliceBoundaryFlag(), false, false, false, !m_bLFCrossTileBoundary);
+      }
+
+      iQP_P = pcCUP->getQP(uiPartPIdx);
+      iQP = QpUV((iQP_P + iQP_Q + 1) >> 1);
+      Int iBitdepthScale = (1<<(g_uiBitIncrement+g_uiBitDepth-8));
+      
+      Int iIndexTC = Clip3(0, MAX_QP+DEFAULT_INTRA_TC_OFFSET, iQP + DEFAULT_INTRA_TC_OFFSET*(ucBs - 1) + (m_tcOffsetDiv2 << 1));
+      Int iTc =  tctable_8x8[iIndexTC]*iBitdepthScale;
+      
+      if (bPCMFilter || pcCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
+      {
+        // Check if each of PUs is I_PCM with LF disabling
+        bPartPNoFilter = (bPCMFilter && pcCUP->getIPCMFlag(uiPartPIdx));
+        bPartQNoFilter = (bPCMFilter && pcCUQ->getIPCMFlag(uiPartQIdx));
+
+        // check if each of PUs is lossless coded
+        bPartPNoFilter = bPartPNoFilter || (pcCUP->isLosslessCoded(uiPartPIdx));
+        bPartQNoFilter = bPartQNoFilter || (pcCUQ->isLosslessCoded(uiPartQIdx));
+      }
+      
+      for ( UInt uiStep = 0; uiStep < uiPelsInPartChroma; uiStep++ )
+      {
+        xPelFilterChroma( piTmpSrcCb + iSrcStep*(uiStep+iIdx*uiPelsInPartChroma), iOffset, iTc , bPartPNoFilter, bPartQNoFilter);
+        xPelFilterChroma( piTmpSrcCr + iSrcStep*(uiStep+iIdx*uiPelsInPartChroma), iOffset, iTc , bPartPNoFilter, bPartQNoFilter);
+      }
+    }
+  }
+}
+
+/**
+ - Deblocking for the luminance component with strong or weak filter
+ .
+ \param piSrc           pointer to picture data
+ \param iOffset         offset value for picture data
+ \param d               d value
+ \param beta            beta value
+ \param tc              tc value
+ \param sw              decision strong/weak filter
+ \param bPartPNoFilter  indicator to disable filtering on partP
+ \param bPartQNoFilter  indicator to disable filtering on partQ
+ \param iThrCut         threshold value for weak filter decision
+ \param bFilterSecondP  decision weak filter/no filter for partP
+ \param bFilterSecondQ  decision weak filter/no filter for partQ
+*/
+__inline Void TComLoopFilter::xPelFilterLuma( Pel* piSrc, Int iOffset, Int d, Int beta, Int tc , Bool sw, Bool bPartPNoFilter, Bool bPartQNoFilter, Int iThrCut, Bool bFilterSecondP, Bool bFilterSecondQ)
+{
+  Int delta;
+  
+  Pel m4  = piSrc[0];
+  Pel m3  = piSrc[-iOffset];
+  Pel m5  = piSrc[ iOffset];
+  Pel m2  = piSrc[-iOffset*2];
+  Pel m6  = piSrc[ iOffset*2];
+  Pel m1  = piSrc[-iOffset*3];
+  Pel m7  = piSrc[ iOffset*3];
+  Pel m0  = piSrc[-iOffset*4];
+
+  if (sw)
+  {
+    piSrc[-iOffset]   = Clip3(m3-2*tc, m3+2*tc, ((m1 + 2*m2 + 2*m3 + 2*m4 + m5 + 4) >> 3));
+    piSrc[0]          = Clip3(m4-2*tc, m4+2*tc, ((m2 + 2*m3 + 2*m4 + 2*m5 + m6 + 4) >> 3));
+    piSrc[-iOffset*2] = Clip3(m2-2*tc, m2+2*tc, ((m1 + m2 + m3 + m4 + 2)>>2));
+    piSrc[ iOffset]   = Clip3(m5-2*tc, m5+2*tc, ((m3 + m4 + m5 + m6 + 2)>>2));
+    piSrc[-iOffset*3] = Clip3(m1-2*tc, m1+2*tc, ((2*m0 + 3*m1 + m2 + m3 + m4 + 4 )>>3));
+    piSrc[ iOffset*2] = Clip3(m6-2*tc, m6+2*tc, ((m3 + m4 + m5 + 3*m6 + 2*m7 +4 )>>3));
+  }
+  else
+  {
+    /* Weak filter */
+    delta = (9*(m4-m3) -3*(m5-m2) + 8)>>4 ;
+
+    if ( abs(delta) < iThrCut )
+    {
+      delta = Clip3(-tc, tc, delta);        
+      piSrc[-iOffset] = Clip((m3+delta));
+      piSrc[0] = Clip((m4-delta));
+
+      Int tc2 = tc>>1;
+      if(bFilterSecondP)
+      {
+        Int delta1 = Clip3(-tc2, tc2, (( ((m1+m3+1)>>1)- m2+delta)>>1));
+        piSrc[-iOffset*2] = Clip((m2+delta1));
+      }
+      if(bFilterSecondQ)
+      {
+        Int delta2 = Clip3(-tc2, tc2, (( ((m6+m4+1)>>1)- m5-delta)>>1));
+        piSrc[ iOffset] = Clip((m5+delta2));
+      }
+    }
+  }
+
+  if(bPartPNoFilter)
+  {
+    piSrc[-iOffset] = m3;
+    piSrc[-iOffset*2] = m2;
+    piSrc[-iOffset*3] = m1;
+  }
+  if(bPartQNoFilter)
+  {
+    piSrc[0] = m4;
+    piSrc[ iOffset] = m5;
+    piSrc[ iOffset*2] = m6;
+  }
+}
+
+/**
+ - Deblocking of one line/column for the chrominance component
+ .
+ \param piSrc           pointer to picture data
+ \param iOffset         offset value for picture data
+ \param tc              tc value
+ \param bPartPNoFilter  indicator to disable filtering on partP
+ \param bPartQNoFilter  indicator to disable filtering on partQ
+ */
+__inline Void TComLoopFilter::xPelFilterChroma( Pel* piSrc, Int iOffset, Int tc, Bool bPartPNoFilter, Bool bPartQNoFilter)
+{
+  int delta;
+  
+  Pel m4  = piSrc[0];
+  Pel m3  = piSrc[-iOffset];
+  Pel m5  = piSrc[ iOffset];
+  Pel m2  = piSrc[-iOffset*2];
+  
+  delta = Clip3(-tc,tc, (((( m4 - m3 ) << 2 ) + m2 - m5 + 4 ) >> 3) );
+  piSrc[-iOffset] = Clip(m3+delta);
+  piSrc[0] = Clip(m4-delta);
+
+  if(bPartPNoFilter)
+  {
+    piSrc[-iOffset] = m3;
+  }
+  if(bPartQNoFilter)
+  {
+    piSrc[0] = m4;
+  }
+}
+
+/**
+ - Decision between strong and weak filter
+ .
+ \param offset         offset value for picture data
+ \param d               d value
+ \param beta            beta value
+ \param tc              tc value
+ \param piSrc           pointer to picture data
+ */
+__inline Bool TComLoopFilter::xUseStrongFiltering( Int offset, Int d, Int beta, Int tc, Pel* piSrc)
+{
+  Pel m4  = piSrc[0];
+  Pel m3  = piSrc[-offset];
+  Pel m7  = piSrc[ offset*3];
+  Pel m0  = piSrc[-offset*4];
+
+  Int d_strong = abs(m0-m3) + abs(m7-m4);
+
+  return ( (d_strong < (beta>>3)) && (d<(beta>>2)) && ( abs(m3-m4) < ((tc*5+1)>>1)) );
+}
+
+__inline Int TComLoopFilter::xCalcDP( Pel* piSrc, Int iOffset)
+{
+  return abs( piSrc[-iOffset*3] - 2*piSrc[-iOffset*2] + piSrc[-iOffset] ) ;
+}
+  
+__inline Int TComLoopFilter::xCalcDQ( Pel* piSrc, Int iOffset)
+{
+  return abs( piSrc[0] - 2*piSrc[iOffset] + piSrc[iOffset*2] );
+}
+//! \}
Index: /trunk/source/Lib/TLibCommon/TComLoopFilter.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComLoopFilter.h	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComLoopFilter.h	(revision 2)
@@ -0,0 +1,121 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComLoopFilter.h
+    \brief    deblocking filter (header)
+*/
+
+#ifndef __TCOMLOOPFILTER__
+#define __TCOMLOOPFILTER__
+
+#include "CommonDef.h"
+#include "TComPic.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+#define DEBLOCK_SMALLEST_BLOCK  8
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// deblocking filter class
+class TComLoopFilter
+{
+private:
+  Bool      m_disableDeblockingFilterFlag;
+  Int       m_betaOffsetDiv2;
+  Int       m_tcOffsetDiv2;
+
+  UInt      m_uiNumPartitions;
+  UChar*    m_aapucBS[2];              ///< Bs for [Ver/Hor][Y/U/V][Blk_Idx]
+  Bool*     m_aapbEdgeFilter[2][3];
+  LFCUParam m_stLFCUParam;                  ///< status structure
+  
+  Bool      m_bLFCrossTileBoundary;
+
+protected:
+  /// CU-level deblocking function
+  Void xDeblockCU                 ( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, Int Edge );
+
+  // set / get functions
+  Void xSetLoopfilterParam        ( TComDataCU* pcCU, UInt uiAbsZorderIdx );
+  // filtering functions
+  Void xSetEdgefilterTU           ( TComDataCU* pcCU, UInt absTUPartIdx, UInt uiAbsZorderIdx, UInt uiDepth );
+  Void xSetEdgefilterPU           ( TComDataCU* pcCU, UInt uiAbsZorderIdx );
+  Void xGetBoundaryStrengthSingle ( TComDataCU* pcCU, UInt uiAbsZorderIdx, Int iDir, UInt uiPartIdx );
+  UInt xCalcBsIdx                 ( TComDataCU* pcCU, UInt uiAbsZorderIdx, Int iDir, Int iEdgeIdx, Int iBaseUnitIdx )
+  {
+    TComPic* const pcPic = pcCU->getPic();
+    const UInt uiLCUWidthInBaseUnits = pcPic->getNumPartInWidth();
+    if( iDir == 0 )
+    {
+      return g_auiRasterToZscan[g_auiZscanToRaster[uiAbsZorderIdx] + iBaseUnitIdx * uiLCUWidthInBaseUnits + iEdgeIdx ];
+    }
+    else
+    {
+      return g_auiRasterToZscan[g_auiZscanToRaster[uiAbsZorderIdx] + iEdgeIdx * uiLCUWidthInBaseUnits + iBaseUnitIdx ];
+    }
+  } 
+  
+  Void xSetEdgefilterMultiple( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, Int iDir, Int iEdgeIdx, Bool bValue ,UInt uiWidthInBaseUnits = 0, UInt uiHeightInBaseUnits = 0, Bool nonSquare = false );
+  
+  Void xEdgeFilterLuma            ( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, Int iDir, Int iEdge );
+  Void xEdgeFilterChroma          ( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, Int iDir, Int iEdge );
+  
+  __inline Void xPelFilterLuma( Pel* piSrc, Int iOffset, Int d, Int beta, Int tc, Bool sw, Bool bPartPNoFilter, Bool bPartQNoFilter, Int iThrCut, Bool bFilterSecondP, Bool bFilterSecondQ);
+  __inline Void xPelFilterChroma( Pel* piSrc, Int iOffset, Int tc, Bool bPartPNoFilter, Bool bPartQNoFilter);
+  
+
+  __inline Bool xUseStrongFiltering( Int offset, Int d, Int beta, Int tc, Pel* piSrc);
+  __inline Int xCalcDP( Pel* piSrc, Int iOffset);
+  __inline Int xCalcDQ( Pel* piSrc, Int iOffset);
+  
+public:
+  TComLoopFilter();
+  virtual ~TComLoopFilter();
+  
+  Void  create                    ( UInt uiMaxCUDepth );
+  Void  destroy                   ();
+  
+  /// set configuration
+  Void setCfg( Bool deblockingFilterControlPresentFlag, Bool disableDeblockingFilterFlag, Int betaOffsetDiv2, Int tcOffsetDiv2, Bool bLFCrossTileBoundary );
+  
+  /// picture-level deblocking filter
+  Void loopFilterPic( TComPic* pcPic );
+};
+
+//! \}
+
+#endif
Index: /trunk/source/Lib/TLibCommon/TComMotionInfo.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComMotionInfo.cpp	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComMotionInfo.cpp	(revision 2)
@@ -0,0 +1,359 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComMotionInfo.cpp
+    \brief    motion information handling classes
+*/
+
+#include <memory.h>
+#include "TComMotionInfo.h"
+#include "assert.h"
+#include <stdlib.h>
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+// --------------------------------------------------------------------------------------------------------------------
+// Create / destroy
+// --------------------------------------------------------------------------------------------------------------------
+
+Void TComCUMvField::create( UInt uiNumPartition )
+{
+  assert(m_pcMv     == NULL);
+  assert(m_pcMvd    == NULL);
+  assert(m_piRefIdx == NULL);
+  
+  m_pcMv     = new TComMv[ uiNumPartition ];
+  m_pcMvd    = new TComMv[ uiNumPartition ];
+  m_piRefIdx = new Char  [ uiNumPartition ];
+  
+  m_uiNumPartition = uiNumPartition;
+}
+
+Void TComCUMvField::destroy()
+{
+  assert(m_pcMv     != NULL);
+  assert(m_pcMvd    != NULL);
+  assert(m_piRefIdx != NULL);
+  
+  delete[] m_pcMv;
+  delete[] m_pcMvd;
+  delete[] m_piRefIdx;
+  
+  m_pcMv     = NULL;
+  m_pcMvd    = NULL;
+  m_piRefIdx = NULL;
+  
+  m_uiNumPartition = 0;
+}
+
+// --------------------------------------------------------------------------------------------------------------------
+// Clear / copy
+// --------------------------------------------------------------------------------------------------------------------
+
+Void TComCUMvField::clearMvField()
+{
+  for ( Int i = 0; i < m_uiNumPartition; i++ )
+  {
+    m_pcMv [ i ].setZero();
+    m_pcMvd[ i ].setZero();      
+  }
+  assert( sizeof( *m_piRefIdx ) == 1 );
+  memset( m_piRefIdx, NOT_VALID, m_uiNumPartition * sizeof( *m_piRefIdx ) );
+}
+
+Void TComCUMvField::copyFrom( TComCUMvField const * pcCUMvFieldSrc, Int iNumPartSrc, Int iPartAddrDst )
+{
+  Int iSizeInTComMv = sizeof( TComMv ) * iNumPartSrc;
+  
+  memcpy( m_pcMv     + iPartAddrDst, pcCUMvFieldSrc->m_pcMv,     iSizeInTComMv );
+  memcpy( m_pcMvd    + iPartAddrDst, pcCUMvFieldSrc->m_pcMvd,    iSizeInTComMv );
+  memcpy( m_piRefIdx + iPartAddrDst, pcCUMvFieldSrc->m_piRefIdx, sizeof( *m_piRefIdx ) * iNumPartSrc );
+}
+
+Void TComCUMvField::copyTo( TComCUMvField* pcCUMvFieldDst, Int iPartAddrDst ) const
+{
+  copyTo( pcCUMvFieldDst, iPartAddrDst, 0, m_uiNumPartition );
+}
+
+Void TComCUMvField::copyTo( TComCUMvField* pcCUMvFieldDst, Int iPartAddrDst, UInt uiOffset, UInt uiNumPart ) const
+{
+  Int iSizeInTComMv = sizeof( TComMv ) * uiNumPart;
+  Int iOffset = uiOffset + iPartAddrDst;
+  
+  memcpy( pcCUMvFieldDst->m_pcMv     + iOffset, m_pcMv     + uiOffset, iSizeInTComMv );
+  memcpy( pcCUMvFieldDst->m_pcMvd    + iOffset, m_pcMvd    + uiOffset, iSizeInTComMv );
+  memcpy( pcCUMvFieldDst->m_piRefIdx + iOffset, m_piRefIdx + uiOffset, sizeof( *m_piRefIdx ) * uiNumPart );
+}
+
+// --------------------------------------------------------------------------------------------------------------------
+// Set
+// --------------------------------------------------------------------------------------------------------------------
+
+template <typename T>
+Void TComCUMvField::setAll( T *p, T const & val, PartSize eCUMode, Int iPartAddr, UInt uiDepth, Int iPartIdx  )
+{
+  Int i;
+  p += iPartAddr;
+  Int numElements = m_uiNumPartition >> ( 2 * uiDepth );
+  
+  switch( eCUMode )
+  {
+    case SIZE_2Nx2N:
+      for ( i = 0; i < numElements; i++ )
+      {
+        p[ i ] = val;
+      }
+      break;
+      
+    case SIZE_2NxN:
+      numElements >>= 1;
+      for ( i = 0; i < numElements; i++ )
+      {
+        p[ i ] = val;
+      }
+      break;
+      
+    case SIZE_Nx2N:
+      numElements >>= 2;
+      for ( i = 0; i < numElements; i++ )
+      {
+        p[ i                   ] = val;
+        p[ i + 2 * numElements ] = val;
+      }
+      break;
+      
+    case SIZE_NxN:
+      numElements >>= 2;
+      for ( i = 0; i < numElements; i++)
+      {
+        p[ i ] = val;
+      }
+      break;
+    case SIZE_2NxnU:
+    {
+      Int iCurrPartNumQ = numElements>>2;
+      if( iPartIdx == 0 )
+      {
+        T *pT  = p;
+        T *pT2 = p + iCurrPartNumQ;
+        for (i = 0; i < (iCurrPartNumQ>>1); i++)
+        {
+          pT [i] = val;
+          pT2[i] = val;
+        }
+      }
+      else
+      {
+        T *pT  = p;
+        for (i = 0; i < (iCurrPartNumQ>>1); i++)
+        {
+          pT[i] = val;
+        }
+
+        pT = p + iCurrPartNumQ;
+        for (i = 0; i < ( (iCurrPartNumQ>>1) + (iCurrPartNumQ<<1) ); i++)
+        {
+          pT[i] = val;
+        }
+      }
+      break;
+    }
+  case SIZE_2NxnD:
+    {
+      Int iCurrPartNumQ = numElements>>2;
+      if( iPartIdx == 0 )
+      {
+        T *pT  = p;
+        for (i = 0; i < ( (iCurrPartNumQ>>1) + (iCurrPartNumQ<<1) ); i++)
+        {
+          pT[i] = val;
+        }
+        pT = p + ( numElements - iCurrPartNumQ );
+        for (i = 0; i < (iCurrPartNumQ>>1); i++)
+        {
+          pT[i] = val;
+        }
+      }
+      else
+      {
+        T *pT  = p;
+        T *pT2 = p + iCurrPartNumQ;
+        for (i = 0; i < (iCurrPartNumQ>>1); i++)
+        {
+          pT [i] = val;
+          pT2[i] = val;
+        }
+      }
+      break;
+    }
+  case SIZE_nLx2N:
+    {
+      Int iCurrPartNumQ = numElements>>2;
+      if( iPartIdx == 0 )
+      {
+        T *pT  = p;
+        T *pT2 = p + (iCurrPartNumQ<<1);
+        T *pT3 = p + (iCurrPartNumQ>>1);
+        T *pT4 = p + (iCurrPartNumQ<<1) + (iCurrPartNumQ>>1);
+
+        for (i = 0; i < (iCurrPartNumQ>>2); i++)
+        {
+          pT [i] = val;
+          pT2[i] = val;
+          pT3[i] = val;
+          pT4[i] = val;
+        }
+      }
+      else
+      {
+        T *pT  = p;
+        T *pT2 = p + (iCurrPartNumQ<<1);
+        for (i = 0; i < (iCurrPartNumQ>>2); i++)
+        {
+          pT [i] = val;
+          pT2[i] = val;
+        }
+
+        pT  = p + (iCurrPartNumQ>>1);
+        pT2 = p + (iCurrPartNumQ<<1) + (iCurrPartNumQ>>1);
+        for (i = 0; i < ( (iCurrPartNumQ>>2) + iCurrPartNumQ ); i++)
+        {
+          pT [i] = val;
+          pT2[i] = val;
+        }
+      }
+      break;
+    }
+  case SIZE_nRx2N:
+    {
+      Int iCurrPartNumQ = numElements>>2;
+      if( iPartIdx == 0 )
+      {
+        T *pT  = p;
+        T *pT2 = p + (iCurrPartNumQ<<1);
+        for (i = 0; i < ( (iCurrPartNumQ>>2) + iCurrPartNumQ ); i++)
+        {
+          pT [i] = val;
+          pT2[i] = val;
+        }
+
+        pT  = p + iCurrPartNumQ + (iCurrPartNumQ>>1);
+        pT2 = p + numElements - iCurrPartNumQ + (iCurrPartNumQ>>1);
+        for (i = 0; i < (iCurrPartNumQ>>2); i++)
+        {
+          pT [i] = val;
+          pT2[i] = val;
+        }
+      }
+      else
+      {
+        T *pT  = p;
+        T *pT2 = p + (iCurrPartNumQ>>1);
+        T *pT3 = p + (iCurrPartNumQ<<1);
+        T *pT4 = p + (iCurrPartNumQ<<1) + (iCurrPartNumQ>>1);
+        for (i = 0; i < (iCurrPartNumQ>>2); i++)
+        {
+          pT [i] = val;
+          pT2[i] = val;
+          pT3[i] = val;
+          pT4[i] = val;
+        }
+      }
+      break;
+    }
+    default:
+      assert(0);
+      break;
+  }
+}
+
+Void TComCUMvField::setAllMv( TComMv const & mv, PartSize eCUMode, Int iPartAddr, UInt uiDepth, Int iPartIdx )
+{
+  setAll(m_pcMv, mv, eCUMode, iPartAddr, uiDepth, iPartIdx);
+}
+
+Void TComCUMvField::setAllMvd( TComMv const & mvd, PartSize eCUMode, Int iPartAddr, UInt uiDepth, Int iPartIdx )
+{
+  setAll(m_pcMvd, mvd, eCUMode, iPartAddr, uiDepth, iPartIdx);
+}
+
+Void TComCUMvField::setAllRefIdx ( Int iRefIdx, PartSize eCUMode, Int iPartAddr, UInt uiDepth, Int iPartIdx )
+{
+  setAll(m_piRefIdx, static_cast<Char>(iRefIdx), eCUMode, iPartAddr, uiDepth, iPartIdx);
+}
+
+Void TComCUMvField::setAllMvField( TComMvField const & mvField, PartSize eCUMode, Int iPartAddr, UInt uiDepth, Int iPartIdx )
+{
+  setAllMv    ( mvField.getMv(),     eCUMode, iPartAddr, uiDepth, iPartIdx );
+  setAllRefIdx( mvField.getRefIdx(), eCUMode, iPartAddr, uiDepth, iPartIdx );
+}
+
+/**Subsampling of the stored prediction mode, reference index and motion vector
+ * \param pePredMode Pointer to prediction modes
+ * \param scale      Factor by which to subsample motion information
+ */
+#if SVC_MVP
+Void TComCUMvField::compress(Char* pePredMode, UChar* peInterDir, Int scale)
+#else
+Void TComCUMvField::compress(Char* pePredMode, Int scale)
+#endif
+{
+  Int N = scale * scale;
+  assert( N > 0 && N <= m_uiNumPartition);
+  
+  for ( Int uiPartIdx = 0; uiPartIdx < m_uiNumPartition; uiPartIdx += N )
+  {
+    TComMv cMv(0,0); 
+    PredMode predMode = MODE_INTRA;
+    Int iRefIdx = 0;
+    
+    cMv = m_pcMv[ uiPartIdx ];
+    predMode = static_cast<PredMode>( pePredMode[ uiPartIdx ] );
+    iRefIdx = m_piRefIdx[ uiPartIdx ];
+    for ( Int i = 0; i < N; i++ )
+    {
+      m_pcMv[ uiPartIdx + i ] = cMv;
+      pePredMode[ uiPartIdx + i ] = predMode;
+      m_piRefIdx[ uiPartIdx + i ] = iRefIdx;
+#if SVC_MVP
+      peInterDir[ uiPartIdx + i ] = peInterDir[ uiPartIdx ];
+#endif
+    }
+  }
+} 
+//! \}
Index: /trunk/source/Lib/TLibCommon/TComMotionInfo.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComMotionInfo.h	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComMotionInfo.h	(revision 2)
@@ -0,0 +1,164 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComMotionInfo.h
+    \brief    motion information handling classes (header)
+    \todo     TComMvField seems to be better to be inherited from TComMv
+*/
+
+#ifndef __TCOMMOTIONINFO__
+#define __TCOMMOTIONINFO__
+
+#include <memory.h>
+#include "CommonDef.h"
+#include "TComMv.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Type definition
+// ====================================================================================================================
+
+/// parameters for AMVP
+typedef struct _AMVPInfo
+{
+  TComMv m_acMvCand[ AMVP_MAX_NUM_CANDS_MEM ];  ///< array of motion vector predictor candidates
+  Int    iN;                                ///< number of motion vector predictor candidates
+} AMVPInfo;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// class for motion vector with reference index
+class TComMvField
+{
+private:
+  TComMv    m_acMv;
+  Int       m_iRefIdx;
+  
+public:
+  TComMvField() : m_iRefIdx( NOT_VALID ) {}
+  
+  Void setMvField( TComMv const & cMv, Int iRefIdx )
+  {
+    m_acMv    = cMv;
+    m_iRefIdx = iRefIdx;
+  }
+  
+  Void setRefIdx( Int refIdx ) { m_iRefIdx = refIdx; }
+  
+  TComMv const & getMv() const { return  m_acMv; }
+  TComMv       & getMv()       { return  m_acMv; }
+  
+  Int getRefIdx() const { return  m_iRefIdx;       }
+  Int getHor   () const { return  m_acMv.getHor(); }
+  Int getVer   () const { return  m_acMv.getVer(); }
+};
+
+/// class for motion information in one CU
+class TComCUMvField
+{
+private:
+  TComMv*   m_pcMv;
+  TComMv*   m_pcMvd;
+  Char*     m_piRefIdx;
+  UInt      m_uiNumPartition;
+  AMVPInfo  m_cAMVPInfo;
+    
+  template <typename T>
+  Void setAll( T *p, T const & val, PartSize eCUMode, Int iPartAddr, UInt uiDepth, Int iPartIdx );
+
+public:
+  TComCUMvField() : m_pcMv(NULL), m_pcMvd(NULL), m_piRefIdx(NULL), m_uiNumPartition(0) {}
+  ~TComCUMvField() {}
+
+  // ------------------------------------------------------------------------------------------------------------------
+  // create / destroy
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  Void    create( UInt uiNumPartition );
+  Void    destroy();
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  // clear / copy
+  // ------------------------------------------------------------------------------------------------------------------
+
+  Void    clearMvField();
+  
+  Void    copyFrom( TComCUMvField const * pcCUMvFieldSrc, Int iNumPartSrc, Int iPartAddrDst );
+  Void    copyTo  ( TComCUMvField* pcCUMvFieldDst, Int iPartAddrDst ) const;
+  Void    copyTo  ( TComCUMvField* pcCUMvFieldDst, Int iPartAddrDst, UInt uiOffset, UInt uiNumPart ) const;
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  // get
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  TComMv const & getMv    ( Int iIdx ) const { return  m_pcMv    [iIdx]; }
+  TComMv const & getMvd   ( Int iIdx ) const { return  m_pcMvd   [iIdx]; }
+  Int            getRefIdx( Int iIdx ) const { return  m_piRefIdx[iIdx]; }
+  
+  AMVPInfo* getAMVPInfo () { return &m_cAMVPInfo; }
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  // set
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  Void    setAllMv     ( TComMv const & rcMv,         PartSize eCUMode, Int iPartAddr, UInt uiDepth, Int iPartIdx=0 );
+  Void    setAllMvd    ( TComMv const & rcMvd,        PartSize eCUMode, Int iPartAddr, UInt uiDepth, Int iPartIdx=0 );
+  Void    setAllRefIdx ( Int iRefIdx,                 PartSize eMbMode, Int iPartAddr, UInt uiDepth, Int iPartIdx=0 );
+  Void    setAllMvField( TComMvField const & mvField, PartSize eMbMode, Int iPartAddr, UInt uiDepth, Int iPartIdx=0 );
+
+  Void setNumPartition( Int iNumPart )
+  {
+    m_uiNumPartition = iNumPart;
+  }
+  
+  Void linkToWithOffset( TComCUMvField const * src, Int offset )
+  {
+    m_pcMv     = src->m_pcMv     + offset;
+    m_pcMvd    = src->m_pcMvd    + offset;
+    m_piRefIdx = src->m_piRefIdx + offset;
+  }
+  
+#if SVC_MVP
+  Void compress(Char* pePredMode, UChar* peInterDir, Int scale);
+#else
+  Void compress(Char* pePredMode, Int scale); 
+#endif
+};
+
+//! \}
+
+#endif // __TCOMMOTIONINFO__
Index: /trunk/source/Lib/TLibCommon/TComMv.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComMv.h	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComMv.h	(revision 2)
@@ -0,0 +1,155 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComMv.h
+    \brief    motion vector class (header)
+*/
+
+#ifndef __TCOMMV__
+#define __TCOMMV__
+
+#include "CommonDef.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// basic motion vector class
+class TComMv
+{
+private:
+  Short m_iHor;     ///< horizontal component of motion vector
+  Short m_iVer;     ///< vertical component of motion vector
+  
+public:
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  // constructors
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  TComMv() :
+  m_iHor(0),
+  m_iVer(0)
+  {
+  }
+  
+  TComMv( Short iHor, Short iVer ) :
+  m_iHor(iHor),
+  m_iVer(iVer)
+  {
+  }
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  // set
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  Void  set       ( Short iHor, Short iVer)     { m_iHor = iHor;  m_iVer = iVer;            }
+  Void  setHor    ( Short i )                   { m_iHor = i;                               }
+  Void  setVer    ( Short i )                   { m_iVer = i;                               }
+  Void  setZero   ()                            { m_iHor = m_iVer = 0;  }
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  // get
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  Int   getHor    () const { return m_iHor;          }
+  Int   getVer    () const { return m_iVer;          }
+  Int   getAbsHor () const { return abs( m_iHor );   }
+  Int   getAbsVer () const { return abs( m_iVer );   }
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  // operations
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  const TComMv& operator += (const TComMv& rcMv)
+  {
+    m_iHor += rcMv.m_iHor;
+    m_iVer += rcMv.m_iVer;
+    return  *this;
+  }
+  
+  const TComMv& operator-= (const TComMv& rcMv)
+  {
+    m_iHor -= rcMv.m_iHor;
+    m_iVer -= rcMv.m_iVer;
+    return  *this;
+  }
+  
+  const TComMv& operator>>= (const Int i)
+  {
+    m_iHor >>= i;
+    m_iVer >>= i;
+    return  *this;
+  }
+  
+  const TComMv& operator<<= (const Int i)
+  {
+    m_iHor <<= i;
+    m_iVer <<= i;
+    return  *this;
+  }
+  
+  const TComMv operator - ( const TComMv& rcMv ) const
+  {
+    return TComMv( m_iHor - rcMv.m_iHor, m_iVer - rcMv.m_iVer );
+  }
+  
+  const TComMv operator + ( const TComMv& rcMv ) const
+  {
+    return TComMv( m_iHor + rcMv.m_iHor, m_iVer + rcMv.m_iVer );
+  }
+  
+  Bool operator== ( const TComMv& rcMv ) const
+  {
+    return (m_iHor==rcMv.m_iHor && m_iVer==rcMv.m_iVer);
+  }
+  
+  Bool operator!= ( const TComMv& rcMv ) const
+  {
+    return (m_iHor!=rcMv.m_iHor || m_iVer!=rcMv.m_iVer);
+  }
+  
+  const TComMv scaleMv( Int iScale ) const
+  {
+    Int mvx = Clip3( -32768, 32767, (iScale * getHor() + 127 + (iScale * getHor() < 0)) >> 8 );
+    Int mvy = Clip3( -32768, 32767, (iScale * getVer() + 127 + (iScale * getVer() < 0)) >> 8 );
+    return TComMv( mvx, mvy );
+  }
+};// END CLASS DEFINITION TComMV
+
+//! \}
+
+#endif // __TCOMMV__
Index: /trunk/source/Lib/TLibCommon/TComPattern.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComPattern.cpp	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComPattern.cpp	(revision 2)
@@ -0,0 +1,787 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComPattern.cpp
+    \brief    neighbouring pixel access classes
+*/
+
+#include "TComPic.h"
+#include "TComPattern.h"
+#include "TComDataCU.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Tables
+// ====================================================================================================================
+
+const UChar TComPattern::m_aucIntraFilter[5] =
+{
+  10, //4x4
+  7, //8x8
+  1, //16x16
+  0, //32x32
+  10, //64x64
+};
+
+// ====================================================================================================================
+// Public member functions (TComPatternParam)
+// ====================================================================================================================
+
+/** \param  piTexture     pixel data
+ \param  iRoiWidth     pattern width
+ \param  iRoiHeight    pattern height
+ \param  iStride       buffer stride
+ \param  iOffsetLeft   neighbour offset (left)
+ \param  iOffsetRight  neighbour offset (right)
+ \param  iOffsetAbove  neighbour offset (above)
+ \param  iOffsetBottom neighbour offset (bottom)
+ */
+Void TComPatternParam::setPatternParamPel ( Pel* piTexture,
+                                           Int iRoiWidth,
+                                           Int iRoiHeight,
+                                           Int iStride,
+                                           Int iOffsetLeft,
+                                           Int iOffsetRight,
+                                           Int iOffsetAbove,
+                                           Int iOffsetBottom )
+{
+  m_piPatternOrigin = piTexture;
+  m_iROIWidth       = iRoiWidth;
+  m_iROIHeight      = iRoiHeight;
+  m_iPatternStride  = iStride;
+  m_iOffsetLeft     = iOffsetLeft;
+  m_iOffsetAbove    = iOffsetAbove;
+  m_iOffsetRight    = iOffsetRight;
+  m_iOffsetBottom   = iOffsetBottom;
+}
+
+/**
+ \param  pcCU          CU data structure
+ \param  iComp         component index (0=Y, 1=Cb, 2=Cr)
+ \param  iRoiWidth     pattern width
+ \param  iRoiHeight    pattern height
+ \param  iStride       buffer stride
+ \param  iOffsetLeft   neighbour offset (left)
+ \param  iOffsetRight  neighbour offset (right)
+ \param  iOffsetAbove  neighbour offset (above)
+ \param  iOffsetBottom neighbour offset (bottom)
+ \param  uiPartDepth   CU depth
+ \param  uiAbsPartIdx  part index
+ */
+Void TComPatternParam::setPatternParamCU( TComDataCU* pcCU,
+                                         UChar       iComp,
+                                         UChar       iRoiWidth,
+                                         UChar       iRoiHeight,
+                                         Int         iOffsetLeft,
+                                         Int         iOffsetRight,
+                                         Int         iOffsetAbove,
+                                         Int         iOffsetBottom,
+                                         UInt        uiPartDepth,
+                                         UInt        uiAbsPartIdx )
+{
+  m_iOffsetLeft   = iOffsetLeft;
+  m_iOffsetRight  = iOffsetRight;
+  m_iOffsetAbove  = iOffsetAbove;
+  m_iOffsetBottom = iOffsetBottom;
+  
+  m_iROIWidth     = iRoiWidth;
+  m_iROIHeight    = iRoiHeight;
+  
+  UInt uiAbsZorderIdx = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
+  
+  if ( iComp == 0 )
+  {
+    m_iPatternStride  = pcCU->getPic()->getStride();
+    m_piPatternOrigin = pcCU->getPic()->getPicYuvRec()->getLumaAddr(pcCU->getAddr(), uiAbsZorderIdx) - m_iOffsetAbove * m_iPatternStride - m_iOffsetLeft;
+  }
+  else
+  {
+    m_iPatternStride = pcCU->getPic()->getCStride();
+    if ( iComp == 1 )
+    {
+      m_piPatternOrigin = pcCU->getPic()->getPicYuvRec()->getCbAddr(pcCU->getAddr(), uiAbsZorderIdx) - m_iOffsetAbove * m_iPatternStride - m_iOffsetLeft;
+    }
+    else
+    {
+      m_piPatternOrigin = pcCU->getPic()->getPicYuvRec()->getCrAddr(pcCU->getAddr(), uiAbsZorderIdx) - m_iOffsetAbove * m_iPatternStride - m_iOffsetLeft;
+    }
+  }
+}
+
+// ====================================================================================================================
+// Public member functions (TComPattern)
+// ====================================================================================================================
+
+Void TComPattern::initPattern ( Pel* piY,
+                               Pel* piCb,
+                               Pel* piCr,
+                               Int iRoiWidth,
+                               Int iRoiHeight,
+                               Int iStride,
+                               Int iOffsetLeft,
+                               Int iOffsetRight,
+                               Int iOffsetAbove,
+                               Int iOffsetBottom )
+{
+  m_cPatternY. setPatternParamPel( piY,  iRoiWidth,      iRoiHeight,      iStride,      iOffsetLeft,      iOffsetRight,      iOffsetAbove,      iOffsetBottom );
+  m_cPatternCb.setPatternParamPel( piCb, iRoiWidth >> 1, iRoiHeight >> 1, iStride >> 1, iOffsetLeft >> 1, iOffsetRight >> 1, iOffsetAbove >> 1, iOffsetBottom >> 1 );
+  m_cPatternCr.setPatternParamPel( piCr, iRoiWidth >> 1, iRoiHeight >> 1, iStride >> 1, iOffsetLeft >> 1, iOffsetRight >> 1, iOffsetAbove >> 1, iOffsetBottom >> 1 );
+  
+  return;
+}
+
+Void TComPattern::initPattern( TComDataCU* pcCU, UInt uiPartDepth, UInt uiAbsPartIdx )
+{
+  Int   uiOffsetLeft  = 0;
+  Int   uiOffsetRight = 0;
+  Int   uiOffsetAbove = 0;
+  
+  TComPic* pcPic         = pcCU->getPic();
+  UChar uiWidth          = pcCU->getWidth (0)>>uiPartDepth;
+  UChar uiHeight         = pcCU->getHeight(0)>>uiPartDepth;
+  
+  UInt  uiAbsZorderIdx   = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
+  UInt  uiCurrPicPelX    = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsZorderIdx] ];
+  UInt  uiCurrPicPelY    = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsZorderIdx] ];
+  
+  if( uiCurrPicPelX != 0 )
+  {
+    uiOffsetLeft = 1;
+  }
+  
+  if( uiCurrPicPelY != 0 )
+  {
+    UInt uiNumPartInWidth = ( uiWidth/pcPic->getMinCUWidth() );
+    uiOffsetAbove = 1;
+    
+    if( uiCurrPicPelX + uiWidth < pcCU->getSlice()->getSPS()->getPicWidthInLumaSamples() )
+    {
+      if( ( g_auiZscanToRaster[uiAbsZorderIdx] + uiNumPartInWidth ) % pcPic->getNumPartInWidth() ) // Not CU boundary
+      {
+        if( g_auiRasterToZscan[ (Int)g_auiZscanToRaster[uiAbsZorderIdx] - (Int)pcPic->getNumPartInWidth() + (Int)uiNumPartInWidth ] < uiAbsZorderIdx )
+        {
+          uiOffsetRight = 1;
+        }
+      }
+      else // if it is CU boundary
+      {
+        if( g_auiZscanToRaster[uiAbsZorderIdx] < pcPic->getNumPartInWidth() && (uiCurrPicPelX+uiWidth) < pcPic->getPicYuvRec()->getWidth() ) // first line
+        {
+          uiOffsetRight = 1;
+        }
+      }
+    }
+  }
+  
+  m_cPatternY .setPatternParamCU( pcCU, 0, uiWidth,      uiHeight,      uiOffsetLeft, uiOffsetRight, uiOffsetAbove, 0, uiPartDepth, uiAbsPartIdx );
+  m_cPatternCb.setPatternParamCU( pcCU, 1, uiWidth >> 1, uiHeight >> 1, uiOffsetLeft, uiOffsetRight, uiOffsetAbove, 0, uiPartDepth, uiAbsPartIdx );
+  m_cPatternCr.setPatternParamCU( pcCU, 2, uiWidth >> 1, uiHeight >> 1, uiOffsetLeft, uiOffsetRight, uiOffsetAbove, 0, uiPartDepth, uiAbsPartIdx );
+}
+
+  Void TComPattern::initAdiPattern( TComDataCU* pcCU, UInt uiZorderIdxInPart, UInt uiPartDepth, Int* piAdiBuf, Int iOrgBufStride, Int iOrgBufHeight, Bool& bAbove, Bool& bLeft, Bool bLMmode )
+{
+  Pel*  piRoiOrigin;
+  Int*  piAdiTemp;
+  UInt  uiCuWidth   = pcCU->getWidth(0) >> uiPartDepth;
+  UInt  uiCuHeight  = pcCU->getHeight(0)>> uiPartDepth;
+  UInt  uiCuWidth2  = uiCuWidth<<1;
+  UInt  uiCuHeight2 = uiCuHeight<<1;
+  UInt  uiWidth;
+  UInt  uiHeight;
+  Int   iPicStride = pcCU->getPic()->getStride();
+  Int   iUnitSize = 0;
+  Int   iNumUnitsInCu = 0;
+  Int   iTotalUnits = 0;
+  Bool  bNeighborFlags[4 * MAX_NUM_SPU_W + 1];
+  Int   iNumIntraNeighbor = 0;
+  
+  UInt uiPartIdxLT, uiPartIdxRT, uiPartIdxLB;
+
+  
+  pcCU->deriveLeftRightTopIdxAdi( uiPartIdxLT, uiPartIdxRT, uiZorderIdxInPart, uiPartDepth );
+  pcCU->deriveLeftBottomIdxAdi  ( uiPartIdxLB,              uiZorderIdxInPart, uiPartDepth );
+  
+  iUnitSize      = g_uiMaxCUWidth >> g_uiMaxCUDepth;
+  iNumUnitsInCu  = uiCuWidth / iUnitSize;
+  iTotalUnits    = (iNumUnitsInCu << 2) + 1;
+
+  bNeighborFlags[iNumUnitsInCu*2] = isAboveLeftAvailable( pcCU, uiPartIdxLT );
+  iNumIntraNeighbor  += (Int)(bNeighborFlags[iNumUnitsInCu*2]);
+  iNumIntraNeighbor  += isAboveAvailable     ( pcCU, uiPartIdxLT, uiPartIdxRT, bNeighborFlags+(iNumUnitsInCu*2)+1 );
+  iNumIntraNeighbor  += isAboveRightAvailable( pcCU, uiPartIdxLT, uiPartIdxRT, bNeighborFlags+(iNumUnitsInCu*3)+1 );
+  iNumIntraNeighbor  += isLeftAvailable      ( pcCU, uiPartIdxLT, uiPartIdxLB, bNeighborFlags+(iNumUnitsInCu*2)-1 );
+  iNumIntraNeighbor  += isBelowLeftAvailable ( pcCU, uiPartIdxLT, uiPartIdxLB, bNeighborFlags+ iNumUnitsInCu   -1 );
+  
+  bAbove = true;
+  bLeft  = true;
+
+  uiWidth=uiCuWidth2+1;
+  uiHeight=uiCuHeight2+1;
+  
+  if (((uiWidth<<2)>iOrgBufStride)||((uiHeight<<2)>iOrgBufHeight))
+  {
+    return;
+  }
+  
+  piRoiOrigin = pcCU->getPic()->getPicYuvRec()->getLumaAddr(pcCU->getAddr(), pcCU->getZorderIdxInCU()+uiZorderIdxInPart);
+  piAdiTemp   = piAdiBuf;
+
+  fillReferenceSamples ( pcCU, piRoiOrigin, piAdiTemp, bNeighborFlags, iNumIntraNeighbor, iUnitSize, iNumUnitsInCu, iTotalUnits, uiCuWidth, uiCuHeight, uiWidth, uiHeight, iPicStride, bLMmode);
+  
+  Int   i;
+  // generate filtered intra prediction samples
+  Int iBufSize = uiCuHeight2 + uiCuWidth2 + 1;  // left and left above border + above and above right border + top left corner = length of 3. filter buffer
+
+  UInt uiWH = uiWidth * uiHeight;               // number of elements in one buffer
+
+  Int* piFilteredBuf1 = piAdiBuf + uiWH;        // 1. filter buffer
+  Int* piFilteredBuf2 = piFilteredBuf1 + uiWH;  // 2. filter buffer
+  Int* piFilterBuf = piFilteredBuf2 + uiWH;     // buffer for 2. filtering (sequential)
+  Int* piFilterBufN = piFilterBuf + iBufSize;   // buffer for 1. filtering (sequential)
+
+  Int l = 0;
+  // left border from bottom to top
+  for (i = 0; i < uiCuHeight2; i++)
+  {
+    piFilterBuf[l++] = piAdiTemp[uiWidth * (uiCuHeight2 - i)];
+  }
+  // top left corner
+  piFilterBuf[l++] = piAdiTemp[0];
+  // above border from left to right
+  for (i=0; i < uiCuWidth2; i++)
+  {
+    piFilterBuf[l++] = piAdiTemp[1 + i];
+  }
+
+  // 1. filtering with [1 2 1]
+  piFilterBufN[0] = piFilterBuf[0];
+  piFilterBufN[iBufSize - 1] = piFilterBuf[iBufSize - 1];
+  for (i = 1; i < iBufSize - 1; i++)
+  {
+    piFilterBufN[i] = (piFilterBuf[i - 1] + 2 * piFilterBuf[i]+piFilterBuf[i + 1] + 2) >> 2;
+  }
+
+  // fill 1. filter buffer with filtered values
+  l=0;
+  for (i = 0; i < uiCuHeight2; i++)
+  {
+    piFilteredBuf1[uiWidth * (uiCuHeight2 - i)] = piFilterBufN[l++];
+  }
+  piFilteredBuf1[0] = piFilterBufN[l++];
+  for (i = 0; i < uiCuWidth2; i++)
+  {
+    piFilteredBuf1[1 + i] = piFilterBufN[l++];
+  }
+}
+
+Void TComPattern::initAdiPatternChroma( TComDataCU* pcCU, UInt uiZorderIdxInPart, UInt uiPartDepth, Int* piAdiBuf, Int iOrgBufStride, Int iOrgBufHeight, Bool& bAbove, Bool& bLeft )
+{
+  Pel*  piRoiOrigin;
+  Int*  piAdiTemp;
+  UInt  uiCuWidth  = pcCU->getWidth (0) >> uiPartDepth;
+  UInt  uiCuHeight = pcCU->getHeight(0) >> uiPartDepth;
+  UInt  uiWidth;
+  UInt  uiHeight;
+  Int   iPicStride = pcCU->getPic()->getCStride();
+
+  Int   iUnitSize = 0;
+  Int   iNumUnitsInCu = 0;
+  Int   iTotalUnits = 0;
+  Bool  bNeighborFlags[4 * MAX_NUM_SPU_W + 1];
+  Int   iNumIntraNeighbor = 0;
+  
+  UInt uiPartIdxLT, uiPartIdxRT, uiPartIdxLB;
+  
+  pcCU->deriveLeftRightTopIdxAdi( uiPartIdxLT, uiPartIdxRT, uiZorderIdxInPart, uiPartDepth );
+  pcCU->deriveLeftBottomIdxAdi  ( uiPartIdxLB,              uiZorderIdxInPart, uiPartDepth );
+  
+  iUnitSize      = (g_uiMaxCUWidth >> g_uiMaxCUDepth) >> 1; // for chroma
+  iNumUnitsInCu  = (uiCuWidth / iUnitSize) >> 1;            // for chroma
+  iTotalUnits    = (iNumUnitsInCu << 2) + 1;
+
+  bNeighborFlags[iNumUnitsInCu*2] = isAboveLeftAvailable( pcCU, uiPartIdxLT );
+  iNumIntraNeighbor  += (Int)(bNeighborFlags[iNumUnitsInCu*2]);
+  iNumIntraNeighbor  += isAboveAvailable     ( pcCU, uiPartIdxLT, uiPartIdxRT, bNeighborFlags+(iNumUnitsInCu*2)+1 );
+  iNumIntraNeighbor  += isAboveRightAvailable( pcCU, uiPartIdxLT, uiPartIdxRT, bNeighborFlags+(iNumUnitsInCu*3)+1 );
+  iNumIntraNeighbor  += isLeftAvailable      ( pcCU, uiPartIdxLT, uiPartIdxLB, bNeighborFlags+(iNumUnitsInCu*2)-1 );
+  iNumIntraNeighbor  += isBelowLeftAvailable ( pcCU, uiPartIdxLT, uiPartIdxLB, bNeighborFlags+ iNumUnitsInCu   -1 );
+  
+  bAbove = true;
+  bLeft  = true;
+  
+  uiCuWidth=uiCuWidth>>1;  // for chroma
+  uiCuHeight=uiCuHeight>>1;  // for chroma
+  
+  uiWidth=uiCuWidth*2+1;
+  uiHeight=uiCuHeight*2+1;
+  
+  if ((4*uiWidth>iOrgBufStride)||(4*uiHeight>iOrgBufHeight))
+  {
+    return;
+  }
+  
+  // get Cb pattern
+  piRoiOrigin = pcCU->getPic()->getPicYuvRec()->getCbAddr(pcCU->getAddr(), pcCU->getZorderIdxInCU()+uiZorderIdxInPart);
+  piAdiTemp   = piAdiBuf;
+
+  fillReferenceSamples ( pcCU, piRoiOrigin, piAdiTemp, bNeighborFlags, iNumIntraNeighbor, iUnitSize, iNumUnitsInCu, iTotalUnits, uiCuWidth, uiCuHeight, uiWidth, uiHeight, iPicStride);
+  
+  // get Cr pattern
+  piRoiOrigin = pcCU->getPic()->getPicYuvRec()->getCrAddr(pcCU->getAddr(), pcCU->getZorderIdxInCU()+uiZorderIdxInPart);
+  piAdiTemp   = piAdiBuf+uiWidth*uiHeight;
+  
+  fillReferenceSamples ( pcCU, piRoiOrigin, piAdiTemp, bNeighborFlags, iNumIntraNeighbor, iUnitSize, iNumUnitsInCu, iTotalUnits, uiCuWidth, uiCuHeight, uiWidth, uiHeight, iPicStride);
+}
+
+Void TComPattern::fillReferenceSamples( TComDataCU* pcCU, Pel* piRoiOrigin, Int* piAdiTemp, Bool* bNeighborFlags, Int iNumIntraNeighbor, Int iUnitSize, Int iNumUnitsInCu, Int iTotalUnits, UInt uiCuWidth, UInt uiCuHeight, UInt uiWidth, UInt uiHeight, Int iPicStride, Bool bLMmode )
+{
+  Pel* piRoiTemp;
+  Int  i, j;
+  Int  iDCValue = ( 1<<( g_uiBitDepth + g_uiBitIncrement - 1) );
+
+  if (iNumIntraNeighbor == 0)
+  {
+    // Fill border with DC value
+    for (i=0; i<uiWidth; i++)
+    {
+      piAdiTemp[i] = iDCValue;
+    }
+    for (i=1; i<uiHeight; i++)
+    {
+      piAdiTemp[i*uiWidth] = iDCValue;
+    }
+  }
+  else if (iNumIntraNeighbor == iTotalUnits)
+  {
+    // Fill top-left border with rec. samples
+    piRoiTemp = piRoiOrigin - iPicStride - 1;
+    piAdiTemp[0] = piRoiTemp[0];
+
+    // Fill left border with rec. samples
+    piRoiTemp = piRoiOrigin - 1;
+
+    if (bLMmode)
+    {
+      piRoiTemp --; // move to the second left column
+    }
+
+    for (i=0; i<uiCuHeight; i++)
+    {
+      piAdiTemp[(1+i)*uiWidth] = piRoiTemp[0];
+      piRoiTemp += iPicStride;
+    }
+
+    // Fill below left border with rec. samples
+    for (i=0; i<uiCuHeight; i++)
+    {
+      piAdiTemp[(1+uiCuHeight+i)*uiWidth] = piRoiTemp[0];
+      piRoiTemp += iPicStride;
+    }
+
+    // Fill top border with rec. samples
+    piRoiTemp = piRoiOrigin - iPicStride;
+    for (i=0; i<uiCuWidth; i++)
+    {
+      piAdiTemp[1+i] = piRoiTemp[i];
+    }
+    
+    // Fill top right border with rec. samples
+    piRoiTemp = piRoiOrigin - iPicStride + uiCuWidth;
+    for (i=0; i<uiCuWidth; i++)
+    {
+      piAdiTemp[1+uiCuWidth+i] = piRoiTemp[i];
+    }
+  }
+  else // reference samples are partially available
+  {
+    Int  iNumUnits2 = iNumUnitsInCu<<1;
+    Int  iTotalSamples = iTotalUnits*iUnitSize;
+    Pel  piAdiLine[5 * MAX_CU_SIZE];
+    Pel  *piAdiLineTemp; 
+    Bool *pbNeighborFlags;
+    Int  iNext, iCurr;
+    Pel  piRef = 0;
+
+    // Initialize
+    for (i=0; i<iTotalSamples; i++)
+    {
+      piAdiLine[i] = iDCValue;
+    }
+    
+    // Fill top-left sample
+    piRoiTemp = piRoiOrigin - iPicStride - 1;
+    piAdiLineTemp = piAdiLine + (iNumUnits2*iUnitSize);
+    pbNeighborFlags = bNeighborFlags + iNumUnits2;
+    if (*pbNeighborFlags)
+    {
+      piAdiLineTemp[0] = piRoiTemp[0];
+      for (i=1; i<iUnitSize; i++)
+      {
+        piAdiLineTemp[i] = piAdiLineTemp[0];
+      }
+    }
+
+    // Fill left & below-left samples
+    piRoiTemp += iPicStride;
+    if (bLMmode)
+    {
+      piRoiTemp --; // move the second left column
+    }
+    piAdiLineTemp--;
+    pbNeighborFlags--;
+    for (j=0; j<iNumUnits2; j++)
+    {
+      if (*pbNeighborFlags)
+      {
+        for (i=0; i<iUnitSize; i++)
+        {
+          piAdiLineTemp[-i] = piRoiTemp[i*iPicStride];
+        }
+      }
+      piRoiTemp += iUnitSize*iPicStride;
+      piAdiLineTemp -= iUnitSize;
+      pbNeighborFlags--;
+    }
+
+    // Fill above & above-right samples
+    piRoiTemp = piRoiOrigin - iPicStride;
+    piAdiLineTemp = piAdiLine + ((iNumUnits2+1)*iUnitSize);
+    pbNeighborFlags = bNeighborFlags + iNumUnits2 + 1;
+    for (j=0; j<iNumUnits2; j++)
+    {
+      if (*pbNeighborFlags)
+      {
+        for (i=0; i<iUnitSize; i++)
+        {
+          piAdiLineTemp[i] = piRoiTemp[i];
+        }
+      }
+      piRoiTemp += iUnitSize;
+      piAdiLineTemp += iUnitSize;
+      pbNeighborFlags++;
+    }
+
+    // Pad reference samples when necessary
+    iCurr = 0;
+    iNext = 1;
+    piAdiLineTemp = piAdiLine;
+    while (iCurr < iTotalUnits)
+    {
+      if (!bNeighborFlags[iCurr])
+      {
+        if(iCurr == 0)
+        {
+          while (iNext < iTotalUnits && !bNeighborFlags[iNext])
+          {
+            iNext++;
+          }
+          piRef = piAdiLine[iNext*iUnitSize];
+          // Pad unavailable samples with new value
+          while (iCurr < iNext)
+          {
+            for (i=0; i<iUnitSize; i++)
+            {
+              piAdiLineTemp[i] = piRef;
+            }
+            piAdiLineTemp += iUnitSize;
+            iCurr++;
+          }
+        }
+        else
+        {
+          piRef = piAdiLine[iCurr*iUnitSize-1];
+          for (i=0; i<iUnitSize; i++)
+          {
+            piAdiLineTemp[i] = piRef;
+          }
+          piAdiLineTemp += iUnitSize;
+          iCurr++;
+        }
+      }
+      else
+      {
+        piAdiLineTemp += iUnitSize;
+        iCurr++;
+      }
+    }
+
+    // Copy processed samples
+    piAdiLineTemp = piAdiLine + uiHeight + iUnitSize - 2;
+    for (i=0; i<uiWidth; i++)
+    {
+      piAdiTemp[i] = piAdiLineTemp[i];
+    }
+    piAdiLineTemp = piAdiLine + uiHeight - 1;
+    for (i=1; i<uiHeight; i++)
+    {
+      piAdiTemp[i*uiWidth] = piAdiLineTemp[-i];
+    }
+  }
+}
+
+Int* TComPattern::getAdiOrgBuf( Int iCuWidth, Int iCuHeight, Int* piAdiBuf)
+{
+  return piAdiBuf;
+}
+
+Int* TComPattern::getAdiCbBuf( Int iCuWidth, Int iCuHeight, Int* piAdiBuf)
+{
+  return piAdiBuf;
+}
+
+Int* TComPattern::getAdiCrBuf(Int iCuWidth,Int iCuHeight, Int* piAdiBuf)
+{
+  return piAdiBuf+(iCuWidth*2+1)*(iCuHeight*2+1);
+}
+
+/** Get pointer to reference samples for intra prediction
+ * \param uiDirMode   prediction mode index
+ * \param log2BlkSize size of block (2 = 4x4, 3 = 8x8, 4 = 16x16, 5 = 32x32, 6 = 64x64)
+ * \param piAdiBuf    pointer to unfiltered reference samples
+ * \return            pointer to (possibly filtered) reference samples
+ *
+ * The prediction mode index is used to determine whether a smoothed reference sample buffer is returned.
+ */
+Int* TComPattern::getPredictorPtr( UInt uiDirMode, UInt log2BlkSize, Int* piAdiBuf )
+{
+  Int* piSrc;
+  assert(log2BlkSize >= 2 && log2BlkSize < 7);
+  Int diff = min<Int>(abs((Int) uiDirMode - HOR_IDX), abs((Int)uiDirMode - VER_IDX));
+  UChar ucFiltIdx = diff > m_aucIntraFilter[log2BlkSize - 2] ? 1 : 0;
+#if REMOVE_LMCHROMA
+  if (uiDirMode == DC_IDX)
+#else
+  if (uiDirMode == DC_IDX || uiDirMode == LM_CHROMA_IDX)
+#endif
+  {
+    ucFiltIdx = 0; //no smoothing for DC or LM chroma
+  }
+
+  assert( ucFiltIdx <= 1 );
+
+  Int width  = 1 << log2BlkSize;
+  Int height = 1 << log2BlkSize;
+  
+  piSrc = getAdiOrgBuf( width, height, piAdiBuf );
+
+  if ( ucFiltIdx )
+  {
+    piSrc += (2 * width + 1) * (2 * height + 1);
+  }
+
+  return piSrc;
+}
+
+Bool TComPattern::isAboveLeftAvailable( TComDataCU* pcCU, UInt uiPartIdxLT )
+{
+  Bool bAboveLeftFlag;
+  UInt uiPartAboveLeft;
+  TComDataCU* pcCUAboveLeft = pcCU->getPUAboveLeft( uiPartAboveLeft, uiPartIdxLT, true, false );
+  if(pcCU->getSlice()->getPPS()->getConstrainedIntraPred())
+  {
+    bAboveLeftFlag = ( pcCUAboveLeft && pcCUAboveLeft->getPredictionMode( uiPartAboveLeft ) == MODE_INTRA );
+  }
+  else
+  {
+    bAboveLeftFlag = (pcCUAboveLeft ? true : false);
+  }
+  return bAboveLeftFlag;
+}
+
+Int TComPattern::isAboveAvailable( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxRT, Bool *bValidFlags )
+{
+  const UInt uiRasterPartBegin = g_auiZscanToRaster[uiPartIdxLT];
+  const UInt uiRasterPartEnd = g_auiZscanToRaster[uiPartIdxRT]+1;
+  const UInt uiIdxStep = 1;
+  Bool *pbValidFlags = bValidFlags;
+  Int iNumIntra = 0;
+
+  for ( UInt uiRasterPart = uiRasterPartBegin; uiRasterPart < uiRasterPartEnd; uiRasterPart += uiIdxStep )
+  {
+    UInt uiPartAbove;
+    TComDataCU* pcCUAbove = pcCU->getPUAbove( uiPartAbove, g_auiRasterToZscan[uiRasterPart], true, false );
+    if(pcCU->getSlice()->getPPS()->getConstrainedIntraPred())
+    {
+      if ( pcCUAbove && pcCUAbove->getPredictionMode( uiPartAbove ) == MODE_INTRA )
+      {
+        iNumIntra++;
+        *pbValidFlags = true;
+      }
+      else
+      {
+        *pbValidFlags = false;
+      }
+    }
+    else
+    {
+      if (pcCUAbove)
+      {
+        iNumIntra++;
+        *pbValidFlags = true;
+      }
+      else
+      {
+        *pbValidFlags = false;
+      }
+    }
+    pbValidFlags++;
+  }
+  return iNumIntra;
+}
+
+Int TComPattern::isLeftAvailable( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxLB, Bool *bValidFlags )
+{
+  const UInt uiRasterPartBegin = g_auiZscanToRaster[uiPartIdxLT];
+  const UInt uiRasterPartEnd = g_auiZscanToRaster[uiPartIdxLB]+1;
+  const UInt uiIdxStep = pcCU->getPic()->getNumPartInWidth();
+  Bool *pbValidFlags = bValidFlags;
+  Int iNumIntra = 0;
+
+  for ( UInt uiRasterPart = uiRasterPartBegin; uiRasterPart < uiRasterPartEnd; uiRasterPart += uiIdxStep )
+  {
+    UInt uiPartLeft;
+    TComDataCU* pcCULeft = pcCU->getPULeft( uiPartLeft, g_auiRasterToZscan[uiRasterPart], true, false );
+    if(pcCU->getSlice()->getPPS()->getConstrainedIntraPred())
+    {
+      if ( pcCULeft && pcCULeft->getPredictionMode( uiPartLeft ) == MODE_INTRA )
+      {
+        iNumIntra++;
+        *pbValidFlags = true;
+      }
+      else
+      {
+        *pbValidFlags = false;
+      }
+    }
+    else
+    {
+      if ( pcCULeft )
+      {
+        iNumIntra++;
+        *pbValidFlags = true;
+      }
+      else
+      {
+        *pbValidFlags = false;
+      }
+    }
+    pbValidFlags--; // opposite direction
+  }
+
+  return iNumIntra;
+}
+
+Int TComPattern::isAboveRightAvailable( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxRT, Bool *bValidFlags )
+{
+  const UInt uiNumUnitsInPU = g_auiZscanToRaster[uiPartIdxRT] - g_auiZscanToRaster[uiPartIdxLT] + 1;
+  const UInt uiPuWidth = uiNumUnitsInPU * pcCU->getPic()->getMinCUWidth();
+  Bool *pbValidFlags = bValidFlags;
+  Int iNumIntra = 0;
+
+  for ( UInt uiOffset = 1; uiOffset <= uiNumUnitsInPU; uiOffset++ )
+  {
+    UInt uiPartAboveRight;
+    TComDataCU* pcCUAboveRight = pcCU->getPUAboveRightAdi( uiPartAboveRight, uiPuWidth, uiPartIdxRT, uiOffset, true, false );
+    if(pcCU->getSlice()->getPPS()->getConstrainedIntraPred())
+    {
+      if ( pcCUAboveRight && pcCUAboveRight->getPredictionMode( uiPartAboveRight ) == MODE_INTRA )
+      {
+        iNumIntra++;
+        *pbValidFlags = true;
+      }
+      else
+      {
+        *pbValidFlags = false;
+      }
+    }
+    else
+    {
+      if ( pcCUAboveRight )
+      {
+        iNumIntra++;
+        *pbValidFlags = true;
+      }
+      else
+      {
+        *pbValidFlags = false;
+      }
+    }
+    pbValidFlags++;
+  }
+
+  return iNumIntra;
+}
+
+Int TComPattern::isBelowLeftAvailable( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxLB, Bool *bValidFlags )
+{
+  const UInt uiNumUnitsInPU = (g_auiZscanToRaster[uiPartIdxLB] - g_auiZscanToRaster[uiPartIdxLT]) / pcCU->getPic()->getNumPartInWidth() + 1;
+  const UInt uiPuHeight = uiNumUnitsInPU * pcCU->getPic()->getMinCUHeight();
+  Bool *pbValidFlags = bValidFlags;
+  Int iNumIntra = 0;
+
+  for ( UInt uiOffset = 1; uiOffset <= uiNumUnitsInPU; uiOffset++ )
+  {
+    UInt uiPartBelowLeft;
+    TComDataCU* pcCUBelowLeft = pcCU->getPUBelowLeftAdi( uiPartBelowLeft, uiPuHeight, uiPartIdxLB, uiOffset, true, false );
+    if(pcCU->getSlice()->getPPS()->getConstrainedIntraPred())
+    {
+      if ( pcCUBelowLeft && pcCUBelowLeft->getPredictionMode( uiPartBelowLeft ) == MODE_INTRA )
+      {
+        iNumIntra++;
+        *pbValidFlags = true;
+      }
+      else
+      {
+        *pbValidFlags = false;
+      }
+    }
+    else
+    {
+      if ( pcCUBelowLeft )
+      {
+        iNumIntra++;
+        *pbValidFlags = true;
+      }
+      else
+      {
+        *pbValidFlags = false;
+      }
+    }
+    pbValidFlags--; // opposite direction
+  }
+
+  return iNumIntra;
+}
+//! \}
Index: /trunk/source/Lib/TLibCommon/TComPattern.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComPattern.h	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComPattern.h	(revision 2)
@@ -0,0 +1,185 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComPattern.h
+    \brief    neighbouring pixel access classes (header)
+*/
+
+#ifndef __TCOMPATTERN__
+#define __TCOMPATTERN__
+
+// Include files
+#include <stdio.h>
+#include "CommonDef.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+class TComDataCU;
+
+/// neighbouring pixel access class for one component
+class TComPatternParam
+{
+private:
+  Int   m_iOffsetLeft;
+  Int   m_iOffsetRight;
+  Int   m_iOffsetAbove;
+  Int   m_iOffsetBottom;
+  Pel*  m_piPatternOrigin;
+  
+public:
+  Int   m_iROIWidth;
+  Int   m_iROIHeight;
+  Int   m_iPatternStride;
+  
+  /// return starting position of buffer
+  Pel*  getPatternOrigin()        { return  m_piPatternOrigin; }
+  
+  /// return starting position of ROI (ROI = &pattern[AboveOffset][LeftOffset])
+  __inline Pel*  getROIOrigin()
+  {
+    return  m_piPatternOrigin + m_iPatternStride * m_iOffsetAbove + m_iOffsetLeft;
+  }
+  
+  /// set parameters from Pel buffer for accessing neighbouring pixels
+  Void setPatternParamPel ( Pel*        piTexture,
+                           Int         iRoiWidth,
+                           Int         iRoiHeight,
+                           Int         iStride,
+                           Int         iOffsetLeft,
+                           Int         iOffsetRight,
+                           Int         iOffsetAbove,
+                           Int         iOffsetBottom );
+  
+  /// set parameters of one color component from CU data for accessing neighbouring pixels
+  Void setPatternParamCU  ( TComDataCU* pcCU,
+                           UChar       iComp,
+                           UChar       iRoiWidth,
+                           UChar       iRoiHeight,
+                           Int         iOffsetLeft,
+                           Int         iOffsetRight,
+                           Int         iOffsetAbove,
+                           Int         iOffsetBottom,
+                           UInt        uiPartDepth,
+                           UInt        uiAbsZorderIdx );
+};
+
+/// neighbouring pixel access class for all components
+class TComPattern
+{
+private:
+  TComPatternParam  m_cPatternY;
+  TComPatternParam  m_cPatternCb;
+  TComPatternParam  m_cPatternCr;
+  
+  static const UChar m_aucIntraFilter[5];
+  
+public:
+  
+  // 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;  }
+
+  // access functions of ADI buffers
+  Int*  getAdiOrgBuf              ( Int iCuWidth, Int iCuHeight, Int* piAdiBuf );
+  Int*  getAdiCbBuf               ( Int iCuWidth, Int iCuHeight, Int* piAdiBuf );
+  Int*  getAdiCrBuf               ( Int iCuWidth, Int iCuHeight, Int* piAdiBuf );
+  
+  Int*  getPredictorPtr           ( UInt uiDirMode, UInt uiWidthBits, Int* piAdiBuf );
+  // -------------------------------------------------------------------------------------------------------------------
+  // initialization functions
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  /// set parameters from Pel buffers for accessing neighbouring pixels
+  Void initPattern            ( Pel*        piY,
+                               Pel*        piCb,
+                               Pel*        piCr,
+                               Int         iRoiWidth,
+                               Int         iRoiHeight,
+                               Int         iStride,
+                               Int         iOffsetLeft,
+                               Int         iOffsetRight,
+                               Int         iOffsetAbove,
+                               Int         iOffsetBottom );
+  
+  /// set parameters from CU data for accessing neighbouring pixels
+  Void  initPattern           ( TComDataCU* pcCU,
+                               UInt        uiPartDepth,
+                               UInt        uiAbsPartIdx );
+  
+  /// set luma parameters from CU data for accessing ADI data
+  Void  initAdiPattern        ( TComDataCU* pcCU,
+                               UInt        uiZorderIdxInPart,
+                               UInt        uiPartDepth,
+                               Int*        piAdiBuf,
+                               Int         iOrgBufStride,
+                               Int         iOrgBufHeight,
+                               Bool&       bAbove,
+                               Bool&       bLeft
+                              ,Bool        bLMmode = false // using for LM chroma or not
+                               );
+  
+  /// set chroma parameters from CU data for accessing ADI data
+  Void  initAdiPatternChroma  ( TComDataCU* pcCU,
+                               UInt        uiZorderIdxInPart,
+                               UInt        uiPartDepth,
+                               Int*        piAdiBuf,
+                               Int         iOrgBufStride,
+                               Int         iOrgBufHeight,
+                               Bool&       bAbove,
+                               Bool&       bLeft );
+
+private:
+
+  /// padding of unavailable reference samples for intra prediction
+  Void  fillReferenceSamples        ( TComDataCU* pcCU, Pel* piRoiOrigin, Int* piAdiTemp, Bool* bNeighborFlags, Int iNumIntraNeighbor, Int iUnitSize, Int iNumUnitsInCu, Int iTotalUnits, UInt uiCuWidth, UInt uiCuHeight, UInt uiWidth, UInt uiHeight, Int iPicStride, Bool bLMmode = false);
+  
+
+  /// 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 );
+
+};
+
+//! \}
+
+#endif // __TCOMPATTERN__
Index: /trunk/source/Lib/TLibCommon/TComPic.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComPic.cpp	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComPic.cpp	(revision 2)
@@ -0,0 +1,555 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComPic.cpp
+    \brief    picture class
+*/
+
+#include "TComPic.h"
+#include "SEI.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TComPic::TComPic()
+: m_uiTLayer                              (0)
+, m_bUsedByCurr                           (false)
+, m_bIsLongTerm                           (false)
+, m_bIsUsedAsLongTerm                     (false)
+, m_apcPicSym                             (NULL)
+, m_pcPicYuvPred                          (NULL)
+, m_pcPicYuvResi                          (NULL)
+, m_bReconstructed                        (false)
+, m_bNeededForOutput                      (false)
+, m_uiCurrSliceIdx                        (0)
+, m_pSliceSUMap                           (NULL)
+, m_pbValidSlice                          (NULL)
+, m_sliceGranularityForNDBFilter          (0)
+, m_bIndependentSliceBoundaryForNDBFilter (false)
+, m_bIndependentTileBoundaryForNDBFilter  (false)
+, m_pNDBFilterYuvTmp                      (NULL)
+, m_bCheckLTMSB                           (false)
+, m_SEIs                                  (NULL)
+#if SVC_EXTENSION
+, m_bSpatialEnhLayer( false )
+, m_pcFullPelBaseRec( NULL )
+#endif
+{
+  m_apcPicYuv[0]      = NULL;
+  m_apcPicYuv[1]      = NULL;
+}
+
+TComPic::~TComPic()
+{
+}
+
+#if SVC_UPSAMPLING
+Void TComPic::create( Int iWidth, Int iHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth, TComSPS* pcSps,  Bool bIsVirtual )
+{
+  m_apcPicSym     = new TComPicSym;  m_apcPicSym   ->create( iWidth, iHeight, uiMaxWidth, uiMaxHeight, uiMaxDepth );
+  if (!bIsVirtual)
+  {
+    m_apcPicYuv[0]  = new TComPicYuv;  m_apcPicYuv[0]->create( iWidth, iHeight, uiMaxWidth, uiMaxHeight, uiMaxDepth, pcSps );
+  }
+  m_apcPicYuv[1]  = new TComPicYuv;  m_apcPicYuv[1]->create( iWidth, iHeight, uiMaxWidth, uiMaxHeight, uiMaxDepth, pcSps );
+  
+  if (m_bSpatialEnhLayer)
+  {
+    m_pcFullPelBaseRec = new TComPicYuv;  m_pcFullPelBaseRec->create( iWidth, iHeight, uiMaxWidth, uiMaxHeight, uiMaxDepth, pcSps );
+  }
+
+  /* there are no SEI messages associated with this picture initially */
+  m_SEIs = NULL;
+  m_bUsedByCurr = false;
+  return;
+}
+#if REF_IDX_FRAMEWORK
+Void TComPic::createWithOutYuv( Int iWidth, Int iHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth, TComSPS* pcSps,  Bool bIsVirtual)
+{
+  m_apcPicSym     = new TComPicSym;  m_apcPicSym   ->create( iWidth, iHeight, uiMaxWidth, uiMaxHeight, uiMaxDepth );
+  if (!bIsVirtual)
+  {
+    m_apcPicYuv[0]  = new TComPicYuv;  m_apcPicYuv[0]->create( iWidth, iHeight, uiMaxWidth, uiMaxHeight, uiMaxDepth, pcSps );
+  }
+  m_apcPicYuv[1]  = NULL;
+ 
+#if SVC_UPSAMPLING
+  if (m_bSpatialEnhLayer)
+  {
+    m_pcFullPelBaseRec = new TComPicYuv;  m_pcFullPelBaseRec->create( iWidth, iHeight, uiMaxWidth, uiMaxHeight, uiMaxDepth, pcSps );
+  }
+#endif
+
+  /* there are no SEI messages associated with this picture initially */
+  m_SEIs = NULL;
+  m_bUsedByCurr = false;
+  return;
+}
+#endif
+#else
+
+Void TComPic::create( Int iWidth, Int iHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth, Bool bIsVirtual )
+{
+  m_apcPicSym     = new TComPicSym;  m_apcPicSym   ->create( iWidth, iHeight, uiMaxWidth, uiMaxHeight, uiMaxDepth );
+  if (!bIsVirtual)
+  {
+    m_apcPicYuv[0]  = new TComPicYuv;  m_apcPicYuv[0]->create( iWidth, iHeight, uiMaxWidth, uiMaxHeight, uiMaxDepth );
+  }
+  m_apcPicYuv[1]  = new TComPicYuv;  m_apcPicYuv[1]->create( iWidth, iHeight, uiMaxWidth, uiMaxHeight, uiMaxDepth );
+  
+  /* there are no SEI messages associated with this picture initially */
+  m_SEIs = NULL;
+  m_bUsedByCurr = false;
+  return;
+}
+#endif
+
+Void TComPic::destroy()
+{
+  if (m_apcPicSym)
+  {
+    m_apcPicSym->destroy();
+    delete m_apcPicSym;
+    m_apcPicSym = NULL;
+  }
+  
+  if (m_apcPicYuv[0])
+  {
+    m_apcPicYuv[0]->destroy();
+    delete m_apcPicYuv[0];
+    m_apcPicYuv[0]  = NULL;
+  }
+  
+  if (m_apcPicYuv[1])
+  {
+    m_apcPicYuv[1]->destroy();
+    delete m_apcPicYuv[1];
+    m_apcPicYuv[1]  = NULL;
+  }
+  
+#if SVC_EXTENSION && SVC_UPSAMPLING
+  if (m_bSpatialEnhLayer)
+  {
+    m_pcFullPelBaseRec->destroy();
+    delete m_pcFullPelBaseRec;    m_pcFullPelBaseRec  = NULL;
+  }
+#endif 
+
+  delete m_SEIs;
+}
+
+Void TComPic::compressMotion()
+{
+  TComPicSym* pPicSym = getPicSym(); 
+  for ( UInt uiCUAddr = 0; uiCUAddr < pPicSym->getFrameHeightInCU()*pPicSym->getFrameWidthInCU(); uiCUAddr++ )
+  {
+    TComDataCU* pcCU = pPicSym->getCU(uiCUAddr);
+    pcCU->compressMV(); 
+  } 
+}
+
+/** Create non-deblocked filter information
+ * \param pSliceStartAddress array for storing slice start addresses
+ * \param numSlices number of slices in picture
+ * \param sliceGranularityDepth slice granularity 
+ * \param bNDBFilterCrossSliceBoundary cross-slice-boundary in-loop filtering; true for "cross".
+ * \param numTiles number of tiles in picture
+ * \param bNDBFilterCrossTileBoundary cross-tile-boundary in-loop filtering; true for "cross".
+ */
+Void TComPic::createNonDBFilterInfo(std::vector<Int> sliceStartAddress, Int sliceGranularityDepth
+                                    ,std::vector<Bool>* LFCrossSliceBoundary
+                                    ,Int numTiles
+                                    ,Bool bNDBFilterCrossTileBoundary)
+{
+  UInt maxNumSUInLCU = getNumPartInCU();
+  UInt numLCUInPic   = getNumCUsInFrame();
+  UInt picWidth      = getSlice(0)->getSPS()->getPicWidthInLumaSamples();
+  UInt picHeight     = getSlice(0)->getSPS()->getPicHeightInLumaSamples();
+  Int  numLCUsInPicWidth = getFrameWidthInCU();
+  Int  numLCUsInPicHeight= getFrameHeightInCU();
+  UInt maxNumSUInLCUWidth = getNumPartInWidth();
+  UInt maxNumSUInLCUHeight= getNumPartInHeight();
+  Int  numSlices = (Int) sliceStartAddress.size() - 1;
+  m_bIndependentSliceBoundaryForNDBFilter = false;
+  if(numSlices > 1)
+  {
+    for(Int s=0; s< numSlices; s++)
+    {
+      if((*LFCrossSliceBoundary)[s] == false)
+      {
+        m_bIndependentSliceBoundaryForNDBFilter = true;
+      }
+    }
+  }
+  m_sliceGranularityForNDBFilter = sliceGranularityDepth;
+  m_bIndependentTileBoundaryForNDBFilter  = (bNDBFilterCrossTileBoundary)?(false) :((numTiles > 1)?(true):(false));
+
+  m_pbValidSlice = new Bool[numSlices];
+  for(Int s=0; s< numSlices; s++)
+  {
+    m_pbValidSlice[s] = true;
+  }
+  m_pSliceSUMap = new Int[maxNumSUInLCU * numLCUInPic];
+
+  //initialization
+  for(UInt i=0; i< (maxNumSUInLCU * numLCUInPic); i++ )
+  {
+    m_pSliceSUMap[i] = -1;
+  }
+  for( UInt CUAddr = 0; CUAddr < numLCUInPic ; CUAddr++ )
+  {
+    TComDataCU* pcCU = getCU( CUAddr );
+    pcCU->setSliceSUMap(m_pSliceSUMap + (CUAddr* maxNumSUInLCU)); 
+    pcCU->getNDBFilterBlocks()->clear();
+  }
+  m_vSliceCUDataLink.clear();
+
+  m_vSliceCUDataLink.resize(numSlices);
+
+  UInt startAddr, endAddr, firstCUInStartLCU, startLCU, endLCU, lastCUInEndLCU, uiAddr;
+  UInt LPelX, TPelY, LCUX, LCUY;
+  UInt currSU;
+  UInt startSU, endSU;
+
+  for(Int s=0; s< numSlices; s++)
+  {
+    //1st step: decide the real start address
+    startAddr = sliceStartAddress[s];
+    endAddr   = sliceStartAddress[s+1] -1;
+
+    startLCU            = startAddr / maxNumSUInLCU;
+    firstCUInStartLCU   = startAddr % maxNumSUInLCU;
+
+    endLCU              = endAddr   / maxNumSUInLCU;
+    lastCUInEndLCU      = endAddr   % maxNumSUInLCU;   
+
+    uiAddr = m_apcPicSym->getCUOrderMap(startLCU);
+
+    LCUX      = getCU(uiAddr)->getCUPelX();
+    LCUY      = getCU(uiAddr)->getCUPelY();
+    LPelX     = LCUX + g_auiRasterToPelX[ g_auiZscanToRaster[firstCUInStartLCU] ];
+    TPelY     = LCUY + g_auiRasterToPelY[ g_auiZscanToRaster[firstCUInStartLCU] ];
+    currSU    = firstCUInStartLCU;
+
+    Bool bMoveToNextLCU = false;
+    Bool bSliceInOneLCU = (startLCU == endLCU);
+
+    while(!( LPelX < picWidth ) || !( TPelY < picHeight ))
+    {
+      currSU ++;
+
+      if(bSliceInOneLCU)
+      {
+        if(currSU > lastCUInEndLCU)
+        {
+          m_pbValidSlice[s] = false;
+          break;
+        }
+      }
+
+      if(currSU >= maxNumSUInLCU )
+      {
+        bMoveToNextLCU = true;
+        break;
+      }
+
+      LPelX = LCUX + g_auiRasterToPelX[ g_auiZscanToRaster[currSU] ];
+      TPelY = LCUY + g_auiRasterToPelY[ g_auiZscanToRaster[currSU] ];
+
+    }
+
+
+    if(!m_pbValidSlice[s])
+    {
+      continue;
+    }
+
+    if(currSU != firstCUInStartLCU)
+    {
+      if(!bMoveToNextLCU)
+      {
+        firstCUInStartLCU = currSU;
+      }
+      else
+      {
+        startLCU++;
+        firstCUInStartLCU = 0;
+        assert( startLCU < getNumCUsInFrame());
+      }
+      assert(startLCU*maxNumSUInLCU + firstCUInStartLCU < endAddr);
+    }
+
+
+    //2nd step: assign NonDBFilterInfo to each processing block
+    for(UInt i= startLCU; i <= endLCU; i++)
+    {
+      startSU = (i == startLCU)?(firstCUInStartLCU):(0);
+      endSU   = (i == endLCU  )?(lastCUInEndLCU   ):(maxNumSUInLCU -1);
+
+      uiAddr = m_apcPicSym->getCUOrderMap(i);
+      Int iTileID= m_apcPicSym->getTileIdxMap(uiAddr);
+
+      TComDataCU* pcCU = getCU(uiAddr);
+      m_vSliceCUDataLink[s].push_back(pcCU);
+
+      createNonDBFilterInfoLCU(iTileID, s, pcCU, startSU, endSU, m_sliceGranularityForNDBFilter, picWidth, picHeight);
+    }
+  }
+
+  //step 3: border availability
+  for(Int s=0; s< numSlices; s++)
+  {
+    if(!m_pbValidSlice[s])
+    {
+      continue;
+    }
+
+    for(Int i=0; i< m_vSliceCUDataLink[s].size(); i++)
+    {
+      TComDataCU* pcCU = m_vSliceCUDataLink[s][i];
+      uiAddr = pcCU->getAddr();
+
+      if(pcCU->getPic()==0)
+      {
+        continue;
+      }
+      Int iTileID= m_apcPicSym->getTileIdxMap(uiAddr);
+      Bool bTopTileBoundary = false, bDownTileBoundary= false, bLeftTileBoundary= false, bRightTileBoundary= false;
+
+      if(m_bIndependentTileBoundaryForNDBFilter)
+      {
+        //left
+        if( uiAddr % numLCUsInPicWidth != 0)
+        {
+          bLeftTileBoundary = ( m_apcPicSym->getTileIdxMap(uiAddr -1) != iTileID )?true:false;
+        }
+        //right
+        if( (uiAddr % numLCUsInPicWidth) != (numLCUsInPicWidth -1) )
+        {
+          bRightTileBoundary = ( m_apcPicSym->getTileIdxMap(uiAddr +1) != iTileID)?true:false;
+        }
+        //top
+        if( uiAddr >= numLCUsInPicWidth)
+        {
+          bTopTileBoundary = (m_apcPicSym->getTileIdxMap(uiAddr - numLCUsInPicWidth) !=  iTileID )?true:false;
+        }
+        //down
+        if( uiAddr + numLCUsInPicWidth < numLCUInPic )
+        {
+          bDownTileBoundary = (m_apcPicSym->getTileIdxMap(uiAddr + numLCUsInPicWidth) != iTileID)?true:false;
+        }
+
+      }
+
+      pcCU->setNDBFilterBlockBorderAvailability(numLCUsInPicWidth, numLCUsInPicHeight, maxNumSUInLCUWidth, maxNumSUInLCUHeight,picWidth, picHeight
+        , *LFCrossSliceBoundary
+        ,bTopTileBoundary, bDownTileBoundary, bLeftTileBoundary, bRightTileBoundary
+        ,m_bIndependentTileBoundaryForNDBFilter);
+
+    }
+
+  }
+
+  if( m_bIndependentSliceBoundaryForNDBFilter || m_bIndependentTileBoundaryForNDBFilter)
+  {
+    m_pNDBFilterYuvTmp = new TComPicYuv();
+    m_pNDBFilterYuvTmp->create(picWidth, picHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth);
+  }
+
+}
+
+/** Create non-deblocked filter information for LCU
+ * \param tileID tile index
+ * \param sliceID slice index
+ * \param pcCU CU data pointer
+ * \param startSU start SU index in LCU
+ * \param endSU end SU index in LCU
+ * \param sliceGranularyDepth slice granularity
+ * \param picWidth picture width
+ * \param picHeight picture height
+ */
+Void TComPic::createNonDBFilterInfoLCU(Int tileID, Int sliceID, TComDataCU* pcCU, UInt startSU, UInt endSU, Int sliceGranularyDepth, UInt picWidth, UInt picHeight)
+{
+  UInt LCUX          = pcCU->getCUPelX();
+  UInt LCUY          = pcCU->getCUPelY();
+  Int* pCUSliceMap    = pcCU->getSliceSUMap();
+  UInt maxNumSUInLCU = getNumPartInCU();
+  UInt maxNumSUInSGU = maxNumSUInLCU >> (sliceGranularyDepth << 1);
+  UInt maxNumSUInLCUWidth = getNumPartInWidth();
+  UInt LPelX, TPelY;
+  UInt currSU;
+
+
+  //get the number of valid NBFilterBLock
+  currSU   = startSU;
+  while(currSU <= endSU)
+  {
+    LPelX = LCUX + g_auiRasterToPelX[ g_auiZscanToRaster[currSU] ];
+    TPelY = LCUY + g_auiRasterToPelY[ g_auiZscanToRaster[currSU] ];
+
+    while(!( LPelX < picWidth ) || !( TPelY < picHeight ))
+    {
+      currSU += maxNumSUInSGU;
+      if(currSU >= maxNumSUInLCU || currSU > endSU)
+      {
+        break;
+      }
+      LPelX = LCUX + g_auiRasterToPelX[ g_auiZscanToRaster[currSU] ];
+      TPelY = LCUY + g_auiRasterToPelY[ g_auiZscanToRaster[currSU] ];
+    }
+
+    if(currSU >= maxNumSUInLCU || currSU > endSU)
+    {
+      break;
+    }
+
+    NDBFBlockInfo NDBFBlock;
+
+    NDBFBlock.tileID  = tileID;
+    NDBFBlock.sliceID = sliceID;
+    NDBFBlock.posY    = TPelY;
+    NDBFBlock.posX    = LPelX;
+    NDBFBlock.startSU = currSU;
+
+    UInt uiLastValidSU  = currSU;
+    UInt uiIdx, uiLPelX_su, uiTPelY_su;
+    for(uiIdx = currSU; uiIdx < currSU + maxNumSUInSGU; uiIdx++)
+    {
+      if(uiIdx > endSU)
+      {
+        break;        
+      }
+      uiLPelX_su   = LCUX + g_auiRasterToPelX[ g_auiZscanToRaster[uiIdx] ];
+      uiTPelY_su   = LCUY + g_auiRasterToPelY[ g_auiZscanToRaster[uiIdx] ];
+      if( !(uiLPelX_su < picWidth ) || !( uiTPelY_su < picHeight ))
+      {
+        continue;
+      }
+      pCUSliceMap[uiIdx] = sliceID;
+      uiLastValidSU = uiIdx;
+    }
+    NDBFBlock.endSU = uiLastValidSU;
+
+    UInt rTLSU = g_auiZscanToRaster[ NDBFBlock.startSU ];
+    UInt rBRSU = g_auiZscanToRaster[ NDBFBlock.endSU   ];
+    NDBFBlock.widthSU  = (rBRSU % maxNumSUInLCUWidth) - (rTLSU % maxNumSUInLCUWidth)+ 1;
+    NDBFBlock.heightSU = (UInt)(rBRSU / maxNumSUInLCUWidth) - (UInt)(rTLSU / maxNumSUInLCUWidth)+ 1;
+    NDBFBlock.width    = NDBFBlock.widthSU  * getMinCUWidth();
+    NDBFBlock.height   = NDBFBlock.heightSU * getMinCUHeight();
+
+    pcCU->getNDBFilterBlocks()->push_back(NDBFBlock);
+
+    currSU += maxNumSUInSGU;
+  }
+
+}
+
+/** destroy non-deblocked filter information for LCU
+ */
+Void TComPic::destroyNonDBFilterInfo()
+{
+  if(m_pbValidSlice != NULL)
+  {
+    delete[] m_pbValidSlice;
+    m_pbValidSlice = NULL;
+  }
+
+  if(m_pSliceSUMap != NULL)
+  {
+    delete[] m_pSliceSUMap;
+    m_pSliceSUMap = NULL;
+  }
+  for( UInt CUAddr = 0; CUAddr < getNumCUsInFrame() ; CUAddr++ )
+  {
+    TComDataCU* pcCU = getCU( CUAddr );
+    pcCU->getNDBFilterBlocks()->clear();
+  }
+
+  if( m_bIndependentSliceBoundaryForNDBFilter || m_bIndependentTileBoundaryForNDBFilter)
+  {
+    m_pNDBFilterYuvTmp->destroy();
+    delete m_pNDBFilterYuvTmp;
+    m_pNDBFilterYuvTmp = NULL;
+  }
+
+}
+
+#if REF_IDX_FRAMEWORK
+Void copyOnetoOnePicture(    // SVC_NONCOLL
+                  Pel *in,        
+                  Pel *out,      
+                  Int nCols,
+                  Int nRows, 
+                  Int fullRowWidth)
+{
+  Int rX;
+
+  for (rX = 0; rX < nRows; rX++)       
+  {
+    memcpy( out, in, sizeof(Pel) * nCols );
+    in = in + fullRowWidth;
+    out = out + fullRowWidth;
+  }
+}
+
+Void TComPic:: copyUpsampledPictureYuv(TComPicYuv*   pcPicYuvIn, TComPicYuv*   pcPicYuvOut)
+{
+  Int upsampledRowWidthLuma = pcPicYuvOut->getStride(); // 2 * pcPicYuvOut->getLumaMargin() + pcPicYuvOut->getWidth(); 
+  Int upsampledRowWidthCroma = pcPicYuvOut->getCStride(); //2 * pcPicYuvOut->getChromaMargin() + (pcPicYuvOut->getWidth()>>1);
+
+  copyOnetoOnePicture(
+    pcPicYuvIn->getLumaAddr(),        
+    pcPicYuvOut->getLumaAddr(),      
+    pcPicYuvOut->getWidth(), 
+    pcPicYuvOut->getHeight(),
+    upsampledRowWidthLuma);
+  copyOnetoOnePicture(
+    pcPicYuvIn->getCrAddr(),        
+    pcPicYuvOut->getCrAddr(),      
+    pcPicYuvOut->getWidth()>>1, 
+    pcPicYuvOut->getHeight()>>1,
+    upsampledRowWidthCroma);
+  copyOnetoOnePicture(
+    pcPicYuvIn->getCbAddr(),        
+    pcPicYuvOut->getCbAddr(),      
+    pcPicYuvOut->getWidth()>>1, 
+    pcPicYuvOut->getHeight()>>1,
+    upsampledRowWidthCroma);
+}
+#endif
+
+//! \}
Index: /trunk/source/Lib/TLibCommon/TComPic.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComPic.h	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComPic.h	(revision 2)
@@ -0,0 +1,210 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComPic.h
+    \brief    picture class (header)
+*/
+
+#ifndef __TCOMPIC__
+#define __TCOMPIC__
+
+// Include files
+#include "CommonDef.h"
+#include "TComPicSym.h"
+#include "TComPicYuv.h"
+#include "TComBitStream.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+class SEImessages;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// picture class (symbol + YUV buffers)
+class TComPic
+{
+private:
+  UInt                  m_uiTLayer;               //  Temporal layer
+#if SVC_EXTENSION
+  UInt                  m_layerId;              //  Layer ID
+#endif
+#if REF_IDX_ME_AROUND_ZEROMV
+  Bool                  m_bIsILR;                 //  Is ILR picture
+#endif
+  Bool                  m_bUsedByCurr;            //  Used by current picture
+  Bool                  m_bIsLongTerm;            //  IS long term picture
+  Bool                  m_bIsUsedAsLongTerm;      //  long term picture is used as reference before
+  TComPicSym*           m_apcPicSym;              //  Symbol
+  
+  TComPicYuv*           m_apcPicYuv[2];           //  Texture,  0:org / 1:rec
+  
+  TComPicYuv*           m_pcPicYuvPred;           //  Prediction
+  TComPicYuv*           m_pcPicYuvResi;           //  Residual
+  Bool                  m_bReconstructed;
+  Bool                  m_bNeededForOutput;
+  UInt                  m_uiCurrSliceIdx;         // Index of current slice  
+  Int*                  m_pSliceSUMap;
+  Bool*                 m_pbValidSlice;
+  Int                   m_sliceGranularityForNDBFilter;
+  Bool                  m_bIndependentSliceBoundaryForNDBFilter;
+  Bool                  m_bIndependentTileBoundaryForNDBFilter;
+  TComPicYuv*           m_pNDBFilterYuvTmp;    //!< temporary picture buffer when non-cross slice/tile boundary in-loop filtering is enabled
+  Bool                  m_bCheckLTMSB;
+  std::vector<std::vector<TComDataCU*> > m_vSliceCUDataLink;
+
+  SEImessages* m_SEIs; ///< Any SEI messages that have been received.  If !NULL we own the object.
+
+#if SVC_EXTENSION
+  Bool                  m_bSpatialEnhLayer;       // whether current layer is a spatial enhancement layer,
+  TComPicYuv*           m_pcFullPelBaseRec;    // upsampled base layer recontruction for difference domain inter prediction
+#endif
+
+public:
+  TComPic();
+  virtual ~TComPic();
+  
+#if SVC_UPSAMPLING
+  Void          create( Int iWidth, Int iHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth, TComSPS* pcSps = NULL, Bool bIsVirtual = false );
+#if REF_IDX_FRAMEWORK
+  Void          createWithOutYuv( Int iWidth, Int iHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth, TComSPS* pcSps = NULL, Bool bIsVirtual = false );  
+  Void          setPicYuvRec(TComPicYuv *pPicYuv) { m_apcPicYuv[1]=pPicYuv; }
+#endif
+#else
+  Void          create( Int iWidth, Int iHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth, Bool bIsVirtual = false );
+#endif
+  virtual Void  destroy();
+  
+  UInt          getTLayer()                { return m_uiTLayer;   }
+  Void          setTLayer( UInt uiTLayer ) { m_uiTLayer = uiTLayer; }
+#if SVC_EXTENSION
+  Void          setLayerId (UInt layerId) { m_layerId = layerId; }
+  UInt          getLayerId ()               { return m_layerId; }
+  Bool          isSpatialEnhLayer()             { return m_bSpatialEnhLayer; }
+  Void          setSpatialEnhLayerFlag (Bool b) { m_bSpatialEnhLayer = b; }
+  Void          setFullPelBaseRec   ( TComPicYuv* p) { m_pcFullPelBaseRec = p; }
+  TComPicYuv*   getFullPelBaseRec   ()  { return  m_pcFullPelBaseRec;  }
+#endif
+#if REF_IDX_ME_AROUND_ZEROMV
+  Void          setIsILR( Bool bIsILR)      {m_bIsILR = bIsILR;}
+  Bool          getIsILR()                  {return m_bIsILR;}
+#endif
+
+  Bool          getUsedByCurr()             { return m_bUsedByCurr; }
+  Void          setUsedByCurr( Bool bUsed ) { m_bUsedByCurr = bUsed; }
+  Bool          getIsLongTerm()             { return m_bIsLongTerm; }
+  Void          setIsLongTerm( Bool lt ) { m_bIsLongTerm = lt; }
+  Bool          getIsUsedAsLongTerm()          { return m_bIsUsedAsLongTerm; }
+  Void          setIsUsedAsLongTerm( Bool lt ) { m_bIsUsedAsLongTerm = lt; }
+  Void          setCheckLTMSBPresent     (Bool b ) {m_bCheckLTMSB=b;}
+  Bool          getCheckLTMSBPresent     () { return m_bCheckLTMSB;}
+
+  TComPicSym*   getPicSym()           { return  m_apcPicSym;    }
+  TComSlice*    getSlice(Int i)       { return  m_apcPicSym->getSlice(i);  }
+  Int           getPOC()              { return  m_apcPicSym->getSlice(m_uiCurrSliceIdx)->getPOC();  }
+  TComDataCU*&  getCU( UInt uiCUAddr )  { return  m_apcPicSym->getCU( uiCUAddr ); }
+  
+  TComPicYuv*   getPicYuvOrg()        { return  m_apcPicYuv[0]; }
+  TComPicYuv*   getPicYuvRec()        { return  m_apcPicYuv[1]; }
+  
+  TComPicYuv*   getPicYuvPred()       { return  m_pcPicYuvPred; }
+  TComPicYuv*   getPicYuvResi()       { return  m_pcPicYuvResi; }
+  Void          setPicYuvPred( TComPicYuv* pcPicYuv )       { m_pcPicYuvPred = pcPicYuv; }
+  Void          setPicYuvResi( TComPicYuv* pcPicYuv )       { m_pcPicYuvResi = pcPicYuv; }
+  
+  UInt          getNumCUsInFrame()      { return m_apcPicSym->getNumberOfCUsInFrame(); }
+  UInt          getNumPartInWidth()     { return m_apcPicSym->getNumPartInWidth();     }
+  UInt          getNumPartInHeight()    { return m_apcPicSym->getNumPartInHeight();    }
+  UInt          getNumPartInCU()        { return m_apcPicSym->getNumPartition();       }
+  UInt          getFrameWidthInCU()     { return m_apcPicSym->getFrameWidthInCU();     }
+  UInt          getFrameHeightInCU()    { return m_apcPicSym->getFrameHeightInCU();    }
+  UInt          getMinCUWidth()         { return m_apcPicSym->getMinCUWidth();         }
+  UInt          getMinCUHeight()        { return m_apcPicSym->getMinCUHeight();        }
+  
+  UInt          getParPelX(UChar uhPartIdx) { return getParPelX(uhPartIdx); }
+  UInt          getParPelY(UChar uhPartIdx) { return getParPelX(uhPartIdx); }
+  
+  Int           getStride()           { return m_apcPicYuv[1]->getStride(); }
+  Int           getCStride()          { return m_apcPicYuv[1]->getCStride(); }
+  
+  Void          setReconMark (Bool b) { m_bReconstructed = b;     }
+  Bool          getReconMark ()       { return m_bReconstructed;  }
+  Void          setOutputMark (Bool b) { m_bNeededForOutput = b;     }
+  Bool          getOutputMark ()       { return m_bNeededForOutput;  }
+ 
+
+  Void          compressMotion(); 
+  UInt          getCurrSliceIdx()            { return m_uiCurrSliceIdx;                }
+  Void          setCurrSliceIdx(UInt i)      { m_uiCurrSliceIdx = i;                   }
+  UInt          getNumAllocatedSlice()       {return m_apcPicSym->getNumAllocatedSlice();}
+  Void          allocateNewSlice()           {m_apcPicSym->allocateNewSlice();         }
+  Void          clearSliceBuffer()           {m_apcPicSym->clearSliceBuffer();         }
+
+  Void          createNonDBFilterInfo   (std::vector<Int> sliceStartAddress, Int sliceGranularityDepth
+                                        ,std::vector<Bool>* LFCrossSliceBoundary
+                                        ,Int  numTiles = 1
+                                        ,Bool bNDBFilterCrossTileBoundary = true);
+  Void          createNonDBFilterInfoLCU(Int tileID, Int sliceID, TComDataCU* pcCU, UInt startSU, UInt endSU, Int sliceGranularyDepth, UInt picWidth, UInt picHeight);
+  Void          destroyNonDBFilterInfo();
+
+  Bool          getValidSlice                                  (Int sliceID)  {return m_pbValidSlice[sliceID];}
+#if !REMOVE_FGS
+  Int           getSliceGranularityForNDBFilter                ()             {return m_sliceGranularityForNDBFilter;}
+#endif
+  Bool          getIndependentSliceBoundaryForNDBFilter        ()             {return m_bIndependentSliceBoundaryForNDBFilter;}
+  Bool          getIndependentTileBoundaryForNDBFilter         ()             {return m_bIndependentTileBoundaryForNDBFilter; }
+  TComPicYuv*   getYuvPicBufferForIndependentBoundaryProcessing()             {return m_pNDBFilterYuvTmp;}
+  std::vector<TComDataCU*>& getOneSliceCUDataForNDBFilter      (Int sliceID) { return m_vSliceCUDataLink[sliceID];}
+
+  /** transfer ownership of seis to this picture */
+  void setSEIs(SEImessages* seis) { m_SEIs = seis; }
+
+  /**
+   * return the current list of SEI messages associated with this picture.
+   * Pointer is valid until this->destroy() is called */
+  SEImessages* getSEIs() { return m_SEIs; }
+
+  /**
+   * return the current list of SEI messages associated with this picture.
+   * Pointer is valid until this->destroy() is called */
+  const SEImessages* getSEIs() const { return m_SEIs; }
+#if REF_IDX_FRAMEWORK
+  Void  copyUpsampledPictureYuv(TComPicYuv*   pcPicYuvIn, TComPicYuv*   pcPicYuvOut); 
+#endif
+};// END CLASS DEFINITION TComPic
+
+//! \}
+
+#endif // __TCOMPIC__
Index: /trunk/source/Lib/TLibCommon/TComPicSym.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComPicSym.cpp	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComPicSym.cpp	(revision 2)
@@ -0,0 +1,339 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComPicSym.cpp
+    \brief    picture symbol class
+*/
+
+#include "TComPicSym.h"
+#if REMOVE_APS
+#include "TComSampleAdaptiveOffset.h"
+#endif
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TComPicSym::TComPicSym()
+:m_uiWidthInCU(0)
+,m_uiHeightInCU(0)
+,m_uiMaxCUWidth(0)
+,m_uiMaxCUHeight(0)
+,m_uiMinCUWidth(0)
+,m_uiMinCUHeight(0)
+,m_uhTotalDepth(0)
+,m_uiNumPartitions(0)
+,m_uiNumPartInWidth(0)
+,m_uiNumPartInHeight(0)
+,m_uiNumCUsInFrame(0)
+,m_apcTComSlice(NULL)
+,m_uiNumAllocatedSlice (0)
+,m_apcTComDataCU (NULL)
+,m_iTileBoundaryIndependenceIdr (0)
+,m_iNumColumnsMinus1 (0)
+,m_iNumRowsMinus1(0)
+,m_apcTComTile(NULL)
+,m_puiCUOrderMap(0)
+,m_puiTileIdxMap(NULL)
+,m_puiInverseCUOrderMap(NULL)
+{};
+
+
+Void TComPicSym::create  ( Int iPicWidth, Int iPicHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth )
+{
+  UInt i;
+
+  m_uhTotalDepth      = uiMaxDepth;
+  m_uiNumPartitions   = 1<<(m_uhTotalDepth<<1);
+  
+  m_uiMaxCUWidth      = uiMaxWidth;
+  m_uiMaxCUHeight     = uiMaxHeight;
+  
+  m_uiMinCUWidth      = uiMaxWidth  >> m_uhTotalDepth;
+  m_uiMinCUHeight     = uiMaxHeight >> m_uhTotalDepth;
+  
+  m_uiNumPartInWidth  = m_uiMaxCUWidth  / m_uiMinCUWidth;
+  m_uiNumPartInHeight = m_uiMaxCUHeight / m_uiMinCUHeight;
+  
+  m_uiWidthInCU       = ( iPicWidth %m_uiMaxCUWidth  ) ? iPicWidth /m_uiMaxCUWidth  + 1 : iPicWidth /m_uiMaxCUWidth;
+  m_uiHeightInCU      = ( iPicHeight%m_uiMaxCUHeight ) ? iPicHeight/m_uiMaxCUHeight + 1 : iPicHeight/m_uiMaxCUHeight;
+  
+  m_uiNumCUsInFrame   = m_uiWidthInCU * m_uiHeightInCU;
+  m_apcTComDataCU     = new TComDataCU*[m_uiNumCUsInFrame];
+  
+  if (m_uiNumAllocatedSlice>0)
+  {
+    for ( i=0; i<m_uiNumAllocatedSlice ; i++ )
+    {
+      delete m_apcTComSlice[i];
+    }
+    delete [] m_apcTComSlice;
+  }
+  m_apcTComSlice      = new TComSlice*[m_uiNumCUsInFrame*m_uiNumPartitions];  
+  m_apcTComSlice[0]   = new TComSlice;
+  m_uiNumAllocatedSlice = 1;
+  for ( i=0; i<m_uiNumCUsInFrame ; i++ )
+  {
+    m_apcTComDataCU[i] = new TComDataCU;
+    m_apcTComDataCU[i]->create( m_uiNumPartitions, m_uiMaxCUWidth, m_uiMaxCUHeight, false, m_uiMaxCUWidth >> m_uhTotalDepth
+#if ADAPTIVE_QP_SELECTION
+      , true
+#endif     
+      );
+  }
+
+  m_puiCUOrderMap = new UInt[m_uiNumCUsInFrame+1];
+  m_puiTileIdxMap = new UInt[m_uiNumCUsInFrame];
+  m_puiInverseCUOrderMap = new UInt[m_uiNumCUsInFrame+1];
+
+  for( i=0; i<m_uiNumCUsInFrame; i++ )
+  {
+    m_puiCUOrderMap[i] = i;
+    m_puiInverseCUOrderMap[i] = i;
+  }
+#if REMOVE_APS
+  m_saoParam = NULL;
+#endif
+}
+
+Void TComPicSym::destroy()
+{
+  if (m_uiNumAllocatedSlice>0)
+  {
+    for (Int i = 0; i<m_uiNumAllocatedSlice ; i++ )
+    {
+      delete m_apcTComSlice[i];
+    }
+    delete [] m_apcTComSlice;
+  }
+  m_apcTComSlice = NULL;
+  
+  for (Int i = 0; i < m_uiNumCUsInFrame; i++)
+  {
+    m_apcTComDataCU[i]->destroy();
+    delete m_apcTComDataCU[i];
+    m_apcTComDataCU[i] = NULL;
+  }
+  delete [] m_apcTComDataCU;
+  m_apcTComDataCU = NULL;
+
+#if AVC_BASE || REF_IDX_FRAMEWORK
+  if( m_apcTComTile )
+  {
+#endif
+  for(Int i = 0; i < (m_iNumColumnsMinus1+1)*(m_iNumRowsMinus1+1); i++ )
+  {
+    delete m_apcTComTile[i];
+  }
+  delete [] m_apcTComTile;
+#if AVC_BASE || REF_IDX_FRAMEWORK
+  }
+#endif
+
+  m_apcTComTile = NULL;
+
+  delete [] m_puiCUOrderMap;
+  m_puiCUOrderMap = NULL;
+
+  delete [] m_puiTileIdxMap;
+  m_puiTileIdxMap = NULL;
+
+  delete [] m_puiInverseCUOrderMap;
+  m_puiInverseCUOrderMap = NULL;
+  
+#if REMOVE_APS
+  if (m_saoParam)
+  {
+    TComSampleAdaptiveOffset::freeSaoParam(m_saoParam);
+    delete m_saoParam;
+    m_saoParam = NULL;
+  }
+#endif
+}
+
+Void TComPicSym::allocateNewSlice()
+{
+  m_apcTComSlice[m_uiNumAllocatedSlice ++] = new TComSlice;
+  if (m_uiNumAllocatedSlice>=2)
+  {
+    m_apcTComSlice[m_uiNumAllocatedSlice-1]->copySliceInfo( m_apcTComSlice[m_uiNumAllocatedSlice-2] );
+    m_apcTComSlice[m_uiNumAllocatedSlice-1]->initSlice();
+  }
+}
+
+Void TComPicSym::clearSliceBuffer()
+{
+  UInt i;
+  for (i = 1; i < m_uiNumAllocatedSlice; i++)
+  {
+    delete m_apcTComSlice[i];
+  }
+  m_uiNumAllocatedSlice = 1;
+}
+
+UInt TComPicSym::getPicSCUEncOrder( UInt SCUAddr )
+{ 
+  return getInverseCUOrderMap(SCUAddr/m_uiNumPartitions)*m_uiNumPartitions + SCUAddr%m_uiNumPartitions; 
+}
+
+UInt TComPicSym::getPicSCUAddr( UInt SCUEncOrder )
+{
+  return getCUOrderMap(SCUEncOrder/m_uiNumPartitions)*m_uiNumPartitions + SCUEncOrder%m_uiNumPartitions;
+}
+
+Void TComPicSym::xCreateTComTileArray()
+{
+  m_apcTComTile = new TComTile*[(m_iNumColumnsMinus1+1)*(m_iNumRowsMinus1+1)];
+  for( UInt i=0; i<(m_iNumColumnsMinus1+1)*(m_iNumRowsMinus1+1); i++ )
+  {
+    m_apcTComTile[i] = new TComTile;
+  }
+}
+
+Void TComPicSym::xInitTiles()
+{
+  UInt  uiTileIdx;
+  UInt  uiColumnIdx = 0;
+  UInt  uiRowIdx = 0;
+  UInt  uiRightEdgePosInCU;
+  UInt  uiBottomEdgePosInCU;
+  Int   i, j;
+
+  //initialize each tile of the current picture
+  for( uiRowIdx=0; uiRowIdx < m_iNumRowsMinus1+1; uiRowIdx++ )
+  {
+    for( uiColumnIdx=0; uiColumnIdx < m_iNumColumnsMinus1+1; uiColumnIdx++ )
+    {
+      uiTileIdx = uiRowIdx * (m_iNumColumnsMinus1+1) + uiColumnIdx;
+
+      //initialize the RightEdgePosInCU for each tile
+      uiRightEdgePosInCU = 0;
+      for( i=0; i <= uiColumnIdx; i++ )
+      {
+        uiRightEdgePosInCU += this->getTComTile(uiRowIdx * (m_iNumColumnsMinus1+1) + i)->getTileWidth();
+      }
+      this->getTComTile(uiTileIdx)->setRightEdgePosInCU(uiRightEdgePosInCU-1);
+
+      //initialize the BottomEdgePosInCU for each tile
+      uiBottomEdgePosInCU = 0;
+      for( i=0; i <= uiRowIdx; i++ )
+      {
+        uiBottomEdgePosInCU += this->getTComTile(i * (m_iNumColumnsMinus1+1) + uiColumnIdx)->getTileHeight();
+      }
+      this->getTComTile(uiTileIdx)->setBottomEdgePosInCU(uiBottomEdgePosInCU-1);
+
+      //initialize the FirstCUAddr for each tile
+      this->getTComTile(uiTileIdx)->setFirstCUAddr( (this->getTComTile(uiTileIdx)->getBottomEdgePosInCU() - this->getTComTile(uiTileIdx)->getTileHeight() +1)*m_uiWidthInCU + 
+        this->getTComTile(uiTileIdx)->getRightEdgePosInCU() - this->getTComTile(uiTileIdx)->getTileWidth() + 1);
+    }
+  }
+
+  //initialize the TileIdxMap
+  for( i=0; i<m_uiNumCUsInFrame; i++)
+  {
+    for(j=0; j < m_iNumColumnsMinus1+1; j++)
+    {
+      if(i % m_uiWidthInCU <= this->getTComTile(j)->getRightEdgePosInCU())
+      {
+        uiColumnIdx = j;
+        j = m_iNumColumnsMinus1+1;
+      }
+    }
+    for(j=0; j < m_iNumRowsMinus1+1; j++)
+    {
+      if(i/m_uiWidthInCU <= this->getTComTile(j*(m_iNumColumnsMinus1 + 1))->getBottomEdgePosInCU())
+      {
+        uiRowIdx = j;
+        j = m_iNumRowsMinus1 + 1;
+      }
+    }
+    m_puiTileIdxMap[i] = uiRowIdx * (m_iNumColumnsMinus1 + 1) + uiColumnIdx;
+  }
+
+}
+
+UInt TComPicSym::xCalculateNxtCUAddr( UInt uiCurrCUAddr )
+{
+  UInt  uiNxtCUAddr;
+  UInt  uiTileIdx;
+  
+  //get the tile index for the current LCU
+  uiTileIdx = this->getTileIdxMap(uiCurrCUAddr);
+
+  //get the raster scan address for the next LCU
+  if( uiCurrCUAddr % m_uiWidthInCU == this->getTComTile(uiTileIdx)->getRightEdgePosInCU() && uiCurrCUAddr / m_uiWidthInCU == this->getTComTile(uiTileIdx)->getBottomEdgePosInCU() )
+  //the current LCU is the last LCU of the tile
+  {
+    if(uiTileIdx == (m_iNumColumnsMinus1+1)*(m_iNumRowsMinus1+1)-1)
+    {
+      uiNxtCUAddr = m_uiNumCUsInFrame;
+    }
+    else
+    {
+      uiNxtCUAddr = this->getTComTile(uiTileIdx+1)->getFirstCUAddr();
+    }
+  } 
+  else //the current LCU is not the last LCU of the tile
+  {
+    if( uiCurrCUAddr % m_uiWidthInCU == this->getTComTile(uiTileIdx)->getRightEdgePosInCU() )  //the current LCU is on the rightmost edge of the tile
+    {
+      uiNxtCUAddr = uiCurrCUAddr + m_uiWidthInCU - this->getTComTile(uiTileIdx)->getTileWidth() + 1;
+    }
+    else
+    {
+      uiNxtCUAddr = uiCurrCUAddr + 1;
+    }
+  }
+
+  return uiNxtCUAddr;
+}
+
+#if REMOVE_APS
+Void TComPicSym::allocSaoParam(TComSampleAdaptiveOffset *sao)
+{
+  m_saoParam = new SAOParam;
+  sao->allocSaoParam(m_saoParam);
+}
+#endif
+
+TComTile::TComTile()
+{
+}
+
+TComTile::~TComTile()
+{
+}
+//! \}
Index: /trunk/source/Lib/TLibCommon/TComPicSym.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComPicSym.h	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComPicSym.h	(revision 2)
@@ -0,0 +1,160 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComPicSym.h
+    \brief    picture symbol class (header)
+*/
+
+#ifndef __TCOMPICSYM__
+#define __TCOMPICSYM__
+
+
+// Include files
+#include "CommonDef.h"
+#include "TComSlice.h"
+#include "TComDataCU.h"
+#if REMOVE_APS
+class TComSampleAdaptiveOffset;
+#endif
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+class TComTile
+{
+private:
+  UInt      m_uiTileWidth;
+  UInt      m_uiTileHeight;
+  UInt      m_uiRightEdgePosInCU;
+  UInt      m_uiBottomEdgePosInCU;
+  UInt      m_uiFirstCUAddr;
+
+public:  
+  TComTile();
+  virtual ~TComTile();
+
+  Void      setTileWidth         ( UInt i )            { m_uiTileWidth = i; }
+  UInt      getTileWidth         ()                    { return m_uiTileWidth; }
+  Void      setTileHeight        ( UInt i )            { m_uiTileHeight = i; }
+  UInt      getTileHeight        ()                    { return m_uiTileHeight; }
+  Void      setRightEdgePosInCU  ( UInt i )            { m_uiRightEdgePosInCU = i; }
+  UInt      getRightEdgePosInCU  ()                    { return m_uiRightEdgePosInCU; }
+  Void      setBottomEdgePosInCU ( UInt i )            { m_uiBottomEdgePosInCU = i; }
+  UInt      getBottomEdgePosInCU ()                    { return m_uiBottomEdgePosInCU; }
+  Void      setFirstCUAddr       ( UInt i )            { m_uiFirstCUAddr = i; }
+  UInt      getFirstCUAddr       ()                    { return m_uiFirstCUAddr; }
+};
+
+/// picture symbol class
+class TComPicSym
+{
+private:
+  UInt          m_uiWidthInCU;
+  UInt          m_uiHeightInCU;
+  
+  UInt          m_uiMaxCUWidth;
+  UInt          m_uiMaxCUHeight;
+  UInt          m_uiMinCUWidth;
+  UInt          m_uiMinCUHeight;
+  
+  UChar         m_uhTotalDepth;       ///< max. depth
+  UInt          m_uiNumPartitions;
+  UInt          m_uiNumPartInWidth;
+  UInt          m_uiNumPartInHeight;
+  UInt          m_uiNumCUsInFrame;
+  
+  TComSlice**   m_apcTComSlice;
+  UInt          m_uiNumAllocatedSlice;
+  TComDataCU**  m_apcTComDataCU;        ///< array of CU data
+  
+  Int           m_iTileBoundaryIndependenceIdr;
+  Int           m_iNumColumnsMinus1; 
+  Int           m_iNumRowsMinus1;
+  TComTile**    m_apcTComTile;
+  UInt*         m_puiCUOrderMap;       //the map of LCU raster scan address relative to LCU encoding order 
+  UInt*         m_puiTileIdxMap;       //the map of the tile index relative to LCU raster scan address 
+  UInt*         m_puiInverseCUOrderMap;
+
+#if REMOVE_APS
+  SAOParam *m_saoParam;
+#endif
+public:
+  Void        create  ( Int iPicWidth, Int iPicHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth );
+  Void        destroy ();
+
+  TComPicSym  ();
+  TComSlice*  getSlice(UInt i)          { return  m_apcTComSlice[i];            }
+  UInt        getFrameWidthInCU()       { return m_uiWidthInCU;                 }
+  UInt        getFrameHeightInCU()      { return m_uiHeightInCU;                }
+  UInt        getMinCUWidth()           { return m_uiMinCUWidth;                }
+  UInt        getMinCUHeight()          { return m_uiMinCUHeight;               }
+  UInt        getNumberOfCUsInFrame()   { return m_uiNumCUsInFrame;  }
+  TComDataCU*&  getCU( UInt uiCUAddr )  { return m_apcTComDataCU[uiCUAddr];     }
+  
+  Void        setSlice(TComSlice* p, UInt i) { m_apcTComSlice[i] = p;           }
+  UInt        getNumAllocatedSlice()    { return m_uiNumAllocatedSlice;         }
+  Void        allocateNewSlice();
+  Void        clearSliceBuffer();
+  UInt        getNumPartition()         { return m_uiNumPartitions;             }
+  UInt        getNumPartInWidth()       { return m_uiNumPartInWidth;            }
+  UInt        getNumPartInHeight()      { return m_uiNumPartInHeight;           }
+  Void         setNumColumnsMinus1( Int i )                          { m_iNumColumnsMinus1 = i; }
+  Int          getNumColumnsMinus1()                                 { return m_iNumColumnsMinus1; }  
+  Void         setNumRowsMinus1( Int i )                             { m_iNumRowsMinus1 = i; }
+  Int          getNumRowsMinus1()                                    { return m_iNumRowsMinus1; }
+  Int          getNumTiles()                                         { return (m_iNumRowsMinus1+1)*(m_iNumColumnsMinus1+1); }
+  TComTile*    getTComTile  ( UInt tileIdx )                         { return *(m_apcTComTile + tileIdx); }
+  Void         setCUOrderMap( Int encCUOrder, Int cuAddr )           { *(m_puiCUOrderMap + encCUOrder) = cuAddr; }
+  UInt         getCUOrderMap( Int encCUOrder )                       { return *(m_puiCUOrderMap + (encCUOrder>=m_uiNumCUsInFrame ? m_uiNumCUsInFrame : encCUOrder)); }
+  UInt         getTileIdxMap( Int i )                                { return *(m_puiTileIdxMap + i); }
+  Void         setInverseCUOrderMap( Int cuAddr, Int encCUOrder )    { *(m_puiInverseCUOrderMap + cuAddr) = encCUOrder; }
+  UInt         getInverseCUOrderMap( Int cuAddr )                    { return *(m_puiInverseCUOrderMap + (cuAddr>=m_uiNumCUsInFrame ? m_uiNumCUsInFrame : cuAddr)); }
+  UInt         getPicSCUEncOrder( UInt SCUAddr );
+  UInt         getPicSCUAddr( UInt SCUEncOrder );
+  Void         xCreateTComTileArray();
+  Void         xInitTiles();
+  UInt         xCalculateNxtCUAddr( UInt uiCurrCUAddr );
+#if REMOVE_APS
+  Void allocSaoParam(TComSampleAdaptiveOffset *sao);
+  SAOParam *getSaoParam() { return m_saoParam; }
+#endif
+};// END CLASS DEFINITION TComPicSym
+
+//! \}
+
+#endif // __TCOMPICSYM__
+
Index: /trunk/source/Lib/TLibCommon/TComPicYuv.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComPicYuv.cpp	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComPicYuv.cpp	(revision 2)
@@ -0,0 +1,433 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComPicYuv.cpp
+    \brief    picture YUV buffer class
+*/
+
+#include <cstdlib>
+#include <assert.h>
+#include <memory.h>
+
+#ifdef __APPLE__
+#include <malloc/malloc.h>
+#else
+#include <malloc.h>
+#endif
+
+#include "TComPicYuv.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+TComPicYuv::TComPicYuv()
+{
+  m_apiPicBufY      = NULL;   // Buffer (including margin)
+  m_apiPicBufU      = NULL;
+  m_apiPicBufV      = NULL;
+  
+  m_piPicOrgY       = NULL;    // m_apiPicBufY + m_iMarginLuma*getStride() + m_iMarginLuma
+  m_piPicOrgU       = NULL;
+  m_piPicOrgV       = NULL;
+  
+#if SVC_UPSAMPLING
+  m_picCropLeftOffset   = 0;
+  m_picCropRightOffset  = 0;
+  m_picCropTopOffset    = 0;
+  m_picCropBottomOffset = 0;
+#endif
+
+  m_bIsBorderExtended = false;
+}
+
+TComPicYuv::~TComPicYuv()
+{
+}
+#if SVC_UPSAMPLING
+Void TComPicYuv::create( Int iPicWidth, Int iPicHeight, UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxCUDepth, TComSPS* pcSps )
+#else
+Void TComPicYuv::create( Int iPicWidth, Int iPicHeight, UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxCUDepth )
+#endif
+{
+  m_iPicWidth       = iPicWidth;
+  m_iPicHeight      = iPicHeight;
+  
+#if SVC_UPSAMPLING
+  if(pcSps != NULL)
+  {
+    m_picCropLeftOffset   = pcSps->getPicCropLeftOffset();
+    m_picCropRightOffset  = pcSps->getPicCropRightOffset();
+    m_picCropTopOffset    = pcSps->getPicCropTopOffset();
+    m_picCropBottomOffset = pcSps->getPicCropBottomOffset();
+  }
+#endif
+
+  // --> After config finished!
+  m_iCuWidth        = uiMaxCUWidth;
+  m_iCuHeight       = uiMaxCUHeight;
+
+  Int numCuInWidth  = m_iPicWidth  / m_iCuWidth  + (m_iPicWidth  % m_iCuWidth  != 0);
+  Int numCuInHeight = m_iPicHeight / m_iCuHeight + (m_iPicHeight % m_iCuHeight != 0);
+  
+  m_iLumaMarginX    = g_uiMaxCUWidth  + 16; // for 16-byte alignment
+  m_iLumaMarginY    = g_uiMaxCUHeight + 16;  // margin for 8-tap filter and infinite padding
+  
+  m_iChromaMarginX  = m_iLumaMarginX>>1;
+  m_iChromaMarginY  = m_iLumaMarginY>>1;
+  
+  m_apiPicBufY      = (Pel*)xMalloc( Pel, ( m_iPicWidth       + (m_iLumaMarginX  <<1)) * ( m_iPicHeight       + (m_iLumaMarginY  <<1)));
+  m_apiPicBufU      = (Pel*)xMalloc( Pel, ((m_iPicWidth >> 1) + (m_iChromaMarginX<<1)) * ((m_iPicHeight >> 1) + (m_iChromaMarginY<<1)));
+  m_apiPicBufV      = (Pel*)xMalloc( Pel, ((m_iPicWidth >> 1) + (m_iChromaMarginX<<1)) * ((m_iPicHeight >> 1) + (m_iChromaMarginY<<1)));
+  
+  m_piPicOrgY       = m_apiPicBufY + m_iLumaMarginY   * getStride()  + m_iLumaMarginX;
+  m_piPicOrgU       = m_apiPicBufU + m_iChromaMarginY * getCStride() + m_iChromaMarginX;
+  m_piPicOrgV       = m_apiPicBufV + m_iChromaMarginY * getCStride() + m_iChromaMarginX;
+  
+  m_bIsBorderExtended = false;
+  
+  m_cuOffsetY = new Int[numCuInWidth * numCuInHeight];
+  m_cuOffsetC = new Int[numCuInWidth * numCuInHeight];
+  for (Int cuRow = 0; cuRow < numCuInHeight; cuRow++)
+  {
+    for (Int cuCol = 0; cuCol < numCuInWidth; cuCol++)
+    {
+      m_cuOffsetY[cuRow * numCuInWidth + cuCol] = getStride() * cuRow * m_iCuHeight + cuCol * m_iCuWidth;
+      m_cuOffsetC[cuRow * numCuInWidth + cuCol] = getCStride() * cuRow * (m_iCuHeight / 2) + cuCol * (m_iCuWidth / 2);
+    }
+  }
+  
+  m_buOffsetY = new Int[(size_t)1 << (2 * uiMaxCUDepth)];
+  m_buOffsetC = new Int[(size_t)1 << (2 * uiMaxCUDepth)];
+  for (Int buRow = 0; buRow < (1 << uiMaxCUDepth); buRow++)
+  {
+    for (Int buCol = 0; buCol < (1 << uiMaxCUDepth); buCol++)
+    {
+      m_buOffsetY[(buRow << uiMaxCUDepth) + buCol] = getStride() * buRow * (uiMaxCUHeight >> uiMaxCUDepth) + buCol * (uiMaxCUWidth  >> uiMaxCUDepth);
+      m_buOffsetC[(buRow << uiMaxCUDepth) + buCol] = getCStride() * buRow * (uiMaxCUHeight / 2 >> uiMaxCUDepth) + buCol * (uiMaxCUWidth / 2 >> uiMaxCUDepth);
+    }
+  }
+  return;
+}
+
+Void TComPicYuv::destroy()
+{
+  m_piPicOrgY       = NULL;
+  m_piPicOrgU       = NULL;
+  m_piPicOrgV       = NULL;
+  
+  if( m_apiPicBufY ){ xFree( m_apiPicBufY );    m_apiPicBufY = NULL; }
+  if( m_apiPicBufU ){ xFree( m_apiPicBufU );    m_apiPicBufU = NULL; }
+  if( m_apiPicBufV ){ xFree( m_apiPicBufV );    m_apiPicBufV = NULL; }
+
+  delete[] m_cuOffsetY;
+  delete[] m_cuOffsetC;
+  delete[] m_buOffsetY;
+  delete[] m_buOffsetC;
+}
+
+Void TComPicYuv::createLuma( Int iPicWidth, Int iPicHeight, UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxCUDepth )
+{
+  m_iPicWidth       = iPicWidth;
+  m_iPicHeight      = iPicHeight;
+  
+  // --> After config finished!
+  m_iCuWidth        = uiMaxCUWidth;
+  m_iCuHeight       = uiMaxCUHeight;
+  
+  Int numCuInWidth  = m_iPicWidth  / m_iCuWidth  + (m_iPicWidth  % m_iCuWidth  != 0);
+  Int numCuInHeight = m_iPicHeight / m_iCuHeight + (m_iPicHeight % m_iCuHeight != 0);
+  
+  m_iLumaMarginX    = g_uiMaxCUWidth  + 16; // for 16-byte alignment
+  m_iLumaMarginY    = g_uiMaxCUHeight + 16;  // margin for 8-tap filter and infinite padding
+  
+  m_apiPicBufY      = (Pel*)xMalloc( Pel, ( m_iPicWidth       + (m_iLumaMarginX  <<1)) * ( m_iPicHeight       + (m_iLumaMarginY  <<1)));
+  m_piPicOrgY       = m_apiPicBufY + m_iLumaMarginY   * getStride()  + m_iLumaMarginX;
+  
+  m_cuOffsetY = new Int[numCuInWidth * numCuInHeight];
+  m_cuOffsetC = NULL;
+  for (Int cuRow = 0; cuRow < numCuInHeight; cuRow++)
+  {
+    for (Int cuCol = 0; cuCol < numCuInWidth; cuCol++)
+    {
+      m_cuOffsetY[cuRow * numCuInWidth + cuCol] = getStride() * cuRow * m_iCuHeight + cuCol * m_iCuWidth;
+    }
+  }
+  
+  m_buOffsetY = new Int[(size_t)1 << (2 * uiMaxCUDepth)];
+  m_buOffsetC = NULL;
+  for (Int buRow = 0; buRow < (1 << uiMaxCUDepth); buRow++)
+  {
+    for (Int buCol = 0; buCol < (1 << uiMaxCUDepth); buCol++)
+    {
+      m_buOffsetY[(buRow << uiMaxCUDepth) + buCol] = getStride() * buRow * (uiMaxCUHeight >> uiMaxCUDepth) + buCol * (uiMaxCUWidth  >> uiMaxCUDepth);
+    }
+  }
+  return;
+}
+
+Void TComPicYuv::destroyLuma()
+{
+  m_piPicOrgY       = NULL;
+  
+  if( m_apiPicBufY ){ xFree( m_apiPicBufY );    m_apiPicBufY = NULL; }
+  
+  delete[] m_cuOffsetY;
+  delete[] m_buOffsetY;
+}
+
+Void  TComPicYuv::copyToPic (TComPicYuv*  pcPicYuvDst)
+{
+  assert( m_iPicWidth  == pcPicYuvDst->getWidth()  );
+  assert( m_iPicHeight == pcPicYuvDst->getHeight() );
+  
+  ::memcpy ( pcPicYuvDst->getBufY(), m_apiPicBufY, sizeof (Pel) * ( m_iPicWidth       + (m_iLumaMarginX   << 1)) * ( m_iPicHeight       + (m_iLumaMarginY   << 1)) );
+  ::memcpy ( pcPicYuvDst->getBufU(), m_apiPicBufU, sizeof (Pel) * ((m_iPicWidth >> 1) + (m_iChromaMarginX << 1)) * ((m_iPicHeight >> 1) + (m_iChromaMarginY << 1)) );
+  ::memcpy ( pcPicYuvDst->getBufV(), m_apiPicBufV, sizeof (Pel) * ((m_iPicWidth >> 1) + (m_iChromaMarginX << 1)) * ((m_iPicHeight >> 1) + (m_iChromaMarginY << 1)) );
+  return;
+}
+
+Void  TComPicYuv::copyToPicLuma (TComPicYuv*  pcPicYuvDst)
+{
+  assert( m_iPicWidth  == pcPicYuvDst->getWidth()  );
+  assert( m_iPicHeight == pcPicYuvDst->getHeight() );
+  
+  ::memcpy ( pcPicYuvDst->getBufY(), m_apiPicBufY, sizeof (Pel) * ( m_iPicWidth       + (m_iLumaMarginX   << 1)) * ( m_iPicHeight       + (m_iLumaMarginY   << 1)) );
+  return;
+}
+
+Void  TComPicYuv::copyToPicCb (TComPicYuv*  pcPicYuvDst)
+{
+  assert( m_iPicWidth  == pcPicYuvDst->getWidth()  );
+  assert( m_iPicHeight == pcPicYuvDst->getHeight() );
+  
+  ::memcpy ( pcPicYuvDst->getBufU(), m_apiPicBufU, sizeof (Pel) * ((m_iPicWidth >> 1) + (m_iChromaMarginX << 1)) * ((m_iPicHeight >> 1) + (m_iChromaMarginY << 1)) );
+  return;
+}
+
+Void  TComPicYuv::copyToPicCr (TComPicYuv*  pcPicYuvDst)
+{
+  assert( m_iPicWidth  == pcPicYuvDst->getWidth()  );
+  assert( m_iPicHeight == pcPicYuvDst->getHeight() );
+  
+  ::memcpy ( pcPicYuvDst->getBufV(), m_apiPicBufV, sizeof (Pel) * ((m_iPicWidth >> 1) + (m_iChromaMarginX << 1)) * ((m_iPicHeight >> 1) + (m_iChromaMarginY << 1)) );
+  return;
+}
+
+
+Void TComPicYuv::getLumaMinMax( Int *pMin, Int *pMax )
+{
+  Pel*  piY   = getLumaAddr();
+  Int   iMin  = (1<<(g_uiBitDepth))-1;
+  Int   iMax  = 0;
+  Int   x, y;
+  
+  for ( y = 0; y < m_iPicHeight; y++ )
+  {
+    for ( x = 0; x < m_iPicWidth; x++ )
+    {
+      if ( piY[x] < iMin ) iMin = piY[x];
+      if ( piY[x] > iMax ) iMax = piY[x];
+    }
+    piY += getStride();
+  }
+  
+  *pMin = iMin;
+  *pMax = iMax;
+}
+
+Void TComPicYuv::extendPicBorder ()
+{
+  if ( m_bIsBorderExtended ) return;
+  
+  xExtendPicCompBorder( getLumaAddr(), getStride(),  getWidth(),      getHeight(),      m_iLumaMarginX,   m_iLumaMarginY   );
+  xExtendPicCompBorder( getCbAddr()  , getCStride(), getWidth() >> 1, getHeight() >> 1, m_iChromaMarginX, m_iChromaMarginY );
+  xExtendPicCompBorder( getCrAddr()  , getCStride(), getWidth() >> 1, getHeight() >> 1, m_iChromaMarginX, m_iChromaMarginY );
+  
+  m_bIsBorderExtended = true;
+}
+
+Void TComPicYuv::xExtendPicCompBorder  (Pel* piTxt, Int iStride, Int iWidth, Int iHeight, Int iMarginX, Int iMarginY)
+{
+  Int   x, y;
+  Pel*  pi;
+  
+  pi = piTxt;
+  for ( y = 0; y < iHeight; y++)
+  {
+    for ( x = 0; x < iMarginX; x++ )
+    {
+      pi[ -iMarginX + x ] = pi[0];
+      pi[    iWidth + x ] = pi[iWidth-1];
+    }
+    pi += iStride;
+  }
+  
+  pi -= (iStride + iMarginX);
+  for ( y = 0; y < iMarginY; y++ )
+  {
+    ::memcpy( pi + (y+1)*iStride, pi, sizeof(Pel)*(iWidth + (iMarginX<<1)) );
+  }
+  
+  pi -= ((iHeight-1) * iStride);
+  for ( y = 0; y < iMarginY; y++ )
+  {
+    ::memcpy( pi - (y+1)*iStride, pi, sizeof(Pel)*(iWidth + (iMarginX<<1)) );
+  }
+}
+
+
+Void TComPicYuv::dump (char* pFileName, Bool bAdd)
+{
+  FILE* pFile;
+  if (!bAdd)
+  {
+    pFile = fopen (pFileName, "wb");
+  }
+  else
+  {
+    pFile = fopen (pFileName, "ab");
+  }
+  
+  Int     shift = g_uiBitIncrement;
+  Int     offset = (shift>0)?(1<<(shift-1)):0;
+  
+  Int   x, y;
+  UChar uc;
+  
+  Pel*  piY   = getLumaAddr();
+  Pel*  piCb  = getCbAddr();
+  Pel*  piCr  = getCrAddr();
+  
+  Pel  iMax = ((1<<(g_uiBitDepth))-1);
+  
+  for ( y = 0; y < m_iPicHeight; y++ )
+  {
+    for ( x = 0; x < m_iPicWidth; x++ )
+    {
+      uc = (UChar)Clip3<Pel>(0, iMax, (piY[x]+offset)>>shift);
+      
+      fwrite( &uc, sizeof(UChar), 1, pFile );
+    }
+    piY += getStride();
+  }
+  
+  for ( y = 0; y < m_iPicHeight >> 1; y++ )
+  {
+    for ( x = 0; x < m_iPicWidth >> 1; x++ )
+    {
+      uc = (UChar)Clip3<Pel>(0, iMax, (piCb[x]+offset)>>shift);
+      fwrite( &uc, sizeof(UChar), 1, pFile );
+    }
+    piCb += getCStride();
+  }
+  
+  for ( y = 0; y < m_iPicHeight >> 1; y++ )
+  {
+    for ( x = 0; x < m_iPicWidth >> 1; x++ )
+    {
+      uc = (UChar)Clip3<Pel>(0, iMax, (piCr[x]+offset)>>shift);
+      fwrite( &uc, sizeof(UChar), 1, pFile );
+    }
+    piCr += getCStride();
+  }
+  
+  fclose(pFile);
+}
+
+#if FIXED_ROUNDING_FRAME_MEMORY
+Void TComPicYuv::xFixedRoundingPic()
+{
+  Int   x, y;
+  Pel*  pRec    = getLumaAddr();
+  Int   iStride = getStride();
+  Int   iWidth  = getWidth();
+  Int   iHeight = getHeight();
+#if FULL_NBIT
+  Int   iOffset  = ((g_uiBitDepth-8)>0)?(1<<(g_uiBitDepth-8-1)):0;
+  Int   iMask   = (~0<<(g_uiBitDepth-8));
+  Int   iMaxBdi = g_uiBASE_MAX<<(g_uiBitDepth-8);
+#else
+  Int   iOffset  = (g_uiBitIncrement>0)?(1<<(g_uiBitIncrement-1)):0;
+  Int   iMask   = (~0<<g_uiBitIncrement);
+  Int   iMaxBdi = g_uiBASE_MAX<<g_uiBitIncrement;
+#endif
+
+  for( y = 0; y < iHeight; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+#if IBDI_NOCLIP_RANGE
+      pRec[x] = ( pRec[x] + iOffset ) & iMask;
+#else
+      pRec[x] = ( pRec[x]+iOffset>iMaxBdi)? iMaxBdi : ((pRec[x]+iOffset) & iMask);
+#endif
+    }
+    pRec += iStride;
+  }
+
+  iHeight >>= 1;
+  iWidth  >>= 1;
+  iStride >>= 1;
+  pRec  = getCbAddr();
+
+  for( y = 0; y < iHeight; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+#if IBDI_NOCLIP_RANGE
+      pRec[x] = ( pRec[x] + iOffset ) & iMask;
+#else
+      pRec[x] = ( pRec[x]+iOffset>iMaxBdi)? iMaxBdi : ((pRec[x]+iOffset) & iMask);
+#endif
+    }
+    pRec += iStride;
+  }
+
+  pRec  = getCrAddr();
+
+  for( y = 0; y < iHeight; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+#if IBDI_NOCLIP_RANGE
+      pRec[x] = ( pRec[x] + iOffset ) & iMask;
+#else
+      pRec[x] = ( pRec[x]+iOffset>iMaxBdi)? iMaxBdi : ((pRec[x]+iOffset) & iMask);
+#endif
+    }
+    pRec += iStride;
+  }
+}
+#endif
+
+//! \}
Index: /trunk/source/Lib/TLibCommon/TComPicYuv.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComPicYuv.h	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComPicYuv.h	(revision 2)
@@ -0,0 +1,200 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComPicYuv.h
+    \brief    picture YUV buffer class (header)
+*/
+
+#ifndef __TCOMPICYUV__
+#define __TCOMPICYUV__
+
+#include <stdio.h>
+#include "CommonDef.h"
+#include "TComRom.h"
+#if SVC_UPSAMPLING
+#include "TComSlice.h"
+#endif
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// picture YUV buffer class
+class TComPicYuv
+{
+private:
+  
+  // ------------------------------------------------------------------------------------------------
+  //  YUV buffer
+  // ------------------------------------------------------------------------------------------------
+  
+  Pel*  m_apiPicBufY;           ///< Buffer (including margin)
+  Pel*  m_apiPicBufU;
+  Pel*  m_apiPicBufV;
+  
+  Pel*  m_piPicOrgY;            ///< m_apiPicBufY + m_iMarginLuma*getStride() + m_iMarginLuma
+  Pel*  m_piPicOrgU;
+  Pel*  m_piPicOrgV;
+  
+  // ------------------------------------------------------------------------------------------------
+  //  Parameter for general YUV buffer usage
+  // ------------------------------------------------------------------------------------------------
+  
+  Int   m_iPicWidth;            ///< Width of picture
+  Int   m_iPicHeight;           ///< Height of picture
+  
+  Int   m_iCuWidth;             ///< Width of Coding Unit (CU)
+  Int   m_iCuHeight;            ///< Height of Coding Unit (CU)
+  Int*  m_cuOffsetY;
+  Int*  m_cuOffsetC;
+  Int*  m_buOffsetY;
+  Int*  m_buOffsetC;
+  
+  Int   m_iLumaMarginX;
+  Int   m_iLumaMarginY;
+  Int   m_iChromaMarginX;
+  Int   m_iChromaMarginY;
+  
+#if SVC_UPSAMPLING
+  Int   m_picCropLeftOffset;
+  Int   m_picCropRightOffset;
+  Int   m_picCropTopOffset;
+  Int   m_picCropBottomOffset;
+#endif
+
+  Bool  m_bIsBorderExtended;
+  
+protected:
+  Void  xExtendPicCompBorder (Pel* piTxt, Int iStride, Int iWidth, Int iHeight, Int iMarginX, Int iMarginY);
+  
+public:
+  TComPicYuv         ();
+  virtual ~TComPicYuv();
+  
+  // ------------------------------------------------------------------------------------------------
+  //  Memory management
+  // ------------------------------------------------------------------------------------------------
+#if SVC_UPSAMPLING
+  Void  create      ( Int iPicWidth, Int iPicHeight, UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxCUDepth, TComSPS* pcSps = NULL);
+#else
+  Void  create      ( Int iPicWidth, Int iPicHeight, UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxCUDepth );
+#endif  
+  
+  Void  destroy     ();
+  
+  Void  createLuma  ( Int iPicWidth, Int iPicHeight, UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uhMaxCUDepth );
+  Void  destroyLuma ();
+  
+  // ------------------------------------------------------------------------------------------------
+  //  Get information of picture
+  // ------------------------------------------------------------------------------------------------
+  
+  Int   getWidth    ()     { return  m_iPicWidth;    }
+  Int   getHeight   ()     { return  m_iPicHeight;   }
+
+#if SVC_EXTENSION
+  Void   setHeight   ( Int iPicHeight )     { m_iPicHeight = iPicHeight; }
+#endif
+
+  Int   getStride   ()     { return (m_iPicWidth     ) + (m_iLumaMarginX  <<1); }
+  Int   getCStride  ()     { return (m_iPicWidth >> 1) + (m_iChromaMarginX<<1); }
+  
+  Int   getLumaMargin   () { return m_iLumaMarginX;  }
+  Int   getChromaMargin () { return m_iChromaMarginX;}
+  
+  Void  getLumaMinMax( Int* pMin, Int* pMax );
+  
+  // ------------------------------------------------------------------------------------------------
+  //  Access function for picture buffer
+  // ------------------------------------------------------------------------------------------------
+  
+  //  Access starting position of picture buffer with margin
+  Pel*  getBufY     ()     { return  m_apiPicBufY;   }
+  Pel*  getBufU     ()     { return  m_apiPicBufU;   }
+  Pel*  getBufV     ()     { return  m_apiPicBufV;   }
+  
+  //  Access starting position of original picture
+  Pel*  getLumaAddr ()     { return  m_piPicOrgY;    }
+  Pel*  getCbAddr   ()     { return  m_piPicOrgU;    }
+  Pel*  getCrAddr   ()     { return  m_piPicOrgV;    }
+  
+  //  Access starting position of original picture for specific coding unit (CU) or partition unit (PU)
+  Pel*  getLumaAddr ( Int iCuAddr ) { return m_piPicOrgY + m_cuOffsetY[ iCuAddr ]; }
+  Pel*  getCbAddr   ( Int iCuAddr ) { return m_piPicOrgU + m_cuOffsetC[ iCuAddr ]; }
+  Pel*  getCrAddr   ( Int iCuAddr ) { return m_piPicOrgV + m_cuOffsetC[ iCuAddr ]; }
+  Pel*  getLumaAddr ( Int iCuAddr, Int uiAbsZorderIdx ) { return m_piPicOrgY + m_cuOffsetY[iCuAddr] + m_buOffsetY[g_auiZscanToRaster[uiAbsZorderIdx]]; }
+  Pel*  getCbAddr   ( Int iCuAddr, Int uiAbsZorderIdx ) { return m_piPicOrgU + m_cuOffsetC[iCuAddr] + m_buOffsetC[g_auiZscanToRaster[uiAbsZorderIdx]]; }
+  Pel*  getCrAddr   ( Int iCuAddr, Int uiAbsZorderIdx ) { return m_piPicOrgV + m_cuOffsetC[iCuAddr] + m_buOffsetC[g_auiZscanToRaster[uiAbsZorderIdx]]; }
+  
+#if SVC_UPSAMPLING
+  Int  getPicCropLeftOffset() const        { return m_picCropLeftOffset; }
+  Void setPicCropLeftOffset(Int val)       { m_picCropLeftOffset = val; }
+  Int  getPicCropRightOffset() const       { return m_picCropRightOffset; }
+  Void setPicCropRightOffset(Int val)      { m_picCropRightOffset = val; }
+  Int  getPicCropTopOffset() const         { return m_picCropTopOffset; }
+  Void setPicCropTopOffset(Int val)        { m_picCropTopOffset = val; }
+  Int  getPicCropBottomOffset() const      { return m_picCropBottomOffset; }
+  Void setPicCropBottomOffset(Int val)     { m_picCropBottomOffset = val; }
+#endif
+
+  // ------------------------------------------------------------------------------------------------
+  //  Miscellaneous
+  // ------------------------------------------------------------------------------------------------
+  
+  //  Copy function to picture
+  Void  copyToPic       ( TComPicYuv*  pcPicYuvDst );
+  Void  copyToPicLuma   ( TComPicYuv*  pcPicYuvDst );
+  Void  copyToPicCb     ( TComPicYuv*  pcPicYuvDst );
+  Void  copyToPicCr     ( TComPicYuv*  pcPicYuvDst );
+  
+  //  Extend function of picture buffer
+  Void  extendPicBorder      ();
+  
+  //  Dump picture
+  Void  dump (char* pFileName, Bool bAdd = false);
+  
+  // Set border extension flag
+  Void  setBorderExtension(Bool b) { m_bIsBorderExtended = b; }
+#if FIXED_ROUNDING_FRAME_MEMORY
+  Void  xFixedRoundingPic();
+#endif  
+};// END CLASS DEFINITION TComPicYuv
+
+void calcChecksum(TComPicYuv& pic, unsigned char digest[3][16]);
+void calcCRC(TComPicYuv& pic, unsigned char digest[3][16]);
+void calcMD5(TComPicYuv& pic, unsigned char digest[3][16]);
+//! \}
+
+#endif // __TCOMPICYUV__
Index: /trunk/source/Lib/TLibCommon/TComPicYuvMD5.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComPicYuvMD5.cpp	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComPicYuvMD5.cpp	(revision 2)
@@ -0,0 +1,207 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "TComPicYuv.h"
+#include "libmd5/MD5.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+/**
+ * Update md5 using n samples from plane, each sample is adjusted to
+ * OUTBIT_BITDEPTH_DIV8.
+ */
+template<unsigned OUTPUT_BITDEPTH_DIV8>
+static void md5_block(MD5& md5, const Pel* plane, unsigned n)
+{
+  /* create a 64 byte buffer for packing Pel's into */
+  unsigned char buf[64/OUTPUT_BITDEPTH_DIV8][OUTPUT_BITDEPTH_DIV8];
+  for (unsigned i = 0; i < n; i++)
+  {
+    Pel pel = plane[i];
+    /* perform bitdepth and endian conversion */
+    for (unsigned d = 0; d < OUTPUT_BITDEPTH_DIV8; d++)
+    {
+      buf[i][d] = pel >> (d*8);
+    }
+  }
+  md5.update((unsigned char*)buf, n * OUTPUT_BITDEPTH_DIV8);
+}
+
+/**
+ * Update md5 with all samples in plane in raster order, each sample
+ * is adjusted to OUTBIT_BITDEPTH_DIV8.
+ */
+template<unsigned OUTPUT_BITDEPTH_DIV8>
+static void md5_plane(MD5& md5, const Pel* plane, unsigned width, unsigned height, unsigned stride)
+{
+  /* N is the number of samples to process per md5 update.
+   * All N samples must fit in buf */
+  unsigned N = 32;
+  unsigned width_modN = width % N;
+  unsigned width_less_modN = width - width_modN;
+
+  for (unsigned y = 0; y < height; y++)
+  {
+    /* convert pel's into unsigned chars in little endian byte order.
+     * NB, for 8bit data, data is truncated to 8bits. */
+    for (unsigned x = 0; x < width_less_modN; x += N)
+      md5_block<OUTPUT_BITDEPTH_DIV8>(md5, &plane[y*stride + x], N);
+
+    /* mop up any of the remaining line */
+    md5_block<OUTPUT_BITDEPTH_DIV8>(md5, &plane[y*stride + width_less_modN], width_modN);
+  }
+}
+
+void compCRC(const Pel* plane, unsigned int width, unsigned int height, unsigned int stride, unsigned char digest[16])
+{
+  unsigned int bitdepth = g_uiBitDepth + g_uiBitIncrement;
+  unsigned int dataMsbIdx = bitdepth - 1;
+  unsigned int crcMsb;
+  unsigned int bitVal;
+  unsigned int crcVal = 0xffff;
+  unsigned int bitIdx;
+  for (unsigned y = 0; y < height; y++)
+  {
+    for (unsigned x = 0; x < width; x++)
+    {     
+      for(bitIdx=0; bitIdx<bitdepth; bitIdx++)
+      {
+        crcMsb = (crcVal >> 15) & 1;
+        bitVal = (plane[y*stride+x]>> (dataMsbIdx - (bitIdx&dataMsbIdx))) & 1;
+        crcVal = (((crcVal << 1) + bitVal) & 0xffff) ^ (crcMsb * 0x1021);
+      }
+    }
+  }
+  for(bitIdx=0; bitIdx<16; bitIdx++)
+  {
+    crcMsb = (crcVal >> 15) & 1;
+    crcVal = ((crcVal << 1) & 0xffff) ^ (crcMsb * 0x1021);
+  }
+
+  digest[0] = (crcVal>>8)  & 0xff;
+  digest[1] =  crcVal      & 0xff;
+}
+
+void calcCRC(TComPicYuv& pic, unsigned char digest[3][16])
+{
+  unsigned width = pic.getWidth();
+  unsigned height = pic.getHeight();
+  unsigned stride = pic.getStride();
+
+  compCRC(pic.getLumaAddr(), width, height, stride, digest[0]);
+
+  width >>= 1;
+  height >>= 1;
+  stride >>= 1;
+
+  compCRC(pic.getCbAddr(), width, height, stride, digest[1]);
+  compCRC(pic.getCrAddr(), width, height, stride, digest[2]);
+}
+
+void compChecksum(const Pel* plane, unsigned int width, unsigned int height, unsigned int stride, unsigned char digest[16])
+{
+  unsigned int bitdepth = g_uiBitDepth + g_uiBitIncrement;
+
+  unsigned int checksum = 0;
+  unsigned char xor_mask;
+
+  for (unsigned y = 0; y < height; y++)
+  {
+    for (unsigned x = 0; x < width; x++)
+    {
+      xor_mask = (x & 0xff) ^ (y & 0xff) ^ (x >> 8) ^ (y >> 8);
+      checksum = (checksum + ((plane[y*stride+x] & 0xff) ^ xor_mask)) & 0xffffffff;
+
+      if(bitdepth > 8)
+      {
+        checksum = (checksum + ((plane[y*stride+x]>>8) ^ xor_mask)) & 0xffffffff;
+      }
+    }
+  }
+
+  digest[0] = (checksum>>24) & 0xff;
+  digest[1] = (checksum>>16) & 0xff;
+  digest[2] = (checksum>>8)  & 0xff;
+  digest[3] =  checksum      & 0xff;
+}
+
+void calcChecksum(TComPicYuv& pic, unsigned char digest[3][16])
+{
+  unsigned width = pic.getWidth();
+  unsigned height = pic.getHeight();
+  unsigned stride = pic.getStride();
+
+  compChecksum(pic.getLumaAddr(), width, height, stride, digest[0]);
+
+  width >>= 1;
+  height >>= 1;
+  stride >>= 1;
+
+  compChecksum(pic.getCbAddr(), width, height, stride, digest[1]);
+  compChecksum(pic.getCrAddr(), width, height, stride, digest[2]);
+}
+/**
+ * Calculate the MD5sum of pic, storing the result in digest.
+ * MD5 calculation is performed on Y' then Cb, then Cr; each in raster order.
+ * Pel data is inserted into the MD5 function in little-endian byte order,
+ * using sufficient bytes to represent the picture bitdepth.  Eg, 10bit data
+ * uses little-endian two byte words; 8bit data uses single byte words.
+ */
+void calcMD5(TComPicYuv& pic, unsigned char digest[3][16])
+{
+  unsigned bitdepth = g_uiBitDepth + g_uiBitIncrement;
+  /* choose an md5_plane packing function based on the system bitdepth */
+  typedef void (*MD5PlaneFunc)(MD5&, const Pel*, unsigned, unsigned, unsigned);
+  MD5PlaneFunc md5_plane_func;
+  md5_plane_func = bitdepth <= 8 ? (MD5PlaneFunc)md5_plane<1> : (MD5PlaneFunc)md5_plane<2>;
+
+  MD5 md5Y, md5U, md5V;
+  unsigned width = pic.getWidth();
+  unsigned height = pic.getHeight();
+  unsigned stride = pic.getStride();
+
+  md5_plane_func(md5Y, pic.getLumaAddr(), width, height, stride);
+  md5Y.finalize(digest[0]);
+
+  width >>= 1;
+  height >>= 1;
+  stride >>= 1;
+
+  md5_plane_func(md5U, pic.getCbAddr(), width, height, stride);
+  md5U.finalize(digest[1]);
+
+  md5_plane_func(md5V, pic.getCrAddr(), width, height, stride);
+  md5V.finalize(digest[2]);
+}
+//! \}
Index: /trunk/source/Lib/TLibCommon/TComPrediction.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComPrediction.cpp	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComPrediction.cpp	(revision 2)
@@ -0,0 +1,1046 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComPrediction.cpp
+    \brief    prediction class
+*/
+
+#include <memory.h>
+#include "TComPrediction.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / initialize
+// ====================================================================================================================
+
+TComPrediction::TComPrediction()
+: m_pLumaRecBuffer(0)
+, m_iLumaRecStride(0)
+{
+  m_piYuvExt = NULL;
+}
+
+TComPrediction::~TComPrediction()
+{
+  
+  delete[] m_piYuvExt;
+
+  m_acYuvPred[0].destroy();
+  m_acYuvPred[1].destroy();
+
+  m_cYuvPredTemp.destroy();
+
+  if( m_pLumaRecBuffer )
+  {
+    delete [] m_pLumaRecBuffer;
+  }
+  
+  Int i, j;
+  for (i = 0; i < 4; i++)
+  {
+    for (j = 0; j < 4; j++)
+    {
+      m_filteredBlock[i][j].destroy();
+    }
+    m_filteredBlockTmp[i].destroy();
+  }
+}
+
+Void TComPrediction::initTempBuff()
+{
+  if( m_piYuvExt == NULL )
+  {
+    Int extWidth  = g_uiMaxCUWidth + 16; 
+    Int extHeight = g_uiMaxCUHeight + 1;
+    Int i, j;
+    for (i = 0; i < 4; i++)
+    {
+      m_filteredBlockTmp[i].create(extWidth, extHeight + 7);
+      for (j = 0; j < 4; j++)
+      {
+        m_filteredBlock[i][j].create(extWidth, extHeight);
+      }
+    }
+    m_iYuvExtHeight  = ((g_uiMaxCUHeight + 2) << 4);
+    m_iYuvExtStride = ((g_uiMaxCUWidth  + 8) << 4);
+    m_piYuvExt = new Int[ m_iYuvExtStride * m_iYuvExtHeight ];
+
+    // new structure
+    m_acYuvPred[0] .create( g_uiMaxCUWidth, g_uiMaxCUHeight );
+    m_acYuvPred[1] .create( g_uiMaxCUWidth, g_uiMaxCUHeight );
+
+    m_cYuvPredTemp.create( g_uiMaxCUWidth, g_uiMaxCUHeight );
+  }
+
+  if (m_iLumaRecStride != (g_uiMaxCUWidth>>1) + 1)
+  {
+    m_iLumaRecStride =  (g_uiMaxCUWidth>>1) + 1;
+    if (!m_pLumaRecBuffer)
+    {
+      m_pLumaRecBuffer = new Pel[ m_iLumaRecStride * m_iLumaRecStride ];
+    }
+  }
+
+  Int shift = g_uiBitDepth + g_uiBitIncrement + 4;
+
+  for( Int i = 32; i < 64; i++ )
+  {
+    m_uiaShift[i-32] = ( ( 1 << shift ) + i/2 ) / i;
+  }
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+// Function for calculating DC value of the reference samples used in Intra prediction
+Pel TComPrediction::predIntraGetPredValDC( Int* pSrc, Int iSrcStride, UInt iWidth, UInt iHeight, Bool bAbove, Bool bLeft )
+{
+  Int iInd, iSum = 0;
+  Pel pDcVal;
+
+  if (bAbove)
+  {
+    for (iInd = 0;iInd < iWidth;iInd++)
+    {
+      iSum += pSrc[iInd-iSrcStride];
+    }
+  }
+  if (bLeft)
+  {
+    for (iInd = 0;iInd < iHeight;iInd++)
+    {
+      iSum += pSrc[iInd*iSrcStride-1];
+    }
+  }
+
+  if (bAbove && bLeft)
+  {
+    pDcVal = (iSum + iWidth) / (iWidth + iHeight);
+  }
+  else if (bAbove)
+  {
+    pDcVal = (iSum + iWidth/2) / iWidth;
+  }
+  else if (bLeft)
+  {
+    pDcVal = (iSum + iHeight/2) / iHeight;
+  }
+  else
+  {
+    pDcVal = pSrc[-1]; // Default DC value already calculated and placed in the prediction array if no neighbors are available
+  }
+  
+  return pDcVal;
+}
+
+// Function for deriving the angular Intra predictions
+
+/** Function for deriving the simplified angular intra predictions.
+ * \param pSrc pointer to reconstructed sample array
+ * \param srcStride the stride of the reconstructed sample array
+ * \param rpDst reference to pointer for the prediction sample array
+ * \param dstStride the stride of the prediction sample array
+ * \param width the width of the block
+ * \param height the height of the block
+ * \param dirMode the intra prediction mode index
+ * \param blkAboveAvailable boolean indication if the block above is available
+ * \param blkLeftAvailable boolean indication if the block to the left is available
+ *
+ * This function derives the prediction samples for the angular mode based on the prediction direction indicated by
+ * the prediction mode index. The prediction direction is given by the displacement of the bottom row of the block and
+ * the reference row above the block in the case of vertical prediction or displacement of the rightmost column
+ * of the block and reference column left from the block in the case of the horizontal prediction. The displacement
+ * is signalled at 1/32 pixel accuracy. When projection of the predicted pixel falls inbetween reference samples,
+ * the predicted value for the pixel is linearly interpolated from the reference samples. All reference samples are taken
+ * from the extended main reference.
+ */
+Void TComPrediction::xPredIntraAng( Int* pSrc, Int srcStride, Pel*& rpDst, Int dstStride, UInt width, UInt height, UInt dirMode, Bool blkAboveAvailable, Bool blkLeftAvailable, Bool bFilter )
+{
+  Int k,l;
+  Int blkSize        = width;
+  Pel* pDst          = rpDst;
+
+  // Map the mode index to main prediction direction and angle
+  assert( dirMode > 0 ); //no planar
+  Bool modeDC        = dirMode < 2;
+  Bool modeHor       = !modeDC && (dirMode < 18);
+  Bool modeVer       = !modeDC && !modeHor;
+  Int intraPredAngle = modeVer ? (Int)dirMode - VER_IDX : modeHor ? -((Int)dirMode - HOR_IDX) : 0;
+  Int absAng         = abs(intraPredAngle);
+  Int signAng        = intraPredAngle < 0 ? -1 : 1;
+
+  // Set bitshifts and scale the angle parameter to block size
+  Int angTable[9]    = {0,    2,    5,   9,  13,  17,  21,  26,  32};
+  Int invAngTable[9] = {0, 4096, 1638, 910, 630, 482, 390, 315, 256}; // (256 * 32) / Angle
+  Int invAngle       = invAngTable[absAng];
+  absAng             = angTable[absAng];
+  intraPredAngle     = signAng * absAng;
+
+  // Do the DC prediction
+  if (modeDC)
+  {
+    Pel dcval = predIntraGetPredValDC(pSrc, srcStride, width, height, blkAboveAvailable, blkLeftAvailable);
+
+    for (k=0;k<blkSize;k++)
+    {
+      for (l=0;l<blkSize;l++)
+      {
+        pDst[k*dstStride+l] = dcval;
+      }
+    }
+  }
+
+  // Do angular predictions
+  else
+  {
+    Pel* refMain;
+    Pel* refSide;
+    Pel  refAbove[2*MAX_CU_SIZE+1];
+    Pel  refLeft[2*MAX_CU_SIZE+1];
+
+    // Initialise the Main and Left reference array.
+    if (intraPredAngle < 0)
+    {
+      for (k=0;k<blkSize+1;k++)
+      {
+        refAbove[k+blkSize-1] = pSrc[k-srcStride-1];
+      }
+      for (k=0;k<blkSize+1;k++)
+      {
+        refLeft[k+blkSize-1] = pSrc[(k-1)*srcStride-1];
+      }
+      refMain = (modeVer ? refAbove : refLeft) + (blkSize-1);
+      refSide = (modeVer ? refLeft : refAbove) + (blkSize-1);
+
+      // Extend the Main reference to the left.
+      Int invAngleSum    = 128;       // rounding for (shift by 8)
+      for (k=-1; k>blkSize*intraPredAngle>>5; k--)
+      {
+        invAngleSum += invAngle;
+        refMain[k] = refSide[invAngleSum>>8];
+      }
+    }
+    else
+    {
+      for (k=0;k<2*blkSize+1;k++)
+      {
+        refAbove[k] = pSrc[k-srcStride-1];
+      }
+      for (k=0;k<2*blkSize+1;k++)
+      {
+        refLeft[k] = pSrc[(k-1)*srcStride-1];
+      }
+      refMain = modeVer ? refAbove : refLeft;
+      refSide = modeVer ? refLeft  : refAbove;
+    }
+
+    if (intraPredAngle == 0)
+    {
+      for (k=0;k<blkSize;k++)
+      {
+        for (l=0;l<blkSize;l++)
+        {
+          pDst[k*dstStride+l] = refMain[l+1];
+        }
+      }
+
+      if ( bFilter )
+      {
+        for (k=0;k<blkSize;k++)
+        {
+          pDst[k*dstStride] = Clip ( pDst[k*dstStride] + (( refSide[k+1] - refSide[0] ) >> 1) );
+        }
+      }
+    }
+    else
+    {
+      Int deltaPos=0;
+      Int deltaInt;
+      Int deltaFract;
+      Int refMainIndex;
+
+      for (k=0;k<blkSize;k++)
+      {
+        deltaPos += intraPredAngle;
+        deltaInt   = deltaPos >> 5;
+        deltaFract = deltaPos & (32 - 1);
+
+        if (deltaFract)
+        {
+          // Do linear filtering
+          for (l=0;l<blkSize;l++)
+          {
+            refMainIndex        = l+deltaInt+1;
+            pDst[k*dstStride+l] = (Pel) ( ((32-deltaFract)*refMain[refMainIndex]+deltaFract*refMain[refMainIndex+1]+16) >> 5 );
+          }
+        }
+        else
+        {
+          // Just copy the integer samples
+          for (l=0;l<blkSize;l++)
+          {
+            pDst[k*dstStride+l] = refMain[l+deltaInt+1];
+          }
+        }
+      }
+    }
+
+    // Flip the block if this is the horizontal mode
+    if (modeHor)
+    {
+      Pel  tmp;
+      for (k=0;k<blkSize-1;k++)
+      {
+        for (l=k+1;l<blkSize;l++)
+        {
+          tmp                 = pDst[k*dstStride+l];
+          pDst[k*dstStride+l] = pDst[l*dstStride+k];
+          pDst[l*dstStride+k] = tmp;
+        }
+      }
+    }
+  }
+}
+
+Void TComPrediction::predIntraLumaAng(TComPattern* pcTComPattern, UInt uiDirMode, Pel* piPred, UInt uiStride, Int iWidth, Int iHeight,  TComDataCU* pcCU, Bool bAbove, Bool bLeft )
+{
+  Pel *pDst = piPred;
+  Int *ptrSrc;
+
+  assert( g_aucConvertToBit[ iWidth ] >= 0 ); //   4x  4
+  assert( g_aucConvertToBit[ iWidth ] <= 5 ); // 128x128
+  assert( iWidth == iHeight  );
+
+  ptrSrc = pcTComPattern->getPredictorPtr( uiDirMode, g_aucConvertToBit[ iWidth ] + 2, m_piYuvExt );
+
+  // get starting pixel in block
+  Int sw = 2 * iWidth + 1;
+
+  // Create the prediction
+  if ( uiDirMode == PLANAR_IDX )
+  {
+    xPredIntraPlanar( ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight );
+  }
+  else
+  {
+    xPredIntraAng( ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight, uiDirMode, bAbove, bLeft, true );
+
+    if( (uiDirMode == DC_IDX ) && bAbove && bLeft )
+    {
+      xDCPredFiltering( ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight);
+    }
+  }
+}
+
+// Angular chroma
+Void TComPrediction::predIntraChromaAng( TComPattern* pcTComPattern, Int* piSrc, UInt uiDirMode, Pel* piPred, UInt uiStride, Int iWidth, Int iHeight, TComDataCU* pcCU, Bool bAbove, Bool bLeft )
+{
+  Pel *pDst = piPred;
+  Int *ptrSrc = piSrc;
+
+  // get starting pixel in block
+  Int sw = 2 * iWidth + 1;
+
+  if ( uiDirMode == PLANAR_IDX )
+  {
+    xPredIntraPlanar( ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight );
+  }
+  else
+  {
+    // Create the prediction
+    xPredIntraAng( ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight, uiDirMode, bAbove, bLeft, false );
+  }
+}
+
+/** Function for checking identical motion.
+ * \param TComDataCU* pcCU
+ * \param UInt PartAddr
+ */
+Bool TComPrediction::xCheckIdenticalMotion ( TComDataCU* pcCU, UInt PartAddr )
+{
+  if( pcCU->getSlice()->isInterB() && !pcCU->getSlice()->getPPS()->getWPBiPred() )
+  {
+    if( pcCU->getCUMvField(REF_PIC_LIST_0)->getRefIdx(PartAddr) >= 0 && pcCU->getCUMvField(REF_PIC_LIST_1)->getRefIdx(PartAddr) >= 0)
+    {
+      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(RefPOCL0 == RefPOCL1 && pcCU->getCUMvField(REF_PIC_LIST_0)->getMv(PartAddr) == pcCU->getCUMvField(REF_PIC_LIST_1)->getMv(PartAddr))
+      {
+        return true;
+      }
+    }
+  }
+  return false;
+}
+
+#if INTRA_BL
+Void TComPrediction::getBaseBlk( TComDataCU* pcCU, TComYuv* pcYuvPred, Int iPartAddr, Int iWidth, Int iHeight )
+{
+  pcCU->getBaseLumaBlk( iWidth, iHeight, iPartAddr, pcYuvPred->getLumaAddr( iPartAddr ), pcYuvPred->getStride() );
+  pcCU->getBaseChromaBlk( iWidth >> 1, iHeight >> 1, iPartAddr, pcYuvPred->getCbAddr( iPartAddr ), pcYuvPred->getCStride(), 0 );
+  pcCU->getBaseChromaBlk( iWidth >> 1, iHeight >> 1, iPartAddr, pcYuvPred->getCrAddr( iPartAddr ), pcYuvPred->getCStride(), 1 );
+}
+#endif
+
+Void TComPrediction::motionCompensation ( TComDataCU* pcCU, TComYuv* pcYuvPred, RefPicList eRefPicList, Int iPartIdx )
+{
+  Int         iWidth;
+  Int         iHeight;
+  UInt        uiPartAddr;
+
+  if ( iPartIdx >= 0 )
+  {
+    pcCU->getPartIndexAndSize( iPartIdx, uiPartAddr, iWidth, iHeight );
+    if ( eRefPicList != REF_PIC_LIST_X )
+    {
+      if( pcCU->getSlice()->getPPS()->getUseWP())
+      {
+        xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred, iPartIdx, true );
+      }
+      else
+      {
+        xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred, iPartIdx );
+      }
+      if ( pcCU->getSlice()->getPPS()->getUseWP() )
+      {
+        xWeightedPredictionUni( pcCU, pcYuvPred, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred, iPartIdx );
+      }
+    }
+    else
+    {
+      if ( xCheckIdenticalMotion( pcCU, uiPartAddr ) )
+      {
+        xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, REF_PIC_LIST_0, pcYuvPred, iPartIdx );
+      }
+      else
+      {
+        xPredInterBi  (pcCU, uiPartAddr, iWidth, iHeight, pcYuvPred, iPartIdx );
+      }
+    }
+    return;
+  }
+
+  for ( iPartIdx = 0; iPartIdx < pcCU->getNumPartInter(); iPartIdx++ )
+  {
+    pcCU->getPartIndexAndSize( iPartIdx, uiPartAddr, iWidth, iHeight );
+
+    if ( eRefPicList != REF_PIC_LIST_X )
+    {
+      if( pcCU->getSlice()->getPPS()->getUseWP())
+      {
+        xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred, iPartIdx, true );
+      }
+      else
+      {
+        xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred, iPartIdx );
+      }
+      if ( pcCU->getSlice()->getPPS()->getUseWP() )
+      {
+        xWeightedPredictionUni( pcCU, pcYuvPred, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred, iPartIdx );
+      }
+    }
+    else
+    {
+      if ( xCheckIdenticalMotion( pcCU, uiPartAddr ) )
+      {
+        xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, REF_PIC_LIST_0, pcYuvPred, iPartIdx );
+      }
+      else
+      {
+        xPredInterBi  (pcCU, uiPartAddr, iWidth, iHeight, pcYuvPred, iPartIdx );
+      }
+    }
+  }
+  return;
+}
+
+Void TComPrediction::xPredInterUni ( TComDataCU* pcCU, UInt uiPartAddr, Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Int iPartIdx, Bool bi )
+{
+  Int         iRefIdx     = pcCU->getCUMvField( eRefPicList )->getRefIdx( uiPartAddr );           assert (iRefIdx >= 0);
+  TComMv      cMv         = pcCU->getCUMvField( eRefPicList )->getMv( uiPartAddr );
+  pcCU->clipMv(cMv);
+  xPredInterLumaBlk  ( pcCU, pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPicYuvRec(), uiPartAddr, &cMv, iWidth, iHeight, rpcYuvPred, bi );
+  xPredInterChromaBlk( pcCU, pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPicYuvRec(), uiPartAddr, &cMv, iWidth, iHeight, rpcYuvPred, bi );
+}
+
+Void TComPrediction::xPredInterBi ( TComDataCU* pcCU, UInt uiPartAddr, Int iWidth, Int iHeight, TComYuv*& rpcYuvPred, Int iPartIdx )
+{
+  TComYuv* pcMbYuv;
+  Int      iRefIdx[2] = {-1, -1};
+
+  for ( Int iRefList = 0; iRefList < 2; iRefList++ )
+  {
+    RefPicList eRefPicList = (iRefList ? REF_PIC_LIST_1 : REF_PIC_LIST_0);
+    iRefIdx[iRefList] = pcCU->getCUMvField( eRefPicList )->getRefIdx( uiPartAddr );
+
+    if ( iRefIdx[iRefList] < 0 )
+    {
+      continue;
+    }
+
+    assert( iRefIdx[iRefList] < pcCU->getSlice()->getNumRefIdx(eRefPicList) );
+
+    pcMbYuv = &m_acYuvPred[iRefList];
+    if( pcCU->getCUMvField( REF_PIC_LIST_0 )->getRefIdx( uiPartAddr ) >= 0 && pcCU->getCUMvField( REF_PIC_LIST_1 )->getRefIdx( uiPartAddr ) >= 0 )
+    {
+      xPredInterUni ( pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcMbYuv, iPartIdx, true );
+    }
+    else
+    {
+      if ( ( pcCU->getSlice()->getPPS()->getUseWP()       && pcCU->getSlice()->getSliceType() == P_SLICE ) || 
+           ( pcCU->getSlice()->getPPS()->getWPBiPred() && pcCU->getSlice()->getSliceType() == B_SLICE ) )
+      {
+        xPredInterUni ( pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcMbYuv, iPartIdx, true );
+      }
+      else
+      {
+        xPredInterUni ( pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcMbYuv, iPartIdx );
+      }
+    }
+  }
+
+  if ( pcCU->getSlice()->getPPS()->getWPBiPred() && pcCU->getSlice()->getSliceType() == B_SLICE  )
+  {
+    xWeightedPredictionBi( pcCU, &m_acYuvPred[0], &m_acYuvPred[1], iRefIdx[0], iRefIdx[1], uiPartAddr, iWidth, iHeight, rpcYuvPred );
+  }  
+  else if ( pcCU->getSlice()->getPPS()->getUseWP() && pcCU->getSlice()->getSliceType() == P_SLICE )
+  {
+    xWeightedPredictionUni( pcCU, &m_acYuvPred[0], uiPartAddr, iWidth, iHeight, REF_PIC_LIST_0, rpcYuvPred, iPartIdx ); 
+  }
+  else
+  {
+    xWeightedAverage( pcCU, &m_acYuvPred[0], &m_acYuvPred[1], iRefIdx[0], iRefIdx[1], uiPartAddr, iWidth, iHeight, rpcYuvPred );
+  }
+}
+
+/**
+ * \brief Generate motion-compensated luma block
+ *
+ * \param cu       Pointer to current CU
+ * \param refPic   Pointer to reference picture
+ * \param partAddr Address of block within CU
+ * \param mv       Motion vector
+ * \param width    Width of block
+ * \param height   Height of block
+ * \param dstPic   Pointer to destination picture
+ * \param bi       Flag indicating whether bipred is used
+ */
+Void TComPrediction::xPredInterLumaBlk( TComDataCU *cu, TComPicYuv *refPic, UInt partAddr, TComMv *mv, Int width, Int height, TComYuv *&dstPic, Bool bi )
+{
+  Int refStride = refPic->getStride();  
+  Int refOffset = ( mv->getHor() >> 2 ) + ( mv->getVer() >> 2 ) * refStride;
+  Pel *ref      = refPic->getLumaAddr( cu->getAddr(), cu->getZorderIdxInCU() + partAddr ) + refOffset;
+  
+  Int dstStride = dstPic->getStride();
+  Pel *dst      = dstPic->getLumaAddr( partAddr );
+  
+  Int xFrac = mv->getHor() & 0x3;
+  Int yFrac = mv->getVer() & 0x3;
+
+  if ( yFrac == 0 )
+  {
+    m_if.filterHorLuma( ref, refStride, dst, dstStride, width, height, xFrac,       !bi );
+  }
+  else if ( xFrac == 0 )
+  {
+    m_if.filterVerLuma( ref, refStride, dst, dstStride, width, height, yFrac, true, !bi );
+  }
+  else
+  {
+    Int tmpStride = m_filteredBlockTmp[0].getStride();
+    Short *tmp    = m_filteredBlockTmp[0].getLumaAddr();
+
+    Int filterSize = NTAPS_LUMA;
+    Int halfFilterSize = ( filterSize >> 1 );
+
+    m_if.filterHorLuma(ref - (halfFilterSize-1)*refStride, refStride, tmp, tmpStride, width, height+filterSize-1, xFrac, false     );
+    m_if.filterVerLuma(tmp + (halfFilterSize-1)*tmpStride, tmpStride, dst, dstStride, width, height,              yFrac, false, !bi);    
+  }
+}
+
+/**
+ * \brief Generate motion-compensated chroma block
+ *
+ * \param cu       Pointer to current CU
+ * \param refPic   Pointer to reference picture
+ * \param partAddr Address of block within CU
+ * \param mv       Motion vector
+ * \param width    Width of block
+ * \param height   Height of block
+ * \param dstPic   Pointer to destination picture
+ * \param bi       Flag indicating whether bipred is used
+ */
+Void TComPrediction::xPredInterChromaBlk( TComDataCU *cu, TComPicYuv *refPic, UInt partAddr, TComMv *mv, Int width, Int height, TComYuv *&dstPic, Bool bi )
+{
+  Int     refStride  = refPic->getCStride();
+  Int     dstStride  = dstPic->getCStride();
+  
+  Int     refOffset  = (mv->getHor() >> 3) + (mv->getVer() >> 3) * refStride;
+  
+  Pel*    refCb     = refPic->getCbAddr( cu->getAddr(), cu->getZorderIdxInCU() + partAddr ) + refOffset;
+  Pel*    refCr     = refPic->getCrAddr( cu->getAddr(), cu->getZorderIdxInCU() + partAddr ) + refOffset;
+  
+  Pel* dstCb = dstPic->getCbAddr( partAddr );
+  Pel* dstCr = dstPic->getCrAddr( partAddr );
+  
+  Int     xFrac  = mv->getHor() & 0x7;
+  Int     yFrac  = mv->getVer() & 0x7;
+  UInt    cxWidth  = width  >> 1;
+  UInt    cxHeight = height >> 1;
+  
+  Int     extStride = m_filteredBlockTmp[0].getStride();
+  Short*  extY      = m_filteredBlockTmp[0].getLumaAddr();
+  
+  Int filterSize = NTAPS_CHROMA;
+  
+  Int halfFilterSize = (filterSize>>1);
+  
+  if ( yFrac == 0 )
+  {
+    m_if.filterHorChroma(refCb, refStride, dstCb,  dstStride, cxWidth, cxHeight, xFrac, !bi);    
+    m_if.filterHorChroma(refCr, refStride, dstCr,  dstStride, cxWidth, cxHeight, xFrac, !bi);    
+  }
+  else if ( xFrac == 0 )
+  {
+    m_if.filterVerChroma(refCb, refStride, dstCb, dstStride, cxWidth, cxHeight, yFrac, true, !bi);    
+    m_if.filterVerChroma(refCr, refStride, dstCr, dstStride, cxWidth, cxHeight, yFrac, true, !bi);    
+  }
+  else
+  {
+    m_if.filterHorChroma(refCb - (halfFilterSize-1)*refStride, refStride, extY,  extStride, cxWidth, cxHeight+filterSize-1, xFrac, false);
+    m_if.filterVerChroma(extY  + (halfFilterSize-1)*extStride, extStride, dstCb, dstStride, cxWidth, cxHeight  , yFrac, false, !bi);
+    
+    m_if.filterHorChroma(refCr - (halfFilterSize-1)*refStride, refStride, extY,  extStride, cxWidth, cxHeight+filterSize-1, xFrac, false);
+    m_if.filterVerChroma(extY  + (halfFilterSize-1)*extStride, extStride, dstCr, dstStride, cxWidth, cxHeight  , yFrac, false, !bi);    
+  }
+}
+
+Void TComPrediction::xWeightedAverage( TComDataCU* pcCU, TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, Int iRefIdx0, Int iRefIdx1, UInt uiPartIdx, Int iWidth, Int iHeight, TComYuv*& rpcYuvDst )
+{
+  if( iRefIdx0 >= 0 && iRefIdx1 >= 0 )
+  {
+    rpcYuvDst->addAvg( pcYuvSrc0, pcYuvSrc1, uiPartIdx, iWidth, iHeight );
+  }
+  else if ( iRefIdx0 >= 0 && iRefIdx1 <  0 )
+  {
+    pcYuvSrc0->copyPartToPartYuv( rpcYuvDst, uiPartIdx, iWidth, iHeight );
+  }
+  else if ( iRefIdx0 <  0 && iRefIdx1 >= 0 )
+  {
+    pcYuvSrc1->copyPartToPartYuv( rpcYuvDst, uiPartIdx, iWidth, iHeight );
+  }
+}
+
+// AMVP
+Void TComPrediction::getMvPredAMVP( TComDataCU* pcCU, UInt uiPartIdx, UInt uiPartAddr, RefPicList eRefPicList, Int iRefIdx, TComMv& rcMvPred )
+{
+  AMVPInfo* pcAMVPInfo = pcCU->getCUMvField(eRefPicList)->getAMVPInfo();
+#if !SPS_AMVP_CLEANUP
+  if( pcCU->getAMVPMode(uiPartAddr) == AM_NONE || (pcAMVPInfo->iN <= 1 && pcCU->getAMVPMode(uiPartAddr) == AM_EXPL) )
+#else
+  if( pcAMVPInfo->iN <= 1 )
+#endif
+  {
+    rcMvPred = pcAMVPInfo->m_acMvCand[0];
+
+    pcCU->setMVPIdxSubParts( 0, eRefPicList, uiPartAddr, uiPartIdx, pcCU->getDepth(uiPartAddr));
+    pcCU->setMVPNumSubParts( pcAMVPInfo->iN, eRefPicList, uiPartAddr, uiPartIdx, pcCU->getDepth(uiPartAddr));
+    return;
+  }
+
+  assert(pcCU->getMVPIdx(eRefPicList,uiPartAddr) >= 0);
+  rcMvPred = pcAMVPInfo->m_acMvCand[pcCU->getMVPIdx(eRefPicList,uiPartAddr)];
+  return;
+}
+
+/** Function for deriving planar intra prediction.
+ * \param pSrc pointer to reconstructed sample array
+ * \param srcStride the stride of the reconstructed sample array
+ * \param rpDst reference to pointer for the prediction sample array
+ * \param dstStride the stride of the prediction sample array
+ * \param width the width of the block
+ * \param height the height of the block
+ *
+ * This function derives the prediction samples for planar mode (intra coding).
+ */
+Void TComPrediction::xPredIntraPlanar( Int* pSrc, Int srcStride, Pel* rpDst, Int dstStride, UInt width, UInt height )
+{
+  assert(width == height);
+
+  Int k, l, bottomLeft, topRight;
+  Int horPred;
+  Int leftColumn[MAX_CU_SIZE], topRow[MAX_CU_SIZE], bottomRow[MAX_CU_SIZE], rightColumn[MAX_CU_SIZE];
+  UInt blkSize = width;
+  UInt offset2D = width;
+  UInt shift1D = g_aucConvertToBit[ width ] + 2;
+  UInt shift2D = shift1D + 1;
+
+  // Get left and above reference column and row
+  for(k=0;k<blkSize+1;k++)
+  {
+    topRow[k] = pSrc[k-srcStride];
+    leftColumn[k] = pSrc[k*srcStride-1];
+  }
+
+  // Prepare intermediate variables used in interpolation
+  bottomLeft = leftColumn[blkSize];
+  topRight   = topRow[blkSize];
+  for (k=0;k<blkSize;k++)
+  {
+    bottomRow[k]   = bottomLeft - topRow[k];
+    rightColumn[k] = topRight   - leftColumn[k];
+    topRow[k]      <<= shift1D;
+    leftColumn[k]  <<= shift1D;
+  }
+
+  // Generate prediction signal
+  for (k=0;k<blkSize;k++)
+  {
+    horPred = leftColumn[k] + offset2D;
+    for (l=0;l<blkSize;l++)
+    {
+      horPred += rightColumn[k];
+      topRow[l] += bottomRow[l];
+      rpDst[k*dstStride+l] = ( (horPred + topRow[l]) >> shift2D );
+    }
+  }
+}
+
+#if !REMOVE_LMCHROMA
+/** Function for deriving chroma LM intra prediction.
+ * \param pcPattern pointer to neighbouring pixel access pattern
+ * \param piSrc pointer to reconstructed chroma sample array
+ * \param pPred pointer for the prediction sample array
+ * \param uiPredStride the stride of the prediction sample array
+ * \param uiCWidth the width of the chroma block
+ * \param uiCHeight the height of the chroma block
+ * \param uiChromaId boolean indication of chroma component
+ *
+ * This function derives the prediction samples for chroma LM mode (chroma intra coding)
+ */
+Void TComPrediction::predLMIntraChroma( TComPattern* pcPattern, Int* piSrc, Pel* pPred, UInt uiPredStride, UInt uiCWidth, UInt uiCHeight, UInt uiChromaId )
+{
+  UInt uiWidth  = 2 * uiCWidth;
+
+  xGetLLSPrediction( pcPattern, piSrc+uiWidth+2, uiWidth+1, pPred, uiPredStride, uiCWidth, uiCHeight, 1 );  
+}
+
+/** Function for deriving downsampled luma sample of current chroma block and its above, left causal pixel
+ * \param pcPattern pointer to neighbouring pixel access pattern
+ * \param uiCWidth the width of the chroma block
+ * \param uiCHeight the height of the chroma block
+ *
+ * This function derives downsampled luma sample of current chroma block and its above, left causal pixel
+ */
+Void TComPrediction::getLumaRecPixels( TComPattern* pcPattern, UInt uiCWidth, UInt uiCHeight )
+{
+  UInt uiWidth  = 2 * uiCWidth;
+  UInt uiHeight = 2 * uiCHeight;  
+
+  Pel* pRecSrc = pcPattern->getROIY();
+  Pel* pDst0 = m_pLumaRecBuffer + m_iLumaRecStride + 1;
+
+  Int iRecSrcStride = pcPattern->getPatternLStride();
+  Int iRecSrcStride2 = iRecSrcStride << 1;
+  Int iDstStride = m_iLumaRecStride;
+  Int iSrcStride = ( max( uiWidth, uiHeight ) << 1 ) + 1;
+
+  Int* ptrSrc = pcPattern->getAdiOrgBuf( uiWidth, uiHeight, m_piYuvExt );
+
+  // initial pointers
+  Pel* pDst = pDst0 - 1 - iDstStride;  
+  Int* piSrc = ptrSrc;
+
+  // top left corner downsampled from ADI buffer
+  // don't need this point
+
+  // top row downsampled from ADI buffer
+  pDst++;     
+  piSrc ++;
+  for (Int i = 0; i < uiCWidth; i++)
+  {
+    pDst[i] = ((piSrc[2*i] * 2 ) + piSrc[2*i - 1] + piSrc[2*i + 1] + 2) >> 2;
+  }
+
+  // left column downsampled from ADI buffer
+  pDst = pDst0 - 1; 
+  piSrc = ptrSrc + iSrcStride;
+  for (Int j = 0; j < uiCHeight; j++)
+  {
+    pDst[0] = ( piSrc[0] + piSrc[iSrcStride] ) >> 1;
+    piSrc += iSrcStride << 1; 
+    pDst += iDstStride;    
+  }
+
+  // inner part from reconstructed picture buffer
+  for( Int j = 0; j < uiCHeight; j++ )
+  {
+    for (Int i = 0; i < uiCWidth; i++)
+    {
+      pDst0[i] = (pRecSrc[2*i] + pRecSrc[2*i + iRecSrcStride]) >> 1;
+    }
+
+    pDst0 += iDstStride;
+    pRecSrc += iRecSrcStride2;
+  }
+}
+
+/** Function for deriving the positon of first non-zero binary bit of a value
+ * \param x input value
+ *
+ * This function derives the positon of first non-zero binary bit of a value
+ */
+Int GetFloorLog2( UInt x )
+{
+  int bits = -1;
+  while( x > 0 )
+  {
+    bits ++;
+    x >>= 1;
+  }
+  return bits;
+}
+
+/** Function for deriving LM intra prediction.
+ * \param pcPattern pointer to neighbouring pixel access pattern
+ * \param pSrc0 pointer to reconstructed chroma sample array
+ * \param iSrcStride the stride of reconstructed chroma sample array
+ * \param pDst0 reference to pointer for the prediction sample array
+ * \param iDstStride the stride of the prediction sample array
+ * \param uiWidth the width of the chroma block
+ * \param uiHeight the height of the chroma block
+ * \param uiExt0 line number of neiggboirng pixels for calculating LM model parameter, default value is 1
+ *
+ * This function derives the prediction samples for chroma LM mode (chroma intra coding)
+ */
+Void TComPrediction::xGetLLSPrediction( TComPattern* pcPattern, Int* pSrc0, Int iSrcStride, Pel* pDst0, Int iDstStride, UInt uiWidth, UInt uiHeight, UInt uiExt0 )
+{
+
+  Pel  *pDst, *pLuma;
+  Int  *pSrc;
+
+  Int  iLumaStride = m_iLumaRecStride;
+  Pel* pLuma0 = m_pLumaRecBuffer + uiExt0 * iLumaStride + uiExt0;
+
+  Int i, j, iCountShift = 0;
+  UInt uiInternalBitDepth = g_uiBitDepth + g_uiBitIncrement;
+
+  UInt uiExt = uiExt0;
+
+  // LLS parameters estimation -->
+
+  Int x = 0, y = 0, xx = 0, xy = 0;
+
+  pSrc  = pSrc0  - iSrcStride;
+  pLuma = pLuma0 - iLumaStride;
+
+  for( j = 0; j < uiWidth; j++ )
+  {
+    x += pLuma[j];
+    y += pSrc[j];
+    xx += pLuma[j] * pLuma[j];
+    xy += pLuma[j] * pSrc[j];
+  }
+
+  pSrc  = pSrc0 - uiExt;
+  pLuma = pLuma0 - uiExt;
+
+  for( i = 0; i < uiHeight; i++ )
+  {
+    x += pLuma[0];
+    y += pSrc[0];
+    xx += pLuma[0] * pLuma[0];
+    xy += pLuma[0] * pSrc[0];
+
+    pSrc  += iSrcStride;
+    pLuma += iLumaStride;
+  }
+  iCountShift = g_aucConvertToBit[ uiWidth ] + 3;
+
+  Int iTempShift = uiInternalBitDepth + iCountShift - 15;
+
+  if(iTempShift > 0)
+  {
+    x  = ( x +  ( 1 << ( iTempShift - 1 ) ) ) >> iTempShift;
+    y  = ( y +  ( 1 << ( iTempShift - 1 ) ) ) >> iTempShift;
+    xx = ( xx + ( 1 << ( iTempShift - 1 ) ) ) >> iTempShift;
+    xy = ( xy + ( 1 << ( iTempShift - 1 ) ) ) >> iTempShift;
+    iCountShift -= iTempShift;
+  }
+
+  Int avgLuma =  x   >> iCountShift;
+  Int avgSrc =  y  >> iCountShift;
+  Int RErrLuma = x & ( ( 1 << iCountShift ) - 1 );
+  Int RErrSrc =  y & ( ( 1 << iCountShift ) - 1 );
+
+  Int a, b, iShift = 13;
+
+  Int iB = 7;
+  iShift -= iB;
+
+  if( iCountShift == 0 )
+  {
+    a = 0;
+    b = 1 << (uiInternalBitDepth - 1);
+    iShift = 0;
+  }
+  else
+  {
+    Int a1 = xy - ( avgLuma*avgSrc << iCountShift ) - avgLuma*RErrSrc - avgSrc*RErrLuma;
+    Int a2 = xx - ( avgLuma*avgLuma << iCountShift ) - 2*avgLuma*RErrLuma;
+
+    const Int iShiftA1 = uiInternalBitDepth - 2;
+    const Int iShiftA2 = 5;
+    const Int iAccuracyShift = uiInternalBitDepth + 4;
+
+    Int iScaleShiftA2 = 0;
+    Int iScaleShiftA1 = 0;
+    Int a1s = a1;
+    Int a2s = a2;
+
+    iScaleShiftA1 = a1 == 0 ? 0 : GetFloorLog2( abs( a1 ) ) - iShiftA1;
+    iScaleShiftA2 = a2 == 0 ? 0 : GetFloorLog2( abs( a2 ) ) - iShiftA2;
+
+    if( iScaleShiftA1 < 0 )
+    {
+      iScaleShiftA1 = 0;
+    }
+    
+    if( iScaleShiftA2 < 0 )
+    {
+      iScaleShiftA2 = 0;
+    }
+
+    Int iScaleShiftA = iScaleShiftA2 + iAccuracyShift - iShift - iScaleShiftA1;
+
+    a2s = a2 >> iScaleShiftA2;
+
+    a1s = a1 >> iScaleShiftA1;
+
+    if (a2s >= 32)
+    {
+      UInt a2t = m_uiaShift[ a2s - 32 ] ;
+      a2t = Clip( a2t );
+      a = a1s * a2t;
+    }
+    else
+    {
+      a = 0;
+    }
+    
+    if( iScaleShiftA < 0 )
+    {
+      a = a << -iScaleShiftA;
+    }
+    else
+    {
+      a = a >> iScaleShiftA;
+    }
+    a = Clip3(-( 1 << (15-iB) ), ( 1 << (15-iB )) - 1, a);
+    a = a << iB;
+   
+    Short n = 0;
+    if (a != 0)
+    {
+      n = GetFloorLog2(abs( a ) + ( (a < 0 ? -1 : 1) - 1)/2 ) - 5;
+    }
+    
+    iShift =(iShift+iB)-n;
+    a = a>>n;
+
+    b =  avgSrc - ( (  a * avgLuma ) >> iShift );
+  }   
+
+  // <-- end of LLS parameters estimation
+
+  // get prediction -->
+  uiExt = uiExt0;
+  pLuma = pLuma0;
+  pDst = pDst0;
+
+  for( i = 0; i < uiHeight; i++ )
+  {
+    for( j = 0; j < uiWidth; j++ )
+    {
+      pDst[j] = Clip( ( ( a * pLuma[j] ) >> iShift ) + b );
+    }
+    
+    pDst  += iDstStride;
+    pLuma += iLumaStride;
+  }
+  // <-- end of get prediction
+
+}
+#endif
+
+/** Function for filtering intra DC predictor.
+ * \param pSrc pointer to reconstructed sample array
+ * \param iSrcStride the stride of the reconstructed sample array
+ * \param rpDst reference to pointer for the prediction sample array
+ * \param iDstStride the stride of the prediction sample array
+ * \param iWidth the width of the block
+ * \param iHeight the height of the block
+ *
+ * This function performs filtering left and top edges of the prediction samples for DC mode (intra coding).
+ */
+Void TComPrediction::xDCPredFiltering( Int* pSrc, Int iSrcStride, Pel*& rpDst, Int iDstStride, Int iWidth, Int iHeight )
+{
+  Pel* pDst = rpDst;
+  Int x, y, iDstStride2, iSrcStride2;
+
+  // boundary pixels processing
+  pDst[0] = (Pel)((pSrc[-iSrcStride] + pSrc[-1] + 2 * pDst[0] + 2) >> 2);
+
+  for ( x = 1; x < iWidth; x++ )
+  {
+    pDst[x] = (Pel)((pSrc[x - iSrcStride] +  3 * pDst[x] + 2) >> 2);
+  }
+
+  for ( y = 1, iDstStride2 = iDstStride, iSrcStride2 = iSrcStride-1; y < iHeight; y++, iDstStride2+=iDstStride, iSrcStride2+=iSrcStride )
+  {
+    pDst[iDstStride2] = (Pel)((pSrc[iSrcStride2] + 3 * pDst[iDstStride2] + 2) >> 2);
+  }
+
+  return;
+}
+
+#if SVC_UPSAMPLING
+Void TComPrediction::upsampleBasePic( TComPicYuv* pcUsPic, TComPicYuv* pcBasePic, TComPicYuv* pcTempPic)
+{
+  m_cUsf.upsampleBasePic( pcUsPic, pcBasePic, pcTempPic);
+}
+#endif
+//! \}
Index: /trunk/source/Lib/TLibCommon/TComPrediction.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComPrediction.h	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComPrediction.h	(revision 2)
@@ -0,0 +1,136 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComPrediction.h
+    \brief    prediction class (header)
+*/
+
+#ifndef __TCOMPREDICTION__
+#define __TCOMPREDICTION__
+
+
+// Include files
+#include "TComPic.h"
+#include "TComMotionInfo.h"
+#include "TComPattern.h"
+#include "TComTrQuant.h"
+#include "TComInterpolationFilter.h"
+#include "TComWeightPrediction.h"
+
+#if SVC_UPSAMPLING
+#include "TComDataCU.h"
+#include "TComUpsampleFilter.h"
+#endif
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// prediction class
+class TComPrediction : public TComWeightPrediction
+{
+protected:
+  Int*      m_piYuvExt;
+  Int       m_iYuvExtStride;
+  Int       m_iYuvExtHeight;
+  
+  TComYuv   m_acYuvPred[2];
+  TComYuv   m_cYuvPredTemp;
+  TComYuv m_filteredBlock[4][4];
+  TComYuv m_filteredBlockTmp[4];
+  
+  TComInterpolationFilter m_if;
+
+#if SVC_UPSAMPLING
+  TComUpsampleFilter      m_cUsf;
+#endif
+
+  Pel*   m_pLumaRecBuffer;       ///< array for downsampled reconstructed luma sample 
+  Int    m_iLumaRecStride;       ///< stride of #m_pLumaRecBuffer array
+  UInt   m_uiaShift[ 63 ];       // Table for multiplication to substitue of division operation
+
+  Void xPredIntraAng            ( Int* pSrc, Int srcStride, Pel*& rpDst, Int dstStride, UInt width, UInt height, UInt dirMode, Bool blkAboveAvailable, Bool blkLeftAvailable, Bool bFilter );
+  Void xPredIntraPlanar         ( Int* pSrc, Int srcStride, Pel* rpDst, Int dstStride, UInt width, UInt height );
+  
+  // motion compensation functions
+  Void xPredInterUni            ( TComDataCU* pcCU,                          UInt uiPartAddr,               Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Int iPartIdx, Bool bi=false          );
+  Void xPredInterBi             ( TComDataCU* pcCU,                          UInt uiPartAddr,               Int iWidth, Int iHeight,                         TComYuv*& rpcYuvPred, Int iPartIdx          );
+  Void xPredInterLumaBlk  ( TComDataCU *cu, TComPicYuv *refPic, UInt partAddr, TComMv *mv, Int width, Int height, TComYuv *&dstPic, Bool bi );
+  Void xPredInterChromaBlk( TComDataCU *cu, TComPicYuv *refPic, UInt partAddr, TComMv *mv, Int width, Int height, TComYuv *&dstPic, Bool bi );
+  Void xWeightedAverage         ( TComDataCU* pcCU, TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, Int iRefIdx0, Int iRefIdx1, UInt uiPartAddr, Int iWidth, Int iHeight, TComYuv*& rpcYuvDst );
+  
+  Void xGetLLSPrediction ( TComPattern* pcPattern, Int* pSrc0, Int iSrcStride, Pel* pDst0, Int iDstStride, UInt uiWidth, UInt uiHeight, UInt uiExt0 );
+
+  Void xDCPredFiltering( Int* pSrc, Int iSrcStride, Pel*& rpDst, Int iDstStride, Int iWidth, Int iHeight );
+  Bool xCheckIdenticalMotion    ( TComDataCU* pcCU, UInt PartAddr);
+
+public:
+  TComPrediction();
+  virtual ~TComPrediction();
+  
+  Void    initTempBuff();
+  
+#if INTRA_BL
+  Void getBaseBlk ( TComDataCU* pcCU, TComYuv* pcYuvPred, Int iPartAddr, Int iWidth, Int iHeight );
+#endif
+  // inter
+  Void motionCompensation         ( TComDataCU*  pcCU, TComYuv* pcYuvPred, RefPicList eRefPicList = REF_PIC_LIST_X, Int iPartIdx = -1 );
+  
+  // motion vector prediction
+  Void getMvPredAMVP              ( TComDataCU* pcCU, UInt uiPartIdx, UInt uiPartAddr, RefPicList eRefPicList, Int iRefIdx, TComMv& rcMvPred );
+  
+  // Angular Intra
+  Void predIntraLumaAng           ( TComPattern* pcTComPattern, UInt uiDirMode, Pel* piPred, UInt uiStride, Int iWidth, Int iHeight,  TComDataCU* pcCU, Bool bAbove, Bool bLeft );
+  Void predIntraChromaAng         ( TComPattern* pcTComPattern, Int* piSrc, UInt uiDirMode, Pel* piPred, UInt uiStride, Int iWidth, Int iHeight, TComDataCU* pcCU, Bool bAbove, Bool bLeft );
+  
+  Pel  predIntraGetPredValDC      ( Int* pSrc, Int iSrcStride, UInt iWidth, UInt iHeight, Bool bAbove, Bool bLeft );
+  
+  Int* getPredicBuf()             { return m_piYuvExt;      }
+  Int  getPredicBufWidth()        { return m_iYuvExtStride; }
+  Int  getPredicBufHeight()       { return m_iYuvExtHeight; }
+
+#if !REMOVE_LMCHROMA
+  Void predLMIntraChroma( TComPattern* pcPattern, Int* piSrc, Pel* pPred, UInt uiPredStride, UInt uiCWidth, UInt uiCHeight, UInt uiChromaId );
+  Void getLumaRecPixels  ( TComPattern* pcPattern, UInt uiWidth0, UInt uiHeight0 );
+#endif
+
+#if SVC_UPSAMPLING
+  Void upsampleBasePic( TComPicYuv* pcUsPic, TComPicYuv* pcBasePic, TComPicYuv* pcTempPic );
+#endif
+};
+
+//! \}
+
+#endif // __TCOMPREDICTION__
Index: /trunk/source/Lib/TLibCommon/TComRdCost.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComRdCost.cpp	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComRdCost.cpp	(revision 2)
@@ -0,0 +1,2289 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComRdCost.cpp
+    \brief    RD cost computation class
+*/
+
+#include <math.h>
+#include <assert.h>
+#include "TComRom.h"
+#include "TComRdCost.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+TComRdCost::TComRdCost()
+{
+  init();
+}
+
+TComRdCost::~TComRdCost()
+{
+#if !FIX203
+  xUninit();
+#endif
+}
+
+// Calculate RD functions
+Double TComRdCost::calcRdCost( UInt uiBits, UInt uiDistortion, Bool bFlag, DFunc eDFunc )
+{
+  Double dRdCost = 0.0;
+  Double dLambda = 0.0;
+  
+  switch ( eDFunc )
+  {
+    case DF_SSE:
+      assert(0);
+      break;
+    case DF_SAD:
+      dLambda = (Double)m_uiLambdaMotionSAD;
+      break;
+    case DF_DEFAULT:
+      dLambda =         m_dLambda;
+      break;
+    case DF_SSE_FRAME:
+      dLambda =         m_dFrameLambda;
+      break;
+    default:
+      assert (0);
+      break;
+  }
+  
+  if (bFlag)
+  {
+    // Intra8x8, Intra4x4 Block only...
+#if SEQUENCE_LEVEL_LOSSLESS
+    dRdCost = (Double)(uiBits);
+#else
+    dRdCost = (((Double)uiDistortion) + ((Double)uiBits * dLambda));
+#endif
+  }
+  else
+  {
+    if (eDFunc == DF_SAD)
+    {
+      dRdCost = ((Double)uiDistortion + (Double)((Int)(uiBits * dLambda+.5)>>16));
+      dRdCost = (Double)(UInt)floor(dRdCost);
+    }
+    else
+    {
+#if SEQUENCE_LEVEL_LOSSLESS
+      dRdCost = (Double)(uiBits);
+#else
+      dRdCost = ((Double)uiDistortion + (Double)((Int)(uiBits * dLambda+.5)));
+      dRdCost = (Double)(UInt)floor(dRdCost);
+#endif
+    }
+  }
+  
+  return dRdCost;
+}
+
+Double TComRdCost::calcRdCost64( UInt64 uiBits, UInt64 uiDistortion, Bool bFlag, DFunc eDFunc )
+{
+  Double dRdCost = 0.0;
+  Double dLambda = 0.0;
+  
+  switch ( eDFunc )
+  {
+    case DF_SSE:
+      assert(0);
+      break;
+    case DF_SAD:
+      dLambda = (Double)m_uiLambdaMotionSAD;
+      break;
+    case DF_DEFAULT:
+      dLambda =         m_dLambda;
+      break;
+    case DF_SSE_FRAME:
+      dLambda =         m_dFrameLambda;
+      break;
+    default:
+      assert (0);
+      break;
+  }
+  
+  if (bFlag)
+  {
+    // Intra8x8, Intra4x4 Block only...
+#if SEQUENCE_LEVEL_LOSSLESS
+    dRdCost = (Double)(uiBits);
+#else
+    dRdCost = (((Double)(Int64)uiDistortion) + ((Double)(Int64)uiBits * dLambda));
+#endif
+  }
+  else
+  {
+    if (eDFunc == DF_SAD)
+    {
+      dRdCost = ((Double)(Int64)uiDistortion + (Double)((Int)((Int64)uiBits * dLambda+.5)>>16));
+      dRdCost = (Double)(UInt)floor(dRdCost);
+    }
+    else
+    {
+#if SEQUENCE_LEVEL_LOSSLESS
+      dRdCost = (Double)(uiBits);
+#else
+      dRdCost = ((Double)(Int64)uiDistortion + (Double)((Int)((Int64)uiBits * dLambda+.5)));
+      dRdCost = (Double)(UInt)floor(dRdCost);
+#endif
+    }
+  }
+  
+  return dRdCost;
+}
+
+Void TComRdCost::setLambda( Double dLambda )
+{
+  m_dLambda           = dLambda;
+  m_sqrtLambda        = sqrt(m_dLambda);
+  m_uiLambdaMotionSAD = (UInt)floor(65536.0 * m_sqrtLambda);
+  m_uiLambdaMotionSSE = (UInt)floor(65536.0 * m_dLambda   );
+}
+
+
+// Initalize Function Pointer by [eDFunc]
+Void TComRdCost::init()
+{
+  m_afpDistortFunc[0]  = NULL;                  // for DF_DEFAULT
+  
+  m_afpDistortFunc[1]  = TComRdCost::xGetSSE;
+  m_afpDistortFunc[2]  = TComRdCost::xGetSSE4;
+  m_afpDistortFunc[3]  = TComRdCost::xGetSSE8;
+  m_afpDistortFunc[4]  = TComRdCost::xGetSSE16;
+  m_afpDistortFunc[5]  = TComRdCost::xGetSSE32;
+  m_afpDistortFunc[6]  = TComRdCost::xGetSSE64;
+  m_afpDistortFunc[7]  = TComRdCost::xGetSSE16N;
+  
+  m_afpDistortFunc[8]  = TComRdCost::xGetSAD;
+  m_afpDistortFunc[9]  = TComRdCost::xGetSAD4;
+  m_afpDistortFunc[10] = TComRdCost::xGetSAD8;
+  m_afpDistortFunc[11] = TComRdCost::xGetSAD16;
+  m_afpDistortFunc[12] = TComRdCost::xGetSAD32;
+  m_afpDistortFunc[13] = TComRdCost::xGetSAD64;
+  m_afpDistortFunc[14] = TComRdCost::xGetSAD16N;
+  
+  m_afpDistortFunc[15] = TComRdCost::xGetSAD;
+  m_afpDistortFunc[16] = TComRdCost::xGetSAD4;
+  m_afpDistortFunc[17] = TComRdCost::xGetSAD8;
+  m_afpDistortFunc[18] = TComRdCost::xGetSAD16;
+  m_afpDistortFunc[19] = TComRdCost::xGetSAD32;
+  m_afpDistortFunc[20] = TComRdCost::xGetSAD64;
+  m_afpDistortFunc[21] = TComRdCost::xGetSAD16N;
+  
+#if AMP_SAD
+  m_afpDistortFunc[43] = TComRdCost::xGetSAD12;
+  m_afpDistortFunc[44] = TComRdCost::xGetSAD24;
+  m_afpDistortFunc[45] = TComRdCost::xGetSAD48;
+
+  m_afpDistortFunc[46] = TComRdCost::xGetSAD12;
+  m_afpDistortFunc[47] = TComRdCost::xGetSAD24;
+  m_afpDistortFunc[48] = TComRdCost::xGetSAD48;
+#endif
+  m_afpDistortFunc[22] = TComRdCost::xGetHADs;
+  m_afpDistortFunc[23] = TComRdCost::xGetHADs;
+  m_afpDistortFunc[24] = TComRdCost::xGetHADs;
+  m_afpDistortFunc[25] = TComRdCost::xGetHADs;
+  m_afpDistortFunc[26] = TComRdCost::xGetHADs;
+  m_afpDistortFunc[27] = TComRdCost::xGetHADs;
+  m_afpDistortFunc[28] = TComRdCost::xGetHADs;
+  
+#if !FIX203
+  m_puiComponentCostOriginP = NULL;
+  m_puiComponentCost        = NULL;
+  m_puiVerCost              = NULL;
+  m_puiHorCost              = NULL;
+#endif
+  m_uiCost                  = 0;
+  m_iCostScale              = 0;
+#if !FIX203
+  m_iSearchLimit            = 0xdeaddead;
+#endif
+}
+
+#if !FIX203
+Void TComRdCost::initRateDistortionModel( Int iSubPelSearchLimit )
+{
+  // make it larger
+  iSubPelSearchLimit += 4;
+  iSubPelSearchLimit *= 8;
+  
+  if( m_iSearchLimit != iSubPelSearchLimit )
+  {
+    xUninit();
+    
+    m_iSearchLimit = iSubPelSearchLimit;
+    
+    m_puiComponentCostOriginP = new UInt[ 4 * iSubPelSearchLimit ];
+    iSubPelSearchLimit *= 2;
+    
+    m_puiComponentCost = m_puiComponentCostOriginP + iSubPelSearchLimit;
+    
+    for( Int n = -iSubPelSearchLimit; n < iSubPelSearchLimit; n++)
+    {
+      m_puiComponentCost[n] = xGetComponentBits( n );
+    }
+  }
+}
+
+Void TComRdCost::xUninit()
+{
+  if( NULL != m_puiComponentCostOriginP )
+  {
+    delete [] m_puiComponentCostOriginP;
+    m_puiComponentCostOriginP = NULL;
+  }
+}
+#endif
+
+UInt TComRdCost::xGetComponentBits( Int iVal )
+{
+  UInt uiLength = 1;
+  UInt uiTemp   = ( iVal <= 0) ? (-iVal<<1)+1: (iVal<<1);
+  
+  assert ( uiTemp );
+  
+  while ( 1 != uiTemp )
+  {
+    uiTemp >>= 1;
+    uiLength += 2;
+  }
+  
+  return uiLength;
+}
+
+Void TComRdCost::setDistParam( UInt uiBlkWidth, UInt uiBlkHeight, DFunc eDFunc, DistParam& rcDistParam )
+{
+  // set Block Width / Height
+  rcDistParam.iCols    = uiBlkWidth;
+  rcDistParam.iRows    = uiBlkHeight;
+  rcDistParam.DistFunc = m_afpDistortFunc[eDFunc + g_aucConvertToBit[ rcDistParam.iCols ] + 1 ];
+  
+  // initialize
+  rcDistParam.iSubShift  = 0;
+}
+
+// Setting the Distortion Parameter for Inter (ME)
+Void TComRdCost::setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, DistParam& rcDistParam )
+{
+  // set Original & Curr Pointer / Stride
+  rcDistParam.pOrg = pcPatternKey->getROIY();
+  rcDistParam.pCur = piRefY;
+  
+  rcDistParam.iStrideOrg = pcPatternKey->getPatternLStride();
+  rcDistParam.iStrideCur = iRefStride;
+  
+  // set Block Width / Height
+  rcDistParam.iCols    = pcPatternKey->getROIYWidth();
+  rcDistParam.iRows    = pcPatternKey->getROIYHeight();
+  rcDistParam.DistFunc = m_afpDistortFunc[DF_SAD + g_aucConvertToBit[ rcDistParam.iCols ] + 1 ];
+  
+#if AMP_SAD
+  if (rcDistParam.iCols == 12)
+  {
+    rcDistParam.DistFunc = m_afpDistortFunc[43 ];
+  }
+  else if (rcDistParam.iCols == 24)
+  {
+    rcDistParam.DistFunc = m_afpDistortFunc[44 ];
+  }
+  else if (rcDistParam.iCols == 48)
+  {
+    rcDistParam.DistFunc = m_afpDistortFunc[45 ];
+  }
+#endif
+
+  // initialize
+  rcDistParam.iSubShift  = 0;
+}
+
+// Setting the Distortion Parameter for Inter (subpel ME with step)
+#if NS_HAD
+Void TComRdCost::setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, Int iStep, DistParam& rcDistParam, Bool bHADME, Bool bUseNSHAD )
+#else
+Void TComRdCost::setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, Int iStep, DistParam& rcDistParam, Bool bHADME )
+#endif
+{
+  // set Original & Curr Pointer / Stride
+  rcDistParam.pOrg = pcPatternKey->getROIY();
+  rcDistParam.pCur = piRefY;
+  
+  rcDistParam.iStrideOrg = pcPatternKey->getPatternLStride();
+  rcDistParam.iStrideCur = iRefStride * iStep;
+  
+  // set Step for interpolated buffer
+  rcDistParam.iStep = iStep;
+  
+  // set Block Width / Height
+  rcDistParam.iCols    = pcPatternKey->getROIYWidth();
+  rcDistParam.iRows    = pcPatternKey->getROIYHeight();
+#if NS_HAD
+  rcDistParam.bUseNSHAD = bUseNSHAD;
+#endif
+  
+  // set distortion function
+  if ( !bHADME )
+  {
+    rcDistParam.DistFunc = m_afpDistortFunc[DF_SADS + g_aucConvertToBit[ rcDistParam.iCols ] + 1 ];
+#if AMP_SAD
+    if (rcDistParam.iCols == 12)
+    {
+      rcDistParam.DistFunc = m_afpDistortFunc[46 ];
+    }
+    else if (rcDistParam.iCols == 24)
+    {
+      rcDistParam.DistFunc = m_afpDistortFunc[47 ];
+    }
+    else if (rcDistParam.iCols == 48)
+    {
+      rcDistParam.DistFunc = m_afpDistortFunc[48 ];
+    }
+#endif
+  }
+  else
+  {
+    rcDistParam.DistFunc = m_afpDistortFunc[DF_HADS + g_aucConvertToBit[ rcDistParam.iCols ] + 1 ];
+  }
+  
+  // initialize
+  rcDistParam.iSubShift  = 0;
+}
+
+Void
+#if NS_HAD
+TComRdCost::setDistParam( DistParam& rcDP, Pel* p1, Int iStride1, Pel* p2, Int iStride2, Int iWidth, Int iHeight, Bool bHadamard, Bool bUseNSHAD )
+#else
+TComRdCost::setDistParam( DistParam& rcDP, Pel* p1, Int iStride1, Pel* p2, Int iStride2, Int iWidth, Int iHeight, Bool bHadamard )
+#endif
+{
+  rcDP.pOrg       = p1;
+  rcDP.pCur       = p2;
+  rcDP.iStrideOrg = iStride1;
+  rcDP.iStrideCur = iStride2;
+  rcDP.iCols      = iWidth;
+  rcDP.iRows      = iHeight;
+  rcDP.iStep      = 1;
+  rcDP.iSubShift  = 0;
+  rcDP.DistFunc   = m_afpDistortFunc[ ( bHadamard ? DF_HADS : DF_SADS ) + g_aucConvertToBit[ iWidth ] + 1 ];
+#if NS_HAD
+  rcDP.bUseNSHAD  = bUseNSHAD;
+#endif
+}
+
+UInt TComRdCost::calcHAD( Pel* pi0, Int iStride0, Pel* pi1, Int iStride1, Int iWidth, Int iHeight )
+{
+  UInt uiSum = 0;
+  Int x, y;
+  
+  if ( ( (iWidth % 8) == 0 ) && ( (iHeight % 8) == 0 ) )
+  {
+    for ( y=0; y<iHeight; y+= 8 )
+    {
+      for ( x=0; x<iWidth; x+= 8 )
+      {
+        uiSum += xCalcHADs8x8( &pi0[x], &pi1[x], iStride0, iStride1, 1 );
+      }
+      pi0 += iStride0*8;
+      pi1 += iStride1*8;
+    }
+  }
+  else if ( ( (iWidth % 4) == 0 ) && ( (iHeight % 4) == 0 ) )
+  {
+    for ( y=0; y<iHeight; y+= 4 )
+    {
+      for ( x=0; x<iWidth; x+= 4 )
+      {
+        uiSum += xCalcHADs4x4( &pi0[x], &pi1[x], iStride0, iStride1, 1 );
+      }
+      pi0 += iStride0*4;
+      pi1 += iStride1*4;
+    }
+  }
+  else
+  {
+    for ( y=0; y<iHeight; y+= 2 )
+    {
+      for ( x=0; x<iWidth; x+= 2 )
+      {
+        uiSum += xCalcHADs8x8( &pi0[x], &pi1[x], iStride0, iStride1, 1 );
+      }
+      pi0 += iStride0*2;
+      pi1 += iStride1*2;
+    }
+  }
+  
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+#if WEIGHTED_CHROMA_DISTORTION
+UInt TComRdCost::getDistPart( Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, Bool bWeighted, DFunc eDFunc )
+#else
+UInt TComRdCost::getDistPart( Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, DFunc eDFunc )
+#endif
+{
+  DistParam cDtParam;
+  setDistParam( uiBlkWidth, uiBlkHeight, eDFunc, cDtParam );
+  cDtParam.pOrg       = piOrg;
+  cDtParam.pCur       = piCur;
+  cDtParam.iStrideOrg = iOrgStride;
+  cDtParam.iStrideCur = iCurStride;
+  cDtParam.iStep      = 1;
+
+  cDtParam.bApplyWeight = false;
+  cDtParam.uiComp       = 255;    // just for assert: to be sure it was set before use, since only values 0,1 or 2 are allowed.
+
+#if WEIGHTED_CHROMA_DISTORTION
+  if (bWeighted)
+  {
+    return ((int) (m_chromaDistortionWeight * cDtParam.DistFunc( &cDtParam )));
+  }
+  else
+  {
+    return cDtParam.DistFunc( &cDtParam );
+  }
+#else
+  return cDtParam.DistFunc( &cDtParam );
+#endif
+}
+
+
+
+// ====================================================================================================================
+// Distortion functions
+// ====================================================================================================================
+
+// --------------------------------------------------------------------------------------------------------------------
+// SAD
+// --------------------------------------------------------------------------------------------------------------------
+
+UInt TComRdCost::xGetSAD( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    for (Int n = 0; n < iCols; n++ )
+    {
+      uiSum += abs( piOrg[n] - piCur[n] );
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCost::xGetSAD4( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight ) 
+  {
+    return xGetSADw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] );
+    uiSum += abs( piOrg[1] - piCur[1] );
+    uiSum += abs( piOrg[2] - piCur[2] );
+    uiSum += abs( piOrg[3] - piCur[3] );
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCost::xGetSAD8( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+  Pel* piOrg      = pcDtParam->pOrg;
+  Pel* piCur      = pcDtParam->pCur;
+  Int  iRows      = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] );
+    uiSum += abs( piOrg[1] - piCur[1] );
+    uiSum += abs( piOrg[2] - piCur[2] );
+    uiSum += abs( piOrg[3] - piCur[3] );
+    uiSum += abs( piOrg[4] - piCur[4] );
+    uiSum += abs( piOrg[5] - piCur[5] );
+    uiSum += abs( piOrg[6] - piCur[6] );
+    uiSum += abs( piOrg[7] - piCur[7] );
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCost::xGetSAD16( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] );
+    uiSum += abs( piOrg[1] - piCur[1] );
+    uiSum += abs( piOrg[2] - piCur[2] );
+    uiSum += abs( piOrg[3] - piCur[3] );
+    uiSum += abs( piOrg[4] - piCur[4] );
+    uiSum += abs( piOrg[5] - piCur[5] );
+    uiSum += abs( piOrg[6] - piCur[6] );
+    uiSum += abs( piOrg[7] - piCur[7] );
+    uiSum += abs( piOrg[8] - piCur[8] );
+    uiSum += abs( piOrg[9] - piCur[9] );
+    uiSum += abs( piOrg[10] - piCur[10] );
+    uiSum += abs( piOrg[11] - piCur[11] );
+    uiSum += abs( piOrg[12] - piCur[12] );
+    uiSum += abs( piOrg[13] - piCur[13] );
+    uiSum += abs( piOrg[14] - piCur[14] );
+    uiSum += abs( piOrg[15] - piCur[15] );
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+#if AMP_SAD
+UInt TComRdCost::xGetSAD12( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] );
+    uiSum += abs( piOrg[1] - piCur[1] );
+    uiSum += abs( piOrg[2] - piCur[2] );
+    uiSum += abs( piOrg[3] - piCur[3] );
+    uiSum += abs( piOrg[4] - piCur[4] );
+    uiSum += abs( piOrg[5] - piCur[5] );
+    uiSum += abs( piOrg[6] - piCur[6] );
+    uiSum += abs( piOrg[7] - piCur[7] );
+    uiSum += abs( piOrg[8] - piCur[8] );
+    uiSum += abs( piOrg[9] - piCur[9] );
+    uiSum += abs( piOrg[10] - piCur[10] );
+    uiSum += abs( piOrg[11] - piCur[11] );
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+#endif
+
+UInt TComRdCost::xGetSAD16N( DistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    for (Int n = 0; n < iCols; n+=16 )
+    {
+      uiSum += abs( piOrg[n+ 0] - piCur[n+ 0] );
+      uiSum += abs( piOrg[n+ 1] - piCur[n+ 1] );
+      uiSum += abs( piOrg[n+ 2] - piCur[n+ 2] );
+      uiSum += abs( piOrg[n+ 3] - piCur[n+ 3] );
+      uiSum += abs( piOrg[n+ 4] - piCur[n+ 4] );
+      uiSum += abs( piOrg[n+ 5] - piCur[n+ 5] );
+      uiSum += abs( piOrg[n+ 6] - piCur[n+ 6] );
+      uiSum += abs( piOrg[n+ 7] - piCur[n+ 7] );
+      uiSum += abs( piOrg[n+ 8] - piCur[n+ 8] );
+      uiSum += abs( piOrg[n+ 9] - piCur[n+ 9] );
+      uiSum += abs( piOrg[n+10] - piCur[n+10] );
+      uiSum += abs( piOrg[n+11] - piCur[n+11] );
+      uiSum += abs( piOrg[n+12] - piCur[n+12] );
+      uiSum += abs( piOrg[n+13] - piCur[n+13] );
+      uiSum += abs( piOrg[n+14] - piCur[n+14] );
+      uiSum += abs( piOrg[n+15] - piCur[n+15] );
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCost::xGetSAD32( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] );
+    uiSum += abs( piOrg[1] - piCur[1] );
+    uiSum += abs( piOrg[2] - piCur[2] );
+    uiSum += abs( piOrg[3] - piCur[3] );
+    uiSum += abs( piOrg[4] - piCur[4] );
+    uiSum += abs( piOrg[5] - piCur[5] );
+    uiSum += abs( piOrg[6] - piCur[6] );
+    uiSum += abs( piOrg[7] - piCur[7] );
+    uiSum += abs( piOrg[8] - piCur[8] );
+    uiSum += abs( piOrg[9] - piCur[9] );
+    uiSum += abs( piOrg[10] - piCur[10] );
+    uiSum += abs( piOrg[11] - piCur[11] );
+    uiSum += abs( piOrg[12] - piCur[12] );
+    uiSum += abs( piOrg[13] - piCur[13] );
+    uiSum += abs( piOrg[14] - piCur[14] );
+    uiSum += abs( piOrg[15] - piCur[15] );
+    uiSum += abs( piOrg[16] - piCur[16] );
+    uiSum += abs( piOrg[17] - piCur[17] );
+    uiSum += abs( piOrg[18] - piCur[18] );
+    uiSum += abs( piOrg[19] - piCur[19] );
+    uiSum += abs( piOrg[20] - piCur[20] );
+    uiSum += abs( piOrg[21] - piCur[21] );
+    uiSum += abs( piOrg[22] - piCur[22] );
+    uiSum += abs( piOrg[23] - piCur[23] );
+    uiSum += abs( piOrg[24] - piCur[24] );
+    uiSum += abs( piOrg[25] - piCur[25] );
+    uiSum += abs( piOrg[26] - piCur[26] );
+    uiSum += abs( piOrg[27] - piCur[27] );
+    uiSum += abs( piOrg[28] - piCur[28] );
+    uiSum += abs( piOrg[29] - piCur[29] );
+    uiSum += abs( piOrg[30] - piCur[30] );
+    uiSum += abs( piOrg[31] - piCur[31] );
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+#if AMP_SAD
+UInt TComRdCost::xGetSAD24( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] );
+    uiSum += abs( piOrg[1] - piCur[1] );
+    uiSum += abs( piOrg[2] - piCur[2] );
+    uiSum += abs( piOrg[3] - piCur[3] );
+    uiSum += abs( piOrg[4] - piCur[4] );
+    uiSum += abs( piOrg[5] - piCur[5] );
+    uiSum += abs( piOrg[6] - piCur[6] );
+    uiSum += abs( piOrg[7] - piCur[7] );
+    uiSum += abs( piOrg[8] - piCur[8] );
+    uiSum += abs( piOrg[9] - piCur[9] );
+    uiSum += abs( piOrg[10] - piCur[10] );
+    uiSum += abs( piOrg[11] - piCur[11] );
+    uiSum += abs( piOrg[12] - piCur[12] );
+    uiSum += abs( piOrg[13] - piCur[13] );
+    uiSum += abs( piOrg[14] - piCur[14] );
+    uiSum += abs( piOrg[15] - piCur[15] );
+    uiSum += abs( piOrg[16] - piCur[16] );
+    uiSum += abs( piOrg[17] - piCur[17] );
+    uiSum += abs( piOrg[18] - piCur[18] );
+    uiSum += abs( piOrg[19] - piCur[19] );
+    uiSum += abs( piOrg[20] - piCur[20] );
+    uiSum += abs( piOrg[21] - piCur[21] );
+    uiSum += abs( piOrg[22] - piCur[22] );
+    uiSum += abs( piOrg[23] - piCur[23] );
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+#endif
+
+UInt TComRdCost::xGetSAD64( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] );
+    uiSum += abs( piOrg[1] - piCur[1] );
+    uiSum += abs( piOrg[2] - piCur[2] );
+    uiSum += abs( piOrg[3] - piCur[3] );
+    uiSum += abs( piOrg[4] - piCur[4] );
+    uiSum += abs( piOrg[5] - piCur[5] );
+    uiSum += abs( piOrg[6] - piCur[6] );
+    uiSum += abs( piOrg[7] - piCur[7] );
+    uiSum += abs( piOrg[8] - piCur[8] );
+    uiSum += abs( piOrg[9] - piCur[9] );
+    uiSum += abs( piOrg[10] - piCur[10] );
+    uiSum += abs( piOrg[11] - piCur[11] );
+    uiSum += abs( piOrg[12] - piCur[12] );
+    uiSum += abs( piOrg[13] - piCur[13] );
+    uiSum += abs( piOrg[14] - piCur[14] );
+    uiSum += abs( piOrg[15] - piCur[15] );
+    uiSum += abs( piOrg[16] - piCur[16] );
+    uiSum += abs( piOrg[17] - piCur[17] );
+    uiSum += abs( piOrg[18] - piCur[18] );
+    uiSum += abs( piOrg[19] - piCur[19] );
+    uiSum += abs( piOrg[20] - piCur[20] );
+    uiSum += abs( piOrg[21] - piCur[21] );
+    uiSum += abs( piOrg[22] - piCur[22] );
+    uiSum += abs( piOrg[23] - piCur[23] );
+    uiSum += abs( piOrg[24] - piCur[24] );
+    uiSum += abs( piOrg[25] - piCur[25] );
+    uiSum += abs( piOrg[26] - piCur[26] );
+    uiSum += abs( piOrg[27] - piCur[27] );
+    uiSum += abs( piOrg[28] - piCur[28] );
+    uiSum += abs( piOrg[29] - piCur[29] );
+    uiSum += abs( piOrg[30] - piCur[30] );
+    uiSum += abs( piOrg[31] - piCur[31] );
+    uiSum += abs( piOrg[32] - piCur[32] );
+    uiSum += abs( piOrg[33] - piCur[33] );
+    uiSum += abs( piOrg[34] - piCur[34] );
+    uiSum += abs( piOrg[35] - piCur[35] );
+    uiSum += abs( piOrg[36] - piCur[36] );
+    uiSum += abs( piOrg[37] - piCur[37] );
+    uiSum += abs( piOrg[38] - piCur[38] );
+    uiSum += abs( piOrg[39] - piCur[39] );
+    uiSum += abs( piOrg[40] - piCur[40] );
+    uiSum += abs( piOrg[41] - piCur[41] );
+    uiSum += abs( piOrg[42] - piCur[42] );
+    uiSum += abs( piOrg[43] - piCur[43] );
+    uiSum += abs( piOrg[44] - piCur[44] );
+    uiSum += abs( piOrg[45] - piCur[45] );
+    uiSum += abs( piOrg[46] - piCur[46] );
+    uiSum += abs( piOrg[47] - piCur[47] );
+    uiSum += abs( piOrg[48] - piCur[48] );
+    uiSum += abs( piOrg[49] - piCur[49] );
+    uiSum += abs( piOrg[50] - piCur[50] );
+    uiSum += abs( piOrg[51] - piCur[51] );
+    uiSum += abs( piOrg[52] - piCur[52] );
+    uiSum += abs( piOrg[53] - piCur[53] );
+    uiSum += abs( piOrg[54] - piCur[54] );
+    uiSum += abs( piOrg[55] - piCur[55] );
+    uiSum += abs( piOrg[56] - piCur[56] );
+    uiSum += abs( piOrg[57] - piCur[57] );
+    uiSum += abs( piOrg[58] - piCur[58] );
+    uiSum += abs( piOrg[59] - piCur[59] );
+    uiSum += abs( piOrg[60] - piCur[60] );
+    uiSum += abs( piOrg[61] - piCur[61] );
+    uiSum += abs( piOrg[62] - piCur[62] );
+    uiSum += abs( piOrg[63] - piCur[63] );
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+#if AMP_SAD
+UInt TComRdCost::xGetSAD48( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] );
+    uiSum += abs( piOrg[1] - piCur[1] );
+    uiSum += abs( piOrg[2] - piCur[2] );
+    uiSum += abs( piOrg[3] - piCur[3] );
+    uiSum += abs( piOrg[4] - piCur[4] );
+    uiSum += abs( piOrg[5] - piCur[5] );
+    uiSum += abs( piOrg[6] - piCur[6] );
+    uiSum += abs( piOrg[7] - piCur[7] );
+    uiSum += abs( piOrg[8] - piCur[8] );
+    uiSum += abs( piOrg[9] - piCur[9] );
+    uiSum += abs( piOrg[10] - piCur[10] );
+    uiSum += abs( piOrg[11] - piCur[11] );
+    uiSum += abs( piOrg[12] - piCur[12] );
+    uiSum += abs( piOrg[13] - piCur[13] );
+    uiSum += abs( piOrg[14] - piCur[14] );
+    uiSum += abs( piOrg[15] - piCur[15] );
+    uiSum += abs( piOrg[16] - piCur[16] );
+    uiSum += abs( piOrg[17] - piCur[17] );
+    uiSum += abs( piOrg[18] - piCur[18] );
+    uiSum += abs( piOrg[19] - piCur[19] );
+    uiSum += abs( piOrg[20] - piCur[20] );
+    uiSum += abs( piOrg[21] - piCur[21] );
+    uiSum += abs( piOrg[22] - piCur[22] );
+    uiSum += abs( piOrg[23] - piCur[23] );
+    uiSum += abs( piOrg[24] - piCur[24] );
+    uiSum += abs( piOrg[25] - piCur[25] );
+    uiSum += abs( piOrg[26] - piCur[26] );
+    uiSum += abs( piOrg[27] - piCur[27] );
+    uiSum += abs( piOrg[28] - piCur[28] );
+    uiSum += abs( piOrg[29] - piCur[29] );
+    uiSum += abs( piOrg[30] - piCur[30] );
+    uiSum += abs( piOrg[31] - piCur[31] );
+    uiSum += abs( piOrg[32] - piCur[32] );
+    uiSum += abs( piOrg[33] - piCur[33] );
+    uiSum += abs( piOrg[34] - piCur[34] );
+    uiSum += abs( piOrg[35] - piCur[35] );
+    uiSum += abs( piOrg[36] - piCur[36] );
+    uiSum += abs( piOrg[37] - piCur[37] );
+    uiSum += abs( piOrg[38] - piCur[38] );
+    uiSum += abs( piOrg[39] - piCur[39] );
+    uiSum += abs( piOrg[40] - piCur[40] );
+    uiSum += abs( piOrg[41] - piCur[41] );
+    uiSum += abs( piOrg[42] - piCur[42] );
+    uiSum += abs( piOrg[43] - piCur[43] );
+    uiSum += abs( piOrg[44] - piCur[44] );
+    uiSum += abs( piOrg[45] - piCur[45] );
+    uiSum += abs( piOrg[46] - piCur[46] );
+    uiSum += abs( piOrg[47] - piCur[47] );
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+#endif
+
+// --------------------------------------------------------------------------------------------------------------------
+// SSE
+// --------------------------------------------------------------------------------------------------------------------
+
+#if IBDI_DISTORTION
+UInt TComRdCost::xGetSSE( DistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+
+  UInt uiSum = 0;
+  Int  iShift = g_uiBitIncrement;
+  Int  iOffset = (g_uiBitIncrement>0)? (1<<(g_uiBitIncrement-1)):0;
+
+  Int iTemp;
+
+  for( ; iRows != 0; iRows-- )
+  {
+    for (Int n = 0; n < iCols; n++ )
+    {
+      iTemp = ((piOrg[n  ]+iOffset)>>iShift) - ((piCur[n  ]+iOffset)>>iShift);
+      uiSum += iTemp * iTemp;
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE4( DistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+
+  UInt uiSum = 0;
+  Int  iShift = g_uiBitIncrement;
+  Int  iOffset = (g_uiBitIncrement>0)? (1<<(g_uiBitIncrement-1)):0;
+
+  Int  iTemp;
+
+  for( ; iRows != 0; iRows-- )
+  {
+
+    iTemp = ((piOrg[0]+iOffset)>>iShift) - ((piCur[0]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[1]+iOffset)>>iShift) - ((piCur[1]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[2]+iOffset)>>iShift) - ((piCur[2]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[3]+iOffset)>>iShift) - ((piCur[3]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE8( DistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+
+  UInt uiSum = 0;
+  Int  iShift = g_uiBitIncrement;
+  Int  iOffset = (g_uiBitIncrement>0)? (1<<(g_uiBitIncrement-1)):0;
+
+  Int  iTemp;
+
+  for( ; iRows != 0; iRows-- )
+  {
+    iTemp = ((piOrg[0]+iOffset)>>iShift) - ((piCur[0]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[1]+iOffset)>>iShift) - ((piCur[1]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[2]+iOffset)>>iShift) - ((piCur[2]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[3]+iOffset)>>iShift) - ((piCur[3]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[4]+iOffset)>>iShift) - ((piCur[4]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[5]+iOffset)>>iShift) - ((piCur[5]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[6]+iOffset)>>iShift) - ((piCur[6]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[7]+iOffset)>>iShift) - ((piCur[7]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE16( DistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+
+  UInt uiSum = 0;
+  Int  iShift = g_uiBitIncrement;
+  Int  iOffset = (g_uiBitIncrement>0)? (1<<(g_uiBitIncrement-1)):0;
+
+  Int  iTemp;
+
+  for( ; iRows != 0; iRows-- )
+  {
+
+    iTemp = ((piOrg[ 0]+iOffset)>>iShift) - ((piCur[ 0]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 1]+iOffset)>>iShift) - ((piCur[ 1]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 2]+iOffset)>>iShift) - ((piCur[ 2]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 3]+iOffset)>>iShift) - ((piCur[ 3]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 4]+iOffset)>>iShift) - ((piCur[ 4]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 5]+iOffset)>>iShift) - ((piCur[ 5]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 6]+iOffset)>>iShift) - ((piCur[ 6]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 7]+iOffset)>>iShift) - ((piCur[ 7]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 8]+iOffset)>>iShift) - ((piCur[ 8]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 9]+iOffset)>>iShift) - ((piCur[ 9]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[10]+iOffset)>>iShift) - ((piCur[10]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[11]+iOffset)>>iShift) - ((piCur[11]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[12]+iOffset)>>iShift) - ((piCur[12]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[13]+iOffset)>>iShift) - ((piCur[13]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[14]+iOffset)>>iShift) - ((piCur[14]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[15]+iOffset)>>iShift) - ((piCur[15]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE16N( DistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+
+  UInt uiSum = 0;
+  Int  iShift = g_uiBitIncrement;
+  Int  iOffset = (g_uiBitIncrement>0)? (1<<(g_uiBitIncrement-1)):0;
+  Int  iTemp;
+
+  for( ; iRows != 0; iRows-- )
+  {
+    for (Int n = 0; n < iCols; n+=16 )
+    {
+
+      iTemp = ((piOrg[n+ 0]+iOffset)>>iShift) - ((piCur[n+ 0]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      iTemp = ((piOrg[n+ 1]+iOffset)>>iShift) - ((piCur[n+ 1]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      iTemp = ((piOrg[n+ 2]+iOffset)>>iShift) - ((piCur[n+ 2]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      iTemp = ((piOrg[n+ 3]+iOffset)>>iShift) - ((piCur[n+ 3]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      iTemp = ((piOrg[n+ 4]+iOffset)>>iShift) - ((piCur[n+ 4]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      iTemp = ((piOrg[n+ 5]+iOffset)>>iShift) - ((piCur[n+ 5]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      iTemp = ((piOrg[n+ 6]+iOffset)>>iShift) - ((piCur[n+ 6]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      iTemp = ((piOrg[n+ 7]+iOffset)>>iShift) - ((piCur[n+ 7]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      iTemp = ((piOrg[n+ 8]+iOffset)>>iShift) - ((piCur[n+ 8]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      iTemp = ((piOrg[n+ 9]+iOffset)>>iShift) - ((piCur[n+ 9]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      iTemp = ((piOrg[n+10]+iOffset)>>iShift) - ((piCur[n+10]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      iTemp = ((piOrg[n+11]+iOffset)>>iShift) - ((piCur[n+11]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      iTemp = ((piOrg[n+12]+iOffset)>>iShift) - ((piCur[n+12]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      iTemp = ((piOrg[n+13]+iOffset)>>iShift) - ((piCur[n+13]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      iTemp = ((piOrg[n+14]+iOffset)>>iShift) - ((piCur[n+14]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      iTemp = ((piOrg[n+15]+iOffset)>>iShift) - ((piCur[n+15]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE32( DistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+
+  UInt uiSum = 0;
+  Int  iShift = g_uiBitIncrement;
+  Int  iOffset = (g_uiBitIncrement>0)? (1<<(g_uiBitIncrement-1)):0;
+  Int  iTemp;
+
+  for( ; iRows != 0; iRows-- )
+  {
+
+    iTemp = ((piOrg[ 0]+iOffset)>>iShift) - ((piCur[ 0]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 1]+iOffset)>>iShift) - ((piCur[ 1]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 2]+iOffset)>>iShift) - ((piCur[ 2]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 3]+iOffset)>>iShift) - ((piCur[ 3]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 4]+iOffset)>>iShift) - ((piCur[ 4]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 5]+iOffset)>>iShift) - ((piCur[ 5]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 6]+iOffset)>>iShift) - ((piCur[ 6]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 7]+iOffset)>>iShift) - ((piCur[ 7]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 8]+iOffset)>>iShift) - ((piCur[ 8]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 9]+iOffset)>>iShift) - ((piCur[ 9]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[10]+iOffset)>>iShift) - ((piCur[10]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[11]+iOffset)>>iShift) - ((piCur[11]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[12]+iOffset)>>iShift) - ((piCur[12]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[13]+iOffset)>>iShift) - ((piCur[13]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[14]+iOffset)>>iShift) - ((piCur[14]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[15]+iOffset)>>iShift) - ((piCur[15]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[16]+iOffset)>>iShift) - ((piCur[16]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[17]+iOffset)>>iShift) - ((piCur[17]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[18]+iOffset)>>iShift) - ((piCur[18]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[19]+iOffset)>>iShift) - ((piCur[19]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[20]+iOffset)>>iShift) - ((piCur[20]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[21]+iOffset)>>iShift) - ((piCur[21]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[22]+iOffset)>>iShift) - ((piCur[22]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[23]+iOffset)>>iShift) - ((piCur[23]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[24]+iOffset)>>iShift) - ((piCur[24]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[25]+iOffset)>>iShift) - ((piCur[25]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[26]+iOffset)>>iShift) - ((piCur[26]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[27]+iOffset)>>iShift) - ((piCur[27]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[28]+iOffset)>>iShift) - ((piCur[28]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[29]+iOffset)>>iShift) - ((piCur[29]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[30]+iOffset)>>iShift) - ((piCur[30]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[31]+iOffset)>>iShift) - ((piCur[31]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE64( DistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+
+  UInt uiSum = 0;
+  Int  iShift = g_uiBitIncrement;
+  Int  iOffset = (g_uiBitIncrement>0)? (1<<(g_uiBitIncrement-1)):0;
+  Int  iTemp;
+
+  for( ; iRows != 0; iRows-- )
+  {
+    iTemp = ((piOrg[ 0]+iOffset)>>iShift) - ((piCur[ 0]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 1]+iOffset)>>iShift) - ((piCur[ 1]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 2]+iOffset)>>iShift) - ((piCur[ 2]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 3]+iOffset)>>iShift) - ((piCur[ 3]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 4]+iOffset)>>iShift) - ((piCur[ 4]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 5]+iOffset)>>iShift) - ((piCur[ 5]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 6]+iOffset)>>iShift) - ((piCur[ 6]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 7]+iOffset)>>iShift) - ((piCur[ 7]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 8]+iOffset)>>iShift) - ((piCur[ 8]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 9]+iOffset)>>iShift) - ((piCur[ 9]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[10]+iOffset)>>iShift) - ((piCur[10]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[11]+iOffset)>>iShift) - ((piCur[11]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[12]+iOffset)>>iShift) - ((piCur[12]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[13]+iOffset)>>iShift) - ((piCur[13]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[14]+iOffset)>>iShift) - ((piCur[14]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[15]+iOffset)>>iShift) - ((piCur[15]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[16]+iOffset)>>iShift) - ((piCur[16]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[17]+iOffset)>>iShift) - ((piCur[17]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[18]+iOffset)>>iShift) - ((piCur[18]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[19]+iOffset)>>iShift) - ((piCur[19]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[20]+iOffset)>>iShift) - ((piCur[20]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[21]+iOffset)>>iShift) - ((piCur[21]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[22]+iOffset)>>iShift) - ((piCur[22]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[23]+iOffset)>>iShift) - ((piCur[23]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[24]+iOffset)>>iShift) - ((piCur[24]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[25]+iOffset)>>iShift) - ((piCur[25]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[26]+iOffset)>>iShift) - ((piCur[26]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[27]+iOffset)>>iShift) - ((piCur[27]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[28]+iOffset)>>iShift) - ((piCur[28]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[29]+iOffset)>>iShift) - ((piCur[29]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[30]+iOffset)>>iShift) - ((piCur[30]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[31]+iOffset)>>iShift) - ((piCur[31]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[32]+iOffset)>>iShift) - ((piCur[32]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[33]+iOffset)>>iShift) - ((piCur[33]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[34]+iOffset)>>iShift) - ((piCur[34]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[35]+iOffset)>>iShift) - ((piCur[35]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[36]+iOffset)>>iShift) - ((piCur[36]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[37]+iOffset)>>iShift) - ((piCur[37]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[38]+iOffset)>>iShift) - ((piCur[38]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[39]+iOffset)>>iShift) - ((piCur[39]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[40]+iOffset)>>iShift) - ((piCur[40]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[41]+iOffset)>>iShift) - ((piCur[41]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[42]+iOffset)>>iShift) - ((piCur[42]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[43]+iOffset)>>iShift) - ((piCur[43]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[44]+iOffset)>>iShift) - ((piCur[44]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[45]+iOffset)>>iShift) - ((piCur[45]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[46]+iOffset)>>iShift) - ((piCur[46]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[47]+iOffset)>>iShift) - ((piCur[47]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[48]+iOffset)>>iShift) - ((piCur[48]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[49]+iOffset)>>iShift) - ((piCur[49]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[50]+iOffset)>>iShift) - ((piCur[50]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[51]+iOffset)>>iShift) - ((piCur[51]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[52]+iOffset)>>iShift) - ((piCur[52]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[53]+iOffset)>>iShift) - ((piCur[53]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[54]+iOffset)>>iShift) - ((piCur[54]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[55]+iOffset)>>iShift) - ((piCur[55]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[56]+iOffset)>>iShift) - ((piCur[56]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[57]+iOffset)>>iShift) - ((piCur[57]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[58]+iOffset)>>iShift) - ((piCur[58]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[59]+iOffset)>>iShift) - ((piCur[59]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[60]+iOffset)>>iShift) - ((piCur[60]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[61]+iOffset)>>iShift) - ((piCur[61]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[62]+iOffset)>>iShift) - ((piCur[62]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[63]+iOffset)>>iShift) - ((piCur[63]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum );
+}
+#else
+UInt TComRdCost::xGetSSE( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSSEw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  
+  UInt uiSum = 0;
+  UInt uiShift = g_uiBitIncrement<<1;
+  
+  Int iTemp;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    for (Int n = 0; n < iCols; n++ )
+    {
+      iTemp = piOrg[n  ] - piCur[n  ];
+      uiSum += ( iTemp * iTemp ) >> uiShift;
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE4( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    assert( pcDtParam->iCols == 4 );
+    return xGetSSEw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  
+  UInt uiSum = 0;
+  UInt uiShift = g_uiBitIncrement<<1;
+  
+  Int  iTemp;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    
+    iTemp = piOrg[0] - piCur[0]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[1] - piCur[1]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[2] - piCur[2]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[3] - piCur[3]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE8( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    assert( pcDtParam->iCols == 8 );
+    return xGetSSEw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  
+  UInt uiSum = 0;
+  UInt uiShift = g_uiBitIncrement<<1;
+  
+  Int  iTemp;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    iTemp = piOrg[0] - piCur[0]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[1] - piCur[1]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[2] - piCur[2]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[3] - piCur[3]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[4] - piCur[4]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[5] - piCur[5]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[6] - piCur[6]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[7] - piCur[7]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE16( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    assert( pcDtParam->iCols == 16 );
+    return xGetSSEw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  
+  UInt uiSum = 0;
+  UInt uiShift = g_uiBitIncrement<<1;
+  
+  Int  iTemp;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    
+    iTemp = piOrg[ 0] - piCur[ 0]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 1] - piCur[ 1]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 2] - piCur[ 2]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 3] - piCur[ 3]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 4] - piCur[ 4]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 5] - piCur[ 5]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 6] - piCur[ 6]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 7] - piCur[ 7]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 8] - piCur[ 8]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 9] - piCur[ 9]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[10] - piCur[10]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[11] - piCur[11]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[12] - piCur[12]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[13] - piCur[13]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[14] - piCur[14]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[15] - piCur[15]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE16N( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSSEw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  
+  UInt uiSum = 0;
+  UInt uiShift = g_uiBitIncrement<<1;
+  Int  iTemp;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    for (Int n = 0; n < iCols; n+=16 )
+    {
+      
+      iTemp = piOrg[n+ 0] - piCur[n+ 0]; uiSum += ( iTemp * iTemp ) >> uiShift;
+      iTemp = piOrg[n+ 1] - piCur[n+ 1]; uiSum += ( iTemp * iTemp ) >> uiShift;
+      iTemp = piOrg[n+ 2] - piCur[n+ 2]; uiSum += ( iTemp * iTemp ) >> uiShift;
+      iTemp = piOrg[n+ 3] - piCur[n+ 3]; uiSum += ( iTemp * iTemp ) >> uiShift;
+      iTemp = piOrg[n+ 4] - piCur[n+ 4]; uiSum += ( iTemp * iTemp ) >> uiShift;
+      iTemp = piOrg[n+ 5] - piCur[n+ 5]; uiSum += ( iTemp * iTemp ) >> uiShift;
+      iTemp = piOrg[n+ 6] - piCur[n+ 6]; uiSum += ( iTemp * iTemp ) >> uiShift;
+      iTemp = piOrg[n+ 7] - piCur[n+ 7]; uiSum += ( iTemp * iTemp ) >> uiShift;
+      iTemp = piOrg[n+ 8] - piCur[n+ 8]; uiSum += ( iTemp * iTemp ) >> uiShift;
+      iTemp = piOrg[n+ 9] - piCur[n+ 9]; uiSum += ( iTemp * iTemp ) >> uiShift;
+      iTemp = piOrg[n+10] - piCur[n+10]; uiSum += ( iTemp * iTemp ) >> uiShift;
+      iTemp = piOrg[n+11] - piCur[n+11]; uiSum += ( iTemp * iTemp ) >> uiShift;
+      iTemp = piOrg[n+12] - piCur[n+12]; uiSum += ( iTemp * iTemp ) >> uiShift;
+      iTemp = piOrg[n+13] - piCur[n+13]; uiSum += ( iTemp * iTemp ) >> uiShift;
+      iTemp = piOrg[n+14] - piCur[n+14]; uiSum += ( iTemp * iTemp ) >> uiShift;
+      iTemp = piOrg[n+15] - piCur[n+15]; uiSum += ( iTemp * iTemp ) >> uiShift;
+      
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE32( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    assert( pcDtParam->iCols == 32 );
+    return xGetSSEw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  
+  UInt uiSum = 0;
+  UInt uiShift = g_uiBitIncrement<<1;
+  Int  iTemp;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    
+    iTemp = piOrg[ 0] - piCur[ 0]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 1] - piCur[ 1]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 2] - piCur[ 2]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 3] - piCur[ 3]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 4] - piCur[ 4]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 5] - piCur[ 5]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 6] - piCur[ 6]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 7] - piCur[ 7]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 8] - piCur[ 8]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 9] - piCur[ 9]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[10] - piCur[10]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[11] - piCur[11]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[12] - piCur[12]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[13] - piCur[13]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[14] - piCur[14]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[15] - piCur[15]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[16] - piCur[16]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[17] - piCur[17]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[18] - piCur[18]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[19] - piCur[19]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[20] - piCur[20]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[21] - piCur[21]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[22] - piCur[22]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[23] - piCur[23]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[24] - piCur[24]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[25] - piCur[25]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[26] - piCur[26]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[27] - piCur[27]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[28] - piCur[28]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[29] - piCur[29]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[30] - piCur[30]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[31] - piCur[31]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE64( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    assert( pcDtParam->iCols == 64 );
+    return xGetSSEw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  
+  UInt uiSum = 0;
+  UInt uiShift = g_uiBitIncrement<<1;
+  Int  iTemp;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    iTemp = piOrg[ 0] - piCur[ 0]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 1] - piCur[ 1]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 2] - piCur[ 2]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 3] - piCur[ 3]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 4] - piCur[ 4]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 5] - piCur[ 5]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 6] - piCur[ 6]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 7] - piCur[ 7]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 8] - piCur[ 8]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 9] - piCur[ 9]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[10] - piCur[10]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[11] - piCur[11]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[12] - piCur[12]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[13] - piCur[13]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[14] - piCur[14]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[15] - piCur[15]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[16] - piCur[16]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[17] - piCur[17]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[18] - piCur[18]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[19] - piCur[19]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[20] - piCur[20]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[21] - piCur[21]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[22] - piCur[22]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[23] - piCur[23]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[24] - piCur[24]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[25] - piCur[25]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[26] - piCur[26]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[27] - piCur[27]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[28] - piCur[28]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[29] - piCur[29]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[30] - piCur[30]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[31] - piCur[31]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[32] - piCur[32]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[33] - piCur[33]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[34] - piCur[34]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[35] - piCur[35]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[36] - piCur[36]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[37] - piCur[37]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[38] - piCur[38]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[39] - piCur[39]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[40] - piCur[40]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[41] - piCur[41]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[42] - piCur[42]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[43] - piCur[43]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[44] - piCur[44]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[45] - piCur[45]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[46] - piCur[46]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[47] - piCur[47]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[48] - piCur[48]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[49] - piCur[49]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[50] - piCur[50]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[51] - piCur[51]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[52] - piCur[52]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[53] - piCur[53]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[54] - piCur[54]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[55] - piCur[55]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[56] - piCur[56]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[57] - piCur[57]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[58] - piCur[58]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[59] - piCur[59]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[60] - piCur[60]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[61] - piCur[61]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[62] - piCur[62]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[63] - piCur[63]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  return ( uiSum );
+}
+#endif
+
+// --------------------------------------------------------------------------------------------------------------------
+// HADAMARD with step (used in fractional search)
+// --------------------------------------------------------------------------------------------------------------------
+
+UInt TComRdCost::xCalcHADs2x2( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
+{
+  Int satd = 0, diff[4], m[4];
+  assert( iStep == 1 );
+  diff[0] = piOrg[0             ] - piCur[0];
+  diff[1] = piOrg[1             ] - piCur[1];
+  diff[2] = piOrg[iStrideOrg    ] - piCur[0 + iStrideCur];
+  diff[3] = piOrg[iStrideOrg + 1] - piCur[1 + iStrideCur];
+  m[0] = diff[0] + diff[2];
+  m[1] = diff[1] + diff[3];
+  m[2] = diff[0] - diff[2];
+  m[3] = diff[1] - diff[3];
+  
+  satd += abs(m[0] + m[1]);
+  satd += abs(m[0] - m[1]);
+  satd += abs(m[2] + m[3]);
+  satd += abs(m[2] - m[3]);
+  
+  return satd;
+}
+
+UInt TComRdCost::xCalcHADs4x4( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
+{
+  Int k, satd = 0, diff[16], m[16], d[16];
+  
+  assert( iStep == 1 );
+  for( k = 0; k < 16; k+=4 )
+  {
+    diff[k+0] = piOrg[0] - piCur[0];
+    diff[k+1] = piOrg[1] - piCur[1];
+    diff[k+2] = piOrg[2] - piCur[2];
+    diff[k+3] = piOrg[3] - piCur[3];
+    
+    piCur += iStrideCur;
+    piOrg += iStrideOrg;
+  }
+  
+  /*===== hadamard transform =====*/
+  m[ 0] = diff[ 0] + diff[12];
+  m[ 1] = diff[ 1] + diff[13];
+  m[ 2] = diff[ 2] + diff[14];
+  m[ 3] = diff[ 3] + diff[15];
+  m[ 4] = diff[ 4] + diff[ 8];
+  m[ 5] = diff[ 5] + diff[ 9];
+  m[ 6] = diff[ 6] + diff[10];
+  m[ 7] = diff[ 7] + diff[11];
+  m[ 8] = diff[ 4] - diff[ 8];
+  m[ 9] = diff[ 5] - diff[ 9];
+  m[10] = diff[ 6] - diff[10];
+  m[11] = diff[ 7] - diff[11];
+  m[12] = diff[ 0] - diff[12];
+  m[13] = diff[ 1] - diff[13];
+  m[14] = diff[ 2] - diff[14];
+  m[15] = diff[ 3] - diff[15];
+  
+  d[ 0] = m[ 0] + m[ 4];
+  d[ 1] = m[ 1] + m[ 5];
+  d[ 2] = m[ 2] + m[ 6];
+  d[ 3] = m[ 3] + m[ 7];
+  d[ 4] = m[ 8] + m[12];
+  d[ 5] = m[ 9] + m[13];
+  d[ 6] = m[10] + m[14];
+  d[ 7] = m[11] + m[15];
+  d[ 8] = m[ 0] - m[ 4];
+  d[ 9] = m[ 1] - m[ 5];
+  d[10] = m[ 2] - m[ 6];
+  d[11] = m[ 3] - m[ 7];
+  d[12] = m[12] - m[ 8];
+  d[13] = m[13] - m[ 9];
+  d[14] = m[14] - m[10];
+  d[15] = m[15] - m[11];
+  
+  m[ 0] = d[ 0] + d[ 3];
+  m[ 1] = d[ 1] + d[ 2];
+  m[ 2] = d[ 1] - d[ 2];
+  m[ 3] = d[ 0] - d[ 3];
+  m[ 4] = d[ 4] + d[ 7];
+  m[ 5] = d[ 5] + d[ 6];
+  m[ 6] = d[ 5] - d[ 6];
+  m[ 7] = d[ 4] - d[ 7];
+  m[ 8] = d[ 8] + d[11];
+  m[ 9] = d[ 9] + d[10];
+  m[10] = d[ 9] - d[10];
+  m[11] = d[ 8] - d[11];
+  m[12] = d[12] + d[15];
+  m[13] = d[13] + d[14];
+  m[14] = d[13] - d[14];
+  m[15] = d[12] - d[15];
+  
+  d[ 0] = m[ 0] + m[ 1];
+  d[ 1] = m[ 0] - m[ 1];
+  d[ 2] = m[ 2] + m[ 3];
+  d[ 3] = m[ 3] - m[ 2];
+  d[ 4] = m[ 4] + m[ 5];
+  d[ 5] = m[ 4] - m[ 5];
+  d[ 6] = m[ 6] + m[ 7];
+  d[ 7] = m[ 7] - m[ 6];
+  d[ 8] = m[ 8] + m[ 9];
+  d[ 9] = m[ 8] - m[ 9];
+  d[10] = m[10] + m[11];
+  d[11] = m[11] - m[10];
+  d[12] = m[12] + m[13];
+  d[13] = m[12] - m[13];
+  d[14] = m[14] + m[15];
+  d[15] = m[15] - m[14];
+  
+  for (k=0; k<16; ++k)
+  {
+    satd += abs(d[k]);
+  }
+  satd = ((satd+1)>>1);
+  
+  return satd;
+}
+
+UInt TComRdCost::xCalcHADs8x8( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
+{
+  Int k, i, j, jj, sad=0;
+  Int diff[64], m1[8][8], m2[8][8], m3[8][8];
+  assert( iStep == 1 );
+  for( k = 0; k < 64; k += 8 )
+  {
+    diff[k+0] = piOrg[0] - piCur[0];
+    diff[k+1] = piOrg[1] - piCur[1];
+    diff[k+2] = piOrg[2] - piCur[2];
+    diff[k+3] = piOrg[3] - piCur[3];
+    diff[k+4] = piOrg[4] - piCur[4];
+    diff[k+5] = piOrg[5] - piCur[5];
+    diff[k+6] = piOrg[6] - piCur[6];
+    diff[k+7] = piOrg[7] - piCur[7];
+    
+    piCur += iStrideCur;
+    piOrg += iStrideOrg;
+  }
+  
+  //horizontal
+  for (j=0; j < 8; j++)
+  {
+    jj = j << 3;
+    m2[j][0] = diff[jj  ] + diff[jj+4];
+    m2[j][1] = diff[jj+1] + diff[jj+5];
+    m2[j][2] = diff[jj+2] + diff[jj+6];
+    m2[j][3] = diff[jj+3] + diff[jj+7];
+    m2[j][4] = diff[jj  ] - diff[jj+4];
+    m2[j][5] = diff[jj+1] - diff[jj+5];
+    m2[j][6] = diff[jj+2] - diff[jj+6];
+    m2[j][7] = diff[jj+3] - diff[jj+7];
+    
+    m1[j][0] = m2[j][0] + m2[j][2];
+    m1[j][1] = m2[j][1] + m2[j][3];
+    m1[j][2] = m2[j][0] - m2[j][2];
+    m1[j][3] = m2[j][1] - m2[j][3];
+    m1[j][4] = m2[j][4] + m2[j][6];
+    m1[j][5] = m2[j][5] + m2[j][7];
+    m1[j][6] = m2[j][4] - m2[j][6];
+    m1[j][7] = m2[j][5] - m2[j][7];
+    
+    m2[j][0] = m1[j][0] + m1[j][1];
+    m2[j][1] = m1[j][0] - m1[j][1];
+    m2[j][2] = m1[j][2] + m1[j][3];
+    m2[j][3] = m1[j][2] - m1[j][3];
+    m2[j][4] = m1[j][4] + m1[j][5];
+    m2[j][5] = m1[j][4] - m1[j][5];
+    m2[j][6] = m1[j][6] + m1[j][7];
+    m2[j][7] = m1[j][6] - m1[j][7];
+  }
+  
+  //vertical
+  for (i=0; i < 8; i++)
+  {
+    m3[0][i] = m2[0][i] + m2[4][i];
+    m3[1][i] = m2[1][i] + m2[5][i];
+    m3[2][i] = m2[2][i] + m2[6][i];
+    m3[3][i] = m2[3][i] + m2[7][i];
+    m3[4][i] = m2[0][i] - m2[4][i];
+    m3[5][i] = m2[1][i] - m2[5][i];
+    m3[6][i] = m2[2][i] - m2[6][i];
+    m3[7][i] = m2[3][i] - m2[7][i];
+    
+    m1[0][i] = m3[0][i] + m3[2][i];
+    m1[1][i] = m3[1][i] + m3[3][i];
+    m1[2][i] = m3[0][i] - m3[2][i];
+    m1[3][i] = m3[1][i] - m3[3][i];
+    m1[4][i] = m3[4][i] + m3[6][i];
+    m1[5][i] = m3[5][i] + m3[7][i];
+    m1[6][i] = m3[4][i] - m3[6][i];
+    m1[7][i] = m3[5][i] - m3[7][i];
+    
+    m2[0][i] = m1[0][i] + m1[1][i];
+    m2[1][i] = m1[0][i] - m1[1][i];
+    m2[2][i] = m1[2][i] + m1[3][i];
+    m2[3][i] = m1[2][i] - m1[3][i];
+    m2[4][i] = m1[4][i] + m1[5][i];
+    m2[5][i] = m1[4][i] - m1[5][i];
+    m2[6][i] = m1[6][i] + m1[7][i];
+    m2[7][i] = m1[6][i] - m1[7][i];
+  }
+  
+  for (i = 0; i < 8; i++)
+  {
+    for (j = 0; j < 8; j++)
+    {
+      sad += abs(m2[i][j]);
+    }
+  }
+  
+  sad=((sad+2)>>2);
+  
+  return sad;
+}
+
+#if NS_HAD
+UInt TComRdCost::xCalcHADs16x4( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
+{
+  Int k, i, j, jj, sad=0;
+  Int diff[64], m1[4][16], m2[4][16];
+  assert( iStep == 1 );
+  for( k = 0; k < 64; k += 16 )
+  {
+    diff[k+0] = piOrg[0] - piCur[0];
+    diff[k+1] = piOrg[1] - piCur[1];
+    diff[k+2] = piOrg[2] - piCur[2];
+    diff[k+3] = piOrg[3] - piCur[3];
+    diff[k+4] = piOrg[4] - piCur[4];
+    diff[k+5] = piOrg[5] - piCur[5];
+    diff[k+6] = piOrg[6] - piCur[6];
+    diff[k+7] = piOrg[7] - piCur[7];
+
+    diff[k+8]  = piOrg[8]  - piCur[8] ;
+    diff[k+9]  = piOrg[9]  - piCur[9] ;
+    diff[k+10] = piOrg[10] - piCur[10];
+    diff[k+11] = piOrg[11] - piCur[11];
+    diff[k+12] = piOrg[12] - piCur[12];
+    diff[k+13] = piOrg[13] - piCur[13];
+    diff[k+14] = piOrg[14] - piCur[14];
+    diff[k+15] = piOrg[15] - piCur[15];
+
+    piCur += iStrideCur;
+    piOrg += iStrideOrg;
+  }
+
+  //horizontal
+  for (j=0; j < 4; j++)
+  {
+    jj = j << 4;
+
+    m2[j][0]  = diff[jj  ] + diff[jj+8];
+    m2[j][1]  = diff[jj+1] + diff[jj+9];
+    m2[j][2]  = diff[jj+2] + diff[jj+10];
+    m2[j][3]  = diff[jj+3] + diff[jj+11];
+    m2[j][4]  = diff[jj+4] + diff[jj+12];
+    m2[j][5]  = diff[jj+5] + diff[jj+13];
+    m2[j][6]  = diff[jj+6] + diff[jj+14];
+    m2[j][7]  = diff[jj+7] + diff[jj+15];
+    m2[j][8]  = diff[jj  ] - diff[jj+8];
+    m2[j][9]  = diff[jj+1] - diff[jj+9];
+    m2[j][10] = diff[jj+2] - diff[jj+10];
+    m2[j][11] = diff[jj+3] - diff[jj+11];
+    m2[j][12] = diff[jj+4] - diff[jj+12];
+    m2[j][13] = diff[jj+5] - diff[jj+13];
+    m2[j][14] = diff[jj+6] - diff[jj+14];
+    m2[j][15] = diff[jj+7] - diff[jj+15];
+
+    m1[j][0]  = m2[j][0]  + m2[j][4];
+    m1[j][1]  = m2[j][1]  + m2[j][5];
+    m1[j][2]  = m2[j][2]  + m2[j][6];
+    m1[j][3]  = m2[j][3]  + m2[j][7];
+    m1[j][4]  = m2[j][0]  - m2[j][4];
+    m1[j][5]  = m2[j][1]  - m2[j][5];
+    m1[j][6]  = m2[j][2]  - m2[j][6];
+    m1[j][7]  = m2[j][3]  - m2[j][7];
+    m1[j][8]  = m2[j][8]  + m2[j][12];
+    m1[j][9]  = m2[j][9]  + m2[j][13];
+    m1[j][10] = m2[j][10] + m2[j][14];
+    m1[j][11] = m2[j][11] + m2[j][15];
+    m1[j][12] = m2[j][8]  - m2[j][12];
+    m1[j][13] = m2[j][9]  - m2[j][13];
+    m1[j][14] = m2[j][10] - m2[j][14];
+    m1[j][15] = m2[j][11] - m2[j][15];
+
+    m2[j][0]  = m1[j][0]  + m1[j][2];
+    m2[j][1]  = m1[j][1]  + m1[j][3];
+    m2[j][2]  = m1[j][0]  - m1[j][2];
+    m2[j][3]  = m1[j][1]  - m1[j][3];
+    m2[j][4]  = m1[j][4]  + m1[j][6];
+    m2[j][5]  = m1[j][5]  + m1[j][7];
+    m2[j][6]  = m1[j][4]  - m1[j][6];
+    m2[j][7]  = m1[j][5]  - m1[j][7];
+    m2[j][8]  = m1[j][8]  + m1[j][10];
+    m2[j][9]  = m1[j][9]  + m1[j][11];
+    m2[j][10] = m1[j][8]  - m1[j][10];
+    m2[j][11] = m1[j][9]  - m1[j][11];
+    m2[j][12] = m1[j][12] + m1[j][14];
+    m2[j][13] = m1[j][13] + m1[j][15];
+    m2[j][14] = m1[j][12] - m1[j][14];
+    m2[j][15] = m1[j][13] - m1[j][15];
+
+    m1[j][0]  = m2[j][0]  + m2[j][1];
+    m1[j][1]  = m2[j][0]  - m2[j][1];
+    m1[j][2]  = m2[j][2]  + m2[j][3];
+    m1[j][3]  = m2[j][2]  - m2[j][3];
+    m1[j][4]  = m2[j][4]  + m2[j][5];
+    m1[j][5]  = m2[j][4]  - m2[j][5];
+    m1[j][6]  = m2[j][6]  + m2[j][7];
+    m1[j][7]  = m2[j][6]  - m2[j][7];
+    m1[j][8]  = m2[j][8]  + m2[j][9];
+    m1[j][9]  = m2[j][8]  - m2[j][9];
+    m1[j][10] = m2[j][10] + m2[j][11];
+    m1[j][11] = m2[j][10] - m2[j][11];
+    m1[j][12] = m2[j][12] + m2[j][13];
+    m1[j][13] = m2[j][12] - m2[j][13];
+    m1[j][14] = m2[j][14] + m2[j][15];
+    m1[j][15] = m2[j][14] - m2[j][15];
+  }
+
+  //vertical
+  for (i=0; i < 16; i++)
+  {    
+    m2[0][i] = m1[0][i] + m1[2][i];
+    m2[1][i] = m1[1][i] + m1[3][i];
+    m2[2][i] = m1[0][i] - m1[2][i];
+    m2[3][i] = m1[1][i] - m1[3][i];
+
+    m1[0][i] = m2[0][i] + m2[1][i];
+    m1[1][i] = m2[0][i] - m2[1][i];
+    m1[2][i] = m2[2][i] + m2[3][i];
+    m1[3][i] = m2[2][i] - m2[3][i];
+  }
+
+  for (i = 0; i < 4; i++)
+  {
+    for (j = 0; j < 16; j++)
+    {
+      sad += abs(m1[i][j]);
+    }
+  }
+
+  sad=((sad+2)>>2);
+
+  return sad;
+}
+
+UInt TComRdCost::xCalcHADs4x16( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
+{
+  Int k, i, j, jj, sad=0;
+  Int diff[64], m1[16][4], m2[16][4], m3[16][4];
+  assert( iStep == 1 );
+  for( k = 0; k < 64; k += 4 )
+  {
+    diff[k+0] = piOrg[0] - piCur[0];
+    diff[k+1] = piOrg[1] - piCur[1];
+    diff[k+2] = piOrg[2] - piCur[2];
+    diff[k+3] = piOrg[3] - piCur[3];
+
+    piCur += iStrideCur;
+    piOrg += iStrideOrg;
+  }
+
+  //horizontal
+  for (j=0; j < 16; j++)
+  {
+    jj = j << 2;
+    m2[j][0] = diff[jj  ] + diff[jj+2];
+    m2[j][1] = diff[jj+1] + diff[jj+3];
+    m2[j][2] = diff[jj  ] - diff[jj+2];
+    m2[j][3] = diff[jj+1] - diff[jj+3];
+
+    m1[j][0] = m2[j][0] + m2[j][1];
+    m1[j][1] = m2[j][0] - m2[j][1];
+    m1[j][2] = m2[j][2] + m2[j][3];
+    m1[j][3] = m2[j][2] - m2[j][3];
+  }
+
+  //vertical
+  for (i=0; i < 4; i++)
+  {
+    m2[0][i]  = m1[0][i] + m1[8][i];
+    m2[1][i]  = m1[1][i] + m1[9][i];
+    m2[2][i]  = m1[2][i] + m1[10][i];
+    m2[3][i]  = m1[3][i] + m1[11][i];
+    m2[4][i]  = m1[4][i] + m1[12][i];
+    m2[5][i]  = m1[5][i] + m1[13][i];
+    m2[6][i]  = m1[6][i] + m1[14][i];
+    m2[7][i]  = m1[7][i] + m1[15][i];
+    m2[8][i]  = m1[0][i] - m1[8][i];
+    m2[9][i]  = m1[1][i] - m1[9][i];
+    m2[10][i] = m1[2][i] - m1[10][i];
+    m2[11][i] = m1[3][i] - m1[11][i];
+    m2[12][i] = m1[4][i] - m1[12][i];
+    m2[13][i] = m1[5][i] - m1[13][i];
+    m2[14][i] = m1[6][i] - m1[14][i];
+    m2[15][i] = m1[7][i] - m1[15][i];
+
+    m3[0][i]  = m2[0][i]  + m2[4][i];
+    m3[1][i]  = m2[1][i]  + m2[5][i];
+    m3[2][i]  = m2[2][i]  + m2[6][i];
+    m3[3][i]  = m2[3][i]  + m2[7][i];
+    m3[4][i]  = m2[0][i]  - m2[4][i];
+    m3[5][i]  = m2[1][i]  - m2[5][i];
+    m3[6][i]  = m2[2][i]  - m2[6][i];
+    m3[7][i]  = m2[3][i]  - m2[7][i];
+    m3[8][i]  = m2[8][i]  + m2[12][i];
+    m3[9][i]  = m2[9][i]  + m2[13][i];
+    m3[10][i] = m2[10][i] + m2[14][i];
+    m3[11][i] = m2[11][i] + m2[15][i];
+    m3[12][i] = m2[8][i]  - m2[12][i];
+    m3[13][i] = m2[9][i]  - m2[13][i];
+    m3[14][i] = m2[10][i] - m2[14][i];
+    m3[15][i] = m2[11][i] - m2[15][i];
+
+    m1[0][i]  = m3[0][i]  + m3[2][i];
+    m1[1][i]  = m3[1][i]  + m3[3][i];
+    m1[2][i]  = m3[0][i]  - m3[2][i];
+    m1[3][i]  = m3[1][i]  - m3[3][i];
+    m1[4][i]  = m3[4][i]  + m3[6][i];
+    m1[5][i]  = m3[5][i]  + m3[7][i];
+    m1[6][i]  = m3[4][i]  - m3[6][i];
+    m1[7][i]  = m3[5][i]  - m3[7][i];
+    m1[8][i]  = m3[8][i]  + m3[10][i];
+    m1[9][i]  = m3[9][i]  + m3[11][i];
+    m1[10][i] = m3[8][i]  - m3[10][i];
+    m1[11][i] = m3[9][i]  - m3[11][i];
+    m1[12][i] = m3[12][i] + m3[14][i];
+    m1[13][i] = m3[13][i] + m3[15][i];
+    m1[14][i] = m3[12][i] - m3[14][i];
+    m1[15][i] = m3[13][i] - m3[15][i];
+
+    m2[0][i]  = m1[0][i]  + m1[1][i];
+    m2[1][i]  = m1[0][i]  - m1[1][i];
+    m2[2][i]  = m1[2][i]  + m1[3][i];
+    m2[3][i]  = m1[2][i]  - m1[3][i];
+    m2[4][i]  = m1[4][i]  + m1[5][i];
+    m2[5][i]  = m1[4][i]  - m1[5][i];
+    m2[6][i]  = m1[6][i]  + m1[7][i];
+    m2[7][i]  = m1[6][i]  - m1[7][i];
+    m2[8][i]  = m1[8][i]  + m1[9][i];
+    m2[9][i]  = m1[8][i]  - m1[9][i];
+    m2[10][i] = m1[10][i] + m1[11][i];
+    m2[11][i] = m1[10][i] - m1[11][i];
+    m2[12][i] = m1[12][i] + m1[13][i];
+    m2[13][i] = m1[12][i] - m1[13][i];
+    m2[14][i] = m1[14][i] + m1[15][i];
+    m2[15][i] = m1[14][i] - m1[15][i];
+  }
+
+  for (i = 0; i < 16; i++)
+  {
+    for (j = 0; j < 4; j++)
+    {
+      sad += abs(m2[i][j]);
+    }
+  }
+
+  sad=((sad+2)>>2);
+
+  return sad;
+}
+#endif
+
+UInt TComRdCost::xGetHADs4( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetHADs4w( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStep  = pcDtParam->iStep;
+  Int  y;
+  Int  iOffsetOrg = iStrideOrg<<2;
+  Int  iOffsetCur = iStrideCur<<2;
+  
+  UInt uiSum = 0;
+  
+  for ( y=0; y<iRows; y+= 4 )
+  {
+    uiSum += xCalcHADs4x4( piOrg, piCur, iStrideOrg, iStrideCur, iStep );
+    piOrg += iOffsetOrg;
+    piCur += iOffsetCur;
+  }
+  
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCost::xGetHADs8( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetHADs8w( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStep  = pcDtParam->iStep;
+  Int  y;
+  
+  UInt uiSum = 0;
+  
+  if ( iRows == 4 )
+  {
+    uiSum += xCalcHADs4x4( piOrg+0, piCur        , iStrideOrg, iStrideCur, iStep );
+    uiSum += xCalcHADs4x4( piOrg+4, piCur+4*iStep, iStrideOrg, iStrideCur, iStep );
+  }
+  else
+  {
+    Int  iOffsetOrg = iStrideOrg<<3;
+    Int  iOffsetCur = iStrideCur<<3;
+    for ( y=0; y<iRows; y+= 8 )
+    {
+      uiSum += xCalcHADs8x8( piOrg, piCur, iStrideOrg, iStrideCur, iStep );
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+  
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCost::xGetHADs( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetHADsw( pcDtParam );
+  }
+  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;
+  
+  Int  x, y;
+  
+  UInt uiSum = 0;
+  
+#if NS_HAD
+  if( ( ( iRows % 8 == 0) && (iCols % 8 == 0) && ( iRows == iCols ) ) || ( ( iRows % 8 == 0 ) && (iCols % 8 == 0) && !pcDtParam->bUseNSHAD ) )
+#else
+  if( ( iRows % 8 == 0) && (iCols % 8 == 0) )
+#endif
+  {
+    Int  iOffsetOrg = iStrideOrg<<3;
+    Int  iOffsetCur = iStrideCur<<3;
+    for ( y=0; y<iRows; y+= 8 )
+    {
+      for ( x=0; x<iCols; x+= 8 )
+      {
+        uiSum += xCalcHADs8x8( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+#if NS_HAD
+  else if ( ( iCols > 8 ) && ( iCols > iRows ) && pcDtParam->bUseNSHAD ) 
+  {
+    Int  iOffsetOrg = iStrideOrg<<2;
+    Int  iOffsetCur = iStrideCur<<2;
+    for ( y=0; y<iRows; y+= 4 )
+    {
+      for ( x=0; x<iCols; x+= 16 )
+      {
+        uiSum += xCalcHADs16x4( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+  else if ( ( iRows > 8 ) && ( iCols < iRows ) && pcDtParam->bUseNSHAD ) 
+  {
+    Int  iOffsetOrg = iStrideOrg<<4;
+    Int  iOffsetCur = iStrideCur<<4;
+    for ( y=0; y<iRows; y+= 16 )
+    {
+      for ( x=0; x<iCols; x+= 4 )
+      {
+        uiSum += xCalcHADs4x16( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+#endif
+  else if( ( iRows % 4 == 0) && (iCols % 4 == 0) )
+  {
+    Int  iOffsetOrg = iStrideOrg<<2;
+    Int  iOffsetCur = iStrideCur<<2;
+    
+    for ( y=0; y<iRows; y+= 4 )
+    {
+      for ( x=0; x<iCols; x+= 4 )
+      {
+        uiSum += xCalcHADs4x4( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+  else if( ( iRows % 2 == 0) && (iCols % 2 == 0) )
+  {
+    Int  iOffsetOrg = iStrideOrg<<1;
+    Int  iOffsetCur = iStrideCur<<1;
+    for ( y=0; y<iRows; y+=2 )
+    {
+      for ( x=0; x<iCols; x+=2 )
+      {
+        uiSum += xCalcHADs2x2( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+  else
+  {
+    assert(false);
+  }
+  
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+//! \}
Index: /trunk/source/Lib/TLibCommon/TComRdCost.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComRdCost.h	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComRdCost.h	(revision 2)
@@ -0,0 +1,262 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComRdCost.h
+    \brief    RD cost computation classes (header)
+*/
+
+#ifndef __TCOMRDCOST__
+#define __TCOMRDCOST__
+
+
+#include "CommonDef.h"
+#include "TComPattern.h"
+#include "TComMv.h"
+
+#include "TComSlice.h"
+#include "TComRdCostWeightPrediction.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+#define FIX203 1
+
+class DistParam;
+class TComPattern;
+
+// ====================================================================================================================
+// Type definition
+// ====================================================================================================================
+
+// for function pointer
+typedef UInt (*FpDistFunc) (DistParam*);
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// distortion parameter class
+class DistParam
+{
+public:
+  Pel*  pOrg;
+  Pel*  pCur;
+  Int   iStrideOrg;
+  Int   iStrideCur;
+  Int   iRows;
+  Int   iCols;
+  Int   iStep;
+  FpDistFunc DistFunc;
+
+  Bool            bApplyWeight;     // whether weithed prediction is used or not
+  wpScalingParam  *wpCur;           // weithed prediction scaling parameters for current ref
+  UInt            uiComp;           // uiComp = 0 (luma Y), 1 (chroma U), 2 (chroma V)
+
+#if NS_HAD
+  Bool            bUseNSHAD;
+#endif
+
+  // (vertical) subsampling shift (for reducing complexity)
+  // - 0 = no subsampling, 1 = even rows, 2 = every 4th, etc.
+  Int   iSubShift;
+  
+  DistParam()
+  {
+    pOrg = NULL;
+    pCur = NULL;
+    iStrideOrg = 0;
+    iStrideCur = 0;
+    iRows = 0;
+    iCols = 0;
+    iStep = 1;
+    DistFunc = NULL;
+    iSubShift = 0;
+#if NS_HAD
+    bUseNSHAD = false;
+#endif
+  }
+};
+
+/// RD cost computation class
+class TComRdCost
+  : public TComRdCostWeightPrediction
+{
+private:
+  // for distortion
+  Int                     m_iBlkWidth;
+  Int                     m_iBlkHeight;
+  
+#if AMP_SAD
+  FpDistFunc              m_afpDistortFunc[64]; // [eDFunc]
+#else  
+  FpDistFunc              m_afpDistortFunc[33]; // [eDFunc]
+#endif  
+  
+#if WEIGHTED_CHROMA_DISTORTION
+  Double                  m_chromaDistortionWeight;   
+#endif
+  Double                  m_dLambda;
+  Double                  m_sqrtLambda;
+  UInt                    m_uiLambdaMotionSAD;
+  UInt                    m_uiLambdaMotionSSE;
+  Double                  m_dFrameLambda;
+  
+  // for motion cost
+#if FIX203
+  TComMv                  m_mvPredictor;
+#else
+  UInt*                   m_puiComponentCostOriginP;
+  UInt*                   m_puiComponentCost;
+  UInt*                   m_puiVerCost;
+  UInt*                   m_puiHorCost;
+#endif
+  UInt                    m_uiCost;
+  Int                     m_iCostScale;
+#if !FIX203
+  Int                     m_iSearchLimit;
+#endif
+  
+public:
+  TComRdCost();
+  virtual ~TComRdCost();
+  
+  Double  calcRdCost  ( UInt   uiBits, UInt   uiDistortion, Bool bFlag = false, DFunc eDFunc = DF_DEFAULT );
+  Double  calcRdCost64( UInt64 uiBits, UInt64 uiDistortion, Bool bFlag = false, DFunc eDFunc = DF_DEFAULT );
+  
+#if WEIGHTED_CHROMA_DISTORTION
+  Void    setChromaDistortionWeight      ( Double chromaDistortionWeight) { m_chromaDistortionWeight = chromaDistortionWeight; };
+#endif
+  Void    setLambda      ( Double dLambda );
+  Void    setFrameLambda ( Double dLambda ) { m_dFrameLambda = dLambda; }
+  
+  Double  getSqrtLambda ()   { return m_sqrtLambda; }
+  
+  // Distortion Functions
+  Void    init();
+  
+  Void    setDistParam( UInt uiBlkWidth, UInt uiBlkHeight, DFunc eDFunc, DistParam& rcDistParam );
+  Void    setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride,            DistParam& rcDistParam );
+#if NS_HAD
+  Void    setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, Int iStep, DistParam& rcDistParam, Bool bHADME=false, Bool bUseNSHAD=false );
+  Void    setDistParam( DistParam& rcDP, Pel* p1, Int iStride1, Pel* p2, Int iStride2, Int iWidth, Int iHeight, Bool bHadamard = false, Bool bUseNSHAD=false );
+#else
+  Void    setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, Int iStep, DistParam& rcDistParam, Bool bHADME=false );
+  Void    setDistParam( DistParam& rcDP, Pel* p1, Int iStride1, Pel* p2, Int iStride2, Int iWidth, Int iHeight, Bool bHadamard = false );
+#endif
+  
+  UInt    calcHAD         ( Pel* pi0, Int iStride0, Pel* pi1, Int iStride1, Int iWidth, Int iHeight );
+  
+  // for motion cost
+#if !FIX203
+  Void    initRateDistortionModel( Int iSubPelSearchLimit );
+  Void    xUninit();
+#endif
+  UInt    xGetComponentBits( Int iVal );
+  Void    getMotionCost( Bool bSad, Int iAdd ) { m_uiCost = (bSad ? m_uiLambdaMotionSAD + iAdd : m_uiLambdaMotionSSE + iAdd); }
+  Void    setPredictor( TComMv& rcMv )
+  {
+#if FIX203
+    m_mvPredictor = rcMv;
+#else
+    m_puiHorCost = m_puiComponentCost - rcMv.getHor();
+    m_puiVerCost = m_puiComponentCost - rcMv.getVer();
+#endif
+  }
+  Void    setCostScale( Int iCostScale )    { m_iCostScale = iCostScale; }
+  __inline UInt getCost( Int x, Int y )
+  {
+#if FIX203
+    return m_uiCost * getBits(x, y) >> 16;
+#else
+    return (( m_uiCost * (m_puiHorCost[ x * (1<<m_iCostScale) ] + m_puiVerCost[ y * (1<<m_iCostScale) ]) ) >> 16);
+#endif
+  }
+  UInt    getCost( UInt b )                 { return ( m_uiCost * b ) >> 16; }
+  UInt    getBits( Int x, Int y )          
+  {
+#if FIX203
+    return xGetComponentBits((x << m_iCostScale) - m_mvPredictor.getHor())
+    +      xGetComponentBits((y << m_iCostScale) - m_mvPredictor.getVer());
+#else
+    return m_puiHorCost[ x * (1<<m_iCostScale)] + m_puiVerCost[ y * (1<<m_iCostScale) ];
+#endif
+  }
+  
+private:
+  
+  static UInt xGetSSE           ( DistParam* pcDtParam );
+  static UInt xGetSSE4          ( DistParam* pcDtParam );
+  static UInt xGetSSE8          ( DistParam* pcDtParam );
+  static UInt xGetSSE16         ( DistParam* pcDtParam );
+  static UInt xGetSSE32         ( DistParam* pcDtParam );
+  static UInt xGetSSE64         ( DistParam* pcDtParam );
+  static UInt xGetSSE16N        ( DistParam* pcDtParam );
+  
+  static UInt xGetSAD           ( DistParam* pcDtParam );
+  static UInt xGetSAD4          ( DistParam* pcDtParam );
+  static UInt xGetSAD8          ( DistParam* pcDtParam );
+  static UInt xGetSAD16         ( DistParam* pcDtParam );
+  static UInt xGetSAD32         ( DistParam* pcDtParam );
+  static UInt xGetSAD64         ( DistParam* pcDtParam );
+  static UInt xGetSAD16N        ( DistParam* pcDtParam );
+  
+#if AMP_SAD
+  static UInt xGetSAD12         ( DistParam* pcDtParam );
+  static UInt xGetSAD24         ( DistParam* pcDtParam );
+  static UInt xGetSAD48         ( DistParam* pcDtParam );
+
+#endif
+
+  static UInt xGetHADs4         ( DistParam* pcDtParam );
+  static UInt xGetHADs8         ( DistParam* pcDtParam );
+  static UInt xGetHADs          ( DistParam* pcDtParam );
+  static UInt xCalcHADs2x2      ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
+  static UInt xCalcHADs4x4      ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
+  static UInt xCalcHADs8x8      ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
+#if NS_HAD
+  static UInt xCalcHADs16x4     ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
+  static UInt xCalcHADs4x16     ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
+#endif
+  
+public:
+#if WEIGHTED_CHROMA_DISTORTION
+  UInt   getDistPart( Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, Bool bWeighted = false, DFunc eDFunc = DF_SSE );
+#else
+  UInt   getDistPart( Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, DFunc eDFunc = DF_SSE );
+#endif
+  
+};// END CLASS DEFINITION TComRdCost
+
+//! \}
+
+#endif // __TCOMRDCOST__
Index: /trunk/source/Lib/TLibCommon/TComRdCostWeightPrediction.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComRdCostWeightPrediction.cpp	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComRdCostWeightPrediction.cpp	(revision 2)
@@ -0,0 +1,558 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComRdCostWeightPrediction.cpp
+    \brief    RD cost computation class with Weighted-Prediction
+*/
+
+#include <math.h>
+#include <assert.h>
+#include "TComRdCost.h"
+#include "TComRdCostWeightPrediction.h"
+
+Int   TComRdCostWeightPrediction::m_w0        = 0;
+Int   TComRdCostWeightPrediction::m_w1        = 0;
+Int   TComRdCostWeightPrediction::m_shift     = 0;
+Int   TComRdCostWeightPrediction::m_offset    = 0;
+Int   TComRdCostWeightPrediction::m_round     = 0;
+Bool  TComRdCostWeightPrediction::m_xSetDone  = false;
+
+// ====================================================================================================================
+// Distortion functions
+// ====================================================================================================================
+
+TComRdCostWeightPrediction::TComRdCostWeightPrediction()
+{
+}
+
+TComRdCostWeightPrediction::~TComRdCostWeightPrediction()
+{
+}
+
+// --------------------------------------------------------------------------------------------------------------------
+// SAD
+// --------------------------------------------------------------------------------------------------------------------
+/** get weighted SAD cost
+ * \param pcDtParam
+ * \returns UInt
+ */
+UInt TComRdCostWeightPrediction::xGetSADw( DistParam* pcDtParam )
+{
+  Pel  pred;
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+
+  UInt            uiComp    = pcDtParam->uiComp;
+  assert(uiComp<3);
+  wpScalingParam  *wpCur    = &(pcDtParam->wpCur[uiComp]);
+  Int   w0      = wpCur->w,
+        offset  = wpCur->offset,
+        shift   = wpCur->shift,
+        round   = wpCur->round;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    for (Int n = 0; n < iCols; n++ )
+    {
+      pred = ( (w0*piCur[n] + round) >> shift ) + offset ;
+      
+      uiSum += abs( piOrg[n] - pred );
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  pcDtParam->uiComp = 255;  // reset for DEBUG (assert test)
+
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+// --------------------------------------------------------------------------------------------------------------------
+// SSE
+// --------------------------------------------------------------------------------------------------------------------
+/** get weighted SSD cost
+ * \param pcDtParam
+ * \returns UInt
+ */
+UInt TComRdCostWeightPrediction::xGetSSEw( DistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel  pred;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+
+  assert( pcDtParam->iSubShift == 0 );
+
+  UInt            uiComp    = pcDtParam->uiComp;
+  assert(uiComp<3);
+  wpScalingParam  *wpCur    = &(pcDtParam->wpCur[uiComp]);
+  Int   w0      = wpCur->w,
+        offset  = wpCur->offset,
+        shift   = wpCur->shift,
+        round   = wpCur->round;
+ 
+  UInt uiSum = 0;
+  UInt uiShift = g_uiBitIncrement<<1;
+  
+  Int iTemp;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    for (Int n = 0; n < iCols; n++ )
+    {
+      pred = ( (w0*piCur[n] + round) >> shift ) + offset ;
+
+      iTemp = piOrg[n  ] - pred;
+      uiSum += ( iTemp * iTemp ) >> uiShift;
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  pcDtParam->uiComp = 255;  // reset for DEBUG (assert test)
+
+  return ( uiSum );
+}
+
+// --------------------------------------------------------------------------------------------------------------------
+// HADAMARD with step (used in fractional search)
+// --------------------------------------------------------------------------------------------------------------------
+/** get weighted Hadamard cost for 2x2 block
+ * \param *piOrg
+ * \param *piCur
+ * \param iStrideOrg
+ * \param iStrideCur
+ * \param iStep
+ * \returns UInt
+ */
+UInt TComRdCostWeightPrediction::xCalcHADs2x2w( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
+{
+  Int satd = 0, diff[4], m[4];
+  
+  assert( m_xSetDone );
+  Pel   pred;
+
+  pred    = ( (m_w0*piCur[0*iStep             ] + m_round) >> m_shift ) + m_offset ;
+  diff[0] = piOrg[0             ] - pred;
+  pred    = ( (m_w0*piCur[1*iStep             ] + m_round) >> m_shift ) + m_offset ;
+  diff[1] = piOrg[1             ] - pred;
+  pred    = ( (m_w0*piCur[0*iStep + iStrideCur] + m_round) >> m_shift ) + m_offset ;
+  diff[2] = piOrg[iStrideOrg    ] - pred;
+  pred    = ( (m_w0*piCur[1*iStep + iStrideCur] + m_round) >> m_shift ) + m_offset ;
+  diff[3] = piOrg[iStrideOrg + 1] - pred;
+
+  m[0] = diff[0] + diff[2];
+  m[1] = diff[1] + diff[3];
+  m[2] = diff[0] - diff[2];
+  m[3] = diff[1] - diff[3];
+  
+  satd += abs(m[0] + m[1]);
+  satd += abs(m[0] - m[1]);
+  satd += abs(m[2] + m[3]);
+  satd += abs(m[2] - m[3]);
+  
+  return satd;
+}
+
+/** get weighted Hadamard cost for 4x4 block
+ * \param *piOrg
+ * \param *piCur
+ * \param iStrideOrg
+ * \param iStrideCur
+ * \param iStep
+ * \returns UInt
+ */
+UInt TComRdCostWeightPrediction::xCalcHADs4x4w( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
+{
+  Int k, satd = 0, diff[16], m[16], d[16];
+  
+  assert( m_xSetDone );
+  Pel   pred;
+
+  for( k = 0; k < 16; k+=4 )
+  {
+    pred      = ( (m_w0*piCur[0*iStep] + m_round) >> m_shift ) + m_offset ;
+    diff[k+0] = piOrg[0] - pred;
+    pred      = ( (m_w0*piCur[1*iStep] + m_round) >> m_shift ) + m_offset ;
+    diff[k+1] = piOrg[1] - pred;
+    pred      = ( (m_w0*piCur[2*iStep] + m_round) >> m_shift ) + m_offset ;
+    diff[k+2] = piOrg[2] - pred;
+    pred      = ( (m_w0*piCur[3*iStep] + m_round) >> m_shift ) + m_offset ;
+    diff[k+3] = piOrg[3] - pred;
+
+    piCur += iStrideCur;
+    piOrg += iStrideOrg;
+  }
+  
+  /*===== hadamard transform =====*/
+  m[ 0] = diff[ 0] + diff[12];
+  m[ 1] = diff[ 1] + diff[13];
+  m[ 2] = diff[ 2] + diff[14];
+  m[ 3] = diff[ 3] + diff[15];
+  m[ 4] = diff[ 4] + diff[ 8];
+  m[ 5] = diff[ 5] + diff[ 9];
+  m[ 6] = diff[ 6] + diff[10];
+  m[ 7] = diff[ 7] + diff[11];
+  m[ 8] = diff[ 4] - diff[ 8];
+  m[ 9] = diff[ 5] - diff[ 9];
+  m[10] = diff[ 6] - diff[10];
+  m[11] = diff[ 7] - diff[11];
+  m[12] = diff[ 0] - diff[12];
+  m[13] = diff[ 1] - diff[13];
+  m[14] = diff[ 2] - diff[14];
+  m[15] = diff[ 3] - diff[15];
+  
+  d[ 0] = m[ 0] + m[ 4];
+  d[ 1] = m[ 1] + m[ 5];
+  d[ 2] = m[ 2] + m[ 6];
+  d[ 3] = m[ 3] + m[ 7];
+  d[ 4] = m[ 8] + m[12];
+  d[ 5] = m[ 9] + m[13];
+  d[ 6] = m[10] + m[14];
+  d[ 7] = m[11] + m[15];
+  d[ 8] = m[ 0] - m[ 4];
+  d[ 9] = m[ 1] - m[ 5];
+  d[10] = m[ 2] - m[ 6];
+  d[11] = m[ 3] - m[ 7];
+  d[12] = m[12] - m[ 8];
+  d[13] = m[13] - m[ 9];
+  d[14] = m[14] - m[10];
+  d[15] = m[15] - m[11];
+  
+  m[ 0] = d[ 0] + d[ 3];
+  m[ 1] = d[ 1] + d[ 2];
+  m[ 2] = d[ 1] - d[ 2];
+  m[ 3] = d[ 0] - d[ 3];
+  m[ 4] = d[ 4] + d[ 7];
+  m[ 5] = d[ 5] + d[ 6];
+  m[ 6] = d[ 5] - d[ 6];
+  m[ 7] = d[ 4] - d[ 7];
+  m[ 8] = d[ 8] + d[11];
+  m[ 9] = d[ 9] + d[10];
+  m[10] = d[ 9] - d[10];
+  m[11] = d[ 8] - d[11];
+  m[12] = d[12] + d[15];
+  m[13] = d[13] + d[14];
+  m[14] = d[13] - d[14];
+  m[15] = d[12] - d[15];
+  
+  d[ 0] = m[ 0] + m[ 1];
+  d[ 1] = m[ 0] - m[ 1];
+  d[ 2] = m[ 2] + m[ 3];
+  d[ 3] = m[ 3] - m[ 2];
+  d[ 4] = m[ 4] + m[ 5];
+  d[ 5] = m[ 4] - m[ 5];
+  d[ 6] = m[ 6] + m[ 7];
+  d[ 7] = m[ 7] - m[ 6];
+  d[ 8] = m[ 8] + m[ 9];
+  d[ 9] = m[ 8] - m[ 9];
+  d[10] = m[10] + m[11];
+  d[11] = m[11] - m[10];
+  d[12] = m[12] + m[13];
+  d[13] = m[12] - m[13];
+  d[14] = m[14] + m[15];
+  d[15] = m[15] - m[14];
+  
+  for (k=0; k<16; ++k)
+  {
+    satd += abs(d[k]);
+  }
+  satd = ((satd+1)>>1);
+  
+  return satd;
+}
+
+/** get weighted Hadamard cost for 8x8 block
+ * \param *piOrg
+ * \param *piCur
+ * \param iStrideOrg
+ * \param iStrideCur
+ * \param iStep
+ * \returns UInt
+ */
+UInt TComRdCostWeightPrediction::xCalcHADs8x8w( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
+{
+  Int k, i, j, jj, sad=0;
+  Int diff[64], m1[8][8], m2[8][8], m3[8][8];
+  Int iStep2 = iStep<<1;
+  Int iStep3 = iStep2 + iStep;
+  Int iStep4 = iStep3 + iStep;
+  Int iStep5 = iStep4 + iStep;
+  Int iStep6 = iStep5 + iStep;
+  Int iStep7 = iStep6 + iStep;
+  
+  assert( m_xSetDone );
+  Pel   pred;
+
+  for( k = 0; k < 64; k+=8 )
+  {
+    pred      = ( (m_w0*piCur[     0] + m_round) >> m_shift ) + m_offset ;
+    diff[k+0] = piOrg[0] - pred;
+    pred      = ( (m_w0*piCur[iStep ] + m_round) >> m_shift ) + m_offset ;
+    diff[k+1] = piOrg[1] - pred;
+    pred      = ( (m_w0*piCur[iStep2] + m_round) >> m_shift ) + m_offset ;
+    diff[k+2] = piOrg[2] - pred;
+    pred      = ( (m_w0*piCur[iStep3] + m_round) >> m_shift ) + m_offset ;
+    diff[k+3] = piOrg[3] - pred;
+    pred      = ( (m_w0*piCur[iStep4] + m_round) >> m_shift ) + m_offset ;
+    diff[k+4] = piOrg[4] - pred;
+    pred      = ( (m_w0*piCur[iStep5] + m_round) >> m_shift ) + m_offset ;
+    diff[k+5] = piOrg[5] - pred;
+    pred      = ( (m_w0*piCur[iStep6] + m_round) >> m_shift ) + m_offset ;
+    diff[k+6] = piOrg[6] - pred;
+    pred      = ( (m_w0*piCur[iStep7] + m_round) >> m_shift ) + m_offset ;
+    diff[k+7] = piOrg[7] - pred;
+    
+    piCur += iStrideCur;
+    piOrg += iStrideOrg;
+  }
+  
+  //horizontal
+  for (j=0; j < 8; j++)
+  {
+    jj = j << 3;
+    m2[j][0] = diff[jj  ] + diff[jj+4];
+    m2[j][1] = diff[jj+1] + diff[jj+5];
+    m2[j][2] = diff[jj+2] + diff[jj+6];
+    m2[j][3] = diff[jj+3] + diff[jj+7];
+    m2[j][4] = diff[jj  ] - diff[jj+4];
+    m2[j][5] = diff[jj+1] - diff[jj+5];
+    m2[j][6] = diff[jj+2] - diff[jj+6];
+    m2[j][7] = diff[jj+3] - diff[jj+7];
+    
+    m1[j][0] = m2[j][0] + m2[j][2];
+    m1[j][1] = m2[j][1] + m2[j][3];
+    m1[j][2] = m2[j][0] - m2[j][2];
+    m1[j][3] = m2[j][1] - m2[j][3];
+    m1[j][4] = m2[j][4] + m2[j][6];
+    m1[j][5] = m2[j][5] + m2[j][7];
+    m1[j][6] = m2[j][4] - m2[j][6];
+    m1[j][7] = m2[j][5] - m2[j][7];
+    
+    m2[j][0] = m1[j][0] + m1[j][1];
+    m2[j][1] = m1[j][0] - m1[j][1];
+    m2[j][2] = m1[j][2] + m1[j][3];
+    m2[j][3] = m1[j][2] - m1[j][3];
+    m2[j][4] = m1[j][4] + m1[j][5];
+    m2[j][5] = m1[j][4] - m1[j][5];
+    m2[j][6] = m1[j][6] + m1[j][7];
+    m2[j][7] = m1[j][6] - m1[j][7];
+  }
+  
+  //vertical
+  for (i=0; i < 8; i++)
+  {
+    m3[0][i] = m2[0][i] + m2[4][i];
+    m3[1][i] = m2[1][i] + m2[5][i];
+    m3[2][i] = m2[2][i] + m2[6][i];
+    m3[3][i] = m2[3][i] + m2[7][i];
+    m3[4][i] = m2[0][i] - m2[4][i];
+    m3[5][i] = m2[1][i] - m2[5][i];
+    m3[6][i] = m2[2][i] - m2[6][i];
+    m3[7][i] = m2[3][i] - m2[7][i];
+    
+    m1[0][i] = m3[0][i] + m3[2][i];
+    m1[1][i] = m3[1][i] + m3[3][i];
+    m1[2][i] = m3[0][i] - m3[2][i];
+    m1[3][i] = m3[1][i] - m3[3][i];
+    m1[4][i] = m3[4][i] + m3[6][i];
+    m1[5][i] = m3[5][i] + m3[7][i];
+    m1[6][i] = m3[4][i] - m3[6][i];
+    m1[7][i] = m3[5][i] - m3[7][i];
+    
+    m2[0][i] = m1[0][i] + m1[1][i];
+    m2[1][i] = m1[0][i] - m1[1][i];
+    m2[2][i] = m1[2][i] + m1[3][i];
+    m2[3][i] = m1[2][i] - m1[3][i];
+    m2[4][i] = m1[4][i] + m1[5][i];
+    m2[5][i] = m1[4][i] - m1[5][i];
+    m2[6][i] = m1[6][i] + m1[7][i];
+    m2[7][i] = m1[6][i] - m1[7][i];
+  }
+  
+  for (j=0; j < 8; j++)
+  {
+    for (i=0; i < 8; i++)
+    {
+      sad += (abs(m2[j][i]));
+    }
+  }
+  
+  sad=((sad+2)>>2);
+  
+  return sad;
+}
+
+/** get weighted Hadamard cost
+ * \param *pcDtParam
+ * \returns UInt
+ */
+UInt TComRdCostWeightPrediction::xGetHADs4w( DistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStep  = pcDtParam->iStep;
+  Int  y;
+  Int  iOffsetOrg = iStrideOrg<<2;
+  Int  iOffsetCur = iStrideCur<<2;
+  
+  UInt uiSum = 0;
+  
+  for ( y=0; y<iRows; y+= 4 )
+  {
+    uiSum += xCalcHADs4x4w( piOrg, piCur, iStrideOrg, iStrideCur, iStep );
+    piOrg += iOffsetOrg;
+    piCur += iOffsetCur;
+  }
+  
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+/** get weighted Hadamard cost
+ * \param *pcDtParam
+ * \returns UInt
+ */
+UInt TComRdCostWeightPrediction::xGetHADs8w( DistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStep  = pcDtParam->iStep;
+  Int  y;
+  
+  UInt uiSum = 0;
+  
+  if ( iRows == 4 )
+  {
+    uiSum += xCalcHADs4x4w( piOrg+0, piCur        , iStrideOrg, iStrideCur, iStep );
+    uiSum += xCalcHADs4x4w( piOrg+4, piCur+4*iStep, iStrideOrg, iStrideCur, iStep );
+  }
+  else
+  {
+    Int  iOffsetOrg = iStrideOrg<<3;
+    Int  iOffsetCur = iStrideCur<<3;
+    for ( y=0; y<iRows; y+= 8 )
+    {
+      uiSum += xCalcHADs8x8w( piOrg, piCur, iStrideOrg, iStrideCur, iStep );
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+  
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+/** get weighted Hadamard cost
+ * \param *pcDtParam
+ * \returns UInt
+ */
+UInt TComRdCostWeightPrediction::xGetHADsw( DistParam* pcDtParam )
+{
+  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;
+  
+  Int  x, y;
+  
+  UInt            uiComp    = pcDtParam->uiComp;
+  assert(uiComp<3);
+  wpScalingParam  *wpCur    = &(pcDtParam->wpCur[uiComp]);
+
+  xSetWPscale(wpCur->w, 0, wpCur->shift, wpCur->offset, wpCur->round);
+
+  UInt uiSum = 0;
+  
+  if( ( iRows % 8 == 0) && (iCols % 8 == 0) )
+  {
+    Int  iOffsetOrg = iStrideOrg<<3;
+    Int  iOffsetCur = iStrideCur<<3;
+    for ( y=0; y<iRows; y+= 8 )
+    {
+      for ( x=0; x<iCols; x+= 8 )
+      {
+        uiSum += xCalcHADs8x8w( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+  else if( ( iRows % 4 == 0) && (iCols % 4 == 0) )
+  {
+    Int  iOffsetOrg = iStrideOrg<<2;
+    Int  iOffsetCur = iStrideCur<<2;
+    
+    for ( y=0; y<iRows; y+= 4 )
+    {
+      for ( x=0; x<iCols; x+= 4 )
+      {
+        uiSum += xCalcHADs4x4w( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+  else
+  {
+    for ( y=0; y<iRows; y+=2 )
+    {
+      for ( x=0; x<iCols; x+=2 )
+      {
+        uiSum += xCalcHADs2x2w( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iStrideOrg;
+      piCur += iStrideCur;
+    }
+  }
+  
+  m_xSetDone  = false;
+
+  return ( uiSum >> g_uiBitIncrement );
+}
Index: /trunk/source/Lib/TLibCommon/TComRdCostWeightPrediction.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComRdCostWeightPrediction.h	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComRdCostWeightPrediction.h	(revision 2)
@@ -0,0 +1,96 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComRdCostWeightPrediction.h
+    \brief    RD cost computation classes (header)
+*/
+
+#ifndef __TCOMRDCOSTWEIGHTPREDICTION__
+#define __TCOMRDCOSTWEIGHTPREDICTION__
+
+
+#include "CommonDef.h"
+#include "TComPattern.h"
+#include "TComMv.h"
+#include "TComRdCost.h"
+#include "TComSlice.h"
+
+class DistParam;
+class TComPattern;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// RD cost computation class, with Weighted Prediction
+class TComRdCostWeightPrediction
+{
+private:
+  static  Int   m_w0, m_w1; // current wp scaling values
+  static  Int   m_shift;
+  static  Int   m_offset;
+  static  Int   m_round;
+  static  Bool  m_xSetDone;
+
+public:
+  TComRdCostWeightPrediction();
+  virtual ~TComRdCostWeightPrediction();
+  
+protected:
+    
+  static inline Void  xSetWPscale(Int w0, Int w1, Int shift, Int offset, Int round);
+
+  static UInt xGetSSEw          ( DistParam* pcDtParam );
+  static UInt xGetSADw          ( DistParam* pcDtParam );
+  static UInt xGetHADs4w        ( DistParam* pcDtParam );
+  static UInt xGetHADs8w        ( DistParam* pcDtParam );
+  static UInt xGetHADsw         ( DistParam* pcDtParam );
+  static UInt xCalcHADs2x2w     ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
+  static UInt xCalcHADs4x4w     ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
+  static UInt xCalcHADs8x8w     ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
+  
+};// END CLASS DEFINITION TComRdCostWeightPrediction
+
+inline Void  TComRdCostWeightPrediction::xSetWPscale(Int w0, Int w1, Int shift, Int offset, Int round)
+{
+  m_w0        = w0;
+  m_w1        = w1;
+  m_shift     = shift;
+  m_offset    = offset;
+  m_round     = round;
+
+  m_xSetDone  = true;
+}
+
+#endif // __TCOMRDCOSTWEIGHTPREDICTION__
+
Index: /trunk/source/Lib/TLibCommon/TComRom.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComRom.cpp	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComRom.cpp	(revision 2)
@@ -0,0 +1,835 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComRom.cpp
+    \brief    global variables & functions
+*/
+
+#include "TComRom.h"
+#include <memory.h>
+#include <stdlib.h>
+#include <stdio.h>
+// ====================================================================================================================
+// Initialize / destroy functions
+// ====================================================================================================================
+
+//! \ingroup TLibCommon
+//! \{
+
+// initialize ROM variables
+Void initROM()
+{
+  Int i, c;
+  
+  // g_aucConvertToBit[ x ]: log2(x/4), if x=4 -> 0, x=8 -> 1, x=16 -> 2, ...
+  ::memset( g_aucConvertToBit,   -1, sizeof( g_aucConvertToBit ) );
+  c=0;
+  for ( i=4; i<MAX_CU_SIZE; i*=2 )
+  {
+    g_aucConvertToBit[ i ] = c;
+    c++;
+  }
+  g_aucConvertToBit[ i ] = c;
+  
+  // g_auiFrameScanXY[ g_aucConvertToBit[ transformSize ] ]: zigzag scan array for transformSize
+  c=2;
+  for ( i=0; i<MAX_CU_DEPTH; i++ )
+  {
+#if !REMOVE_ZIGZAG_SCAN
+    g_auiFrameScanXY[ i ] = new UInt[ c*c ];
+    g_auiFrameScanX [ i ] = new UInt[ c*c ];
+    g_auiFrameScanY [ i ] = new UInt[ c*c ];
+    initFrameScanXY( g_auiFrameScanXY[i], g_auiFrameScanX[i], g_auiFrameScanY[i], c, c );
+#endif
+    g_auiSigLastScan[0][i] = new UInt[ c*c ];
+    g_auiSigLastScan[1][i] = new UInt[ c*c ];
+    g_auiSigLastScan[2][i] = new UInt[ c*c ];
+    g_auiSigLastScan[3][i] = new UInt[ c*c ];
+    initSigLastScan( g_auiSigLastScan[0][i], g_auiSigLastScan[1][i], g_auiSigLastScan[2][i], g_auiSigLastScan[3][i], c, c, i);
+
+    c <<= 1;
+  }  
+#if !REMOVE_NSQT
+  g_sigScanNSQT[0] = new UInt[ 64 ];  // 4x16
+  g_sigScanNSQT[1] = new UInt[ 256 ]; // 8x32
+  g_sigScanNSQT[2] = new UInt[ 64 ];  // 16x4
+  g_sigScanNSQT[3] = new UInt[ 256 ]; // 32x8
+  
+  static int diagScanX[ 16 ] =
+  {
+    0, 0, 1, 0, 1, 2, 0, 1, 2, 3, 1, 2, 3, 2, 3, 3
+  };
+  static int diagScanY[ 16 ] =
+  {
+    0, 1, 0, 2, 1, 0, 3, 2, 1, 0, 3, 2, 1, 3, 2, 3
+  };
+  
+  Int j;
+  // 4x16 scan
+  for (i = 0; i < 4; i++)
+  {
+    for (j = 0; j < 16; j++)
+    {
+      g_sigScanNSQT[ 0 ][ 16 * i + j ] = 16 * i + 4 * diagScanY[ j ] + diagScanX[ j ];
+    }
+  }
+  
+  // 8x32 scan
+  for (i = 0; i < 16; i++)
+  {
+    Int x = g_sigCGScanNSQT[ 1 ][ i ] & 1;
+    Int y = g_sigCGScanNSQT[ 1 ][ i ] >> 1;
+    
+    for (j = 0; j < 16; j++)
+    {
+      g_sigScanNSQT[ 1 ][ 16 * i + j ] = 32 * y + 4 * x + 8 * diagScanY[ j ] + diagScanX[ j ];
+    }
+  }
+  
+  // 16x4 scan
+  for (i = 0; i < 4; i++)
+  {
+    for (j = 0; j < 16; j++)
+    {
+      g_sigScanNSQT[ 2 ][ 16 * i + j ] = 4 * i + 16 * diagScanY[ j ] + diagScanX[ j ];
+    }
+  }
+  
+  // 32x8 scan
+  for (i = 0; i < 16; i++)
+  {
+    Int x = g_sigCGScanNSQT[ 3 ][ i ] & 7;
+    Int y = g_sigCGScanNSQT[ 3 ][ i ] >> 3;
+    
+    for (j = 0; j < 16; j++)
+    {
+      g_sigScanNSQT[ 3 ][ 16 * i + j ] = 128 * y + 4 * x + 32 * diagScanY[ j ] + diagScanX[ j ];
+    }
+  }
+#endif
+}
+
+Void destroyROM()
+{
+  Int i;
+  
+  for ( i=0; i<MAX_CU_DEPTH; i++ )
+  {
+#if !REMOVE_ZIGZAG_SCAN
+    delete[] g_auiFrameScanXY[i];
+    delete[] g_auiFrameScanX [i];
+    delete[] g_auiFrameScanY [i];
+#endif
+    delete[] g_auiSigLastScan[0][i];
+    delete[] g_auiSigLastScan[1][i];
+    delete[] g_auiSigLastScan[2][i];
+    delete[] g_auiSigLastScan[3][i];
+  }
+#if !REMOVE_NSQT
+  for (i = 0; i < 4; i++)
+  {
+    delete[] g_sigScanNSQT[ i ];    
+  }
+#endif
+}
+
+// ====================================================================================================================
+// Data structure related table & variable
+// ====================================================================================================================
+
+UInt g_uiMaxCUWidth  = MAX_CU_SIZE;
+UInt g_uiMaxCUHeight = MAX_CU_SIZE;
+UInt g_uiMaxCUDepth  = MAX_CU_DEPTH;
+UInt g_uiAddCUDepth  = 0;
+UInt g_auiZscanToRaster [ MAX_NUM_SPU_W*MAX_NUM_SPU_W ] = { 0, };
+UInt g_auiRasterToZscan [ MAX_NUM_SPU_W*MAX_NUM_SPU_W ] = { 0, };
+UInt g_auiRasterToPelX  [ MAX_NUM_SPU_W*MAX_NUM_SPU_W ] = { 0, };
+UInt g_auiRasterToPelY  [ MAX_NUM_SPU_W*MAX_NUM_SPU_W ] = { 0, };
+UInt g_motionRefer   [ MAX_NUM_SPU_W*MAX_NUM_SPU_W ] = { 0, }; 
+
+UInt g_auiPUOffset[8] = { 0, 8, 4, 4, 2, 10, 1, 5};
+
+Void initZscanToRaster ( Int iMaxDepth, Int iDepth, UInt uiStartVal, UInt*& rpuiCurrIdx )
+{
+  Int iStride = 1 << ( iMaxDepth - 1 );
+  
+  if ( iDepth == iMaxDepth )
+  {
+    rpuiCurrIdx[0] = uiStartVal;
+    rpuiCurrIdx++;
+  }
+  else
+  {
+    Int iStep = iStride >> iDepth;
+    initZscanToRaster( iMaxDepth, iDepth+1, uiStartVal,                     rpuiCurrIdx );
+    initZscanToRaster( iMaxDepth, iDepth+1, uiStartVal+iStep,               rpuiCurrIdx );
+    initZscanToRaster( iMaxDepth, iDepth+1, uiStartVal+iStep*iStride,       rpuiCurrIdx );
+    initZscanToRaster( iMaxDepth, iDepth+1, uiStartVal+iStep*iStride+iStep, rpuiCurrIdx );
+  }
+}
+
+Void initRasterToZscan ( UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxDepth )
+{
+  UInt  uiMinCUWidth  = uiMaxCUWidth  >> ( uiMaxDepth - 1 );
+  UInt  uiMinCUHeight = uiMaxCUHeight >> ( uiMaxDepth - 1 );
+  
+  UInt  uiNumPartInWidth  = (UInt)uiMaxCUWidth  / uiMinCUWidth;
+  UInt  uiNumPartInHeight = (UInt)uiMaxCUHeight / uiMinCUHeight;
+  
+  for ( UInt i = 0; i < uiNumPartInWidth*uiNumPartInHeight; i++ )
+  {
+    g_auiRasterToZscan[ g_auiZscanToRaster[i] ] = i;
+  }
+}
+
+/** generate motion data compression mapping table
+* \param uiMaxCUWidth, width of LCU
+* \param uiMaxCUHeight, hight of LCU
+* \param uiMaxDepth, max depth of LCU
+* \returns Void
+*/
+Void initMotionReferIdx ( UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxDepth )
+{
+  Int  minSUWidth  = (Int)uiMaxCUWidth  >> ( (Int)uiMaxDepth - 1 );
+  Int  minSUHeight = (Int)uiMaxCUHeight >> ( (Int)uiMaxDepth - 1 );
+
+  Int  numPartInWidth  = (Int)uiMaxCUWidth  / (Int)minSUWidth;
+  Int  numPartInHeight = (Int)uiMaxCUHeight / (Int)minSUHeight;
+
+  for ( Int i = 0; i < numPartInWidth*numPartInHeight; i++ )
+  {
+    g_motionRefer[i] = i;
+  }
+
+  UInt maxCUDepth = g_uiMaxCUDepth - ( g_uiAddCUDepth - 1);
+  Int  minCUWidth  = (Int)uiMaxCUWidth  >> ( (Int)maxCUDepth - 1);
+
+  if(!(minCUWidth == 8 && minSUWidth == 4)) //check if Minimum PU width == 4
+  {
+    return;
+  }
+  
+  Int compressionNum = 2;
+
+  for ( Int i = numPartInWidth*(numPartInHeight-1); i < numPartInWidth*numPartInHeight; i += compressionNum*2)
+  {
+    for ( Int j = 1; j < compressionNum; j++ )
+    {
+      g_motionRefer[g_auiRasterToZscan[i+j]] = g_auiRasterToZscan[i];
+    }
+  }
+
+  for ( Int i = numPartInWidth*(numPartInHeight-1)+compressionNum*2-1; i < numPartInWidth*numPartInHeight; i += compressionNum*2)
+  {
+    for ( Int j = 1; j < compressionNum; j++ )
+    {
+      g_motionRefer[g_auiRasterToZscan[i-j]] = g_auiRasterToZscan[i];
+    }
+  }
+}
+
+Void initRasterToPelXY ( UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxDepth )
+{
+  UInt    i;
+  
+  UInt* uiTempX = &g_auiRasterToPelX[0];
+  UInt* uiTempY = &g_auiRasterToPelY[0];
+  
+  UInt  uiMinCUWidth  = uiMaxCUWidth  >> ( uiMaxDepth - 1 );
+  UInt  uiMinCUHeight = uiMaxCUHeight >> ( uiMaxDepth - 1 );
+  
+  UInt  uiNumPartInWidth  = uiMaxCUWidth  / uiMinCUWidth;
+  UInt  uiNumPartInHeight = uiMaxCUHeight / uiMinCUHeight;
+  
+  uiTempX[0] = 0; uiTempX++;
+  for ( i = 1; i < uiNumPartInWidth; i++ )
+  {
+    uiTempX[0] = uiTempX[-1] + uiMinCUWidth; uiTempX++;
+  }
+  for ( i = 1; i < uiNumPartInHeight; i++ )
+  {
+    memcpy(uiTempX, uiTempX-uiNumPartInWidth, sizeof(UInt)*uiNumPartInWidth);
+    uiTempX += uiNumPartInWidth;
+  }
+  
+  for ( i = 1; i < uiNumPartInWidth*uiNumPartInHeight; i++ )
+  {
+    uiTempY[i] = ( i / uiNumPartInWidth ) * uiMinCUWidth;
+  }
+};
+
+
+Int g_quantScales[6] =
+{
+  26214,23302,20560,18396,16384,14564
+};    
+
+Int g_invQuantScales[6] =
+{
+  40,45,51,57,64,72
+};
+
+const short g_aiT4[4][4] =
+{
+  { 64, 64, 64, 64},
+  { 83, 36,-36,-83},
+  { 64,-64,-64, 64},
+  { 36,-83, 83,-36}
+};
+
+const short g_aiT8[8][8] =
+{
+  { 64, 64, 64, 64, 64, 64, 64, 64},
+  { 89, 75, 50, 18,-18,-50,-75,-89},
+  { 83, 36,-36,-83,-83,-36, 36, 83},
+  { 75,-18,-89,-50, 50, 89, 18,-75},
+  { 64,-64,-64, 64, 64,-64,-64, 64},
+  { 50,-89, 18, 75,-75,-18, 89,-50},
+  { 36,-83, 83,-36,-36, 83,-83, 36},
+  { 18,-50, 75,-89, 89,-75, 50,-18}
+};
+
+const short g_aiT16[16][16] =
+{
+  { 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64},
+  { 90, 87, 80, 70, 57, 43, 25,  9, -9,-25,-43,-57,-70,-80,-87,-90},
+  { 89, 75, 50, 18,-18,-50,-75,-89,-89,-75,-50,-18, 18, 50, 75, 89},
+  { 87, 57,  9,-43,-80,-90,-70,-25, 25, 70, 90, 80, 43, -9,-57,-87},
+  { 83, 36,-36,-83,-83,-36, 36, 83, 83, 36,-36,-83,-83,-36, 36, 83},
+  { 80,  9,-70,-87,-25, 57, 90, 43,-43,-90,-57, 25, 87, 70, -9,-80},
+  { 75,-18,-89,-50, 50, 89, 18,-75,-75, 18, 89, 50,-50,-89,-18, 75},
+  { 70,-43,-87,  9, 90, 25,-80,-57, 57, 80,-25,-90, -9, 87, 43,-70},
+  { 64,-64,-64, 64, 64,-64,-64, 64, 64,-64,-64, 64, 64,-64,-64, 64},
+  { 57,-80,-25, 90, -9,-87, 43, 70,-70,-43, 87,  9,-90, 25, 80,-57},
+  { 50,-89, 18, 75,-75,-18, 89,-50,-50, 89,-18,-75, 75, 18,-89, 50},
+  { 43,-90, 57, 25,-87, 70,  9,-80, 80, -9,-70, 87,-25,-57, 90,-43},
+  { 36,-83, 83,-36,-36, 83,-83, 36, 36,-83, 83,-36,-36, 83,-83, 36},
+  { 25,-70, 90,-80, 43,  9,-57, 87,-87, 57, -9,-43, 80,-90, 70,-25},
+  { 18,-50, 75,-89, 89,-75, 50,-18,-18, 50,-75, 89,-89, 75,-50, 18},
+  {  9,-25, 43,-57, 70,-80, 87,-90, 90,-87, 80,-70, 57,-43, 25, -9}
+};
+
+const short g_aiT32[32][32] =
+{
+  { 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64},
+  { 90, 90, 88, 85, 82, 78, 73, 67, 61, 54, 46, 38, 31, 22, 13,  4, -4,-13,-22,-31,-38,-46,-54,-61,-67,-73,-78,-82,-85,-88,-90,-90},
+  { 90, 87, 80, 70, 57, 43, 25,  9, -9,-25,-43,-57,-70,-80,-87,-90,-90,-87,-80,-70,-57,-43,-25, -9,  9, 25, 43, 57, 70, 80, 87, 90},
+  { 90, 82, 67, 46, 22, -4,-31,-54,-73,-85,-90,-88,-78,-61,-38,-13, 13, 38, 61, 78, 88, 90, 85, 73, 54, 31,  4,-22,-46,-67,-82,-90},
+  { 89, 75, 50, 18,-18,-50,-75,-89,-89,-75,-50,-18, 18, 50, 75, 89, 89, 75, 50, 18,-18,-50,-75,-89,-89,-75,-50,-18, 18, 50, 75, 89},
+  { 88, 67, 31,-13,-54,-82,-90,-78,-46, -4, 38, 73, 90, 85, 61, 22,-22,-61,-85,-90,-73,-38,  4, 46, 78, 90, 82, 54, 13,-31,-67,-88},
+  { 87, 57,  9,-43,-80,-90,-70,-25, 25, 70, 90, 80, 43, -9,-57,-87,-87,-57, -9, 43, 80, 90, 70, 25,-25,-70,-90,-80,-43,  9, 57, 87},
+  { 85, 46,-13,-67,-90,-73,-22, 38, 82, 88, 54, -4,-61,-90,-78,-31, 31, 78, 90, 61,  4,-54,-88,-82,-38, 22, 73, 90, 67, 13,-46,-85},
+  { 83, 36,-36,-83,-83,-36, 36, 83, 83, 36,-36,-83,-83,-36, 36, 83, 83, 36,-36,-83,-83,-36, 36, 83, 83, 36,-36,-83,-83,-36, 36, 83},
+  { 82, 22,-54,-90,-61, 13, 78, 85, 31,-46,-90,-67,  4, 73, 88, 38,-38,-88,-73, -4, 67, 90, 46,-31,-85,-78,-13, 61, 90, 54,-22,-82},
+  { 80,  9,-70,-87,-25, 57, 90, 43,-43,-90,-57, 25, 87, 70, -9,-80,-80, -9, 70, 87, 25,-57,-90,-43, 43, 90, 57,-25,-87,-70,  9, 80},
+  { 78, -4,-82,-73, 13, 85, 67,-22,-88,-61, 31, 90, 54,-38,-90,-46, 46, 90, 38,-54,-90,-31, 61, 88, 22,-67,-85,-13, 73, 82,  4,-78},
+  { 75,-18,-89,-50, 50, 89, 18,-75,-75, 18, 89, 50,-50,-89,-18, 75, 75,-18,-89,-50, 50, 89, 18,-75,-75, 18, 89, 50,-50,-89,-18, 75},
+  { 73,-31,-90,-22, 78, 67,-38,-90,-13, 82, 61,-46,-88, -4, 85, 54,-54,-85,  4, 88, 46,-61,-82, 13, 90, 38,-67,-78, 22, 90, 31,-73},
+  { 70,-43,-87,  9, 90, 25,-80,-57, 57, 80,-25,-90, -9, 87, 43,-70,-70, 43, 87, -9,-90,-25, 80, 57,-57,-80, 25, 90,  9,-87,-43, 70},
+  { 67,-54,-78, 38, 85,-22,-90,  4, 90, 13,-88,-31, 82, 46,-73,-61, 61, 73,-46,-82, 31, 88,-13,-90, -4, 90, 22,-85,-38, 78, 54,-67},
+  { 64,-64,-64, 64, 64,-64,-64, 64, 64,-64,-64, 64, 64,-64,-64, 64, 64,-64,-64, 64, 64,-64,-64, 64, 64,-64,-64, 64, 64,-64,-64, 64},
+  { 61,-73,-46, 82, 31,-88,-13, 90, -4,-90, 22, 85,-38,-78, 54, 67,-67,-54, 78, 38,-85,-22, 90,  4,-90, 13, 88,-31,-82, 46, 73,-61},
+  { 57,-80,-25, 90, -9,-87, 43, 70,-70,-43, 87,  9,-90, 25, 80,-57,-57, 80, 25,-90,  9, 87,-43,-70, 70, 43,-87, -9, 90,-25,-80, 57},
+  { 54,-85, -4, 88,-46,-61, 82, 13,-90, 38, 67,-78,-22, 90,-31,-73, 73, 31,-90, 22, 78,-67,-38, 90,-13,-82, 61, 46,-88,  4, 85,-54},
+  { 50,-89, 18, 75,-75,-18, 89,-50,-50, 89,-18,-75, 75, 18,-89, 50, 50,-89, 18, 75,-75,-18, 89,-50,-50, 89,-18,-75, 75, 18,-89, 50},
+  { 46,-90, 38, 54,-90, 31, 61,-88, 22, 67,-85, 13, 73,-82,  4, 78,-78, -4, 82,-73,-13, 85,-67,-22, 88,-61,-31, 90,-54,-38, 90,-46},
+  { 43,-90, 57, 25,-87, 70,  9,-80, 80, -9,-70, 87,-25,-57, 90,-43,-43, 90,-57,-25, 87,-70, -9, 80,-80,  9, 70,-87, 25, 57,-90, 43},
+  { 38,-88, 73, -4,-67, 90,-46,-31, 85,-78, 13, 61,-90, 54, 22,-82, 82,-22,-54, 90,-61,-13, 78,-85, 31, 46,-90, 67,  4,-73, 88,-38},
+  { 36,-83, 83,-36,-36, 83,-83, 36, 36,-83, 83,-36,-36, 83,-83, 36, 36,-83, 83,-36,-36, 83,-83, 36, 36,-83, 83,-36,-36, 83,-83, 36},
+  { 31,-78, 90,-61,  4, 54,-88, 82,-38,-22, 73,-90, 67,-13,-46, 85,-85, 46, 13,-67, 90,-73, 22, 38,-82, 88,-54, -4, 61,-90, 78,-31},
+  { 25,-70, 90,-80, 43,  9,-57, 87,-87, 57, -9,-43, 80,-90, 70,-25,-25, 70,-90, 80,-43, -9, 57,-87, 87,-57,  9, 43,-80, 90,-70, 25},
+  { 22,-61, 85,-90, 73,-38, -4, 46,-78, 90,-82, 54,-13,-31, 67,-88, 88,-67, 31, 13,-54, 82,-90, 78,-46,  4, 38,-73, 90,-85, 61,-22},
+  { 18,-50, 75,-89, 89,-75, 50,-18,-18, 50,-75, 89,-89, 75,-50, 18, 18,-50, 75,-89, 89,-75, 50,-18,-18, 50,-75, 89,-89, 75,-50, 18},
+  { 13,-38, 61,-78, 88,-90, 85,-73, 54,-31,  4, 22,-46, 67,-82, 90,-90, 82,-67, 46,-22, -4, 31,-54, 73,-85, 90,-88, 78,-61, 38,-13},
+  {  9,-25, 43,-57, 70,-80, 87,-90, 90,-87, 80,-70, 57,-43, 25, -9, -9, 25,-43, 57,-70, 80,-87, 90,-90, 87,-80, 70,-57, 43,-25,  9},
+  {  4,-13, 22,-31, 38,-46, 54,-61, 67,-73, 78,-82, 85,-88, 90,-90, 90,-90, 88,-85, 82,-78, 73,-67, 61,-54, 46,-38, 31,-22, 13, -4}
+};
+
+#if CHROMA_QP_EXTENSION
+const UChar g_aucChromaScale[58]=
+{
+   0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16,
+  17,18,19,20,21,22,23,24,25,26,27,28,29,29,30,31,32,
+  33,33,34,34,35,35,36,36,37,37,38,39,40,41,42,43,44,
+  45,46,47,48,49,50,51
+};
+#else
+const UChar g_aucChromaScale[52]=
+{
+  0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,
+  12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,
+  28,29,29,30,31,32,32,33,34,34,35,35,36,36,37,37,
+  37,38,38,38,39,39,39,39
+};
+#endif
+
+
+// Mode-Dependent DCT/DST 
+const short g_as_DST_MAT_4 [4][4]=
+{
+  {29,   55,    74,   84},
+  {74,   74,    0 ,  -74},
+  {84,  -29,   -74,   55},
+  {55,  -84,    74,  -29},
+};
+
+
+// ====================================================================================================================
+// ADI
+// ====================================================================================================================
+
+#if FAST_UDI_USE_MPM
+const UChar g_aucIntraModeNumFast[7] =
+{
+  3,  //   2x2
+  8,  //   4x4
+  8,  //   8x8
+  3,  //  16x16   
+  3,  //  32x32   
+  3,  //  64x64   
+  3   // 128x128  
+};
+#else // FAST_UDI_USE_MPM
+const UChar g_aucIntraModeNumFast[7] =
+{
+  3,  //   2x2
+  9,  //   4x4
+  9,  //   8x8
+  4,  //  16x16   33
+  4,  //  32x32   33
+  5,  //  64x64   33
+  4   // 128x128  33
+};
+#endif // FAST_UDI_USE_MPM
+
+// chroma
+
+const UChar g_aucConvertTxtTypeToIdx[4] = { 0, 1, 1, 2 };
+
+
+// ====================================================================================================================
+// Bit-depth
+// ====================================================================================================================
+
+UInt g_uiBitDepth     = 8;    // base bit-depth
+UInt g_uiBitIncrement = 0;    // increments
+UInt g_uiIBDI_MAX     = 255;  // max. value after  IBDI
+UInt g_uiBASE_MAX     = 255;  // max. value before IBDI
+
+UInt g_uiPCMBitDepthLuma     = 8;    // PCM bit-depth
+UInt g_uiPCMBitDepthChroma   = 8;    // PCM bit-depth
+
+// ====================================================================================================================
+// Misc.
+// ====================================================================================================================
+
+Char  g_aucConvertToBit  [ MAX_CU_SIZE+1 ];
+
+#if ENC_DEC_TRACE
+FILE*  g_hTrace = NULL;
+const Bool g_bEncDecTraceEnable  = true;
+const Bool g_bEncDecTraceDisable = false;
+Bool   g_HLSTraceEnable = true;
+Bool   g_bJustDoIt = false;
+UInt64 g_nSymbolCounter = 0;
+#endif
+// ====================================================================================================================
+// Scanning order & context model mapping
+// ====================================================================================================================
+
+// scanning order table
+#if !REMOVE_ZIGZAG_SCAN
+UInt* g_auiFrameScanXY[ MAX_CU_DEPTH  ];
+UInt* g_auiFrameScanX [ MAX_CU_DEPTH  ];
+UInt* g_auiFrameScanY [ MAX_CU_DEPTH  ];
+#endif
+UInt* g_auiSigLastScan[4][ MAX_CU_DEPTH ];
+#if !REMOVE_NSQT
+UInt *g_sigScanNSQT[ 4 ]; // scan for non-square partitions
+UInt g_sigCGScanNSQT[ 4 ][ 16 ] =
+{
+  { 0, 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
+  { 0, 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13, 15 },
+  { 0, 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
+  { 0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15 }
+};
+#endif
+
+const UInt g_sigLastScan8x8[ 4 ][ 4 ] =
+{
+  {0, 1, 2, 3},
+  {0, 1, 2, 3},
+#if REMOVAL_8x2_2x8_CG
+  {0, 2, 1, 3},
+#else
+  {0, 1, 2, 3},
+#endif
+  {0, 2, 1, 3}
+};
+UInt g_sigLastScanCG32x32[ 64 ];
+
+UInt* g_auiNonSquareSigLastScan[ 4 ];
+
+const UInt g_uiMinInGroup[ 10 ] = {0,1,2,3,4,6,8,12,16,24};
+const UInt g_uiGroupIdx[ 32 ]   = {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};
+
+// Rice parameters for absolute transform levels
+const UInt g_auiGoRiceRange[5] =
+{
+  7, 14, 26, 46, 78
+};
+
+const UInt g_auiGoRicePrefixLen[5] =
+{
+  8, 7, 6, 5, 4
+};
+
+#if !REMOVE_ZIGZAG_SCAN
+// initialize g_auiFrameScanXY
+Void initFrameScanXY( UInt* pBuff, UInt* pBuffX, UInt* pBuffY, Int iWidth, Int iHeight )
+{
+  Int x, y, c = 0;
+  
+  // starting point
+  pBuffX[ c ] = 0;
+  pBuffY[ c ] = 0;
+  pBuff[ c++ ] = 0;
+  
+  // loop
+  x=1; y=0;
+  while (1)
+  {
+    // decrease loop
+    while ( x>=0 )
+    {
+      if ( x >= 0 && x < iWidth && y >= 0 && y < iHeight )
+      {
+        pBuffX[ c ] = x;
+        pBuffY[ c ] = y;
+        pBuff[ c++ ] = x+y*iWidth;
+      }
+      x--; y++;
+    }
+    x=0;
+    
+    // increase loop
+    while ( y>=0 )
+    {
+      if ( x >= 0 && x < iWidth && y >= 0 && y < iHeight )
+      {
+        pBuffX[ c ] = x;
+        pBuffY[ c ] = y;
+        pBuff[ c++ ] = x+y*iWidth;
+      }
+      x++; y--;
+    }
+    y=0;
+    
+    // termination condition
+    if ( c >= iWidth*iHeight ) break;
+  }  
+}
+#endif
+
+Void initSigLastScan(UInt* pBuffZ, UInt* pBuffH, UInt* pBuffV, UInt* pBuffD, Int iWidth, Int iHeight, Int iDepth)
+{
+  const UInt  uiNumScanPos  = UInt( iWidth * iWidth );
+  UInt        uiNextScanPos = 0;
+
+  if( iWidth < 16 )
+  {
+  UInt* pBuffTemp = pBuffD;
+  if( iWidth == 8 )
+  {
+    pBuffTemp = g_sigLastScanCG32x32;
+  }
+  for( UInt uiScanLine = 0; uiNextScanPos < uiNumScanPos; uiScanLine++ )
+  {
+    int    iPrimDim  = int( uiScanLine );
+    int    iScndDim  = 0;
+    while( iPrimDim >= iWidth )
+    {
+      iScndDim++;
+      iPrimDim--;
+    }
+    while( iPrimDim >= 0 && iScndDim < iWidth )
+    {
+      pBuffTemp[ uiNextScanPos ] = iPrimDim * iWidth + iScndDim ;
+      uiNextScanPos++;
+      iScndDim++;
+      iPrimDim--;
+    }
+  }
+  }
+  if( iWidth > 4 )
+  {
+    UInt uiNumBlkSide = iWidth >> 2;
+    UInt uiNumBlks    = uiNumBlkSide * uiNumBlkSide;
+    UInt log2Blk      = g_aucConvertToBit[ uiNumBlkSide ] + 1;
+
+    for( UInt uiBlk = 0; uiBlk < uiNumBlks; uiBlk++ )
+    {
+      uiNextScanPos   = 0;
+      UInt initBlkPos = g_auiSigLastScan[ SCAN_DIAG ][ log2Blk ][ uiBlk ];
+      if( iWidth == 32 )
+      {
+        initBlkPos = g_sigLastScanCG32x32[ uiBlk ];
+      }
+      UInt offsetY    = initBlkPos / uiNumBlkSide;
+      UInt offsetX    = initBlkPos - offsetY * uiNumBlkSide;
+      UInt offsetD    = 4 * ( offsetX + offsetY * iWidth );
+      UInt offsetScan = 16 * uiBlk;
+      for( UInt uiScanLine = 0; uiNextScanPos < 16; uiScanLine++ )
+      {
+        int    iPrimDim  = int( uiScanLine );
+        int    iScndDim  = 0;
+        while( iPrimDim >= 4 )
+        {
+          iScndDim++;
+          iPrimDim--;
+        }
+        while( iPrimDim >= 0 && iScndDim < 4 )
+        {
+          pBuffD[ uiNextScanPos + offsetScan ] = iPrimDim * iWidth + iScndDim + offsetD;
+          uiNextScanPos++;
+          iScndDim++;
+          iPrimDim--;
+        }
+      }
+    }
+  }
+  
+#if !REMOVE_ZIGZAG_SCAN
+  memcpy(pBuffZ, g_auiFrameScanXY[iDepth], sizeof(UInt)*iWidth*iHeight);
+#endif
+
+  UInt uiCnt = 0;
+#if REMOVAL_8x2_2x8_CG
+  if( iWidth > 2 )
+  {
+    UInt numBlkSide = iWidth >> 2;
+    for(Int blkY=0; blkY < numBlkSide; blkY++)
+    {
+      for(Int blkX=0; blkX < numBlkSide; blkX++)
+      {
+        UInt offset    = blkY * 4 * iWidth + blkX * 4;
+        for(Int y=0; y < 4; y++)
+        {
+          for(Int x=0; x < 4; x++)
+          {
+            pBuffH[uiCnt] = y*iWidth + x + offset;
+            uiCnt ++;
+          }
+        }
+      }
+    }
+
+    uiCnt = 0;
+    for(Int blkX=0; blkX < numBlkSide; blkX++)
+    {
+      for(Int blkY=0; blkY < numBlkSide; blkY++)
+      {
+        UInt offset    = blkY * 4 * iWidth + blkX * 4;
+        for(Int x=0; x < 4; x++)
+        {
+          for(Int y=0; y < 4; y++)
+          {
+            pBuffV[uiCnt] = y*iWidth + x + offset;
+            uiCnt ++;
+          }
+        }
+      }
+    }
+  }
+  else
+  {
+#endif
+  for(Int iY=0; iY < iHeight; iY++)
+  {
+    for(Int iX=0; iX < iWidth; iX++)
+    {
+      pBuffH[uiCnt] = iY*iWidth + iX;
+      uiCnt ++;
+    }
+  }
+
+  uiCnt = 0;
+  for(Int iX=0; iX < iWidth; iX++)
+  {
+    for(Int iY=0; iY < iHeight; iY++)
+    {
+      pBuffV[uiCnt] = iY*iWidth + iX;
+      uiCnt ++;
+    }
+  }    
+#if REMOVAL_8x2_2x8_CG
+  }
+#endif
+}
+
+Void initNonSquareSigLastScan(UInt* pBuffZ, UInt uiWidth, UInt uiHeight)
+{
+
+  Int x, y, c = 0;
+
+  // starting point
+  pBuffZ[ c++ ] = 0;
+
+  // loop
+  if ( uiWidth > uiHeight )
+  {
+    x=0; y=1;
+    while (1)
+    {
+      // increase loop
+      while ( y>=0 )
+      {
+        if ( x >= 0 && x < uiWidth && y >= 0 && y < uiHeight )
+        {
+          pBuffZ[ c++ ] = x + y * uiWidth;
+        }
+        x++;
+        y--;
+      }
+      y=0;
+
+      // decrease loop
+      while ( x>=0 )
+      {
+        if ( x >= 0 && x < uiWidth && y >= 0 && y < uiHeight )
+        {
+          pBuffZ[ c++ ] = x + y * uiWidth;
+        }
+        x--;
+        y++;
+      }
+      x=0;
+
+      // termination condition
+      if ( c >= uiWidth * uiHeight ) 
+      {
+        break;
+      }
+    }
+  }
+  else
+  {
+    x=1; y=0;
+    while (1)
+    {
+      // increase loop
+      while ( x>=0 )
+      {
+        if ( x >= 0 && x < uiWidth && y >= 0 && y < uiHeight )
+        {
+          pBuffZ[ c++ ] = x + y * uiWidth;
+        }
+        x--;
+        y++;
+      }
+      x=0;
+
+      // decrease loop
+      while ( y>=0 )
+      {
+        if ( x >= 0 && x < uiWidth && y >= 0 && y < uiHeight )
+        {
+          pBuffZ[ c++ ] = x + y * uiWidth;
+        }
+        x++;
+        y--;
+      }
+      y=0;
+
+      // termination condition
+      if ( c >= uiWidth * uiHeight )
+      {
+        break;
+      }
+    }
+  }
+}
+
+Int g_quantIntraDefault4x4[16] =
+{
+  16,16,17,21,
+  16,17,20,25,
+  17,20,30,41,
+  21,25,41,70
+};
+Int g_quantInterDefault4x4[16] =
+{
+  16,16,17,21,
+  16,17,21,24,
+  17,21,24,36,
+  21,24,36,57
+};
+#if TS_FLAT_QUANTIZATION_MATRIX
+Int g_quantTSDefault4x4[16] =
+{
+  16,16,16,16,
+  16,16,16,16,
+  16,16,16,16,
+  16,16,16,16
+};
+#endif
+
+Int g_quantIntraDefault8x8[64] =
+{
+  16,16,16,16,17,18,21,24,
+  16,16,16,16,17,19,22,25,
+  16,16,17,18,20,22,25,29,
+  16,16,18,21,24,27,31,36,
+  17,17,20,24,30,35,41,47,
+  18,19,22,27,35,44,54,65,
+  21,22,25,31,41,54,70,88,
+  24,25,29,36,47,65,88,115
+};
+
+Int g_quantInterDefault8x8[64] =
+{
+  16,16,16,16,17,18,20,24,
+  16,16,16,17,18,20,24,25,
+  16,16,17,18,20,24,25,28,
+  16,17,18,20,24,25,28,33,
+  17,18,20,24,25,28,33,41,
+  18,20,24,25,28,33,41,54,
+  20,24,25,28,33,41,54,71,
+  24,25,28,33,41,54,71,91
+};
+UInt g_scalingListSize   [4] = {16,64,256,1024}; 
+UInt g_scalingListSizeX  [4] = { 4, 8, 16,  32};
+UInt g_scalingListNum[SCALING_LIST_SIZE_NUM]={6,6,6,2};
+Int  g_eTTable[4] = {0,3,1,2};
+
+//! \}
Index: /trunk/source/Lib/TLibCommon/TComRom.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComRom.h	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComRom.h	(revision 2)
@@ -0,0 +1,320 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComRom.h
+    \brief    global variables & functions (header)
+*/
+
+#ifndef __TCOMROM__
+#define __TCOMROM__
+
+#include "CommonDef.h"
+
+#include<stdio.h>
+#include<iostream>
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Macros
+// ====================================================================================================================
+
+#define     MAX_CU_DEPTH            7                           // log2(LCUSize)
+#define     MAX_CU_SIZE             (1<<(MAX_CU_DEPTH))         // maximum allowable size of CU
+#define     MIN_PU_SIZE             4
+#define     MAX_NUM_SPU_W           (MAX_CU_SIZE/MIN_PU_SIZE)   // maximum number of SPU in horizontal line
+
+// ====================================================================================================================
+// Initialize / destroy functions
+// ====================================================================================================================
+
+Void         initROM();
+Void         destroyROM();
+#if !REMOVE_ZIGZAG_SCAN
+Void         initFrameScanXY( UInt* pBuff, UInt* pBuffX, UInt* pBuffY, Int iWidth, Int iHeight );
+#endif
+Void         initSigLastScan(UInt* pBuffZ, UInt* pBuffH, UInt* pBuffV, UInt* pBuffD, Int iWidth, Int iHeight, Int iDepth);
+Void         initNonSquareSigLastScan(UInt* pBuffZ, UInt uiWidth, UInt uiHeight);
+// ====================================================================================================================
+// Data structure related table & variable
+// ====================================================================================================================
+
+// flexible conversion from relative to absolute index
+extern       UInt   g_auiZscanToRaster[ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
+extern       UInt   g_auiRasterToZscan[ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
+extern       UInt   g_motionRefer[ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
+
+Void         initZscanToRaster ( Int iMaxDepth, Int iDepth, UInt uiStartVal, UInt*& rpuiCurrIdx );
+Void         initRasterToZscan ( UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxDepth         );
+
+Void          initMotionReferIdx ( UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxDepth );
+
+// conversion of partition index to picture pel position
+extern       UInt   g_auiRasterToPelX[ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
+extern       UInt   g_auiRasterToPelY[ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
+
+Void         initRasterToPelXY ( UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxDepth );
+
+// global variable (LCU width/height, max. CU depth)
+extern       UInt g_uiMaxCUWidth;
+extern       UInt g_uiMaxCUHeight;
+extern       UInt g_uiMaxCUDepth;
+extern       UInt g_uiAddCUDepth;
+
+#define MAX_TS_WIDTH  4
+#define MAX_TS_HEIGHT 4
+
+extern       UInt g_auiPUOffset[8];
+
+#define QUANT_IQUANT_SHIFT    20 // Q(QP%6) * IQ(QP%6) = 2^20
+#define QUANT_SHIFT           14 // Q(4) = 2^14
+#define SCALE_BITS            15 // Inherited from TMuC, pressumably for fractional bit estimates in RDOQ
+#define MAX_TR_DYNAMIC_RANGE  15 // Maximum transform dynamic range (excluding sign bit)
+
+#define SHIFT_INV_1ST          7 // Shift after first inverse transform stage
+#define SHIFT_INV_2ND         12 // Shift after second inverse transform stage
+
+extern Int g_quantScales[6];             // Q(QP%6)  
+extern Int g_invQuantScales[6];          // IQ(QP%6)
+extern const short g_aiT4[4][4];
+extern const short g_aiT8[8][8];
+extern const short g_aiT16[16][16];
+extern const short g_aiT32[32][32];
+
+// ====================================================================================================================
+// Luma QP to Chroma QP mapping
+// ====================================================================================================================
+
+#if CHROMA_QP_EXTENSION
+extern const UChar  g_aucChromaScale      [58];
+#else
+extern const UChar  g_aucChromaScale      [52];
+#endif
+
+// ====================================================================================================================
+// Scanning order & context mapping table
+// ====================================================================================================================
+
+#if !REMOVE_ZIGZAG_SCAN
+extern       UInt*  g_auiFrameScanXY[ MAX_CU_DEPTH  ];    // raster index     from scanning index
+extern       UInt*  g_auiFrameScanX [ MAX_CU_DEPTH  ];    // raster index (x) from scanning index
+extern       UInt*  g_auiFrameScanY [ MAX_CU_DEPTH  ];    // raster index (y) from scanning index
+#endif
+extern       UInt*  g_auiSigLastScan[4][ MAX_CU_DEPTH ];  // raster index from scanning index (zigzag, hor, ver, diag)
+#if !REMOVE_NSQT
+extern UInt *g_sigScanNSQT[ 4 ]; // scan for non-square partitions
+extern UInt g_sigCGScanNSQT[ 4 ][ 16 ]; // coarse-grain scan for non-square partitions
+#endif
+
+extern       UInt*  g_auiNonSquareSigLastScan[ 4 ];      // raster index from scanning index (zigzag)
+
+extern const UInt   g_uiGroupIdx[ 32 ];
+extern const UInt   g_uiMinInGroup[ 10 ];
+
+extern const UInt   g_auiGoRiceRange[5];                  //!< maximum value coded with Rice codes
+extern const UInt   g_auiGoRicePrefixLen[5];              //!< prefix length for each maximum value
+  
+extern const UInt   g_sigLastScan8x8[ 4 ][ 4 ];           //!< coefficient group scan order for 8x8 TUs
+extern       UInt   g_sigLastScanCG32x32[ 64 ];
+
+// ====================================================================================================================
+// ADI table
+// ====================================================================================================================
+
+extern const UChar  g_aucIntraModeNumFast[7];
+
+// ====================================================================================================================
+// Angular Intra table
+// ====================================================================================================================
+
+extern const UChar g_aucIntraModeNumAng[7];
+extern const UChar g_aucIntraModeBitsAng[7];
+extern const UChar g_aucAngIntraModeOrder[NUM_INTRA_MODE];
+
+// ====================================================================================================================
+// Bit-depth
+// ====================================================================================================================
+
+extern       UInt g_uiBitDepth;
+extern       UInt g_uiBitIncrement;
+extern       UInt g_uiIBDI_MAX;
+extern       UInt g_uiBASE_MAX;
+extern       UInt g_uiPCMBitDepthLuma;
+extern       UInt g_uiPCMBitDepthChroma;
+
+// ====================================================================================================================
+// Texture type to integer mapping
+// ====================================================================================================================
+
+extern const UChar g_aucConvertTxtTypeToIdx[4];
+
+// ==========================================
+// Mode-Dependent DST Matrices
+extern const short g_as_DST_MAT_4 [4][4];
+extern const UChar g_aucDCTDSTMode_Vert[NUM_INTRA_MODE];
+extern const UChar g_aucDCTDSTMode_Hor[NUM_INTRA_MODE];
+// ==========================================
+
+// ====================================================================================================================
+// Misc.
+// ====================================================================================================================
+
+extern       Char   g_aucConvertToBit  [ MAX_CU_SIZE+1 ];   // from width to log2(width)-2
+
+#define ENC_DEC_TRACE 0
+
+
+#if ENC_DEC_TRACE
+extern FILE*  g_hTrace;
+extern Bool   g_bJustDoIt;
+extern const Bool g_bEncDecTraceEnable;
+extern const Bool g_bEncDecTraceDisable;
+extern Bool   g_HLSTraceEnable;
+extern UInt64 g_nSymbolCounter;
+
+#define COUNTER_START    1
+#define COUNTER_END      0 //( UInt64(1) << 63 )
+
+#define DTRACE_CABAC_F(x)     if ( ( g_nSymbolCounter >= COUNTER_START && g_nSymbolCounter <= COUNTER_END )|| g_bJustDoIt ) fprintf( g_hTrace, "%f", x );
+#define DTRACE_CABAC_V(x)     if ( ( g_nSymbolCounter >= COUNTER_START && g_nSymbolCounter <= COUNTER_END )|| g_bJustDoIt ) fprintf( g_hTrace, "%d", x );
+#define DTRACE_CABAC_VL(x)    if ( ( g_nSymbolCounter >= COUNTER_START && g_nSymbolCounter <= COUNTER_END )|| g_bJustDoIt ) fprintf( g_hTrace, "%lld", x );
+#define DTRACE_CABAC_T(x)     if ( ( g_nSymbolCounter >= COUNTER_START && g_nSymbolCounter <= COUNTER_END )|| g_bJustDoIt ) fprintf( g_hTrace, "%s", x );
+#define DTRACE_CABAC_X(x)     if ( ( g_nSymbolCounter >= COUNTER_START && g_nSymbolCounter <= COUNTER_END )|| g_bJustDoIt ) fprintf( g_hTrace, "%x", x );
+#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"    );
+
+#else
+
+#define DTRACE_CABAC_F(x)
+#define DTRACE_CABAC_V(x)
+#define DTRACE_CABAC_VL(x)
+#define DTRACE_CABAC_T(x)
+#define DTRACE_CABAC_X(x)
+#define DTRACE_CABAC_R( x,y )
+#define DTRACE_CABAC_N
+
+#endif
+
+
+#define SCALING_LIST_NUM 6         ///< list number for quantization matrix
+#define SCALING_LIST_NUM_32x32 2   ///< list number for quantization matrix 32x32
+#define SCALING_LIST_REM_NUM 6     ///< remainder of QP/6
+#define SCALING_LIST_START_VALUE 8 ///< start value for dpcm mode
+#define MAX_MATRIX_COEF_NUM 64     ///< max coefficient number for quantization matrix
+#define MAX_MATRIX_SIZE_NUM 8      ///< max size number for quantization matrix
+#define SCALING_LIST_DC 16         ///< default DC value
+enum ScalingListDIR
+{
+  SCALING_LIST_SQT = 0,
+  SCALING_LIST_VER,
+  SCALING_LIST_HOR,
+  SCALING_LIST_DIR_NUM
+};
+enum ScalingListSize
+{
+  SCALING_LIST_4x4 = 0,
+  SCALING_LIST_8x8,
+  SCALING_LIST_16x16,
+  SCALING_LIST_32x32,
+  SCALING_LIST_SIZE_NUM
+};
+static const char MatrixType[4][6][20] =
+{
+  {
+  "INTRA4X4_LUMA",
+  "INTRA4X4_CHROMAU",
+  "INTRA4X4_CHROMAV",
+  "INTER4X4_LUMA",
+  "INTER4X4_CHROMAU",
+  "INTER4X4_CHROMAV"
+  },
+  {
+  "INTRA8X8_LUMA",
+  "INTRA8X8_CHROMAU", 
+  "INTRA8X8_CHROMAV", 
+  "INTER8X8_LUMA",
+  "INTER8X8_CHROMAU", 
+  "INTER8X8_CHROMAV"  
+  },
+  {
+  "INTRA16X16_LUMA",
+  "INTRA16X16_CHROMAU", 
+  "INTRA16X16_CHROMAV", 
+  "INTER16X16_LUMA",
+  "INTER16X16_CHROMAU", 
+  "INTER16X16_CHROMAV"  
+  },
+  {
+  "INTRA32X32_LUMA",
+  "INTER32X32_LUMA",
+  },
+};
+static const char MatrixType_DC[4][12][22] =
+{
+  {
+  },
+  {
+  },
+  {
+  "INTRA16X16_LUMA_DC",
+  "INTRA16X16_CHROMAU_DC", 
+  "INTRA16X16_CHROMAV_DC", 
+  "INTER16X16_LUMA_DC",
+  "INTER16X16_CHROMAU_DC", 
+  "INTER16X16_CHROMAV_DC"  
+  },
+  {
+  "INTRA32X32_LUMA_DC",
+  "INTER32X32_LUMA_DC",
+  },
+};
+extern Int g_quantIntraDefault4x4[16];
+extern Int g_quantIntraDefault8x8[64];
+extern Int g_quantIntraDefault16x16[256];
+extern Int g_quantIntraDefault32x32[1024];
+extern Int g_quantInterDefault4x4[16];
+extern Int g_quantInterDefault8x8[64];
+extern Int g_quantInterDefault16x16[256];
+extern Int g_quantInterDefault32x32[1024];
+#if TS_FLAT_QUANTIZATION_MATRIX
+extern Int g_quantTSDefault4x4[16];
+#endif
+extern UInt g_scalingListSize [SCALING_LIST_SIZE_NUM];
+extern UInt g_scalingListSizeX[SCALING_LIST_SIZE_NUM];
+extern UInt g_scalingListNum  [SCALING_LIST_SIZE_NUM];
+extern Int  g_eTTable[4];
+//! \}
+
+#endif  //__TCOMROM__
+
Index: /trunk/source/Lib/TLibCommon/TComSampleAdaptiveOffset.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComSampleAdaptiveOffset.cpp	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComSampleAdaptiveOffset.cpp	(revision 2)
@@ -0,0 +1,1524 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComSampleAdaptiveOffset.cpp
+    \brief    sample adaptive offset class
+*/
+
+#include "TComSampleAdaptiveOffset.h"
+#include <string.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <math.h>
+
+//! \ingroup TLibCommon
+//! \{
+
+SAOParam::~SAOParam()
+{
+  for (Int i = 0 ; i<3; i++)
+  {
+    if (psSaoPart[i])
+    {
+      delete [] psSaoPart[i];
+    }
+  }
+}
+
+// ====================================================================================================================
+// Tables
+// ====================================================================================================================
+
+TComSampleAdaptiveOffset::TComSampleAdaptiveOffset()
+{
+  m_pClipTable = NULL;
+  m_pClipTableBase = NULL;
+  m_iOffsetBo = NULL;
+  m_lumaTableBo = NULL;
+  m_iUpBuff1 = NULL;
+  m_iUpBuff2 = NULL;
+  m_iUpBufft = NULL;
+  ipSwap = NULL;
+
+  m_pTmpU1 = NULL;
+  m_pTmpU2 = NULL;
+  m_pTmpL1 = NULL;
+  m_pTmpL2 = NULL;
+  m_iLcuPartIdx = NULL;
+}
+
+TComSampleAdaptiveOffset::~TComSampleAdaptiveOffset()
+{
+
+}
+
+const Int TComSampleAdaptiveOffset::m_aiNumCulPartsLevel[5] =
+{
+  1,   //level 0
+  5,   //level 1
+  21,  //level 2
+  85,  //level 3
+  341, //level 4
+};
+
+const UInt TComSampleAdaptiveOffset::m_auiEoTable[9] =
+{
+  1, //0    
+  2, //1   
+  0, //2
+  3, //3
+  4, //4
+  0, //5  
+  0, //6  
+  0, //7 
+  0
+};
+
+const Int TComSampleAdaptiveOffset::m_iNumClass[MAX_NUM_SAO_TYPE] =
+{
+  SAO_EO_LEN,
+  SAO_EO_LEN,
+  SAO_EO_LEN,
+  SAO_EO_LEN,
+  SAO_BO_LEN
+};
+
+const UInt TComSampleAdaptiveOffset::m_uiMaxDepth = SAO_MAX_DEPTH;
+
+
+/** convert Level Row Col to Idx
+ * \param   level,  row,  col
+ */
+Int  TComSampleAdaptiveOffset::convertLevelRowCol2Idx(int level, int row, int col)
+{
+  Int idx;
+  if (level == 0)
+  {
+    idx = 0;
+  }
+  else if (level == 1)
+  {
+    idx = 1 + row*2 + col;
+  }
+  else if (level == 2)
+  {
+    idx = 5 + row*4 + col;
+  }
+  else if (level == 3)
+  {
+    idx = 21 + row*8 + col;
+  }
+  else // (level == 4)
+  {
+    idx = 85 + row*16 + col;
+  }
+  return idx;
+}
+
+/** create SampleAdaptiveOffset memory.
+ * \param 
+ */
+Void TComSampleAdaptiveOffset::create( UInt uiSourceWidth, UInt uiSourceHeight, UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxCUDepth)
+{
+  m_iPicWidth  = uiSourceWidth;
+  m_iPicHeight = uiSourceHeight;
+
+  m_uiMaxCUWidth  = uiMaxCUWidth;
+  m_uiMaxCUHeight = uiMaxCUHeight;
+
+  m_iNumCuInWidth  = m_iPicWidth / m_uiMaxCUWidth;
+  m_iNumCuInWidth += ( m_iPicWidth % m_uiMaxCUWidth ) ? 1 : 0;
+
+  m_iNumCuInHeight  = m_iPicHeight / m_uiMaxCUHeight;
+  m_iNumCuInHeight += ( m_iPicHeight % m_uiMaxCUHeight ) ? 1 : 0;
+
+  Int iMaxSplitLevelHeight = (Int)(logf((float)m_iNumCuInHeight)/logf(2.0));
+  Int iMaxSplitLevelWidth  = (Int)(logf((float)m_iNumCuInWidth )/logf(2.0));
+
+  m_uiMaxSplitLevel = (iMaxSplitLevelHeight < iMaxSplitLevelWidth)?(iMaxSplitLevelHeight):(iMaxSplitLevelWidth);
+  m_uiMaxSplitLevel = (m_uiMaxSplitLevel< m_uiMaxDepth)?(m_uiMaxSplitLevel):(m_uiMaxDepth);
+  /* various structures are overloaded to store per component data.
+   * m_iNumTotalParts must allow for sufficient storage in any allocated arrays */
+  m_iNumTotalParts  = max(3,m_aiNumCulPartsLevel[m_uiMaxSplitLevel]);
+
+  UInt uiInternalBitDepth = g_uiBitDepth+g_uiBitIncrement;
+  UInt uiPixelRange = 1<<uiInternalBitDepth;
+  UInt uiBoRangeShift = uiInternalBitDepth - SAO_BO_BITS;
+
+  m_lumaTableBo = new Pel [uiPixelRange];
+  for (Int k2=0; k2<uiPixelRange; k2++)
+  {
+    m_lumaTableBo[k2] = 1 + (k2>>uiBoRangeShift);
+  }
+  m_iUpBuff1 = new Int[m_iPicWidth+2];
+  m_iUpBuff2 = new Int[m_iPicWidth+2];
+  m_iUpBufft = new Int[m_iPicWidth+2];
+
+  m_iUpBuff1++;
+  m_iUpBuff2++;
+  m_iUpBufft++;
+  Pel i;
+
+  UInt uiMaxY  = g_uiIBDI_MAX;
+  UInt uiMinY  = 0;
+
+  Int iCRangeExt = uiMaxY>>1;
+
+  m_pClipTableBase = new Pel[uiMaxY+2*iCRangeExt];
+  m_iOffsetBo      = new Int[uiMaxY+2*iCRangeExt];
+
+  for(i=0;i<(uiMinY+iCRangeExt);i++)
+  {
+    m_pClipTableBase[i] = uiMinY;
+  }
+
+  for(i=uiMinY+iCRangeExt;i<(uiMaxY+  iCRangeExt);i++)
+  {
+    m_pClipTableBase[i] = i-iCRangeExt;
+  }
+
+  for(i=uiMaxY+iCRangeExt;i<(uiMaxY+2*iCRangeExt);i++)
+  {
+    m_pClipTableBase[i] = uiMaxY;
+  }
+
+  m_pClipTable = &(m_pClipTableBase[iCRangeExt]);
+
+  m_iLcuPartIdx = new Int [m_iNumCuInHeight*m_iNumCuInWidth];
+  m_pTmpL1 = new Pel [m_uiMaxCUHeight+1];
+  m_pTmpL2 = new Pel [m_uiMaxCUHeight+1];
+  m_pTmpU1 = new Pel [m_iPicWidth];
+  m_pTmpU2 = new Pel [m_iPicWidth];
+}
+
+/** destroy SampleAdaptiveOffset memory.
+ * \param 
+ */
+Void TComSampleAdaptiveOffset::destroy()
+{
+  if (m_pClipTableBase)
+  {
+    delete [] m_pClipTableBase; m_pClipTableBase = NULL;
+  }
+  if (m_iOffsetBo)
+  {
+    delete [] m_iOffsetBo; m_iOffsetBo = NULL;
+  }
+  if (m_lumaTableBo)
+  {
+    delete[] m_lumaTableBo; m_lumaTableBo = NULL;
+  }
+
+  if (m_iUpBuff1)
+  {
+    m_iUpBuff1--;
+    delete [] m_iUpBuff1; m_iUpBuff1 = NULL;
+  }
+  if (m_iUpBuff2)
+  {
+    m_iUpBuff2--;
+    delete [] m_iUpBuff2; m_iUpBuff2 = NULL;
+  }
+  if (m_iUpBufft)
+  {
+    m_iUpBufft--;
+    delete [] m_iUpBufft; m_iUpBufft = NULL;
+  }
+  if (m_pTmpL1)
+  {
+    delete [] m_pTmpL1; m_pTmpL1 = NULL;
+  }
+  if (m_pTmpL2)
+  {
+    delete [] m_pTmpL2; m_pTmpL2 = NULL;
+  }
+  if (m_pTmpU1)
+  {
+    delete [] m_pTmpU1; m_pTmpU1 = NULL;
+  }
+  if (m_pTmpU2)
+  {
+    delete [] m_pTmpU2; m_pTmpU2 = NULL;
+  }
+  if(m_iLcuPartIdx)
+  {
+    delete []m_iLcuPartIdx; m_iLcuPartIdx = NULL;
+  }
+}
+
+/** allocate memory for SAO parameters
+ * \param    *pcSaoParam
+ */
+Void TComSampleAdaptiveOffset::allocSaoParam(SAOParam *pcSaoParam)
+{
+  pcSaoParam->iMaxSplitLevel = m_uiMaxSplitLevel;
+  pcSaoParam->psSaoPart[0] = new SAOQTPart[ m_aiNumCulPartsLevel[pcSaoParam->iMaxSplitLevel] ];
+  initSAOParam(pcSaoParam, 0, 0, 0, -1, 0, m_iNumCuInWidth-1,  0, m_iNumCuInHeight-1,0);
+  pcSaoParam->psSaoPart[1] = new SAOQTPart[ m_aiNumCulPartsLevel[pcSaoParam->iMaxSplitLevel] ];
+  pcSaoParam->psSaoPart[2] = new SAOQTPart[ m_aiNumCulPartsLevel[pcSaoParam->iMaxSplitLevel] ];
+  initSAOParam(pcSaoParam, 0, 0, 0, -1, 0, m_iNumCuInWidth-1,  0, m_iNumCuInHeight-1,1);
+  initSAOParam(pcSaoParam, 0, 0, 0, -1, 0, m_iNumCuInWidth-1,  0, m_iNumCuInHeight-1,2);
+  pcSaoParam->numCuInWidth  = m_iNumCuInWidth;
+  pcSaoParam->numCuInHeight = m_iNumCuInHeight;
+  pcSaoParam->saoLcuParam[0] = new SaoLcuParam [m_iNumCuInHeight*m_iNumCuInWidth];
+  pcSaoParam->saoLcuParam[1] = new SaoLcuParam [m_iNumCuInHeight*m_iNumCuInWidth];
+  pcSaoParam->saoLcuParam[2] = new SaoLcuParam [m_iNumCuInHeight*m_iNumCuInWidth];
+}
+
+/** initialize SAO parameters
+ * \param    *pcSaoParam,  iPartLevel,  iPartRow,  iPartCol,  iParentPartIdx,  StartCUX,  EndCUX,  StartCUY,  EndCUY,  iYCbCr
+ */
+Void TComSampleAdaptiveOffset::initSAOParam(SAOParam *pcSaoParam, Int iPartLevel, Int iPartRow, Int iPartCol, Int iParentPartIdx, Int StartCUX, Int EndCUX, Int StartCUY, Int EndCUY, Int iYCbCr)
+{
+  Int j;
+  Int iPartIdx = convertLevelRowCol2Idx(iPartLevel, iPartRow, iPartCol);
+
+  SAOQTPart* pSaoPart;
+
+  pSaoPart = &(pcSaoParam->psSaoPart[iYCbCr][iPartIdx]);
+
+  pSaoPart->PartIdx   = iPartIdx;
+  pSaoPart->PartLevel = iPartLevel;
+  pSaoPart->PartRow   = iPartRow;
+  pSaoPart->PartCol   = iPartCol;
+
+  pSaoPart->StartCUX  = StartCUX;
+  pSaoPart->EndCUX    = EndCUX;
+  pSaoPart->StartCUY  = StartCUY;
+  pSaoPart->EndCUY    = EndCUY;
+
+  pSaoPart->UpPartIdx = iParentPartIdx;
+  pSaoPart->iBestType   = -1;
+  pSaoPart->iLength     =  0;
+
+#if SAO_TYPE_CODING
+  pSaoPart->subTypeIdx = 0;
+#else
+  pSaoPart->bandPosition = 0;
+#endif
+
+  for (j=0;j<MAX_NUM_SAO_OFFSETS;j++)
+  {
+    pSaoPart->iOffset[j] = 0;
+  }
+
+  if(pSaoPart->PartLevel != m_uiMaxSplitLevel)
+  {
+    Int DownLevel    = (iPartLevel+1 );
+    Int DownRowStart = (iPartRow << 1);
+    Int DownColStart = (iPartCol << 1);
+
+    Int iDownRowIdx, iDownColIdx;
+    Int NumCUWidth,  NumCUHeight;
+    Int NumCULeft;
+    Int NumCUTop;
+
+    Int DownStartCUX, DownStartCUY;
+    Int DownEndCUX, DownEndCUY;
+
+    NumCUWidth  = EndCUX - StartCUX +1;
+    NumCUHeight = EndCUY - StartCUY +1;
+    NumCULeft   = (NumCUWidth  >> 1);
+    NumCUTop    = (NumCUHeight >> 1);
+
+    DownStartCUX= StartCUX;
+    DownEndCUX  = DownStartCUX + NumCULeft - 1;
+    DownStartCUY= StartCUY;
+    DownEndCUY  = DownStartCUY + NumCUTop  - 1;
+    iDownRowIdx = DownRowStart + 0;
+    iDownColIdx = DownColStart + 0;
+
+    pSaoPart->DownPartsIdx[0]= convertLevelRowCol2Idx(DownLevel, iDownRowIdx, iDownColIdx);
+
+    initSAOParam(pcSaoParam, DownLevel, iDownRowIdx, iDownColIdx, iPartIdx, DownStartCUX, DownEndCUX, DownStartCUY, DownEndCUY, iYCbCr);
+
+    DownStartCUX = StartCUX + NumCULeft;
+    DownEndCUX   = EndCUX;
+    DownStartCUY = StartCUY;
+    DownEndCUY   = DownStartCUY + NumCUTop -1;
+    iDownRowIdx  = DownRowStart + 0;
+    iDownColIdx  = DownColStart + 1;
+
+    pSaoPart->DownPartsIdx[1] = convertLevelRowCol2Idx(DownLevel, iDownRowIdx, iDownColIdx);
+
+    initSAOParam(pcSaoParam, DownLevel, iDownRowIdx, iDownColIdx, iPartIdx,  DownStartCUX, DownEndCUX, DownStartCUY, DownEndCUY, iYCbCr);
+
+    DownStartCUX = StartCUX;
+    DownEndCUX   = DownStartCUX + NumCULeft -1;
+    DownStartCUY = StartCUY + NumCUTop;
+    DownEndCUY   = EndCUY;
+    iDownRowIdx  = DownRowStart + 1;
+    iDownColIdx  = DownColStart + 0;
+
+    pSaoPart->DownPartsIdx[2] = convertLevelRowCol2Idx(DownLevel, iDownRowIdx, iDownColIdx);
+
+    initSAOParam(pcSaoParam, DownLevel, iDownRowIdx, iDownColIdx, iPartIdx, DownStartCUX, DownEndCUX, DownStartCUY, DownEndCUY, iYCbCr);
+
+    DownStartCUX = StartCUX+ NumCULeft;
+    DownEndCUX   = EndCUX;
+    DownStartCUY = StartCUY + NumCUTop;
+    DownEndCUY   = EndCUY;
+    iDownRowIdx  = DownRowStart + 1;
+    iDownColIdx  = DownColStart + 1;
+
+    pSaoPart->DownPartsIdx[3] = convertLevelRowCol2Idx(DownLevel, iDownRowIdx, iDownColIdx);
+
+    initSAOParam(pcSaoParam, DownLevel, iDownRowIdx, iDownColIdx, iPartIdx,DownStartCUX, DownEndCUX, DownStartCUY, DownEndCUY, iYCbCr);
+  }
+  else
+  {
+    pSaoPart->DownPartsIdx[0]=pSaoPart->DownPartsIdx[1]= pSaoPart->DownPartsIdx[2]= pSaoPart->DownPartsIdx[3]= -1; 
+  }
+}
+
+/** free memory of SAO parameters
+ * \param   pcSaoParam
+ */
+Void TComSampleAdaptiveOffset::freeSaoParam(SAOParam *pcSaoParam)
+{
+  delete [] pcSaoParam->psSaoPart[0];
+  delete [] pcSaoParam->psSaoPart[1];
+  delete [] pcSaoParam->psSaoPart[2];
+  pcSaoParam->psSaoPart[0] = 0;
+  pcSaoParam->psSaoPart[1] = 0;
+  pcSaoParam->psSaoPart[2] = 0;
+  if( pcSaoParam->saoLcuParam[0]) 
+  {
+    delete [] pcSaoParam->saoLcuParam[0]; pcSaoParam->saoLcuParam[0] = NULL;
+  }
+  if( pcSaoParam->saoLcuParam[1]) 
+  {
+    delete [] pcSaoParam->saoLcuParam[1]; pcSaoParam->saoLcuParam[1] = NULL;
+  }
+  if( pcSaoParam->saoLcuParam[2]) 
+  {
+    delete [] pcSaoParam->saoLcuParam[2]; pcSaoParam->saoLcuParam[2] = NULL;
+  }
+} 
+
+/** reset SAO parameters
+ * \param   pcSaoParam
+ */
+Void TComSampleAdaptiveOffset::resetSAOParam(SAOParam *pcSaoParam)
+{
+  Int iNumComponet = 3;
+  for(Int c=0; c<iNumComponet; c++)
+  {
+#if SAO_TYPE_SHARING
+if (c<2)
+  {
+#endif
+    pcSaoParam->bSaoFlag[c] = 0;
+#if SAO_TYPE_SHARING
+  }
+#endif
+    for(Int i=0; i< m_aiNumCulPartsLevel[m_uiMaxSplitLevel]; i++)
+    {
+      pcSaoParam->psSaoPart[c][i].iBestType     = -1;
+      pcSaoParam->psSaoPart[c][i].iLength       =  0;
+      pcSaoParam->psSaoPart[c][i].bSplit        = false; 
+      pcSaoParam->psSaoPart[c][i].bProcessed    = false;
+      pcSaoParam->psSaoPart[c][i].dMinCost      = MAX_DOUBLE;
+      pcSaoParam->psSaoPart[c][i].iMinDist      = MAX_INT;
+      pcSaoParam->psSaoPart[c][i].iMinRate      = MAX_INT;
+#if SAO_TYPE_CODING
+      pcSaoParam->psSaoPart[c][i].subTypeIdx    = 0;
+#else
+      pcSaoParam->psSaoPart[c][i].bandPosition = 0;
+#endif
+      for (Int j=0;j<MAX_NUM_SAO_OFFSETS;j++)
+      {
+        pcSaoParam->psSaoPart[c][i].iOffset[j] = 0;
+        pcSaoParam->psSaoPart[c][i].iOffset[j] = 0;
+        pcSaoParam->psSaoPart[c][i].iOffset[j] = 0;
+      }
+    }
+    pcSaoParam->oneUnitFlag[0]   = 0;
+    pcSaoParam->oneUnitFlag[1]   = 0;
+    pcSaoParam->oneUnitFlag[2]   = 0;
+    resetLcuPart(pcSaoParam->saoLcuParam[0]);
+    resetLcuPart(pcSaoParam->saoLcuParam[1]);
+    resetLcuPart(pcSaoParam->saoLcuParam[2]);
+  }
+}
+
+/** get the sign of input variable
+ * \param   x
+ */
+inline int xSign(int x)
+{
+  return ((x >> 31) | ((int)( (((unsigned int) -x)) >> 31)));
+}
+
+/** initialize variables for SAO process
+ * \param  pcPic picture data pointer
+ * \param  numSlicesInPic number of slices in picture
+ */
+Void TComSampleAdaptiveOffset::createPicSaoInfo(TComPic* pcPic, Int numSlicesInPic)
+{
+  m_pcPic   = pcPic;
+  m_uiNumSlicesInPic = numSlicesInPic;
+#if REMOVE_FGS
+  m_iSGDepth = 0;
+#else
+  m_iSGDepth         = pcPic->getSliceGranularityForNDBFilter();
+#endif
+  m_bUseNIF = ( pcPic->getIndependentSliceBoundaryForNDBFilter() || pcPic->getIndependentTileBoundaryForNDBFilter() );
+  if(m_bUseNIF)
+  {
+    m_pcYuvTmp = pcPic->getYuvPicBufferForIndependentBoundaryProcessing();
+  }
+}
+
+Void TComSampleAdaptiveOffset::destroyPicSaoInfo()
+{
+
+}
+
+/** sample adaptive offset process for one LCU
+ * \param   iAddr, iSaoType, iYCbCr
+ */
+Void TComSampleAdaptiveOffset::processSaoCu(Int iAddr, Int iSaoType, Int iYCbCr)
+{
+  if(!m_bUseNIF)
+  {
+    processSaoCuOrg( iAddr, iSaoType, iYCbCr);
+  }
+  else
+  {  
+    Int  isChroma = (iYCbCr != 0)? 1:0;
+    Int  stride   = (iYCbCr != 0)?(m_pcPic->getCStride()):(m_pcPic->getStride());
+    Pel* pPicRest = getPicYuvAddr(m_pcPic->getPicYuvRec(), iYCbCr);
+    Pel* pPicDec  = getPicYuvAddr(m_pcYuvTmp, iYCbCr);
+
+    std::vector<NDBFBlockInfo>& vFilterBlocks = *(m_pcPic->getCU(iAddr)->getNDBFilterBlocks());
+
+    //variables
+    UInt  xPos, yPos, width, height;
+    Bool* pbBorderAvail;
+    UInt  posOffset;
+
+    for(Int i=0; i< vFilterBlocks.size(); i++)
+    {
+      xPos        = vFilterBlocks[i].posX   >> isChroma;
+      yPos        = vFilterBlocks[i].posY   >> isChroma;
+      width       = vFilterBlocks[i].width  >> isChroma;
+      height      = vFilterBlocks[i].height >> isChroma;
+      pbBorderAvail = vFilterBlocks[i].isBorderAvailable;
+
+      posOffset = (yPos* stride) + xPos;
+
+      processSaoBlock(pPicDec+ posOffset, pPicRest+ posOffset, stride, iSaoType, xPos, yPos, width, height, pbBorderAvail);
+    }
+  }
+}
+
+/** Perform SAO for non-cross-slice or non-cross-tile process
+ * \param  pDec to-be-filtered block buffer pointer
+ * \param  pRest filtered block buffer pointer
+ * \param  stride picture buffer stride
+ * \param  saoType SAO offset type
+ * \param  xPos x coordinate
+ * \param  yPos y coordinate
+ * \param  width block width
+ * \param  height block height
+ * \param  pbBorderAvail availabilities of block border pixels
+ */
+Void TComSampleAdaptiveOffset::processSaoBlock(Pel* pDec, Pel* pRest, Int stride, Int saoType, UInt xPos, UInt yPos, UInt width, UInt height, Bool* pbBorderAvail)
+{
+  //variables
+  Int startX, startY, endX, endY, x, y;
+  Int signLeft,signRight,signDown,signDown1;
+  UInt edgeType;
+
+  switch (saoType)
+  {
+  case SAO_EO_0: // dir: -
+    {
+
+      startX = (pbBorderAvail[SGU_L]) ? 0 : 1;
+      endX   = (pbBorderAvail[SGU_R]) ? width : (width -1);
+      for (y=0; y< height; y++)
+      {
+        signLeft = xSign(pDec[startX] - pDec[startX-1]);
+        for (x=startX; x< endX; x++)
+        {
+          signRight =  xSign(pDec[x] - pDec[x+1]); 
+          edgeType =  signRight + signLeft + 2;
+          signLeft  = -signRight;
+
+          pRest[x] = m_pClipTable[pDec[x] + m_iOffsetEo[edgeType]];
+        }
+        pDec  += stride;
+        pRest += stride;
+      }
+      break;
+    }
+  case SAO_EO_1: // dir: |
+    {
+      startY = (pbBorderAvail[SGU_T]) ? 0 : 1;
+      endY   = (pbBorderAvail[SGU_B]) ? height : height-1;
+      if (!pbBorderAvail[SGU_T])
+      {
+        pDec  += stride;
+        pRest += stride;
+      }
+      for (x=0; x< width; x++)
+      {
+        m_iUpBuff1[x] = xSign(pDec[x] - pDec[x-stride]);
+      }
+      for (y=startY; y<endY; y++)
+      {
+        for (x=0; x< width; x++)
+        {
+          signDown  = xSign(pDec[x] - pDec[x+stride]); 
+          edgeType = signDown + m_iUpBuff1[x] + 2;
+          m_iUpBuff1[x]= -signDown;
+
+          pRest[x] = m_pClipTable[pDec[x] + m_iOffsetEo[edgeType]];
+        }
+        pDec  += stride;
+        pRest += stride;
+      }
+      break;
+    }
+  case SAO_EO_2: // dir: 135
+    {
+      Int posShift= stride + 1;
+
+      startX = (pbBorderAvail[SGU_L]) ? 0 : 1 ;
+      endX   = (pbBorderAvail[SGU_R]) ? width : (width-1);
+
+      //prepare 2nd line upper sign
+      pDec += stride;
+      for (x=startX; x< endX+1; x++)
+      {
+        m_iUpBuff1[x] = xSign(pDec[x] - pDec[x- posShift]);
+      }
+
+      //1st line
+      pDec -= stride;
+      if(pbBorderAvail[SGU_TL])
+      {
+        x= 0;
+        edgeType      =  xSign(pDec[x] - pDec[x- posShift]) - m_iUpBuff1[x+1] + 2;
+        pRest[x] = m_pClipTable[pDec[x] + m_iOffsetEo[edgeType]];
+
+      }
+      if(pbBorderAvail[SGU_T])
+      {
+        for(x= 1; x< endX; x++)
+        {
+          edgeType      =  xSign(pDec[x] - pDec[x- posShift]) - m_iUpBuff1[x+1] + 2;
+          pRest[x] = m_pClipTable[pDec[x] + m_iOffsetEo[edgeType]];
+        }
+      }
+      pDec   += stride;
+      pRest  += stride;
+
+
+      //middle lines
+      for (y= 1; y< height-1; y++)
+      {
+        for (x=startX; x<endX; x++)
+        {
+          signDown1      =  xSign(pDec[x] - pDec[x+ posShift]) ;
+          edgeType      =  signDown1 + m_iUpBuff1[x] + 2;
+          pRest[x] = m_pClipTable[pDec[x] + m_iOffsetEo[edgeType]];
+
+          m_iUpBufft[x+1] = -signDown1; 
+        }
+        m_iUpBufft[startX] = xSign(pDec[stride+startX] - pDec[startX-1]);
+
+        ipSwap     = m_iUpBuff1;
+        m_iUpBuff1 = m_iUpBufft;
+        m_iUpBufft = ipSwap;
+
+        pDec  += stride;
+        pRest += stride;
+      }
+
+      //last line
+      if(pbBorderAvail[SGU_B])
+      {
+        for(x= startX; x< width-1; x++)
+        {
+          edgeType =  xSign(pDec[x] - pDec[x+ posShift]) + m_iUpBuff1[x] + 2;
+          pRest[x] = m_pClipTable[pDec[x] + m_iOffsetEo[edgeType]];
+        }
+      }
+      if(pbBorderAvail[SGU_BR])
+      {
+        x= width -1;
+        edgeType =  xSign(pDec[x] - pDec[x+ posShift]) + m_iUpBuff1[x] + 2;
+        pRest[x] = m_pClipTable[pDec[x] + m_iOffsetEo[edgeType]];
+      }
+      break;
+    } 
+  case SAO_EO_3: // dir: 45
+    {
+      Int  posShift     = stride - 1;
+      startX = (pbBorderAvail[SGU_L]) ? 0 : 1;
+      endX   = (pbBorderAvail[SGU_R]) ? width : (width -1);
+
+      //prepare 2nd line upper sign
+      pDec += stride;
+      for (x=startX-1; x< endX; x++)
+      {
+        m_iUpBuff1[x] = xSign(pDec[x] - pDec[x- posShift]);
+      }
+
+
+      //first line
+      pDec -= stride;
+      if(pbBorderAvail[SGU_T])
+      {
+        for(x= startX; x< width -1; x++)
+        {
+          edgeType = xSign(pDec[x] - pDec[x- posShift]) -m_iUpBuff1[x-1] + 2;
+          pRest[x] = m_pClipTable[pDec[x] + m_iOffsetEo[edgeType]];
+        }
+      }
+      if(pbBorderAvail[SGU_TR])
+      {
+        x= width-1;
+        edgeType = xSign(pDec[x] - pDec[x- posShift]) -m_iUpBuff1[x-1] + 2;
+        pRest[x] = m_pClipTable[pDec[x] + m_iOffsetEo[edgeType]];
+      }
+      pDec  += stride;
+      pRest += stride;
+
+      //middle lines
+      for (y= 1; y< height-1; y++)
+      {
+        for(x= startX; x< endX; x++)
+        {
+          signDown1      =  xSign(pDec[x] - pDec[x+ posShift]) ;
+          edgeType      =  signDown1 + m_iUpBuff1[x] + 2;
+
+          pRest[x] = m_pClipTable[pDec[x] + m_iOffsetEo[edgeType]];
+          m_iUpBuff1[x-1] = -signDown1; 
+        }
+        m_iUpBuff1[endX-1] = xSign(pDec[endX-1 + stride] - pDec[endX]);
+
+        pDec  += stride;
+        pRest += stride;
+      }
+
+      //last line
+      if(pbBorderAvail[SGU_BL])
+      {
+        x= 0;
+        edgeType = xSign(pDec[x] - pDec[x+ posShift]) + m_iUpBuff1[x] + 2;
+        pRest[x] = m_pClipTable[pDec[x] + m_iOffsetEo[edgeType]];
+
+      }
+      if(pbBorderAvail[SGU_B])
+      {
+        for(x= 1; x< endX; x++)
+        {
+          edgeType = xSign(pDec[x] - pDec[x+ posShift]) + m_iUpBuff1[x] + 2;
+          pRest[x] = m_pClipTable[pDec[x] + m_iOffsetEo[edgeType]];
+        }
+      }
+      break;
+    }   
+  case SAO_BO:
+    {
+      for (y=0; y< height; y++)
+      {
+        for (x=0; x< width; x++)
+        {
+          pRest[x] = m_iOffsetBo[pDec[x]];
+        }
+        pRest += stride;
+        pDec  += stride;
+      }
+      break;
+    }
+  default: break;
+  }
+
+}
+
+/** sample adaptive offset process for one LCU crossing LCU boundary
+ * \param   iAddr, iSaoType, iYCbCr
+ */
+Void TComSampleAdaptiveOffset::processSaoCuOrg(Int iAddr, Int iSaoType, Int iYCbCr)
+{
+  Int x,y;
+  TComDataCU *pTmpCu = m_pcPic->getCU(iAddr);
+  Pel* pRec;
+  Int  iStride;
+  Int  iLcuWidth  = m_uiMaxCUWidth;
+  Int  iLcuHeight = m_uiMaxCUHeight;
+  UInt uiLPelX    = pTmpCu->getCUPelX();
+  UInt uiTPelY    = pTmpCu->getCUPelY();
+  UInt uiRPelX;
+  UInt uiBPelY;
+  Int  iSignLeft;
+  Int  iSignRight;
+  Int  iSignDown;
+  Int  iSignDown1;
+  Int  iSignDown2;
+  UInt uiEdgeType;
+  Int iPicWidthTmp;
+  Int iPicHeightTmp;
+  Int iStartX;
+  Int iStartY;
+  Int iEndX;
+  Int iEndY;
+  Int iIsChroma = (iYCbCr!=0)? 1:0;
+  Int iShift;
+  Int iCuHeightTmp;
+  Pel *pTmpLSwap;
+  Pel *pTmpL;
+  Pel *pTmpU;
+
+  iPicWidthTmp  = m_iPicWidth  >> iIsChroma;
+  iPicHeightTmp = m_iPicHeight >> iIsChroma;
+  iLcuWidth     = iLcuWidth    >> iIsChroma;
+  iLcuHeight    = iLcuHeight   >> iIsChroma;
+  uiLPelX       = uiLPelX      >> iIsChroma;
+  uiTPelY       = uiTPelY      >> iIsChroma;
+  uiRPelX       = uiLPelX + iLcuWidth  ;
+  uiBPelY       = uiTPelY + iLcuHeight ;
+  uiRPelX       = uiRPelX > iPicWidthTmp  ? iPicWidthTmp  : uiRPelX;
+  uiBPelY       = uiBPelY > iPicHeightTmp ? iPicHeightTmp : uiBPelY;
+  iLcuWidth     = uiRPelX - uiLPelX;
+  iLcuHeight    = uiBPelY - uiTPelY;
+
+  if(pTmpCu->getPic()==0)
+  {
+    return;
+  }
+  if (iYCbCr == 0)
+  {
+    pRec       = m_pcPic->getPicYuvRec()->getLumaAddr(iAddr);
+    iStride    = m_pcPic->getStride();
+  } 
+  else if (iYCbCr == 1)
+  {
+    pRec       = m_pcPic->getPicYuvRec()->getCbAddr(iAddr);
+    iStride    = m_pcPic->getCStride();
+  }
+  else 
+  {
+    pRec       = m_pcPic->getPicYuvRec()->getCrAddr(iAddr);
+    iStride    = m_pcPic->getCStride();
+  }
+
+//   if (iSaoType!=SAO_BO_0 || iSaoType!=SAO_BO_1)
+  {
+    iCuHeightTmp = (m_uiMaxCUHeight >> iIsChroma);
+    iShift = (m_uiMaxCUWidth>> iIsChroma)-1;
+    for (Int i=0;i<iCuHeightTmp+1;i++)
+    {
+      m_pTmpL2[i] = pRec[iShift];
+      pRec += iStride;
+    }
+    pRec -= (iStride*(iCuHeightTmp+1));
+
+    pTmpL = m_pTmpL1; 
+    pTmpU = &(m_pTmpU1[uiLPelX]); 
+  }
+
+  switch (iSaoType)
+  {
+  case SAO_EO_0: // dir: -
+    {
+      iStartX = (uiLPelX == 0) ? 1 : 0;
+      iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth-1 : iLcuWidth;
+      for (y=0; y<iLcuHeight; y++)
+      {
+        iSignLeft = xSign(pRec[iStartX] - pTmpL[y]);
+        for (x=iStartX; x< iEndX; x++)
+        {
+          iSignRight =  xSign(pRec[x] - pRec[x+1]); 
+          uiEdgeType =  iSignRight + iSignLeft + 2;
+          iSignLeft  = -iSignRight;
+
+          pRec[x] = m_pClipTable[pRec[x] + m_iOffsetEo[uiEdgeType]];
+        }
+        pRec += iStride;
+      }
+      break;
+    }
+  case SAO_EO_1: // dir: |
+    {
+      iStartY = (uiTPelY == 0) ? 1 : 0;
+      iEndY   = (uiBPelY == iPicHeightTmp) ? iLcuHeight-1 : iLcuHeight;
+      if (uiTPelY == 0)
+      {
+        pRec += iStride;
+      }
+      for (x=0; x< iLcuWidth; x++)
+      {
+        m_iUpBuff1[x] = xSign(pRec[x] - pTmpU[x]);
+      }
+      for (y=iStartY; y<iEndY; y++)
+      {
+        for (x=0; x<iLcuWidth; x++)
+        {
+          iSignDown  = xSign(pRec[x] - pRec[x+iStride]); 
+          uiEdgeType = iSignDown + m_iUpBuff1[x] + 2;
+          m_iUpBuff1[x]= -iSignDown;
+
+          pRec[x] = m_pClipTable[pRec[x] + m_iOffsetEo[uiEdgeType]];
+        }
+        pRec += iStride;
+      }
+      break;
+    }
+  case SAO_EO_2: // dir: 135
+    {
+      iStartX = (uiLPelX == 0)            ? 1 : 0;
+      iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth-1 : iLcuWidth;
+
+      iStartY = (uiTPelY == 0) ?             1 : 0;
+      iEndY   = (uiBPelY == iPicHeightTmp) ? iLcuHeight-1 : iLcuHeight;
+
+      if (uiTPelY == 0)
+      {
+        pRec += iStride;
+      }
+
+      for (x=iStartX; x<iEndX; x++)
+      {
+        m_iUpBuff1[x] = xSign(pRec[x] - pTmpU[x-1]);
+      }
+      for (y=iStartY; y<iEndY; y++)
+      {
+        iSignDown2 = xSign(pRec[iStride+iStartX] - pTmpL[y]);
+        for (x=iStartX; x<iEndX; x++)
+        {
+          iSignDown1      =  xSign(pRec[x] - pRec[x+iStride+1]) ;
+          uiEdgeType      =  iSignDown1 + m_iUpBuff1[x] + 2;
+          m_iUpBufft[x+1] = -iSignDown1; 
+          pRec[x] = m_pClipTable[pRec[x] + m_iOffsetEo[uiEdgeType]];
+        }
+        m_iUpBufft[iStartX] = iSignDown2;
+
+        ipSwap     = m_iUpBuff1;
+        m_iUpBuff1 = m_iUpBufft;
+        m_iUpBufft = ipSwap;
+
+        pRec += iStride;
+      }
+      break;
+    } 
+  case SAO_EO_3: // dir: 45
+    {
+      iStartX = (uiLPelX == 0) ? 1 : 0;
+      iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth-1 : iLcuWidth;
+
+      iStartY = (uiTPelY == 0) ? 1 : 0;
+      iEndY   = (uiBPelY == iPicHeightTmp) ? iLcuHeight-1 : iLcuHeight;
+
+      if (iStartY == 1)
+      {
+        pRec += iStride;
+      }
+
+      for (x=iStartX-1; x<iEndX; x++)
+      {
+        m_iUpBuff1[x] = xSign(pRec[x] - pTmpU[x+1]);
+      }
+      for (y=iStartY; y<iEndY; y++)
+      {
+        x=iStartX;
+        iSignDown1      =  xSign(pRec[x] - pTmpL[y+1]) ;
+        uiEdgeType      =  iSignDown1 + m_iUpBuff1[x] + 2;
+        m_iUpBuff1[x-1] = -iSignDown1; 
+        pRec[x] = m_pClipTable[pRec[x] + m_iOffsetEo[uiEdgeType]];
+        for (x=iStartX+1; x<iEndX; x++)
+        {
+          iSignDown1      =  xSign(pRec[x] - pRec[x+iStride-1]) ;
+          uiEdgeType      =  iSignDown1 + m_iUpBuff1[x] + 2;
+          m_iUpBuff1[x-1] = -iSignDown1; 
+          pRec[x] = m_pClipTable[pRec[x] + m_iOffsetEo[uiEdgeType]];
+        }
+        m_iUpBuff1[iEndX-1] = xSign(pRec[iEndX-1 + iStride] - pRec[iEndX]);
+
+        pRec += iStride;
+      } 
+      break;
+    }   
+  case SAO_BO:
+    {
+      for (y=0; y<iLcuHeight; y++)
+      {
+        for (x=0; x<iLcuWidth; x++)
+        {
+          pRec[x] = m_iOffsetBo[pRec[x]];
+        }
+        pRec += iStride;
+      }
+      break;
+    }
+  default: break;
+  }
+//   if (iSaoType!=SAO_BO_0 || iSaoType!=SAO_BO_1)
+  {
+    pTmpLSwap = m_pTmpL1;
+    m_pTmpL1  = m_pTmpL2;
+    m_pTmpL2  = pTmpLSwap;
+  }
+}
+/** Sample adaptive offset process
+ * \param pcPic, pcSaoParam  
+ */
+Void TComSampleAdaptiveOffset::SAOProcess(TComPic* pcPic, SAOParam* pcSaoParam)
+{
+#if SAO_LUM_CHROMA_ONOFF_FLAGS && SAO_TYPE_SHARING
+  if (pcSaoParam->bSaoFlag[0] || pcSaoParam->bSaoFlag[1])
+#elif SAO_LUM_CHROMA_ONOFF_FLAGS
+  if (pcSaoParam->bSaoFlag[0] || pcSaoParam->bSaoFlag[1] || pcSaoParam->bSaoFlag[2])
+#else
+  if (pcSaoParam->bSaoFlag[0])
+#endif
+  {
+#if FULL_NBIT
+    m_uiSaoBitIncrease = g_uiBitDepth + (g_uiBitDepth-8) - min((Int)(g_uiBitDepth + (g_uiBitDepth-8)), 10);
+#else
+    m_uiSaoBitIncrease = g_uiBitDepth + g_uiBitIncrement - min((Int)(g_uiBitDepth + g_uiBitIncrement), 10);
+#endif
+
+    if(m_bUseNIF)
+    {
+      m_pcPic->getPicYuvRec()->copyToPic(m_pcYuvTmp);
+    }
+    if (m_saoLcuBasedOptimization)
+    {
+      pcSaoParam->oneUnitFlag[0] = 0;  
+      pcSaoParam->oneUnitFlag[1] = 0;  
+      pcSaoParam->oneUnitFlag[2] = 0;  
+    }
+    Int iY  = 0;
+#if SAO_LUM_CHROMA_ONOFF_FLAGS
+    if (pcSaoParam->bSaoFlag[0])
+#endif
+    {
+      processSaoUnitAll( pcSaoParam->saoLcuParam[iY], pcSaoParam->oneUnitFlag[iY], iY);
+    }
+#if SAO_TYPE_SHARING
+    if(pcSaoParam->bSaoFlag[1])
+    {
+       processSaoUnitAll( pcSaoParam->saoLcuParam[1], pcSaoParam->oneUnitFlag[1], 1);//Cb
+       processSaoUnitAll( pcSaoParam->saoLcuParam[2], pcSaoParam->oneUnitFlag[2], 2);//Cr
+    }
+#else
+    Int iCb = 1;
+    Int iCr = 2;
+    if (pcSaoParam->bSaoFlag[iCb])
+    {
+      processSaoUnitAll( pcSaoParam->saoLcuParam[iCb], pcSaoParam->oneUnitFlag[iCb], iCb);
+    }
+    if (pcSaoParam->bSaoFlag[iCr])
+    {
+      processSaoUnitAll( pcSaoParam->saoLcuParam[iCr], pcSaoParam->oneUnitFlag[iCr], iCr);
+    }
+#endif
+    m_pcPic = NULL;
+  }
+}
+
+Pel* TComSampleAdaptiveOffset::getPicYuvAddr(TComPicYuv* pcPicYuv, Int iYCbCr, Int iAddr)
+{
+  switch (iYCbCr)
+  {
+  case 0:
+    return pcPicYuv->getLumaAddr(iAddr);
+    break;
+  case 1:
+    return pcPicYuv->getCbAddr(iAddr);
+    break;
+  case 2:
+    return pcPicYuv->getCrAddr(iAddr);
+    break;
+  default:
+    return NULL;
+    break;
+  }
+}
+/** Process SAO all units 
+ * \param saoLcuParam SAO LCU parameters
+ * \param oneUnitFlag one unit flag
+ * \param yCbCr color componet index
+ */
+Void TComSampleAdaptiveOffset::processSaoUnitAll(SaoLcuParam* saoLcuParam, Bool oneUnitFlag, Int yCbCr)
+{
+  Pel *pRec;
+  Int picWidthTmp;
+
+  if (yCbCr == 0)
+  {
+    pRec        = m_pcPic->getPicYuvRec()->getLumaAddr();
+    picWidthTmp = m_iPicWidth;
+  } 
+  else if (yCbCr == 1)
+  {
+    pRec        = m_pcPic->getPicYuvRec()->getCbAddr();
+    picWidthTmp = m_iPicWidth>>1;
+  }
+  else 
+  {
+    pRec        = m_pcPic->getPicYuvRec()->getCrAddr();
+    picWidthTmp = m_iPicWidth>>1;
+  }
+
+  memcpy(m_pTmpU1, pRec, sizeof(Pel)*picWidthTmp);
+
+  int  i;
+  UInt edgeType;
+  Pel* ppLumaTable = NULL;
+  Int  typeIdx;
+
+  Int offset[LUMA_GROUP_NUM+1];
+  Int idxX;
+  Int idxY;
+  Int addr;
+  Int frameWidthInCU = m_pcPic->getFrameWidthInCU();
+  Int frameHeightInCU = m_pcPic->getFrameHeightInCU();
+  Int stride;
+  Pel *tmpUSwap;
+  Int isChroma = (yCbCr == 0) ? 0:1;
+  Bool mergeLeftFlag;
+
+  offset[0] = 0;
+  for (idxY = 0; idxY< frameHeightInCU; idxY++)
+  { 
+    addr = idxY * frameWidthInCU;
+    if (yCbCr == 0)
+    {
+      pRec  = m_pcPic->getPicYuvRec()->getLumaAddr(addr);
+      stride = m_pcPic->getStride();
+      picWidthTmp = m_iPicWidth;
+    }
+    else if (yCbCr == 1)
+    {
+      pRec  = m_pcPic->getPicYuvRec()->getCbAddr(addr);
+      stride = m_pcPic->getCStride();
+      picWidthTmp = m_iPicWidth>>1;
+    }
+    else
+    {
+      pRec  = m_pcPic->getPicYuvRec()->getCrAddr(addr);
+      stride = m_pcPic->getCStride();
+      picWidthTmp = m_iPicWidth>>1;
+    }
+
+    //     pRec += iStride*(m_uiMaxCUHeight-1);
+    for (i=0;i<(m_uiMaxCUHeight>>isChroma)+1;i++)
+    {
+      m_pTmpL1[i] = pRec[0];
+      pRec+=stride;
+    }
+    pRec-=(stride<<1);
+
+    memcpy(m_pTmpU2, pRec, sizeof(Pel)*picWidthTmp);
+
+    for (idxX = 0; idxX < frameWidthInCU; idxX++)
+    {
+      addr = idxY * frameWidthInCU + idxX;
+
+      if (oneUnitFlag)
+      {
+        typeIdx = saoLcuParam[0].typeIdx;
+        mergeLeftFlag = (addr == 0)? 0:1;
+      }
+      else
+      {
+        typeIdx = saoLcuParam[addr].typeIdx;
+        mergeLeftFlag = saoLcuParam[addr].mergeLeftFlag;
+      }
+      if (typeIdx>=0)
+      {
+        if (!mergeLeftFlag)
+        {
+
+          if (typeIdx == SAO_BO)
+          {
+            for (i=0; i<SAO_MAX_BO_CLASSES+1;i++)
+            {
+              offset[i] = 0;
+            }
+            for (i=0; i<saoLcuParam[addr].length; i++)
+            {
+#if SAO_TYPE_CODING
+              offset[ (saoLcuParam[addr].subTypeIdx +i)%SAO_MAX_BO_CLASSES  +1] = saoLcuParam[addr].offset[i] << m_uiSaoBitIncrease;
+#else
+              offset[ (saoLcuParam[addr].bandPosition +i)%SAO_MAX_BO_CLASSES  +1] = saoLcuParam[addr].offset[i] << m_uiSaoBitIncrease;
+#endif
+            }
+
+            ppLumaTable = m_lumaTableBo;
+
+#if FULL_NBIT
+            for (i=0;i<(1<<(g_uiBitDepth));i++)
+#else
+            for (i=0;i<(1<<(g_uiBitIncrement+8));i++)
+#endif
+            {
+              m_iOffsetBo[i] = m_pClipTable[i + offset[ppLumaTable[i]]];
+            }
+
+          }
+          if (typeIdx == SAO_EO_0 || typeIdx == SAO_EO_1 || typeIdx == SAO_EO_2 || typeIdx == SAO_EO_3)
+          {
+            for (i=0;i<saoLcuParam[addr].length;i++)
+            {
+              offset[i+1] = saoLcuParam[addr].offset[i] << m_uiSaoBitIncrease;
+            }
+            for (edgeType=0;edgeType<6;edgeType++)
+            {
+              m_iOffsetEo[edgeType]= offset[m_auiEoTable[edgeType]];
+            }
+          }
+        }
+        processSaoCu(addr, typeIdx, yCbCr);
+      }
+      else
+      {
+        if (idxX != (frameWidthInCU-1))
+        {
+          if (yCbCr == 0)
+          {
+            pRec  = m_pcPic->getPicYuvRec()->getLumaAddr(addr);
+            stride = m_pcPic->getStride();
+          }
+          else if (yCbCr == 1)
+          {
+            pRec  = m_pcPic->getPicYuvRec()->getCbAddr(addr);
+            stride = m_pcPic->getCStride();
+          }
+          else
+          {
+            pRec  = m_pcPic->getPicYuvRec()->getCrAddr(addr);
+            stride = m_pcPic->getCStride();
+          }
+          Int widthShift = m_uiMaxCUWidth>>isChroma;
+          for (i=0;i<(m_uiMaxCUHeight>>isChroma)+1;i++)
+          {
+            m_pTmpL1[i] = pRec[widthShift-1];
+            pRec+=stride;
+          }
+        }
+      }
+    }
+    tmpUSwap = m_pTmpU1;
+    m_pTmpU1 = m_pTmpU2;
+    m_pTmpU2 = tmpUSwap;
+  }
+
+}
+/** Reset SAO LCU part 
+ * \param saoLcuParam
+ */
+Void TComSampleAdaptiveOffset::resetLcuPart(SaoLcuParam* saoLcuParam)
+{
+  Int i,j;
+  for (i=0;i<m_iNumCuInWidth*m_iNumCuInHeight;i++)
+  {
+    saoLcuParam[i].mergeUpFlag     =  1;
+    saoLcuParam[i].mergeLeftFlag =  0;
+    saoLcuParam[i].partIdx   =  0;
+    saoLcuParam[i].typeIdx      = -1;
+    for (j=0;j<MAX_NUM_SAO_OFFSETS;j++)
+    {
+      saoLcuParam[i].offset[j] = 0;
+    }
+#if SAO_TYPE_CODING
+    saoLcuParam[i].subTypeIdx = 0;
+#else
+    saoLcuParam[i].bandPosition = 0;
+#endif
+  }
+}
+
+/** convert QP part to SAO unit 
+* \param saoParam SAO parameter 
+* \param partIdx SAO part index
+* \param yCbCr color component index
+ */
+Void TComSampleAdaptiveOffset::convertQT2SaoUnit(SAOParam *saoParam, UInt partIdx, Int yCbCr)
+{
+
+  SAOQTPart*  saoPart= &(saoParam->psSaoPart[yCbCr][partIdx]);
+  if (!saoPart->bSplit)
+  {
+    convertOnePart2SaoUnit(saoParam, partIdx, yCbCr);
+    return;
+  }
+
+  if (saoPart->PartLevel < m_uiMaxSplitLevel)
+  {
+    convertQT2SaoUnit(saoParam, saoPart->DownPartsIdx[0], yCbCr);
+    convertQT2SaoUnit(saoParam, saoPart->DownPartsIdx[1], yCbCr);
+    convertQT2SaoUnit(saoParam, saoPart->DownPartsIdx[2], yCbCr);
+    convertQT2SaoUnit(saoParam, saoPart->DownPartsIdx[3], yCbCr);
+  }
+}
+/** convert one SAO part to SAO unit 
+* \param saoParam SAO parameter 
+* \param partIdx SAO part index
+* \param yCbCr color component index
+ */
+Void TComSampleAdaptiveOffset::convertOnePart2SaoUnit(SAOParam *saoParam, UInt partIdx, Int yCbCr)
+{
+  Int j;
+  Int idxX;
+  Int idxY;
+  Int addr;
+  Int frameWidthInCU = m_pcPic->getFrameWidthInCU();
+  SAOQTPart* saoQTPart = saoParam->psSaoPart[yCbCr];
+  SaoLcuParam* saoLcuParam = saoParam->saoLcuParam[yCbCr];
+
+  for (idxY = saoQTPart[partIdx].StartCUY; idxY<= saoQTPart[partIdx].EndCUY; idxY++)
+  {
+    for (idxX = saoQTPart[partIdx].StartCUX; idxX<= saoQTPart[partIdx].EndCUX; idxX++)
+    {
+      addr = idxY * frameWidthInCU + idxX;
+      saoLcuParam[addr].partIdxTmp = (Int)partIdx; 
+      saoLcuParam[addr].typeIdx    = saoQTPart[partIdx].iBestType;
+#if SAO_TYPE_CODING
+      saoLcuParam[addr].subTypeIdx = saoQTPart[partIdx].subTypeIdx;
+#else
+      saoLcuParam[addr].bandPosition = saoQTPart[partIdx].bandPosition;
+#endif
+      if (saoLcuParam[addr].typeIdx!=-1)
+      {
+        saoLcuParam[addr].length    = saoQTPart[partIdx].iLength;
+        for (j=0;j<MAX_NUM_SAO_OFFSETS;j++)
+        {
+          saoLcuParam[addr].offset[j] = saoQTPart[partIdx].iOffset[j];
+        }
+      }
+      else
+      {
+        saoLcuParam[addr].length    = 0;
+#if SAO_TYPE_CODING
+        saoLcuParam[addr].subTypeIdx = saoQTPart[partIdx].subTypeIdx;
+#else
+        saoLcuParam[addr].bandPosition = saoQTPart[partIdx].bandPosition;
+#endif
+        for (j=0;j<MAX_NUM_SAO_OFFSETS;j++)
+        {
+          saoLcuParam[addr].offset[j] = 0;
+        }
+      }
+    }
+  }
+}
+
+Void TComSampleAdaptiveOffset::resetSaoUnit(SaoLcuParam* saoUnit)
+{
+  saoUnit->partIdx       = 0;
+  saoUnit->partIdxTmp    = 0;
+  saoUnit->mergeLeftFlag = 0;
+  saoUnit->mergeUpFlag   = 0;
+  saoUnit->typeIdx       = -1;
+  saoUnit->length        = 0;
+#if SAO_TYPE_CODING
+  saoUnit->subTypeIdx    = 0;
+#else
+  saoUnit->bandPosition  = 0;
+#endif
+
+  for (Int i=0;i<4;i++)
+  {
+    saoUnit->offset[i] = 0;
+  }
+}
+
+#if SAO_SINGLE_MERGE
+Void TComSampleAdaptiveOffset::copySaoUnit(SaoLcuParam* saoUnitDst, SaoLcuParam* saoUnitSrc )
+{
+  saoUnitDst->mergeLeftFlag = saoUnitSrc->mergeLeftFlag;
+  saoUnitDst->mergeUpFlag   = saoUnitSrc->mergeUpFlag;
+  saoUnitDst->typeIdx       = saoUnitSrc->typeIdx;
+  saoUnitDst->length        = saoUnitSrc->length;
+
+#if SAO_TYPE_CODING
+  saoUnitDst->subTypeIdx  = saoUnitSrc->subTypeIdx;
+#else
+  saoUnitDst->bandPosition  = saoUnitSrc->bandPosition;
+#endif
+  for (Int i=0;i<4;i++)
+  {
+    saoUnitDst->offset[i] = saoUnitSrc->offset[i];
+  }
+}
+#endif
+
+#if REMOVE_ALF
+/** PCM LF disable process. 
+ * \param pcPic picture (TComPic) pointer
+ * \returns Void
+ *
+ * \note Replace filtered sample values of PCM mode blocks with the transmitted and reconstructed ones.
+ */
+Void TComSampleAdaptiveOffset::PCMLFDisableProcess (TComPic* pcPic)
+{
+  xPCMRestoration(pcPic);
+}
+
+/** Picture-level PCM restoration. 
+ * \param pcPic picture (TComPic) pointer
+ * \returns Void
+ */
+Void TComSampleAdaptiveOffset::xPCMRestoration(TComPic* pcPic)
+{
+  Bool  bPCMFilter = (pcPic->getSlice(0)->getSPS()->getUsePCM() && pcPic->getSlice(0)->getSPS()->getPCMFilterDisableFlag())? true : false;
+
+  if(bPCMFilter || pcPic->getSlice(0)->getPPS()->getTransquantBypassEnableFlag())
+  {
+    for( UInt uiCUAddr = 0; uiCUAddr < pcPic->getNumCUsInFrame() ; uiCUAddr++ )
+    {
+      TComDataCU* pcCU = pcPic->getCU(uiCUAddr);
+
+      xPCMCURestoration(pcCU, 0, 0); 
+    } 
+  }
+}
+
+/** PCM CU restoration. 
+ * \param pcCU pointer to current CU
+ * \param uiAbsPartIdx part index
+ * \param uiDepth CU depth
+ * \returns Void
+ */
+Void TComSampleAdaptiveOffset::xPCMCURestoration ( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth )
+{
+  TComPic* pcPic     = pcCU->getPic();
+  UInt uiCurNumParts = pcPic->getNumPartInCU() >> (uiDepth<<1);
+  UInt uiQNumParts   = uiCurNumParts>>2;
+
+  // go to sub-CU
+  if( pcCU->getDepth(uiAbsZorderIdx) > uiDepth )
+  {
+    for ( UInt uiPartIdx = 0; uiPartIdx < 4; uiPartIdx++, uiAbsZorderIdx+=uiQNumParts )
+    {
+      UInt uiLPelX   = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsZorderIdx] ];
+      UInt uiTPelY   = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsZorderIdx] ];
+      if( ( uiLPelX < pcCU->getSlice()->getSPS()->getPicWidthInLumaSamples() ) && ( uiTPelY < pcCU->getSlice()->getSPS()->getPicHeightInLumaSamples() ) )
+        xPCMCURestoration( pcCU, uiAbsZorderIdx, uiDepth+1 );
+    }
+    return;
+  }
+
+  // restore PCM samples
+  if ((pcCU->getIPCMFlag(uiAbsZorderIdx)&& pcPic->getSlice(0)->getSPS()->getPCMFilterDisableFlag()) || pcCU->isLosslessCoded( uiAbsZorderIdx))
+  {
+    xPCMSampleRestoration (pcCU, uiAbsZorderIdx, uiDepth, TEXT_LUMA    );
+    xPCMSampleRestoration (pcCU, uiAbsZorderIdx, uiDepth, TEXT_CHROMA_U);
+    xPCMSampleRestoration (pcCU, uiAbsZorderIdx, uiDepth, TEXT_CHROMA_V);
+  }
+}
+
+/** PCM sample restoration. 
+ * \param pcCU pointer to current CU
+ * \param uiAbsPartIdx part index
+ * \param uiDepth CU depth
+ * \param ttText texture component type
+ * \returns Void
+ */
+Void TComSampleAdaptiveOffset::xPCMSampleRestoration (TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, TextType ttText)
+{
+  TComPicYuv* pcPicYuvRec = pcCU->getPic()->getPicYuvRec();
+  Pel* piSrc;
+  Pel* piPcm;
+  UInt uiStride;
+  UInt uiWidth;
+  UInt uiHeight;
+  UInt uiPcmLeftShiftBit; 
+  UInt uiX, uiY;
+  UInt uiMinCoeffSize = pcCU->getPic()->getMinCUWidth()*pcCU->getPic()->getMinCUHeight();
+  UInt uiLumaOffset   = uiMinCoeffSize*uiAbsZorderIdx;
+  UInt uiChromaOffset = uiLumaOffset>>2;
+
+  if( ttText == TEXT_LUMA )
+  {
+    piSrc = pcPicYuvRec->getLumaAddr( pcCU->getAddr(), uiAbsZorderIdx);
+    piPcm = pcCU->getPCMSampleY() + uiLumaOffset;
+    uiStride  = pcPicYuvRec->getStride();
+    uiWidth  = (g_uiMaxCUWidth >> uiDepth);
+    uiHeight = (g_uiMaxCUHeight >> uiDepth);
+    if ( pcCU->isLosslessCoded(uiAbsZorderIdx) )
+    {
+      uiPcmLeftShiftBit = 0;
+    }
+    else
+    {
+        uiPcmLeftShiftBit = g_uiBitDepth + g_uiBitIncrement - pcCU->getSlice()->getSPS()->getPCMBitDepthLuma();
+    }
+  }
+  else
+  {
+    if( ttText == TEXT_CHROMA_U )
+    {
+      piSrc = pcPicYuvRec->getCbAddr( pcCU->getAddr(), uiAbsZorderIdx );
+      piPcm = pcCU->getPCMSampleCb() + uiChromaOffset;
+    }
+    else
+    {
+      piSrc = pcPicYuvRec->getCrAddr( pcCU->getAddr(), uiAbsZorderIdx );
+      piPcm = pcCU->getPCMSampleCr() + uiChromaOffset;
+    }
+
+    uiStride = pcPicYuvRec->getCStride();
+    uiWidth  = ((g_uiMaxCUWidth >> uiDepth)/2);
+    uiHeight = ((g_uiMaxCUWidth >> uiDepth)/2);
+    if ( pcCU->isLosslessCoded(uiAbsZorderIdx) )
+    {
+      uiPcmLeftShiftBit = 0;
+    }
+    else
+    {
+      uiPcmLeftShiftBit = g_uiBitDepth + g_uiBitIncrement - pcCU->getSlice()->getSPS()->getPCMBitDepthChroma();
+    }
+  }
+
+  for( uiY = 0; uiY < uiHeight; uiY++ )
+  {
+    for( uiX = 0; uiX < uiWidth; uiX++ )
+    {
+      piSrc[uiX] = (piPcm[uiX] << uiPcmLeftShiftBit);
+    }
+    piPcm += uiWidth;
+    piSrc += uiStride;
+  }
+}
+#endif
+
+//! \}
Index: /trunk/source/Lib/TLibCommon/TComSampleAdaptiveOffset.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComSampleAdaptiveOffset.h	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComSampleAdaptiveOffset.h	(revision 2)
@@ -0,0 +1,163 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComSampleAdaptiveOffset.h
+    \brief    sample adaptive offset class (header)
+*/
+
+#ifndef __TCOMSAMPLEADAPTIVEOFFSET__
+#define __TCOMSAMPLEADAPTIVEOFFSET__
+
+#include "CommonDef.h"
+#include "TComPic.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+#define SAO_MAX_DEPTH                 4
+#define SAO_BO_BITS                   5
+#define LUMA_GROUP_NUM                (1<<SAO_BO_BITS)
+#define MAX_NUM_SAO_OFFSETS           4
+#define MAX_NUM_SAO_CLASS             33
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// Sample Adaptive Offset class
+class TComSampleAdaptiveOffset
+{
+protected:
+  TComPic*          m_pcPic;
+
+  static const UInt m_uiMaxDepth;
+  static const Int m_aiNumCulPartsLevel[5];
+  static const UInt m_auiEoTable[9];
+  Int *m_iOffsetBo;
+  Int m_iOffsetEo[LUMA_GROUP_NUM];
+
+  Int  m_iPicWidth;
+  Int  m_iPicHeight;
+  UInt m_uiMaxSplitLevel;
+  UInt m_uiMaxCUWidth;
+  UInt m_uiMaxCUHeight;
+  Int  m_iNumCuInWidth;
+  Int  m_iNumCuInHeight;
+  Int  m_iNumTotalParts;
+  static const Int m_iNumClass[MAX_NUM_SAO_TYPE];
+  SliceType  m_eSliceType;
+  Int        m_iPicNalReferenceIdc;
+
+  UInt m_uiSaoBitIncrease;
+  UInt m_uiQP;
+
+  Pel   *m_pClipTable;
+  Pel   *m_pClipTableBase;
+  Pel   *m_lumaTableBo;
+  Int   *m_iUpBuff1;
+  Int   *m_iUpBuff2;
+  Int   *m_iUpBufft;
+  Int   *ipSwap;
+  Bool  m_bUseNIF;       //!< true for performing non-cross slice boundary ALF
+  UInt  m_uiNumSlicesInPic;      //!< number of slices in picture
+  Int   m_iSGDepth;              //!< slice granularity depth
+  TComPicYuv* m_pcYuvTmp;    //!< temporary picture buffer pointer when non-across slice/tile boundary SAO is enabled
+
+  Pel* m_pTmpU1;
+  Pel* m_pTmpU2;
+  Pel* m_pTmpL1;
+  Pel* m_pTmpL2;
+  Int* m_iLcuPartIdx;
+  Int     m_maxNumOffsetsPerPic;
+#if SAO_LCU_BOUNDARY
+  Bool    m_saoLcuBoundary;
+#endif
+  Bool    m_saoLcuBasedOptimization;
+
+#if REMOVE_ALF
+  Void xPCMRestoration        (TComPic* pcPic);
+  Void xPCMCURestoration      (TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth);
+  Void xPCMSampleRestoration  (TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, TextType ttText);
+#endif
+public:
+  TComSampleAdaptiveOffset         ();
+  virtual ~TComSampleAdaptiveOffset();
+
+  Void create( UInt uiSourceWidth, UInt uiSourceHeight, UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxCUDepth );
+  Void destroy ();
+
+  Int  convertLevelRowCol2Idx(int level, int row, int col);
+
+  Void initSAOParam   (SAOParam *pcSaoParam, Int iPartLevel, Int iPartRow, Int iPartCol, Int iParentPartIdx, Int StartCUX, Int EndCUX, Int StartCUY, Int EndCUY, Int iYCbCr);
+  Void allocSaoParam  (SAOParam* pcSaoParam);
+  Void resetSAOParam  (SAOParam *pcSaoParam);
+#if REMOVE_APS
+  static Void freeSaoParam   (SAOParam *pcSaoParam);
+#else
+  Void freeSaoParam   (SAOParam *pcSaoParam);
+#endif
+  
+  Void SAOProcess(TComPic* pcPic, SAOParam* pcSaoParam);
+  Void processSaoCu(Int iAddr, Int iSaoType, Int iYCbCr);
+  Pel* getPicYuvAddr(TComPicYuv* pcPicYuv, Int iYCbCr,Int iAddr = 0);
+
+  Void processSaoCuOrg(Int iAddr, Int iPartIdx, Int iYCbCr);  //!< LCU-basd SAO process without slice granularity 
+  Void createPicSaoInfo(TComPic* pcPic, Int numSlicesInPic = 1);
+  Void destroyPicSaoInfo();
+  Void processSaoBlock(Pel* pDec, Pel* pRest, Int stride, Int iSaoType, UInt xPos, UInt yPos, UInt width, UInt height, Bool* pbBorderAvail);
+
+  Void resetLcuPart(SaoLcuParam* saoLcuParam);
+  Void convertQT2SaoUnit(SAOParam* saoParam, UInt partIdx, Int yCbCr);
+  Void convertOnePart2SaoUnit(SAOParam *saoParam, UInt partIdx, Int yCbCr);
+  Void processSaoUnitAll(SaoLcuParam* saoLcuParam, Bool oneUnitFlag, Int yCbCr);
+#if SAO_LCU_BOUNDARY
+  Void setSaoLcuBoundary (Bool bVal)  {m_saoLcuBoundary = bVal;}
+  Bool getSaoLcuBoundary ()           {return m_saoLcuBoundary;}
+#endif
+  Void setSaoLcuBasedOptimization (Bool bVal)  {m_saoLcuBasedOptimization = bVal;}
+  Bool getSaoLcuBasedOptimization ()           {return m_saoLcuBasedOptimization;}
+  Void resetSaoUnit(SaoLcuParam* saoUnit);
+#if SAO_SINGLE_MERGE
+  Void copySaoUnit(SaoLcuParam* saoUnitDst, SaoLcuParam* saoUnitSrc );
+#endif
+#if REMOVE_ALF
+  Void PCMLFDisableProcess    ( TComPic* pcPic);                        ///< interface function for ALF process 
+#endif
+};
+
+//! \}
+#endif
+
Index: /trunk/source/Lib/TLibCommon/TComSlice.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComSlice.cpp	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComSlice.cpp	(revision 2)
@@ -0,0 +1,2134 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComSlice.cpp
+    \brief    slice header and SPS class
+*/
+
+#include "CommonDef.h"
+#include "TComSlice.h"
+#include "TComPic.h"
+#include "TLibEncoder/TEncSbac.h"
+#include "TLibDecoder/TDecSbac.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+TComSlice::TComSlice()
+: m_iPPSId                        ( -1 )
+, m_iPOC                          ( 0 )
+, m_iLastIDR                      ( 0 )
+, m_eNalUnitType                  ( NAL_UNIT_CODED_SLICE_IDR )
+, m_eSliceType                    ( I_SLICE )
+, m_iSliceQp                      ( 0 )
+#if SLICEHEADER_SYNTAX_FIX
+, m_dependentSliceFlag            ( false )
+#endif
+#if ADAPTIVE_QP_SELECTION
+, m_iSliceQpBase                  ( 0 )
+#endif
+, m_deblockingFilterDisable        ( false )
+, m_deblockingFilterOverrideFlag   ( false )
+, m_deblockingFilterBetaOffsetDiv2 ( 0 )
+, m_deblockingFilterTcOffsetDiv2   ( 0 )
+, m_bRefPicListModificationFlagLC ( false )
+, m_bRefPicListCombinationFlag    ( false )
+, m_bCheckLDC                     ( false )
+, m_iSliceQpDelta                 ( 0 )
+#if CHROMA_QP_EXTENSION
+, m_iSliceQpDeltaCb               ( 0 )
+, m_iSliceQpDeltaCr               ( 0 )
+#endif
+, m_iDepth                        ( 0 )
+, m_bRefenced                     ( false )
+, m_pcSPS                         ( NULL )
+, m_pcPPS                         ( NULL )
+, m_pcPic                         ( NULL )
+, m_colFromL0Flag                 ( 1 )
+, m_colRefIdx                     ( 0 )
+#if ALF_CHROMA_LAMBDA || SAO_CHROMA_LAMBDA
+, m_dLambdaLuma( 0.0 )
+, m_dLambdaChroma( 0.0 )
+#else
+, m_dLambda                       ( 0.0 )
+#endif
+, m_bNoBackPredFlag               ( false )
+, m_uiTLayer                      ( 0 )
+#if SVC_EXTENSION
+, m_layerId                     ( 0 )
+, m_pcBaseColPic                  ( NULL )
+#endif
+, m_bTLayerSwitchingFlag          ( false )
+, m_uiSliceMode                   ( 0 )
+, m_uiSliceArgument               ( 0 )
+, m_uiSliceCurStartCUAddr         ( 0 )
+, m_uiSliceCurEndCUAddr           ( 0 )
+, m_uiSliceIdx                    ( 0 )
+, m_uiDependentSliceMode            ( 0 )
+, m_uiDependentSliceArgument        ( 0 )
+, m_uiDependentSliceCurStartCUAddr  ( 0 )
+, m_uiDependentSliceCurEndCUAddr    ( 0 )
+, m_bNextSlice                    ( false )
+, m_bNextDependentSlice             ( false )
+, m_uiSliceBits                   ( 0 )
+, m_uiDependentSliceCounter         ( 0 )
+, m_bFinalized                    ( false )
+, m_uiTileOffstForMultES          ( 0 )
+, m_puiSubstreamSizes             ( NULL )
+, m_cabacInitFlag                 ( false )
+, m_bLMvdL1Zero                   ( false )
+, m_numEntryPointOffsets          ( 0 )
+#if TEMPORAL_LAYER_NON_REFERENCE
+, m_temporalLayerNonReferenceFlag ( false )
+#endif
+#if !REMOVE_NAL_REF_FLAG
+, m_nalRefFlag                    ( 0 )
+#endif
+, m_enableTMVPFlag                ( true )
+{
+  m_aiNumRefIdx[0] = m_aiNumRefIdx[1] = m_aiNumRefIdx[2] = 0;
+  
+  initEqualRef();
+  
+  for(Int iNumCount = 0; iNumCount < MAX_NUM_REF_LC; iNumCount++)
+  {
+    m_iRefIdxOfLC[REF_PIC_LIST_0][iNumCount]=-1;
+    m_iRefIdxOfLC[REF_PIC_LIST_1][iNumCount]=-1;
+    m_eListIdFromIdxOfLC[iNumCount]=0;
+    m_iRefIdxFromIdxOfLC[iNumCount]=0;
+    m_iRefIdxOfL0FromRefIdxOfL1[iNumCount] = -1;
+    m_iRefIdxOfL1FromRefIdxOfL0[iNumCount] = -1;
+  }    
+  for(Int iNumCount = 0; iNumCount < MAX_NUM_REF; iNumCount++)
+  {
+    m_apcRefPicList [0][iNumCount] = NULL;
+    m_apcRefPicList [1][iNumCount] = NULL;
+    m_aiRefPOCList  [0][iNumCount] = 0;
+    m_aiRefPOCList  [1][iNumCount] = 0;
+  }
+  m_bCombineWithReferenceFlag = 0;
+  resetWpScaling(m_weightPredTable);
+  initWpAcDcParam();
+  m_saoEnabledFlag = false;
+#if !REMOVE_ALF
+  m_alfEnabledFlag[0] = m_alfEnabledFlag[1] = m_alfEnabledFlag[2] = false;
+#endif
+}
+
+TComSlice::~TComSlice()
+{
+  delete[] m_puiSubstreamSizes;
+  m_puiSubstreamSizes = NULL;
+}
+
+
+Void TComSlice::initSlice()
+{
+  m_aiNumRefIdx[0]      = 0;
+  m_aiNumRefIdx[1]      = 0;
+  
+  m_colFromL0Flag = 1;
+  
+  m_colRefIdx = 0;
+  initEqualRef();
+  m_bNoBackPredFlag = false;
+  m_bRefPicListCombinationFlag = false;
+  m_bRefPicListModificationFlagLC = false;
+  m_bCheckLDC = false;
+#if CHROMA_QP_EXTENSION
+  m_iSliceQpDeltaCb = 0;
+  m_iSliceQpDeltaCr = 0;
+#endif
+
+  m_aiNumRefIdx[REF_PIC_LIST_C]      = 0;
+
+  m_maxNumMergeCand = MRG_MAX_NUM_CANDS;
+
+  m_bFinalized=false;
+
+  m_tileByteLocation.clear();
+  m_cabacInitFlag        = false;
+  m_numEntryPointOffsets = 0;
+  m_enableTMVPFlag = true;
+}
+
+Bool TComSlice::getRapPicFlag()
+{
+  return getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR
+#if SUPPORT_FOR_RAP_N_LP
+      || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP
+      || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP
+#endif
+      || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLANT
+      || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA
+#if !NAL_UNIT_TYPES_J1003_D7
+      || getNalUnitType() == NAL_UNIT_CODED_SLICE_CRANT
+#endif
+      || getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA;
+}
+
+/**
+ - allocate table to contain substream sizes to be written to the slice header.
+ .
+ \param uiNumSubstreams Number of substreams -- the allocation will be this value - 1.
+ */
+Void  TComSlice::allocSubstreamSizes(UInt uiNumSubstreams)
+{
+  delete[] m_puiSubstreamSizes;
+  m_puiSubstreamSizes = new UInt[uiNumSubstreams > 0 ? uiNumSubstreams-1 : 0];
+}
+
+Void  TComSlice::sortPicList        (TComList<TComPic*>& rcListPic)
+{
+  TComPic*    pcPicExtract;
+  TComPic*    pcPicInsert;
+  
+  TComList<TComPic*>::iterator    iterPicExtract;
+  TComList<TComPic*>::iterator    iterPicExtract_1;
+  TComList<TComPic*>::iterator    iterPicInsert;
+  
+  for (Int i = 1; i < (Int)(rcListPic.size()); i++)
+  {
+    iterPicExtract = rcListPic.begin();
+    for (Int j = 0; j < i; j++) iterPicExtract++;
+    pcPicExtract = *(iterPicExtract);
+    pcPicExtract->setCurrSliceIdx(0);
+    
+    iterPicInsert = rcListPic.begin();
+    while (iterPicInsert != iterPicExtract)
+    {
+      pcPicInsert = *(iterPicInsert);
+      pcPicInsert->setCurrSliceIdx(0);
+      if (pcPicInsert->getPOC() >= pcPicExtract->getPOC())
+      {
+        break;
+      }
+      
+      iterPicInsert++;
+    }
+    
+    iterPicExtract_1 = iterPicExtract;    iterPicExtract_1++;
+    
+    //  swap iterPicExtract and iterPicInsert, iterPicExtract = curr. / iterPicInsert = insertion position
+    rcListPic.insert (iterPicInsert, iterPicExtract, iterPicExtract_1);
+    rcListPic.erase  (iterPicExtract);
+  }
+}
+
+TComPic* TComSlice::xGetRefPic (TComList<TComPic*>& rcListPic,
+                                UInt                uiPOC)
+{
+  TComList<TComPic*>::iterator  iterPic = rcListPic.begin();  
+  TComPic*                      pcPic = *(iterPic);
+  while ( iterPic != rcListPic.end() )
+  {
+    if(pcPic->getPOC() == uiPOC)
+    {
+      break;
+    }
+    iterPic++;
+    pcPic = *(iterPic);
+  }
+  return  pcPic;
+}
+
+
+TComPic* TComSlice::xGetLongTermRefPic (TComList<TComPic*>& rcListPic,
+                                UInt                uiPOC)
+{
+  TComList<TComPic*>::iterator  iterPic = rcListPic.begin();  
+  TComPic*                      pcPic = *(iterPic);
+  TComPic*                      pcStPic = pcPic;
+  while ( iterPic != rcListPic.end() )
+  {
+    pcPic = *(iterPic);
+    if(pcPic && (pcPic->getPOC()%(1<<getSPS()->getBitsForPOC())) == (uiPOC%(1<<getSPS()->getBitsForPOC())))
+    {
+      if(pcPic->getIsLongTerm())
+      {
+        return pcPic;
+      }
+      else
+      {
+        pcStPic = pcPic;
+      }
+      break;
+    }
+
+    iterPic++;
+  }
+  return  pcStPic;
+}
+
+Void TComSlice::setRefPOCList       ()
+{
+  for (Int iDir = 0; iDir < 2; iDir++)
+  {
+    for (Int iNumRefIdx = 0; iNumRefIdx < m_aiNumRefIdx[iDir]; iNumRefIdx++)
+    {
+      m_aiRefPOCList[iDir][iNumRefIdx] = m_apcRefPicList[iDir][iNumRefIdx]->getPOC();
+    }
+  }
+
+}
+
+Void TComSlice::generateCombinedList()
+{
+  if(m_aiNumRefIdx[REF_PIC_LIST_C] > 0)
+  {
+    m_aiNumRefIdx[REF_PIC_LIST_C]=0;
+    for(Int iNumCount = 0; iNumCount < MAX_NUM_REF_LC; iNumCount++)
+    {
+      m_iRefIdxOfLC[REF_PIC_LIST_0][iNumCount]=-1;
+      m_iRefIdxOfLC[REF_PIC_LIST_1][iNumCount]=-1;
+      m_eListIdFromIdxOfLC[iNumCount]=0;
+      m_iRefIdxFromIdxOfLC[iNumCount]=0;
+      m_iRefIdxOfL0FromRefIdxOfL1[iNumCount] = -1;
+      m_iRefIdxOfL1FromRefIdxOfL0[iNumCount] = -1;
+    }
+
+    for (Int iNumRefIdx = 0; iNumRefIdx < MAX_NUM_REF; iNumRefIdx++)
+    {
+      if(iNumRefIdx < m_aiNumRefIdx[REF_PIC_LIST_0])
+      {
+        Bool bTempRefIdxInL2 = true;
+        for ( Int iRefIdxLC = 0; iRefIdxLC < m_aiNumRefIdx[REF_PIC_LIST_C]; iRefIdxLC++ )
+        {
+          if ( m_apcRefPicList[REF_PIC_LIST_0][iNumRefIdx]->getPOC() == m_apcRefPicList[m_eListIdFromIdxOfLC[iRefIdxLC]][m_iRefIdxFromIdxOfLC[iRefIdxLC]]->getPOC() )
+          {
+            m_iRefIdxOfL1FromRefIdxOfL0[iNumRefIdx] = m_iRefIdxFromIdxOfLC[iRefIdxLC];
+            m_iRefIdxOfL0FromRefIdxOfL1[m_iRefIdxFromIdxOfLC[iRefIdxLC]] = iNumRefIdx;
+            bTempRefIdxInL2 = false;
+            break;
+          }
+        }
+
+        if(bTempRefIdxInL2 == true)
+        { 
+          m_eListIdFromIdxOfLC[m_aiNumRefIdx[REF_PIC_LIST_C]] = REF_PIC_LIST_0;
+          m_iRefIdxFromIdxOfLC[m_aiNumRefIdx[REF_PIC_LIST_C]] = iNumRefIdx;
+          m_iRefIdxOfLC[REF_PIC_LIST_0][iNumRefIdx] = m_aiNumRefIdx[REF_PIC_LIST_C]++;
+        }
+      }
+
+      if(iNumRefIdx < m_aiNumRefIdx[REF_PIC_LIST_1])
+      {
+        Bool bTempRefIdxInL2 = true;
+        for ( Int iRefIdxLC = 0; iRefIdxLC < m_aiNumRefIdx[REF_PIC_LIST_C]; iRefIdxLC++ )
+        {
+          if ( m_apcRefPicList[REF_PIC_LIST_1][iNumRefIdx]->getPOC() == m_apcRefPicList[m_eListIdFromIdxOfLC[iRefIdxLC]][m_iRefIdxFromIdxOfLC[iRefIdxLC]]->getPOC() )
+          {
+            m_iRefIdxOfL0FromRefIdxOfL1[iNumRefIdx] = m_iRefIdxFromIdxOfLC[iRefIdxLC];
+            m_iRefIdxOfL1FromRefIdxOfL0[m_iRefIdxFromIdxOfLC[iRefIdxLC]] = iNumRefIdx;
+            bTempRefIdxInL2 = false;
+            break;
+          }
+        }
+        if(bTempRefIdxInL2 == true)
+        {
+          m_eListIdFromIdxOfLC[m_aiNumRefIdx[REF_PIC_LIST_C]] = REF_PIC_LIST_1;
+          m_iRefIdxFromIdxOfLC[m_aiNumRefIdx[REF_PIC_LIST_C]] = iNumRefIdx;
+          m_iRefIdxOfLC[REF_PIC_LIST_1][iNumRefIdx] = m_aiNumRefIdx[REF_PIC_LIST_C]++;
+        }
+      }
+    }
+  }
+}
+
+Void TComSlice::setRefPicList( TComList<TComPic*>& rcListPic )
+{
+  if (m_eSliceType == I_SLICE
+#if REF_IDX_FRAMEWORK
+      || ( getSPS()->getLayerId() && 
+         (getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA) &&
+         (getNalUnitType() <= NAL_UNIT_CODED_SLICE_CRA) )
+#endif
+    )
+  {
+    ::memset( m_apcRefPicList, 0, sizeof (m_apcRefPicList));
+    ::memset( m_aiNumRefIdx,   0, sizeof ( m_aiNumRefIdx ));
+    
+    return;
+  }
+  
+  m_aiNumRefIdx[0] = getNumRefIdx(REF_PIC_LIST_0);
+  m_aiNumRefIdx[1] = getNumRefIdx(REF_PIC_LIST_1);
+
+  TComPic*  pcRefPic= NULL;
+  TComPic*  RefPicSetStCurr0[16];
+  TComPic*  RefPicSetStCurr1[16];
+  TComPic*  RefPicSetLtCurr[16];
+  UInt NumPocStCurr0 = 0;
+  UInt NumPocStCurr1 = 0;
+  UInt NumPocLtCurr = 0;
+  Int i;
+
+  for(i=0; i < m_pcRPS->getNumberOfNegativePictures(); i++)
+  {
+    if(m_pcRPS->getUsed(i))
+    {
+      pcRefPic = xGetRefPic(rcListPic, getPOC()+m_pcRPS->getDeltaPOC(i));
+      pcRefPic->setIsLongTerm(0);
+      pcRefPic->setIsUsedAsLongTerm(0);
+      pcRefPic->getPicYuvRec()->extendPicBorder();
+      RefPicSetStCurr0[NumPocStCurr0] = pcRefPic;
+      NumPocStCurr0++;
+      pcRefPic->setCheckLTMSBPresent(false);  
+    }
+  }
+  for(; i < m_pcRPS->getNumberOfNegativePictures()+m_pcRPS->getNumberOfPositivePictures(); i++)
+  {
+    if(m_pcRPS->getUsed(i))
+    {
+      pcRefPic = xGetRefPic(rcListPic, getPOC()+m_pcRPS->getDeltaPOC(i));
+      pcRefPic->setIsLongTerm(0);
+      pcRefPic->setIsUsedAsLongTerm(0);
+      pcRefPic->getPicYuvRec()->extendPicBorder();
+      RefPicSetStCurr1[NumPocStCurr1] = pcRefPic;
+      NumPocStCurr1++;
+      pcRefPic->setCheckLTMSBPresent(false);  
+    }
+  }
+  for(i = m_pcRPS->getNumberOfNegativePictures()+m_pcRPS->getNumberOfPositivePictures()+m_pcRPS->getNumberOfLongtermPictures()-1; i > m_pcRPS->getNumberOfNegativePictures()+m_pcRPS->getNumberOfPositivePictures()-1 ; i--)
+  {
+    if(m_pcRPS->getUsed(i))
+    {
+      pcRefPic = xGetLongTermRefPic(rcListPic, m_pcRPS->getPOC(i));
+      pcRefPic->setIsLongTerm(1);
+      pcRefPic->setIsUsedAsLongTerm(1);
+      pcRefPic->getPicYuvRec()->extendPicBorder();
+      RefPicSetLtCurr[NumPocLtCurr] = pcRefPic;
+      NumPocLtCurr++;
+    }
+    if(pcRefPic==NULL) 
+    {
+      pcRefPic = xGetLongTermRefPic(rcListPic, m_pcRPS->getPOC(i));
+    }
+    pcRefPic->setCheckLTMSBPresent(m_pcRPS->getCheckLTMSBPresent(i));  
+  }
+
+  // ref_pic_list_init
+  UInt cIdx = 0;
+  UInt num_ref_idx_l0_active_minus1 = m_aiNumRefIdx[0] - 1;
+  UInt num_ref_idx_l1_active_minus1 = m_aiNumRefIdx[1] - 1;
+  TComPic*  refPicListTemp0[MAX_NUM_REF+1];
+  TComPic*  refPicListTemp1[MAX_NUM_REF+1];
+  Int  numRpsCurrTempList0, numRpsCurrTempList1;
+  
+  numRpsCurrTempList0 = numRpsCurrTempList1 = NumPocStCurr0 + NumPocStCurr1 + NumPocLtCurr;
+  if (numRpsCurrTempList0 <= num_ref_idx_l0_active_minus1)
+  {
+    numRpsCurrTempList0 = num_ref_idx_l0_active_minus1 + 1;
+  }
+  if (numRpsCurrTempList1 <= num_ref_idx_l1_active_minus1)
+  {
+    numRpsCurrTempList1 = num_ref_idx_l1_active_minus1 + 1;
+  }
+
+  cIdx = 0;
+  while (cIdx < numRpsCurrTempList0)
+  {
+    for ( i=0; i<NumPocStCurr0 && cIdx<numRpsCurrTempList0; cIdx++,i++)
+    {
+      refPicListTemp0[cIdx] = RefPicSetStCurr0[ i ];
+    }
+    for ( i=0; i<NumPocStCurr1 && cIdx<numRpsCurrTempList0; cIdx++,i++)
+    {
+      refPicListTemp0[cIdx] = RefPicSetStCurr1[ i ];
+    }
+    for ( i=0; i<NumPocLtCurr && cIdx<numRpsCurrTempList0; cIdx++,i++)
+    {
+      refPicListTemp0[cIdx] = RefPicSetLtCurr[ i ];
+    }
+  }
+  cIdx = 0;
+  while (cIdx<numRpsCurrTempList1 && m_eSliceType==B_SLICE)
+  {
+    for ( i=0; i<NumPocStCurr1 && cIdx<numRpsCurrTempList1; cIdx++,i++)
+    {
+      refPicListTemp1[cIdx] = RefPicSetStCurr1[ i ];
+    }
+    for ( i=0; i<NumPocStCurr0 && cIdx<numRpsCurrTempList1; cIdx++,i++)
+    {
+      refPicListTemp1[cIdx] = RefPicSetStCurr0[ i ];
+    }
+    for ( i=0; i<NumPocLtCurr && cIdx<numRpsCurrTempList1; cIdx++,i++)
+    {
+      refPicListTemp1[cIdx] = RefPicSetLtCurr[ i ];
+    }
+  }
+
+  for (cIdx = 0; cIdx <= num_ref_idx_l0_active_minus1; cIdx ++)
+  {
+    m_apcRefPicList[0][cIdx] = m_RefPicListModification.getRefPicListModificationFlagL0() ? refPicListTemp0[ m_RefPicListModification.getRefPicSetIdxL0(cIdx) ] : refPicListTemp0[cIdx];
+  }
+  if ( m_eSliceType == P_SLICE )
+  {
+    m_aiNumRefIdx[1] = 0;
+    ::memset( m_apcRefPicList[1], 0, sizeof(m_apcRefPicList[1]));
+  }
+  else
+  {
+    for (cIdx = 0; cIdx <= num_ref_idx_l1_active_minus1; cIdx ++)
+    {
+      m_apcRefPicList[1][cIdx] = m_RefPicListModification.getRefPicListModificationFlagL1() ? refPicListTemp1[ m_RefPicListModification.getRefPicSetIdxL1(cIdx) ] : refPicListTemp1[cIdx];
+    }
+  }
+}
+
+#if REF_IDX_FRAMEWORK
+Void TComSlice::addRefPicList( TComPic **pIlpPicList, Int iRefPicNum, Int iInsertOffset )
+{
+  if(getSPS()->getLayerId() && m_eSliceType != I_SLICE)
+  {
+    //add to list 0;
+    Int iOffset;
+    m_aiNumRefIdx[REF_PIC_LIST_0] += iInsertOffset;
+    iOffset = m_aiNumRefIdx[REF_PIC_LIST_0];
+    for (Int i=0; i<iRefPicNum; i++)
+    {
+      pIlpPicList[i]->setIsLongTerm(1);  //mark ilp as long-term reference
+      pIlpPicList[i]->setIsUsedAsLongTerm(1);  //mark ilp as long-term reference
+      m_apcRefPicList[REF_PIC_LIST_0][iOffset + i] = pIlpPicList[i]; 
+      m_aiNumRefIdx[REF_PIC_LIST_0]++;
+      //m_aiNumRefIdx[REF_PIC_LIST_C]++;
+    }
+    if(m_eSliceType == B_SLICE)
+    {
+      m_aiNumRefIdx[REF_PIC_LIST_1] += iInsertOffset;
+      iOffset = m_aiNumRefIdx[REF_PIC_LIST_1];
+      for (Int i=0; i<iRefPicNum; i++)
+      {
+        pIlpPicList[i]->setIsLongTerm(1);  //mark ilp as long-term reference
+        pIlpPicList[i]->setIsUsedAsLongTerm(1);  //mark ilp as long-term reference
+        m_apcRefPicList[REF_PIC_LIST_1][iOffset + i] = pIlpPicList[i]; 
+        m_aiNumRefIdx[REF_PIC_LIST_1]++;
+        //m_aiNumRefIdx[REF_PIC_LIST_C]++;
+      }
+    }
+  }
+}
+#endif
+
+Int TComSlice::getNumRpsCurrTempList()
+{
+  Int numRpsCurrTempList = 0;
+
+  if (m_eSliceType == I_SLICE) 
+  {
+    return 0;
+  }
+  for(UInt i=0; i < m_pcRPS->getNumberOfNegativePictures()+ m_pcRPS->getNumberOfPositivePictures() + m_pcRPS->getNumberOfLongtermPictures(); i++)
+  {
+    if(m_pcRPS->getUsed(i))
+    {
+      numRpsCurrTempList++;
+    }
+  }
+  return numRpsCurrTempList;
+}
+#if SVC_EXTENSION
+Void TComSlice::setBaseColPic(  TComList<TComPic*>& rcListPic, UInt layerID )
+{  
+  if (layerID == 0)
+  {
+    m_pcBaseColPic = NULL;
+    return;
+  }        
+  setBaseColPic(xGetRefPic(rcListPic, getPOC())); 
+}
+#endif 
+
+Void TComSlice::initEqualRef()
+{
+  for (Int iDir = 0; iDir < 2; iDir++)
+  {
+    for (Int iRefIdx1 = 0; iRefIdx1 < MAX_NUM_REF; iRefIdx1++)
+    {
+      for (Int iRefIdx2 = iRefIdx1; iRefIdx2 < MAX_NUM_REF; iRefIdx2++)
+      {
+        m_abEqualRef[iDir][iRefIdx1][iRefIdx2] = m_abEqualRef[iDir][iRefIdx2][iRefIdx1] = (iRefIdx1 == iRefIdx2? true : false);
+      }
+    }
+  }
+}
+
+Void TComSlice::checkColRefIdx(UInt curSliceIdx, TComPic* pic)
+{
+  Int i;
+  TComSlice* curSlice = pic->getSlice(curSliceIdx);
+  Int currColRefPOC =  curSlice->getRefPOC( RefPicList(1-curSlice->getColFromL0Flag()), curSlice->getColRefIdx());
+  TComSlice* preSlice;
+  Int preColRefPOC;
+  for(i=curSliceIdx-1; i>=0; i--)
+  {
+    preSlice = pic->getSlice(i);
+    if(preSlice->getSliceType() != I_SLICE)
+    {
+      preColRefPOC  = preSlice->getRefPOC( RefPicList(1-preSlice->getColFromL0Flag()), preSlice->getColRefIdx());
+      if(currColRefPOC != preColRefPOC)
+      {
+        printf("Collocated_ref_idx shall always be the same for all slices of a coded picture!\n");
+        exit(EXIT_FAILURE);
+      }
+      else
+      {
+        break;
+      }
+    }
+  }
+}
+
+Void TComSlice::checkCRA(TComReferencePictureSet *pReferencePictureSet, Int& pocCRA, Bool& prevRAPisBLA, TComList<TComPic*>& rcListPic)
+{
+  for(Int i = 0; i < pReferencePictureSet->getNumberOfNegativePictures()+pReferencePictureSet->getNumberOfPositivePictures(); i++)
+  {
+    if(pocCRA < MAX_UINT && getPOC() > pocCRA)
+    {
+      assert(getPOC()+pReferencePictureSet->getDeltaPOC(i) >= pocCRA);
+    }
+  }
+  for(Int i = pReferencePictureSet->getNumberOfNegativePictures()+pReferencePictureSet->getNumberOfPositivePictures(); i < pReferencePictureSet->getNumberOfPictures(); i++)
+  {
+    if(pocCRA < MAX_UINT && getPOC() > pocCRA)
+    {
+      assert(pReferencePictureSet->getPOC(i) >= pocCRA);
+    }
+  }
+#if SUPPORT_FOR_RAP_N_LP
+  if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP ) // IDR picture found
+#else
+  if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR ) // IDR picture found
+#endif
+  {
+    prevRAPisBLA = false;
+  }
+#if NAL_UNIT_TYPES_J1003_D7
+  else if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA ) // CRA picture found
+#else
+  else if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA || getNalUnitType() == NAL_UNIT_CODED_SLICE_CRANT ) // CRA/CRANT picture found
+#endif
+  {
+    pocCRA = getPOC();
+    prevRAPisBLA = false;
+  }
+#if SUPPORT_FOR_RAP_N_LP
+  else if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA
+         || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLANT
+         || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP ) // BLA picture found
+#else
+  else if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLANT ) // BLA/BLANT picture found
+#endif
+  {
+    pocCRA = getPOC();
+    prevRAPisBLA = true;
+  }
+}
+
+/** Function for marking the reference pictures when an IDR/CRA/CRANT/BLA/BLANT is encountered.
+ * \param pocCRA POC of the CRA/CRANT/BLA/BLANT picture
+ * \param bRefreshPending flag indicating if a deferred decoding refresh is pending
+ * \param rcListPic reference to the reference picture list
+ * This function marks the reference pictures as "unused for reference" in the following conditions.
+ * If the nal_unit_type is IDR/BLA/BLANT, all pictures in the reference picture list  
+ * are marked as "unused for reference"
+ *    If the nal_unit_type is BLA/BLANT, set the pocCRA to the temporal reference of the current picture.
+ * Otherwise
+ *    If the bRefreshPending flag is true (a deferred decoding refresh is pending) and the current 
+ *    temporal reference is greater than the temporal reference of the latest CRA/CRANT/BLA/BLANT picture (pocCRA), 
+ *    mark all reference pictures except the latest CRA/CRANT/BLA/BLANT picture as "unused for reference" and set 
+ *    the bRefreshPending flag to false.
+ *    If the nal_unit_type is CRA/CRANT, set the bRefreshPending flag to true and pocCRA to the temporal 
+ *    reference of the current picture.
+ * Note that the current picture is already placed in the reference list and its marking is not changed.
+ * If the current picture has a nal_ref_idc that is not 0, it will remain marked as "used for reference".
+ */
+Void TComSlice::decodingRefreshMarking(Int& pocCRA, Bool& bRefreshPending, TComList<TComPic*>& rcListPic)
+{
+  TComPic*                 rpcPic;
+  UInt uiPOCCurr = getPOC(); 
+
+#if SUPPORT_FOR_RAP_N_LP
+  if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA
+    || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLANT
+    || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP
+    || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR
+    || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP )  // IDR or BLA picture
+#else
+  if (getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLANT)  // IDR/BLA/BLANT
+#endif
+  {
+    // mark all pictures as not used for reference
+    TComList<TComPic*>::iterator        iterPic       = rcListPic.begin();
+    while (iterPic != rcListPic.end())
+    {
+      rpcPic = *(iterPic);
+      rpcPic->setCurrSliceIdx(0);
+      if (rpcPic->getPOC() != uiPOCCurr) rpcPic->getSlice(0)->setReferenced(false);
+      iterPic++;
+    }
+#if SUPPORT_FOR_RAP_N_LP
+    if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA
+      || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLANT
+      || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP )
+#else
+    if (getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLANT)
+#endif
+    {
+      pocCRA = uiPOCCurr;
+    }
+  }
+  else // CRA or No DR
+  {
+    if (bRefreshPending==true && uiPOCCurr > pocCRA) // CRA reference marking pending 
+    {
+      TComList<TComPic*>::iterator        iterPic       = rcListPic.begin();
+      while (iterPic != rcListPic.end())
+      {
+        rpcPic = *(iterPic);
+        if (rpcPic->getPOC() != uiPOCCurr && rpcPic->getPOC() != pocCRA) rpcPic->getSlice(0)->setReferenced(false);
+        iterPic++;
+      }
+      bRefreshPending = false; 
+    }
+#if NAL_UNIT_TYPES_J1003_D7
+    if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA ) // CRA picture found
+#else
+    if (getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA || getNalUnitType() == NAL_UNIT_CODED_SLICE_CRANT) // CRA/CRANT picture found
+#endif
+    {
+      bRefreshPending = true; 
+      pocCRA = uiPOCCurr;
+    }
+  }
+}
+
+Void TComSlice::copySliceInfo(TComSlice *pSrc)
+{
+  assert( pSrc != NULL );
+
+  Int i, j, k;
+
+  m_iPOC                 = pSrc->m_iPOC;
+  m_eNalUnitType         = pSrc->m_eNalUnitType;
+  m_eSliceType           = pSrc->m_eSliceType;
+  m_iSliceQp             = pSrc->m_iSliceQp;
+#if ADAPTIVE_QP_SELECTION
+  m_iSliceQpBase         = pSrc->m_iSliceQpBase;
+#endif
+  m_deblockingFilterDisable   = pSrc->m_deblockingFilterDisable;
+  m_deblockingFilterOverrideFlag = pSrc->m_deblockingFilterOverrideFlag;
+  m_deblockingFilterBetaOffsetDiv2 = pSrc->m_deblockingFilterBetaOffsetDiv2;
+  m_deblockingFilterTcOffsetDiv2 = pSrc->m_deblockingFilterTcOffsetDiv2;
+  
+  for (i = 0; i < 3; i++)
+  {
+    m_aiNumRefIdx[i]     = pSrc->m_aiNumRefIdx[i];
+  }
+
+  for (i = 0; i < 2; i++)
+  {
+    for (j = 0; j < MAX_NUM_REF_LC; j++)
+    {
+       m_iRefIdxOfLC[i][j]  = pSrc->m_iRefIdxOfLC[i][j];
+    }
+  }
+  for (i = 0; i < MAX_NUM_REF_LC; i++)
+  {
+    m_eListIdFromIdxOfLC[i] = pSrc->m_eListIdFromIdxOfLC[i];
+    m_iRefIdxFromIdxOfLC[i] = pSrc->m_iRefIdxFromIdxOfLC[i];
+    m_iRefIdxOfL1FromRefIdxOfL0[i] = pSrc->m_iRefIdxOfL1FromRefIdxOfL0[i];
+    m_iRefIdxOfL0FromRefIdxOfL1[i] = pSrc->m_iRefIdxOfL0FromRefIdxOfL1[i];
+  }
+  m_bRefPicListModificationFlagLC = pSrc->m_bRefPicListModificationFlagLC;
+  m_bRefPicListCombinationFlag    = pSrc->m_bRefPicListCombinationFlag;
+  m_bCheckLDC             = pSrc->m_bCheckLDC;
+  m_iSliceQpDelta        = pSrc->m_iSliceQpDelta;
+#if CHROMA_QP_EXTENSION
+  m_iSliceQpDeltaCb      = pSrc->m_iSliceQpDeltaCb;
+  m_iSliceQpDeltaCr      = pSrc->m_iSliceQpDeltaCr;
+#endif
+  for (i = 0; i < 2; i++)
+  {
+    for (j = 0; j < MAX_NUM_REF; j++)
+    {
+      m_apcRefPicList[i][j]  = pSrc->m_apcRefPicList[i][j];
+      m_aiRefPOCList[i][j]   = pSrc->m_aiRefPOCList[i][j];
+    }
+  }  
+  m_iDepth               = pSrc->m_iDepth;
+
+  // referenced slice
+  m_bRefenced            = pSrc->m_bRefenced;
+
+  // access channel
+  m_pcSPS                = pSrc->m_pcSPS;
+  m_pcPPS                = pSrc->m_pcPPS;
+  m_pcRPS                = pSrc->m_pcRPS;
+  m_iLastIDR             = pSrc->m_iLastIDR;
+
+  m_pcPic                = pSrc->m_pcPic;
+#if !REMOVE_APS
+  m_pcAPS                = pSrc->m_pcAPS;
+  m_iAPSId               = pSrc->m_iAPSId;
+#endif
+
+  m_colFromL0Flag        = pSrc->m_colFromL0Flag;
+  m_colRefIdx            = pSrc->m_colRefIdx;
+#if ALF_CHROMA_LAMBDA || SAO_CHROMA_LAMBDA 
+  m_dLambdaLuma          = pSrc->m_dLambdaLuma;
+  m_dLambdaChroma        = pSrc->m_dLambdaChroma;
+#else
+  m_dLambda              = pSrc->m_dLambda;
+#endif
+  for (i = 0; i < 2; i++)
+  {
+    for (j = 0; j < MAX_NUM_REF; j++)
+    {
+      for (k =0; k < MAX_NUM_REF; k++)
+      {
+        m_abEqualRef[i][j][k] = pSrc->m_abEqualRef[i][j][k];
+      }
+    }
+  }
+
+  m_bNoBackPredFlag      = pSrc->m_bNoBackPredFlag;
+  m_uiTLayer                      = pSrc->m_uiTLayer;
+  m_bTLayerSwitchingFlag          = pSrc->m_bTLayerSwitchingFlag;
+
+  m_uiSliceMode                   = pSrc->m_uiSliceMode;
+  m_uiSliceArgument               = pSrc->m_uiSliceArgument;
+  m_uiSliceCurStartCUAddr         = pSrc->m_uiSliceCurStartCUAddr;
+  m_uiSliceCurEndCUAddr           = pSrc->m_uiSliceCurEndCUAddr;
+  m_uiSliceIdx                    = pSrc->m_uiSliceIdx;
+  m_uiDependentSliceMode            = pSrc->m_uiDependentSliceMode;
+  m_uiDependentSliceArgument        = pSrc->m_uiDependentSliceArgument; 
+  m_uiDependentSliceCurStartCUAddr  = pSrc->m_uiDependentSliceCurStartCUAddr;
+  m_uiDependentSliceCurEndCUAddr    = pSrc->m_uiDependentSliceCurEndCUAddr;
+  m_bNextSlice                    = pSrc->m_bNextSlice;
+  m_bNextDependentSlice             = pSrc->m_bNextDependentSlice;
+  for ( int e=0 ; e<2 ; e++ )
+  {
+    for ( int n=0 ; n<MAX_NUM_REF ; n++ )
+    {
+      memcpy(m_weightPredTable[e][n], pSrc->m_weightPredTable[e][n], sizeof(wpScalingParam)*3 );
+    }
+  }
+  m_saoEnabledFlag = pSrc->m_saoEnabledFlag; 
+#if SAO_TYPE_SHARING
+  m_saoEnabledFlagChroma = pSrc->m_saoEnabledFlagChroma;
+#else
+  m_saoEnabledFlagCb = pSrc->m_saoEnabledFlagCb;
+  m_saoEnabledFlagCr = pSrc->m_saoEnabledFlagCr; 
+#endif
+  m_cabacInitFlag                = pSrc->m_cabacInitFlag;
+  m_numEntryPointOffsets  = pSrc->m_numEntryPointOffsets;
+
+  m_bLMvdL1Zero = pSrc->m_bLMvdL1Zero;
+#if !REMOVE_ALF
+  for(Int compIdx=0; compIdx < 3; compIdx++)
+  {
+    m_alfEnabledFlag[compIdx] = pSrc->m_alfEnabledFlag[compIdx];
+  }
+#endif
+  m_LFCrossSliceBoundaryFlag = pSrc->m_LFCrossSliceBoundaryFlag;
+  m_enableTMVPFlag                = pSrc->m_enableTMVPFlag;
+}
+
+#if PREVREFPIC_DEFN
+int TComSlice::m_prevPOC[MAX_TLAYER] = {0};
+#else
+int TComSlice::m_prevPOC = 0;
+#endif
+/** Function for setting the slice's temporal layer ID and corresponding temporal_layer_switching_point_flag.
+ * \param uiTLayer Temporal layer ID of the current slice
+ * The decoder calls this function to set temporal_layer_switching_point_flag for each temporal layer based on 
+ * the SPS's temporal_id_nesting_flag and the parsed PPS.  Then, current slice's temporal layer ID and 
+ * temporal_layer_switching_point_flag is set accordingly.
+ */
+Void TComSlice::setTLayerInfo( UInt uiTLayer )
+{
+  m_uiTLayer = uiTLayer;
+}
+
+/** Function for checking if this is a switching-point
+*/
+Bool TComSlice::isTemporalLayerSwitchingPoint( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet)
+{
+  TComPic* rpcPic;
+  // loop through all pictures in the reference picture buffer
+  TComList<TComPic*>::iterator iterPic = rcListPic.begin();
+  while ( iterPic != rcListPic.end())
+  {
+    rpcPic = *(iterPic++);
+    if(rpcPic->getSlice(0)->isReferenced() && rpcPic->getPOC() != getPOC())
+    {
+      if(rpcPic->getTLayer() >= getTLayer())
+      {
+        return false;
+      }
+    }
+  }
+  return true;
+}
+
+#if STSA
+/** Function for checking if this is a STSA candidate 
+ */
+Bool TComSlice::isStepwiseTemporalLayerSwitchingPointCandidate( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet)
+{
+    TComPic* rpcPic;
+    
+    TComList<TComPic*>::iterator iterPic = rcListPic.begin();
+    while ( iterPic != rcListPic.end())
+    {
+        rpcPic = *(iterPic++);
+        if(rpcPic->getSlice(0)->isReferenced() &&  (rpcPic->getUsedByCurr()==true) && rpcPic->getPOC() != getPOC())
+        {
+            if(rpcPic->getTLayer() >= getTLayer())
+            {
+                return false;
+            }
+        }
+    }
+    return true;
+}
+#endif
+
+/** Function for applying picture marking based on the Reference Picture Set in pReferencePictureSet.
+*/
+Void TComSlice::applyReferencePictureSet( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet)
+{
+  TComPic* rpcPic;
+  Int i, isReference;
+
+  Int j = 0;
+  // loop through all pictures in the reference picture buffer
+  TComList<TComPic*>::iterator iterPic = rcListPic.begin();
+  while ( iterPic != rcListPic.end())
+  {
+    j++;
+    rpcPic = *(iterPic++);
+
+    isReference = 0;
+    // loop through all pictures in the Reference Picture Set
+    // to see if the picture should be kept as reference picture
+    for(i=0;i<pReferencePictureSet->getNumberOfPositivePictures()+pReferencePictureSet->getNumberOfNegativePictures();i++)
+    {
+      if(!rpcPic->getIsLongTerm() && rpcPic->getPicSym()->getSlice(0)->getPOC() == this->getPOC() + pReferencePictureSet->getDeltaPOC(i))
+      {
+        isReference = 1;
+        rpcPic->setUsedByCurr(pReferencePictureSet->getUsed(i));
+        rpcPic->setIsLongTerm(0);
+        rpcPic->setIsUsedAsLongTerm(0);
+      }
+    }
+    for(;i<pReferencePictureSet->getNumberOfPictures();i++)
+    {
+      if(pReferencePictureSet->getCheckLTMSBPresent(i)==true)
+      {
+        if(rpcPic->getIsLongTerm() && (rpcPic->getPicSym()->getSlice(0)->getPOC()) == pReferencePictureSet->getPOC(i))
+        {
+          isReference = 1;
+          rpcPic->setUsedByCurr(pReferencePictureSet->getUsed(i));
+        }
+      }
+      else 
+      {
+        if(rpcPic->getIsLongTerm() && (rpcPic->getPicSym()->getSlice(0)->getPOC()%(1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC())) == pReferencePictureSet->getPOC(i)%(1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC()))
+        {
+          isReference = 1;
+          rpcPic->setUsedByCurr(pReferencePictureSet->getUsed(i));
+        }
+      }
+
+    }
+    // mark the picture as "unused for reference" if it is not in
+    // the Reference Picture Set
+    if(rpcPic->getPicSym()->getSlice(0)->getPOC() != this->getPOC() && isReference == 0)    
+    {            
+      rpcPic->getSlice( 0 )->setReferenced( false );   
+      rpcPic->setIsLongTerm(0);
+    }
+    //check that pictures of higher temporal layers are not used
+    assert(rpcPic->getSlice( 0 )->isReferenced()==0||rpcPic->getUsedByCurr()==0||rpcPic->getTLayer()<=this->getTLayer());
+    //check that pictures of higher or equal temporal layer are not in the RPS if the current picture is a TSA picture
+#if NAL_UNIT_TYPES_J1003_D7
+    if(this->getNalUnitType() == NAL_UNIT_CODED_SLICE_TLA || this->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_N)
+#else
+    if(this->getNalUnitType() == NAL_UNIT_CODED_SLICE_TLA)
+#endif
+    {
+      assert(rpcPic->getSlice( 0 )->isReferenced()==0||rpcPic->getTLayer()<this->getTLayer());
+    }
+#if TEMPORAL_LAYER_NON_REFERENCE
+    //check that pictures marked as temporal layer non-reference pictures are not used for reference
+    if(rpcPic->getPicSym()->getSlice(0)->getPOC() != this->getPOC() && rpcPic->getTLayer()==this->getTLayer())
+    {
+      assert(rpcPic->getSlice( 0 )->isReferenced()==0||rpcPic->getUsedByCurr()==0||rpcPic->getSlice( 0 )->getTemporalLayerNonReferenceFlag()==false);
+    }
+#endif
+  }
+}
+
+/** Function for applying picture marking based on the Reference Picture Set in pReferencePictureSet.
+*/
+Int TComSlice::checkThatAllRefPicsAreAvailable( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool printErrors, Int pocRandomAccess)
+{
+  TComPic* rpcPic;
+  Int i, isAvailable, j;
+  Int atLeastOneLost = 0;
+  Int atLeastOneRemoved = 0;
+  Int iPocLost = 0;
+
+  // loop through all long-term pictures in the Reference Picture Set
+  // to see if the picture should be kept as reference picture
+  for(i=pReferencePictureSet->getNumberOfNegativePictures()+pReferencePictureSet->getNumberOfPositivePictures();i<pReferencePictureSet->getNumberOfPictures();i++)
+  {
+    j = 0;
+    isAvailable = 0;
+    // loop through all pictures in the reference picture buffer
+    TComList<TComPic*>::iterator iterPic = rcListPic.begin();
+    while ( iterPic != rcListPic.end())
+    {
+      j++;
+      rpcPic = *(iterPic++);
+      if(pReferencePictureSet->getCheckLTMSBPresent(i)==true)
+      {
+        if(rpcPic->getIsLongTerm() && (rpcPic->getPicSym()->getSlice(0)->getPOC()) == pReferencePictureSet->getPOC(i) && rpcPic->getSlice(0)->isReferenced())
+        {
+          isAvailable = 1;
+        }
+      }
+      else 
+      {
+        if(rpcPic->getIsLongTerm() && (rpcPic->getPicSym()->getSlice(0)->getPOC()%(1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC())) == pReferencePictureSet->getPOC(i)%(1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC()) && rpcPic->getSlice(0)->isReferenced())
+        {
+          isAvailable = 1;
+        }
+      }
+    }
+    // if there was no such long-term check the short terms
+    if(!isAvailable)
+    {
+      iterPic = rcListPic.begin();
+      while ( iterPic != rcListPic.end())
+      {
+        j++;
+        rpcPic = *(iterPic++);
+
+        if((rpcPic->getPicSym()->getSlice(0)->getPOC()%(1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC())) == (this->getPOC() + pReferencePictureSet->getDeltaPOC(i))%(1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC()) && rpcPic->getSlice(0)->isReferenced())
+        {
+          isAvailable = 1;
+          rpcPic->setIsLongTerm(1);
+          rpcPic->setIsUsedAsLongTerm(1);
+          break;
+        }
+      }
+    }
+    // report that a picture is lost if it is in the Reference Picture Set
+    // but not available as reference picture
+    if(isAvailable == 0)    
+    {            
+      if (this->getPOC() + pReferencePictureSet->getDeltaPOC(i) >= pocRandomAccess)
+      {
+        if(!pReferencePictureSet->getUsed(i) )
+        {
+          if(printErrors)
+          {
+            printf("\nLong-term reference picture with POC = %3d seems to have been removed or not correctly decoded.", this->getPOC() + pReferencePictureSet->getDeltaPOC(i));
+          }
+          atLeastOneRemoved = 1;
+        }
+        else
+        {
+          if(printErrors)
+          {
+            printf("\nLong-term reference picture with POC = %3d is lost or not correctly decoded!", this->getPOC() + pReferencePictureSet->getDeltaPOC(i));
+          }
+          atLeastOneLost = 1;
+          iPocLost=this->getPOC() + pReferencePictureSet->getDeltaPOC(i);
+        }
+      }
+    }
+  }  
+  // loop through all short-term pictures in the Reference Picture Set
+  // to see if the picture should be kept as reference picture
+  for(i=0;i<pReferencePictureSet->getNumberOfNegativePictures()+pReferencePictureSet->getNumberOfPositivePictures();i++)
+  {
+    j = 0;
+    isAvailable = 0;
+    // loop through all pictures in the reference picture buffer
+    TComList<TComPic*>::iterator iterPic = rcListPic.begin();
+    while ( iterPic != rcListPic.end())
+    {
+      j++;
+      rpcPic = *(iterPic++);
+
+      if(!rpcPic->getIsLongTerm() && rpcPic->getPicSym()->getSlice(0)->getPOC() == this->getPOC() + pReferencePictureSet->getDeltaPOC(i) && rpcPic->getSlice(0)->isReferenced())
+      {
+        isAvailable = 1;
+      }
+    }
+    // report that a picture is lost if it is in the Reference Picture Set
+    // but not available as reference picture
+    if(isAvailable == 0)    
+    {            
+      if (this->getPOC() + pReferencePictureSet->getDeltaPOC(i) >= pocRandomAccess)
+      {
+        if(!pReferencePictureSet->getUsed(i) )
+        {
+          if(printErrors)
+            printf("\nShort-term reference picture with POC = %3d seems to have been removed or not correctly decoded.", this->getPOC() + pReferencePictureSet->getDeltaPOC(i));
+          atLeastOneRemoved = 1;
+        }
+        else
+        {
+          if(printErrors)
+            printf("\nShort-term reference picture with POC = %3d is lost or not correctly decoded!", this->getPOC() + pReferencePictureSet->getDeltaPOC(i));
+          atLeastOneLost = 1;
+          iPocLost=this->getPOC() + pReferencePictureSet->getDeltaPOC(i);
+        }
+      }
+    }
+  }    
+  if(atLeastOneLost)
+  {
+    return iPocLost+1;
+  }
+  if(atLeastOneRemoved)
+  {
+    return -2;
+  }
+  else
+  {
+    return 0;
+  }
+}
+
+/** Function for constructing an explicit Reference Picture Set out of the available pictures in a referenced Reference Picture Set
+*/
+Void TComSlice::createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet)
+{
+  TComPic* rpcPic;
+  Int i, j;
+  Int k = 0;
+  Int nrOfNegativePictures = 0;
+  Int nrOfPositivePictures = 0;
+  TComReferencePictureSet* pcRPS = this->getLocalRPS();
+
+  // loop through all pictures in the Reference Picture Set
+  for(i=0;i<pReferencePictureSet->getNumberOfPictures();i++)
+  {
+    j = 0;
+    // loop through all pictures in the reference picture buffer
+    TComList<TComPic*>::iterator iterPic = rcListPic.begin();
+    while ( iterPic != rcListPic.end())
+    {
+      j++;
+      rpcPic = *(iterPic++);
+
+      if(rpcPic->getPicSym()->getSlice(0)->getPOC() == this->getPOC() + pReferencePictureSet->getDeltaPOC(i) && rpcPic->getSlice(0)->isReferenced())
+      {
+        // This picture exists as a reference picture
+        // and should be added to the explicit Reference Picture Set
+        pcRPS->setDeltaPOC(k, pReferencePictureSet->getDeltaPOC(i));
+        pcRPS->setUsed(k, pReferencePictureSet->getUsed(i));
+        if(pcRPS->getDeltaPOC(k) < 0)
+        {
+          nrOfNegativePictures++;
+        }
+        else
+        {
+          nrOfPositivePictures++;
+        }
+        k++;
+      }
+    }
+  }
+  pcRPS->setNumberOfNegativePictures(nrOfNegativePictures);
+  pcRPS->setNumberOfPositivePictures(nrOfPositivePictures);
+  pcRPS->setNumberOfPictures(nrOfNegativePictures+nrOfPositivePictures);
+  // This is a simplistic inter rps example. A smarter encoder will look for a better reference RPS to do the 
+  // inter RPS prediction with.  Here we just use the reference used by pReferencePictureSet.
+  // If pReferencePictureSet is not inter_RPS_predicted, then inter_RPS_prediction is for the current RPS also disabled.
+  if (!pReferencePictureSet->getInterRPSPrediction())
+  {
+    pcRPS->setInterRPSPrediction(false);
+    pcRPS->setNumRefIdc(0);
+  }
+  else
+  {
+    Int rIdx =  this->getRPSidx() - pReferencePictureSet->getDeltaRIdxMinus1() - 1;
+    Int deltaRPS = pReferencePictureSet->getDeltaRPS();
+    TComReferencePictureSet* pcRefRPS = this->getSPS()->getRPSList()->getReferencePictureSet(rIdx);
+    Int iRefPics = pcRefRPS->getNumberOfPictures();
+    Int iNewIdc=0;
+    for(i=0; i<= iRefPics; i++) 
+    {
+      Int deltaPOC = ((i != iRefPics)? pcRefRPS->getDeltaPOC(i) : 0);  // check if the reference abs POC is >= 0
+      Int iRefIdc = 0;
+      for (j=0; j < pcRPS->getNumberOfPictures(); j++) // loop through the  pictures in the new RPS
+      {
+        if ( (deltaPOC + deltaRPS) == pcRPS->getDeltaPOC(j))
+        {
+          if (pcRPS->getUsed(j))
+          {
+            iRefIdc = 1;
+          }
+          else
+          {
+            iRefIdc = 2;
+          }
+        }
+      }
+      pcRPS->setRefIdc(i, iRefIdc);
+      iNewIdc++;
+    }
+    pcRPS->setInterRPSPrediction(true);
+    pcRPS->setNumRefIdc(iNewIdc);
+    pcRPS->setDeltaRPS(deltaRPS); 
+    pcRPS->setDeltaRIdxMinus1(pReferencePictureSet->getDeltaRIdxMinus1() + this->getSPS()->getRPSList()->getNumberOfReferencePictureSets() - this->getRPSidx());
+  }
+
+  this->setRPS(pcRPS);
+  this->setRPSidx(-1);
+}
+
+/** get AC and DC values for weighted pred
+ * \param *wp
+ * \returns Void
+ */
+Void  TComSlice::getWpAcDcParam(wpACDCParam *&wp)
+{
+  wp = m_weightACDCParam;
+}
+
+/** init AC and DC values for weighted pred
+ * \returns Void
+ */
+Void  TComSlice::initWpAcDcParam()
+{
+  for(Int iComp = 0; iComp < 3; iComp++ )
+  {
+    m_weightACDCParam[iComp].iAC = 0;
+    m_weightACDCParam[iComp].iDC = 0;
+  }
+}
+
+/** get WP tables for weighted pred
+ * \param RefPicList
+ * \param iRefIdx
+ * \param *&wpScalingParam
+ * \returns Void
+ */
+Void  TComSlice::getWpScaling( RefPicList e, Int iRefIdx, wpScalingParam *&wp )
+{
+  wp = m_weightPredTable[e][iRefIdx];
+}
+
+/** reset Default WP tables settings : no weight. 
+ * \param wpScalingParam
+ * \returns Void
+ */
+Void  TComSlice::resetWpScaling(wpScalingParam  wp[2][MAX_NUM_REF][3])
+{
+  for ( int e=0 ; e<2 ; e++ ) 
+  {
+    for ( int i=0 ; i<MAX_NUM_REF ; i++ )
+    {
+      for ( int yuv=0 ; yuv<3 ; yuv++ ) 
+      {
+        wpScalingParam  *pwp = &(wp[e][i][yuv]);
+        pwp->bPresentFlag      = false;
+        pwp->uiLog2WeightDenom = 0;
+        pwp->uiLog2WeightDenom = 0;
+        pwp->iWeight           = 1;
+        pwp->iOffset           = 0;
+      }
+    }
+  }
+}
+
+/** init WP table
+ * \returns Void
+ */
+Void  TComSlice::initWpScaling()
+{
+  initWpScaling(m_weightPredTable);
+}
+
+/** set WP tables 
+ * \param wpScalingParam
+ * \returns Void
+ */
+Void  TComSlice::initWpScaling(wpScalingParam  wp[2][MAX_NUM_REF][3])
+{
+  for ( int e=0 ; e<2 ; e++ ) 
+  {
+    for ( int i=0 ; i<MAX_NUM_REF ; i++ )
+    {
+      for ( int yuv=0 ; yuv<3 ; yuv++ ) 
+      {
+        wpScalingParam  *pwp = &(wp[e][i][yuv]);
+        if ( !pwp->bPresentFlag ) {
+          // Inferring values not present :
+          pwp->iWeight = (1 << pwp->uiLog2WeightDenom);
+          pwp->iOffset = 0;
+        }
+
+        pwp->w      = pwp->iWeight;
+        pwp->o      = pwp->iOffset * (1 << (g_uiBitDepth-8));
+        pwp->shift  = pwp->uiLog2WeightDenom;
+        pwp->round  = (pwp->uiLog2WeightDenom>=1) ? (1 << (pwp->uiLog2WeightDenom-1)) : (0);
+      }
+    }
+  }
+}
+
+// ------------------------------------------------------------------------------------------------
+// Video parameter set (VPS)
+// ------------------------------------------------------------------------------------------------
+TComVPS::TComVPS()
+: m_VPSId                     (  0)
+, m_uiMaxTLayers              (  1)
+, m_uiMaxLayers               (  1)
+, m_bTemporalIdNestingFlag    (false)
+{
+
+  for( Int i = 0; i < MAX_TLAYER; i++)
+  {
+    m_numReorderPics[i] = 0;
+    m_uiMaxDecPicBuffering[i] = 0; 
+    m_uiMaxLatencyIncrease[i] = 0;
+  }
+}
+
+TComVPS::~TComVPS()
+{
+
+
+}
+
+// ------------------------------------------------------------------------------------------------
+// Sequence parameter set (SPS)
+// ------------------------------------------------------------------------------------------------
+
+TComSPS::TComSPS()
+: m_SPSId                     (  0)
+#if !SPS_SYNTAX_CHANGES
+, m_ProfileSpace              (  0)
+, m_ProfileIdc                (  0)
+, m_ReservedIndicatorFlags    (  0)
+, m_LevelIdc                  (  0)
+, m_ProfileCompatibility      (  0)
+#endif
+, m_VPSId                     (  0)
+, m_chromaFormatIdc           (CHROMA_420)
+, m_uiMaxTLayers              (  1)
+// Structure
+, m_picWidthInLumaSamples     (352)
+, m_picHeightInLumaSamples    (288)
+, m_picCroppingFlag           (false)
+, m_picCropLeftOffset         (  0)
+, m_picCropRightOffset        (  0)
+, m_picCropTopOffset          (  0)
+, m_picCropBottomOffset       (  0) 
+, m_uiMaxCUWidth              ( 32)
+, m_uiMaxCUHeight             ( 32)
+, m_uiMaxCUDepth              (  3)
+, m_uiMinTrDepth              (  0)
+, m_uiMaxTrDepth              (  1)
+, m_bLongTermRefsPresent      (false)
+, m_uiQuadtreeTULog2MaxSize   (  0)
+, m_uiQuadtreeTULog2MinSize   (  0)
+, m_uiQuadtreeTUMaxDepthInter (  0)
+, m_uiQuadtreeTUMaxDepthIntra (  0)
+// Tool list
+, m_usePCM                   (false)
+, m_pcmLog2MaxSize            (  5)
+, m_uiPCMLog2MinSize          (  7)
+#if !REMOVE_ALF
+, m_bUseALF                   (false)
+#endif
+#if !REMOVE_LMCHROMA
+, m_bUseLMChroma              (false)
+#endif
+#if !PPS_TS_FLAG
+, m_useTransformSkip           (false)
+, m_useTransformSkipFast       (false)
+#endif
+, m_bUseLComb                 (false)
+, m_restrictedRefPicListsFlag   (  1)
+, m_listsModificationPresentFlag(  0)
+, m_uiBitDepth                (  8)
+, m_uiBitIncrement            (  0)
+, m_qpBDOffsetY               (  0)
+, m_qpBDOffsetC               (  0)
+, m_useLossless               (false)
+, m_uiPCMBitDepthLuma         (  8)
+, m_uiPCMBitDepthChroma       (  8)
+, m_bPCMFilterDisableFlag     (false)
+, m_uiBitsForPOC              (  8)
+#if LTRP_IN_SPS
+, m_numLongTermRefPicSPS    (  0)  
+#endif
+, m_uiMaxTrSize               ( 32)
+#if !MOVE_LOOP_FILTER_SLICES_FLAG
+, m_bLFCrossSliceBoundaryFlag (false)
+#endif
+, m_bUseSAO                   (false) 
+, m_bTemporalIdNestingFlag    (false)
+, m_scalingListEnabledFlag    (false)
+#if SUPPORT_FOR_VUI
+, m_vuiParametersPresentFlag  (false)
+, m_vuiParameters             ()
+#endif
+#if SVC_EXTENSION
+, m_layerId(0)
+#endif
+{
+#if !SPS_AMVP_CLEANUP
+  // AMVP parameter
+  ::memset( m_aeAMVPMode, 0, sizeof( m_aeAMVPMode ) );
+#endif
+  for ( Int i = 0; i < MAX_TLAYER; i++ )
+  {
+    m_uiMaxLatencyIncrease[i] = 0;
+    m_uiMaxDecPicBuffering[i] = 0;
+    m_numReorderPics[i]       = 0;
+  }
+  m_scalingList = new TComScalingList;
+#if LTRP_IN_SPS
+  ::memset(m_ltRefPicPocLsbSps, 0, sizeof(m_ltRefPicPocLsbSps));
+  ::memset(m_usedByCurrPicLtSPSFlag, 0, sizeof(m_usedByCurrPicLtSPSFlag));
+#endif
+}
+
+TComSPS::~TComSPS()
+{
+  delete m_scalingList;
+  m_RPSList.destroy();
+}
+
+Void  TComSPS::createRPSList( Int numRPS )
+{ 
+  m_RPSList.destroy();
+  m_RPSList.create(numRPS);
+}
+#if BUFFERING_PERIOD_AND_TIMING_SEI
+Void TComSPS::setHrdParameters( UInt frameRate, UInt numDU, UInt bitRate, Bool randomAccess )
+{
+  if( !getVuiParametersPresentFlag() )
+  {
+    return;
+  }
+
+  TComVUI *vui = getVuiParameters();
+
+  vui->setTimingInfoPresentFlag( true );
+  switch( frameRate )
+  {
+  case 24:
+    vui->setNumUnitsInTick( 1125000 );    vui->setTimeScale    ( 27000000 );
+    break;
+  case 25:
+    vui->setNumUnitsInTick( 1080000 );    vui->setTimeScale    ( 27000000 );
+    break;
+  case 30:
+    vui->setNumUnitsInTick( 900900 );     vui->setTimeScale    ( 27000000 );
+    break;
+  case 50:
+    vui->setNumUnitsInTick( 540000 );     vui->setTimeScale    ( 27000000 );
+    break;
+  case 60:
+    vui->setNumUnitsInTick( 450450 );     vui->setTimeScale    ( 27000000 );
+    break;
+  default:
+    vui->setNumUnitsInTick( 1001 );       vui->setTimeScale    ( 60000 );
+    break;
+  }
+
+  Bool rateCnt = ( bitRate > 0 );
+  vui->setNalHrdParametersPresentFlag( rateCnt );
+  vui->setVclHrdParametersPresentFlag( rateCnt );
+
+  vui->setSubPicCpbParamsPresentFlag( ( numDU > 1 ) );
+
+  if( vui->getSubPicCpbParamsPresentFlag() )
+  {
+    vui->setTickDivisorMinus2( 100 - 2 );                          // 
+    vui->setDuCpbRemovalDelayLengthMinus1( 7 );                    // 8-bit precision ( plus 1 for last DU in AU )
+  }
+
+  vui->setBitRateScale( 4 );                                       // in units of 2~( 6 + 4 ) = 1,024 bps
+  vui->setCpbSizeScale( 6 );                                       // in units of 2~( 4 + 4 ) = 1,024 bit
+
+  vui->setInitialCpbRemovalDelayLengthMinus1(15);                  // assuming 0.5 sec, log2( 90,000 * 0.5 ) = 16-bit
+  if( randomAccess )
+  {
+    vui->setCpbRemovalDelayLengthMinus1(5);                        // 32 = 2^5 (plus 1)
+    vui->setDpbOutputDelayLengthMinus1 (5);                        // 32 + 3 = 2^6
+  }
+  else
+  {
+    vui->setCpbRemovalDelayLengthMinus1(9);                        // max. 2^10
+    vui->setDpbOutputDelayLengthMinus1 (9);                        // max. 2^10
+  }
+
+/*
+   Note: only the case of "vps_max_temporal_layers_minus1 = 0" is supported.
+*/
+  Int i, j;
+  UInt birateValue, cpbSizeValue;
+
+  for( i = 0; i < MAX_TLAYER; i ++ )
+  {
+    vui->setFixedPicRateFlag( i, 1 );
+    vui->setPicDurationInTcMinus1( i, 0 );
+    vui->setLowDelayHrdFlag( i, 0 );
+    vui->setCpbCntMinus1( i, 0 );
+
+    birateValue  = bitRate;
+    cpbSizeValue = bitRate;                                     // 1 second
+    for( j = 0; j < ( vui->getCpbCntMinus1( i ) + 1 ); j ++ )
+    {
+      vui->setBitRateValueMinus1( i, j, 0, ( birateValue  - 1 ) );
+      vui->setCpbSizeValueMinus1( i, j, 0, ( cpbSizeValue - 1 ) );
+      vui->setCbrFlag( i, j, 0, ( j == 0 ) );
+
+      vui->setBitRateValueMinus1( i, j, 1, ( birateValue  - 1) );
+      vui->setCpbSizeValueMinus1( i, j, 1, ( cpbSizeValue - 1 ) );
+      vui->setCbrFlag( i, j, 1, ( j == 0 ) );
+    }
+  }
+}
+#endif
+const Int TComSPS::m_cropUnitX[]={1,2,2,1};
+const Int TComSPS::m_cropUnitY[]={1,2,1,1};
+
+TComPPS::TComPPS()
+: m_PPSId                       (0)
+, m_SPSId                       (0)
+, m_picInitQPMinus26            (0)
+, m_useDQP                      (false)
+, m_bConstrainedIntraPred       (false)
+#if CHROMA_QP_EXTENSION
+, m_bSliceChromaQpFlag          (false)
+#endif
+, m_pcSPS                       (NULL)
+, m_uiMaxCuDQPDepth             (0)
+, m_uiMinCuDQPSize              (0)
+, m_chromaCbQpOffset            (0)
+, m_chromaCrQpOffset            (0)
+, m_numRefIdxL0DefaultActive    (1)
+, m_numRefIdxL1DefaultActive    (1)
+#if !REMOVE_FGS
+, m_iSliceGranularity           (0)
+#endif
+, m_TransquantBypassEnableFlag  (false)
+#if PPS_TS_FLAG
+, m_useTransformSkip             (false)
+#endif
+#if TILES_WPP_ENTROPYSLICES_FLAGS
+, m_dependentSliceEnabledFlag    (false)
+, m_tilesEnabledFlag               (false)
+, m_entropyCodingSyncEnabledFlag   (false)
+, m_entropySliceEnabledFlag        (false)
+#endif
+, m_loopFilterAcrossTilesEnabledFlag  (true)
+, m_uniformSpacingFlag           (0)
+, m_iNumColumnsMinus1            (0)
+, m_puiColumnWidth               (NULL)
+, m_iNumRowsMinus1               (0)
+, m_puiRowHeight                 (NULL)
+, m_iNumSubstreams             (1)
+, m_signHideFlag(0)
+, m_cabacInitPresentFlag        (false)
+, m_encCABACTableIdx            (I_SLICE)
+#if SLICE_HEADER_EXTENSION
+, m_sliceHeaderExtensionPresentFlag    (false)
+#endif
+#if MOVE_LOOP_FILTER_SLICES_FLAG
+, m_loopFilterAcrossSlicesEnabledFlag (false)
+#endif
+{
+  m_scalingList = new TComScalingList;
+#if !TILES_WPP_ENTROPYSLICES_FLAGS
+#if DEPENDENT_SLICES
+  m_bDependentSliceEnabledFlag = false;
+  m_bCabacIndependentFlag = false;
+#endif
+#endif
+}
+
+TComPPS::~TComPPS()
+{
+  if( m_iNumColumnsMinus1 > 0 && m_uniformSpacingFlag == 0 )
+  {
+    if (m_puiColumnWidth) delete [] m_puiColumnWidth; 
+    m_puiColumnWidth = NULL;
+  }
+  if( m_iNumRowsMinus1 > 0 && m_uniformSpacingFlag == 0 )
+  {
+    if (m_puiRowHeight) delete [] m_puiRowHeight;
+    m_puiRowHeight = NULL;
+  }
+  delete m_scalingList;
+}
+
+TComReferencePictureSet::TComReferencePictureSet()
+: m_numberOfPictures (0)
+, m_numberOfNegativePictures (0)
+, m_numberOfPositivePictures (0)
+, m_numberOfLongtermPictures (0)
+, m_interRPSPrediction (0) 
+, m_deltaRIdxMinus1 (0)   
+, m_deltaRPS (0) 
+, m_numRefIdc (0) 
+{
+  ::memset( m_deltaPOC, 0, sizeof(m_deltaPOC) );
+  ::memset( m_POC, 0, sizeof(m_POC) );
+  ::memset( m_used, 0, sizeof(m_used) );
+  ::memset( m_refIdc, 0, sizeof(m_refIdc) );
+}
+
+TComReferencePictureSet::~TComReferencePictureSet()
+{
+}
+
+Void TComReferencePictureSet::setUsed(Int bufferNum, Bool used)
+{
+  m_used[bufferNum] = used;
+}
+
+Void TComReferencePictureSet::setDeltaPOC(Int bufferNum, Int deltaPOC)
+{
+  m_deltaPOC[bufferNum] = deltaPOC;
+}
+
+Void TComReferencePictureSet::setNumberOfPictures(Int numberOfPictures)
+{
+  m_numberOfPictures = numberOfPictures;
+}
+
+Int TComReferencePictureSet::getUsed(Int bufferNum)
+{
+  return m_used[bufferNum];
+}
+
+Int TComReferencePictureSet::getDeltaPOC(Int bufferNum)
+{
+  return m_deltaPOC[bufferNum];
+}
+
+Int TComReferencePictureSet::getNumberOfPictures()
+{
+  return m_numberOfPictures;
+}
+
+Int TComReferencePictureSet::getPOC(Int bufferNum)
+{
+  return m_POC[bufferNum];
+}
+Void TComReferencePictureSet::setPOC(Int bufferNum, Int POC)
+{
+  m_POC[bufferNum] = POC;
+}
+Bool TComReferencePictureSet::getCheckLTMSBPresent(Int bufferNum)
+{
+  return m_bCheckLTMSB[bufferNum];
+}
+Void TComReferencePictureSet::setCheckLTMSBPresent(Int bufferNum, Bool b)
+{
+  m_bCheckLTMSB[bufferNum] = b;
+}
+
+/** set the reference idc value at uiBufferNum entry to the value of iRefIdc
+ * \param uiBufferNum
+ * \param iRefIdc
+ * \returns Void
+ */
+Void TComReferencePictureSet::setRefIdc(Int bufferNum, Int refIdc)
+{
+  m_refIdc[bufferNum] = refIdc;
+}
+
+/** get the reference idc value at uiBufferNum
+ * \param uiBufferNum
+ * \returns Int
+ */
+Int  TComReferencePictureSet::getRefIdc(Int bufferNum)
+{
+  return m_refIdc[bufferNum];
+}
+
+/** Sorts the deltaPOC and Used by current values in the RPS based on the deltaPOC values.
+ *  deltaPOC values are sorted with -ve values before the +ve values.  -ve values are in decreasing order.
+ *  +ve values are in increasing order.
+ * \returns Void
+ */
+Void TComReferencePictureSet::sortDeltaPOC()
+{
+  // sort in increasing order (smallest first)
+  for(Int j=1; j < getNumberOfPictures(); j++)
+  { 
+    Int deltaPOC = getDeltaPOC(j);
+    Bool used = getUsed(j);
+    for (Int k=j-1; k >= 0; k--)
+    {
+      Int temp = getDeltaPOC(k);
+      if (deltaPOC < temp)
+      {
+        setDeltaPOC(k+1, temp);
+        setUsed(k+1, getUsed(k));
+        setDeltaPOC(k, deltaPOC);
+        setUsed(k, used);
+      }
+    }
+  }
+  // flip the negative values to largest first
+  Int numNegPics = getNumberOfNegativePictures();
+  for(Int j=0, k=numNegPics-1; j < numNegPics>>1; j++, k--)
+  { 
+    Int deltaPOC = getDeltaPOC(j);
+    Bool used = getUsed(j);
+    setDeltaPOC(j, getDeltaPOC(k));
+    setUsed(j, getUsed(k));
+    setDeltaPOC(k, deltaPOC);
+    setUsed(k, used);
+  }
+}
+
+/** Prints the deltaPOC and RefIdc (if available) values in the RPS.
+ *  A "*" is added to the deltaPOC value if it is Used bu current.
+ * \returns Void
+ */
+Void TComReferencePictureSet::printDeltaPOC()
+{
+  printf("DeltaPOC = { ");
+  for(Int j=0; j < getNumberOfPictures(); j++)
+  {
+    printf("%d%s ", getDeltaPOC(j), (getUsed(j)==1)?"*":"");
+  } 
+  if (getInterRPSPrediction()) 
+  {
+    printf("}, RefIdc = { ");
+    for(Int j=0; j < getNumRefIdc(); j++)
+    {
+      printf("%d ", getRefIdc(j));
+    } 
+  }
+  printf("}\n");
+}
+
+TComRPSList::TComRPSList()
+:m_referencePictureSets (NULL)
+{
+}
+
+TComRPSList::~TComRPSList()
+{
+}
+
+Void TComRPSList::create( Int numberOfReferencePictureSets)
+{
+  m_numberOfReferencePictureSets = numberOfReferencePictureSets;
+  m_referencePictureSets = new TComReferencePictureSet[numberOfReferencePictureSets];
+}
+
+Void TComRPSList::destroy()
+{
+  if (m_referencePictureSets)
+  {
+    delete [] m_referencePictureSets;
+  }
+  m_numberOfReferencePictureSets = 0;
+  m_referencePictureSets = NULL;
+}
+
+
+
+TComReferencePictureSet* TComRPSList::getReferencePictureSet(Int referencePictureSetNum)
+{
+  return &m_referencePictureSets[referencePictureSetNum];
+}
+
+Int TComRPSList::getNumberOfReferencePictureSets()
+{
+  return m_numberOfReferencePictureSets;
+}
+
+Void TComRPSList::setNumberOfReferencePictureSets(Int numberOfReferencePictureSets)
+{
+  m_numberOfReferencePictureSets = numberOfReferencePictureSets;
+}
+
+TComRefPicListModification::TComRefPicListModification()
+: m_bRefPicListModificationFlagL0 (false)
+, m_bRefPicListModificationFlagL1 (false)
+{
+  ::memset( m_RefPicSetIdxL0, 0, sizeof(m_RefPicSetIdxL0) );
+  ::memset( m_RefPicSetIdxL1, 0, sizeof(m_RefPicSetIdxL1) );
+}
+
+TComRefPicListModification::~TComRefPicListModification()
+{
+}
+
+#if !REMOVE_APS
+TComAPS::TComAPS()
+{
+  m_apsID = 0;
+  m_pSaoParam = NULL;
+#if !REMOVE_ALF
+  m_alfParam[0] = m_alfParam[1] = m_alfParam[2] = NULL;
+#endif
+}
+
+TComAPS::~TComAPS()
+{
+  delete m_pSaoParam;
+#if !REMOVE_ALF
+  for(Int compIdx =0; compIdx < 3; compIdx++)
+  {
+    delete m_alfParam[compIdx];
+    m_alfParam[compIdx] = NULL;
+  }
+#endif
+}
+
+TComAPS& TComAPS::operator= (const TComAPS& src)
+{
+  m_apsID       = src.m_apsID;
+  m_pSaoParam   = src.m_pSaoParam;
+#if !REMOVE_ALF
+  for(Int compIdx =0; compIdx < 3; compIdx++)
+  {
+    m_alfParam[compIdx] = src.m_alfParam[compIdx];
+  }
+#endif
+  return *this;
+}
+
+Void TComAPS::createSaoParam()
+{
+  m_pSaoParam = new SAOParam;
+}
+
+Void TComAPS::destroySaoParam()
+{
+  if(m_pSaoParam != NULL)
+  {
+    delete m_pSaoParam;
+    m_pSaoParam = NULL;
+  }
+}
+
+#if !REMOVE_ALF
+Void TComAPS::createAlfParam()
+{
+  for(Int compIdx =0; compIdx < 3; compIdx++)
+  {
+    m_alfParam[compIdx] = new ALFParam(compIdx);
+    m_alfParam[compIdx]->alf_flag = 0;
+  }
+}
+Void TComAPS::destroyAlfParam()
+{
+  for(Int compIdx=0; compIdx < 3; compIdx++)
+  {
+    if(m_alfParam[compIdx] != NULL)
+    {
+      delete m_alfParam[compIdx];
+      m_alfParam[compIdx] = NULL;
+    }
+  }
+}
+#endif
+#endif
+
+TComScalingList::TComScalingList()
+{
+#if TS_FLAT_QUANTIZATION_MATRIX
+  m_useTransformSkip = false;
+#endif
+  init();
+}
+TComScalingList::~TComScalingList()
+{
+  destroy();
+}
+
+/** set default quantization matrix to array
+*/
+Void TComSlice::setDefaultScalingList()
+{
+  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
+  {
+    for(UInt listId=0;listId<g_scalingListNum[sizeId];listId++)
+    {
+      getScalingList()->processDefaultMarix(sizeId, listId);
+    }
+  }
+}
+/** check if use default quantization matrix
+ * \returns true if use default quantization matrix in all size
+*/
+Bool TComSlice::checkDefaultScalingList()
+{
+  UInt defaultCounter=0;
+
+  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
+  {
+    for(UInt listId=0;listId<g_scalingListNum[sizeId];listId++)
+    {
+      if( !memcmp(getScalingList()->getScalingListAddress(sizeId,listId), getScalingList()->getScalingListDefaultAddress(sizeId, listId),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId])) // check value of matrix
+     && ((sizeId < SCALING_LIST_16x16) || (getScalingList()->getScalingListDC(sizeId,listId) == 16))) // check DC value
+      {
+        defaultCounter++;
+      }
+    }
+  }
+  return (defaultCounter == (SCALING_LIST_NUM * SCALING_LIST_SIZE_NUM - 4)) ? false : true; // -4 for 32x32
+}
+/** get scaling matrix from RefMatrixID
+ * \param sizeId size index
+ * \param Index of input matrix
+ * \param Index of reference matrix
+ */
+Void TComScalingList::processRefMatrix( UInt sizeId, UInt listId , UInt refListId )
+{
+  ::memcpy(getScalingListAddress(sizeId, listId),((listId == refListId)? getScalingListDefaultAddress(sizeId, refListId): getScalingListAddress(sizeId, refListId)),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]));
+}
+/** parse syntax infomation 
+ *  \param pchFile syntax infomation
+ *  \returns false if successful
+ */
+Bool TComScalingList::xParseScalingList(char* pchFile)
+{
+  FILE *fp;
+  Char line[1024];
+  UInt sizeIdc,listIdc;
+  UInt i,size = 0;
+  Int *src=0,data;
+  Char *ret;
+  UInt  retval;
+
+  if((fp = fopen(pchFile,"r")) == (FILE*)NULL)
+  {
+    printf("can't open file %s :: set Default Matrix\n",pchFile);
+    return true;
+  }
+
+  for(sizeIdc = 0; sizeIdc < SCALING_LIST_SIZE_NUM; sizeIdc++)
+  {
+    size = min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeIdc]);
+    for(listIdc = 0; listIdc < g_scalingListNum[sizeIdc]; listIdc++)
+    {
+      src = getScalingListAddress(sizeIdc, listIdc);
+
+      fseek(fp,0,0);
+      do 
+      {
+        ret = fgets(line, 1024, fp);
+        if ((ret==NULL)||(strstr(line, MatrixType[sizeIdc][listIdc])==NULL && feof(fp)))
+        {
+          printf("Error: can't read Matrix :: set Default Matrix\n");
+          return true;
+        }
+      }
+      while (strstr(line, MatrixType[sizeIdc][listIdc]) == NULL);
+      for (i=0; i<size; i++)
+      {
+        retval = fscanf(fp, "%d,", &data);
+        if (retval!=1)
+        {
+          printf("Error: can't read Matrix :: set Default Matrix\n");
+          return true;
+        }
+        src[i] = data;
+      }
+      //set DC value for default matrix check
+      setScalingListDC(sizeIdc,listIdc,src[0]);
+
+      if(sizeIdc > SCALING_LIST_8x8)
+      {
+        fseek(fp,0,0);
+        do 
+        {
+          ret = fgets(line, 1024, fp);
+          if ((ret==NULL)||(strstr(line, MatrixType_DC[sizeIdc][listIdc])==NULL && feof(fp)))
+          {
+            printf("Error: can't read DC :: set Default Matrix\n");
+            return true;
+          }
+        }
+        while (strstr(line, MatrixType_DC[sizeIdc][listIdc]) == NULL);
+        retval = fscanf(fp, "%d,", &data);
+        if (retval!=1)
+        {
+          printf("Error: can't read Matrix :: set Default Matrix\n");
+          return true;
+        }
+        //overwrite DC value when size of matrix is larger than 16x16
+        setScalingListDC(sizeIdc,listIdc,data);
+      }
+    }
+  }
+  fclose(fp);
+  return false;
+}
+
+/** initialization process of quantization matrix array
+ */
+Void TComScalingList::init()
+{
+  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
+  {
+    for(UInt listId = 0; listId < g_scalingListNum[sizeId]; listId++)
+    {
+      m_scalingListCoef[sizeId][listId] = new Int [min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId])];
+    }
+  }
+  m_scalingListCoef[SCALING_LIST_32x32][3] = m_scalingListCoef[SCALING_LIST_32x32][1]; // copy address for 32x32
+}
+/** destroy quantization matrix array
+ */
+Void TComScalingList::destroy()
+{
+  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
+  {
+    for(UInt listId = 0; listId < g_scalingListNum[sizeId]; listId++)
+    {
+      if(m_scalingListCoef[sizeId][listId]) delete [] m_scalingListCoef[sizeId][listId];
+    }
+  }
+}
+/** get default address of quantization matrix 
+ * \param sizeId size index
+ * \param listId list index
+ * \returns pointer of quantization matrix
+ */
+Int* TComScalingList::getScalingListDefaultAddress(UInt sizeId, UInt listId)
+{
+  Int *src = 0;
+  switch(sizeId)
+  {
+    case SCALING_LIST_4x4:
+#if TS_FLAT_QUANTIZATION_MATRIX
+      if( m_useTransformSkip )
+      {
+        src = g_quantTSDefault4x4;
+      }
+      else
+      {
+        src = (listId<3) ? g_quantIntraDefault4x4 : g_quantInterDefault4x4;
+      }
+#else
+      src = (listId<3) ? g_quantIntraDefault4x4 : g_quantInterDefault4x4;
+#endif
+      break;
+    case SCALING_LIST_8x8:
+      src = (listId<3) ? g_quantIntraDefault8x8 : g_quantInterDefault8x8;
+      break;
+    case SCALING_LIST_16x16:
+      src = (listId<3) ? g_quantIntraDefault8x8 : g_quantInterDefault8x8;
+      break;
+    case SCALING_LIST_32x32:
+      src = (listId<1) ? g_quantIntraDefault8x8 : g_quantInterDefault8x8;
+      break;
+    default:
+      assert(0);
+      src = NULL;
+      break;
+  }
+  return src;
+}
+/** process of default matrix
+ * \param sizeId size index
+ * \param Index of input matrix
+ */
+Void TComScalingList::processDefaultMarix(UInt sizeId, UInt listId)
+{
+  ::memcpy(getScalingListAddress(sizeId, listId),getScalingListDefaultAddress(sizeId,listId),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]));
+  setScalingListDC(sizeId,listId,SCALING_LIST_DC);
+}
+/** check DC value of matrix for default matrix signaling
+ */
+Void TComScalingList::checkDcOfMatrix()
+{
+  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
+  {
+    for(UInt listId = 0; listId < g_scalingListNum[sizeId]; listId++)
+    {
+      //check default matrix?
+      if(getScalingListDC(sizeId,listId) == 0)
+      {
+        processDefaultMarix(sizeId, listId);
+      }
+    }
+  }
+}
+
+ParameterSetManager::ParameterSetManager()
+: m_vpsMap(MAX_NUM_VPS)
+, m_spsMap(MAX_NUM_SPS)
+, m_ppsMap(MAX_NUM_PPS)
+#if !REMOVE_APS
+, m_apsMap(MAX_NUM_APS)
+#endif
+{
+}
+
+
+ParameterSetManager::~ParameterSetManager()
+{
+}
+
+#if PROFILE_TIER_LEVEL_SYNTAX
+ProfileTierLevel::ProfileTierLevel()
+  : m_profileSpace    (0)
+  , m_tierFlag        (false)
+  , m_profileIdc      (0)
+  , m_levelIdc        (0)
+{
+  ::memset(m_profileCompatibilityFlag, 0, sizeof(m_profileCompatibilityFlag));
+}
+TComPTL::TComPTL()
+{
+  ::memset(m_subLayerProfilePresentFlag, 0, sizeof(m_subLayerProfilePresentFlag));
+  ::memset(m_subLayerLevelPresentFlag,   0, sizeof(m_subLayerLevelPresentFlag  ));
+}
+#endif
+//! \}
Index: /trunk/source/Lib/TLibCommon/TComSlice.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComSlice.h	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComSlice.h	(revision 2)
@@ -0,0 +1,1676 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComSlice.h
+    \brief    slice header and SPS class (header)
+*/
+
+#ifndef __TCOMSLICE__
+#define __TCOMSLICE__
+
+#include <cstring>
+#include <map>
+#include <vector>
+#include "CommonDef.h"
+#include "TComRom.h"
+#include "TComList.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+class TComPic;
+class TComTrQuant;
+
+#if SVC_EXTENSION
+class TComPicYuv;
+#endif
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+/// max number of supported APS in software
+#define MAX_NUM_SUPPORTED_APS 1
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// Reference Picture Set class
+class TComReferencePictureSet
+{
+private:
+  Int  m_numberOfPictures;
+  Int  m_numberOfNegativePictures;
+  Int  m_numberOfPositivePictures;
+  Int  m_numberOfLongtermPictures;
+  Int  m_deltaPOC[MAX_NUM_REF_PICS];
+  Int  m_POC[MAX_NUM_REF_PICS];
+  Bool m_used[MAX_NUM_REF_PICS];
+  Bool m_interRPSPrediction;
+  Int  m_deltaRIdxMinus1;   
+  Int  m_deltaRPS; 
+  Int  m_numRefIdc; 
+  Int  m_refIdc[MAX_NUM_REF_PICS+1];
+  Bool m_bCheckLTMSB[MAX_NUM_REF_PICS];
+  Int  m_pocLSBLT[MAX_NUM_REF_PICS];
+  Int  m_deltaPOCMSBCycleLT[MAX_NUM_REF_PICS];
+  Bool m_deltaPocMSBPresentFlag[MAX_NUM_REF_PICS];
+
+public:
+  TComReferencePictureSet();
+  virtual ~TComReferencePictureSet();
+  Int   getPocLSBLT(Int i)                       { return m_pocLSBLT[i]; }
+  Void  setPocLSBLT(Int i, Int x)                { m_pocLSBLT[i] = x; }
+  Int   getDeltaPocMSBCycleLT(Int i)             { return m_deltaPOCMSBCycleLT[i]; }
+  Void  setDeltaPocMSBCycleLT(Int i, Int x)      { m_deltaPOCMSBCycleLT[i] = x; }
+  Bool  getDeltaPocMSBPresentFlag(Int i)         { return m_deltaPocMSBPresentFlag[i]; }
+  Void  setDeltaPocMSBPresentFlag(Int i, Bool x) { m_deltaPocMSBPresentFlag[i] = x;    }
+  Void setUsed(Int bufferNum, Bool used);
+  Void setDeltaPOC(Int bufferNum, Int deltaPOC);
+  Void setPOC(Int bufferNum, Int deltaPOC);
+  Void setNumberOfPictures(Int numberOfPictures);
+  Void setCheckLTMSBPresent(Int bufferNum, Bool b );
+  Bool getCheckLTMSBPresent(Int bufferNum);
+
+  Int  getUsed(Int bufferNum);
+  Int  getDeltaPOC(Int bufferNum);
+  Int  getPOC(Int bufferNum);
+  Int  getNumberOfPictures();
+
+  Void setNumberOfNegativePictures(Int number)  { m_numberOfNegativePictures = number; }
+  Int  getNumberOfNegativePictures()            { return m_numberOfNegativePictures; }
+  Void setNumberOfPositivePictures(Int number)  { m_numberOfPositivePictures = number; }
+  Int  getNumberOfPositivePictures()            { return m_numberOfPositivePictures; }
+  Void setNumberOfLongtermPictures(Int number)  { m_numberOfLongtermPictures = number; }
+  Int  getNumberOfLongtermPictures()            { return m_numberOfLongtermPictures; }
+
+  Void setInterRPSPrediction(Bool flag)         { m_interRPSPrediction = flag; }
+  Bool getInterRPSPrediction()                  { return m_interRPSPrediction; }
+  Void setDeltaRIdxMinus1(Int x)                { m_deltaRIdxMinus1 = x; }
+  Int  getDeltaRIdxMinus1()                     { return m_deltaRIdxMinus1; }
+  Void setDeltaRPS(Int x)                       { m_deltaRPS = x; }
+  Int  getDeltaRPS()                            { return m_deltaRPS; }
+  Void setNumRefIdc(Int x)                      { m_numRefIdc = x; }
+  Int  getNumRefIdc()                           { return m_numRefIdc; }
+
+  Void setRefIdc(Int bufferNum, Int refIdc);
+  Int  getRefIdc(Int bufferNum);
+
+  Void sortDeltaPOC();
+  Void printDeltaPOC();
+};
+
+/// Reference Picture Set set class
+class TComRPSList
+{
+private:
+  Int  m_numberOfReferencePictureSets;
+  TComReferencePictureSet* m_referencePictureSets;
+  
+public:
+  TComRPSList();
+  virtual ~TComRPSList();
+  
+  Void  create  (Int numberOfEntries);
+  Void  destroy ();
+
+
+  TComReferencePictureSet* getReferencePictureSet(Int referencePictureSetNum);
+  Int getNumberOfReferencePictureSets();
+  Void setNumberOfReferencePictureSets(Int numberOfReferencePictureSets);
+};
+
+/// SCALING_LIST class
+class TComScalingList
+{
+public:
+  TComScalingList();
+  virtual ~TComScalingList();
+  Void     setScalingListPresentFlag    (Bool b)                               { m_scalingListPresentFlag = b;    }
+  Bool     getScalingListPresentFlag    ()                                     { return m_scalingListPresentFlag; }
+#if TS_FLAT_QUANTIZATION_MATRIX
+  Bool     getUseTransformSkip    ()                                     { return m_useTransformSkip; }      
+  Void     setUseTransformSkip    (Bool b)                               { m_useTransformSkip = b;    }
+#endif
+  Int*     getScalingListAddress          (UInt sizeId, UInt listId)           { return m_scalingListCoef[sizeId][listId]; } //!< get matrix coefficient
+  Bool     checkPredMode                  (UInt sizeId, UInt listId);
+  Void     setRefMatrixId                 (UInt sizeId, UInt listId, UInt u)   { m_refMatrixId[sizeId][listId] = u;    }     //!< set reference matrix ID
+  UInt     getRefMatrixId                 (UInt sizeId, UInt listId)           { return m_refMatrixId[sizeId][listId]; }     //!< get reference matrix ID
+  Int*     getScalingListDefaultAddress   (UInt sizeId, UInt listId);                                                        //!< get default matrix coefficient
+  Void     processDefaultMarix            (UInt sizeId, UInt listId);
+  Void     setScalingListDC               (UInt sizeId, UInt listId, UInt u)   { m_scalingListDC[sizeId][listId] = u; }      //!< set DC value
+
+  Int      getScalingListDC               (UInt sizeId, UInt listId)           { return m_scalingListDC[sizeId][listId]; }   //!< get DC value
+  Void     checkDcOfMatrix                ();
+  Void     processRefMatrix               (UInt sizeId, UInt listId , UInt refListId );
+  Bool     xParseScalingList              (char* pchFile);
+
+private:
+  Void     init                    ();
+  Void     destroy                 ();
+  Int      m_scalingListDC               [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM]; //!< the DC value of the matrix coefficient for 16x16
+  Bool     m_useDefaultScalingMatrixFlag [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM]; //!< UseDefaultScalingMatrixFlag
+  UInt     m_refMatrixId                 [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM]; //!< RefMatrixID
+  Bool     m_scalingListPresentFlag;                                                //!< flag for using default matrix
+  UInt     m_predMatrixId                [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM]; //!< reference list index
+  Int      *m_scalingListCoef            [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM]; //!< quantization matrix
+#if TS_FLAT_QUANTIZATION_MATRIX
+  Bool     m_useTransformSkip;                                                      //!< transform skipping flag for setting default scaling matrix for 4x4
+#endif
+};
+
+#if PROFILE_TIER_LEVEL_SYNTAX
+class ProfileTierLevel{
+  Int     m_profileSpace;
+  Bool    m_tierFlag;
+  Int     m_profileIdc;
+  Bool    m_profileCompatibilityFlag[32];
+  Int     m_levelIdc;
+
+public:
+  ProfileTierLevel();
+
+  Int   getProfileSpace() const   { return m_profileSpace; }
+  Void  setProfileSpace(Int x)    { m_profileSpace = x; }
+
+  Bool  getTierFlag()     const   { return m_tierFlag; }
+  Void  setTierFlag(Bool x)       { m_tierFlag = x; }
+
+  Int   getProfileIdc()   const   { return m_profileIdc; }
+  Void  setProfileIdc(Int x)      { m_profileIdc = x; }
+
+  Bool  getProfileCompatibilityFlag(Int i) const    { return m_profileCompatibilityFlag[i]; }
+  Void  setProfileCompatibilityFlag(Int i, Bool x)  { m_profileCompatibilityFlag[i] = x; }
+
+  Int   getLevelIdc()   const   { return m_levelIdc; }
+  Void  setLevelIdc(Int x)      { m_levelIdc = x; }
+};
+
+
+class TComPTL{
+  ProfileTierLevel m_generalPTL;
+  ProfileTierLevel m_subLayerPTL[6];      // max. value of max_sub_layers_minus1 is 6
+  Bool m_subLayerProfilePresentFlag[6];
+  Bool m_subLayerLevelPresentFlag[6];
+
+public:
+  TComPTL();
+  Bool getSubLayerProfilePresentFlag(Int i) const { return m_subLayerProfilePresentFlag[i]; }
+  Void setSubLayerProfilePresentFlag(Int i, Bool x) { m_subLayerProfilePresentFlag[i] = x; }
+  
+  Bool getSubLayerLevelPresentFlag(Int i) const { return m_subLayerLevelPresentFlag[i]; }
+  Void setSubLayerLevelPresentFlag(Int i, Bool x) { m_subLayerLevelPresentFlag[i] = x; }
+
+  ProfileTierLevel* getGeneralPTL()  { return &m_generalPTL; }
+  ProfileTierLevel* getSubLayerPTL(Int i)  { return &m_subLayerPTL[i]; }
+};
+#endif
+/// VPS class
+
+class TComVPS
+{
+private:
+  Int         m_VPSId;
+  UInt        m_uiMaxTLayers;
+  UInt        m_uiMaxLayers;
+  Bool        m_bTemporalIdNestingFlag;
+  
+  UInt        m_numReorderPics[MAX_TLAYER];
+  UInt        m_uiMaxDecPicBuffering[MAX_TLAYER]; 
+  UInt        m_uiMaxLatencyIncrease[MAX_TLAYER];
+#if VPS_SYNTAX_CHANGES
+  TComPTL     m_pcPTL;
+#endif
+public:
+  TComVPS();
+  virtual ~TComVPS();
+
+  Int     getVPSId       ()                   { return m_VPSId;          }
+  Void    setVPSId       (Int i)              { m_VPSId = i;             }
+
+  UInt    getMaxTLayers  ()                   { return m_uiMaxTLayers;   }
+  Void    setMaxTLayers  (UInt t)             { m_uiMaxTLayers = t; }
+  
+  UInt    getMaxLayers   ()                   { return m_uiMaxLayers;   }
+  Void    setMaxLayers   (UInt l)             { m_uiMaxLayers = l; }
+
+  Bool    getTemporalNestingFlag   ()         { return m_bTemporalIdNestingFlag;   }
+  Void    setTemporalNestingFlag   (Bool t)   { m_bTemporalIdNestingFlag = t; }
+  
+  Void    setNumReorderPics(UInt v, UInt tLayer)                { m_numReorderPics[tLayer] = v;    }
+  UInt    getNumReorderPics(UInt tLayer)                        { return m_numReorderPics[tLayer]; }
+  
+  Void    setMaxDecPicBuffering(UInt v, UInt tLayer)            { m_uiMaxDecPicBuffering[tLayer] = v;    }
+  UInt    getMaxDecPicBuffering(UInt tLayer)                    { return m_uiMaxDecPicBuffering[tLayer]; }
+  
+  Void    setMaxLatencyIncrease(UInt v, UInt tLayer)            { m_uiMaxLatencyIncrease[tLayer] = v;    }
+  UInt    getMaxLatencyIncrease(UInt tLayer)                    { return m_uiMaxLatencyIncrease[tLayer]; }
+#if VPS_SYNTAX_CHANGES
+  TComPTL* getPTL() { return &m_pcPTL; }
+#endif  
+};
+
+#if BUFFERING_PERIOD_AND_TIMING_SEI
+struct HrdSubLayerInfo
+{
+  Bool fixedPicRateFlag;
+  UInt picDurationInTcMinus1;
+  Bool lowDelayHrdFlag;
+  UInt cpbCntMinus1;
+  UInt bitRateValueMinus1[MAX_CPB_CNT][2];
+  UInt cpbSizeValue      [MAX_CPB_CNT][2];
+  UInt cbrFlag           [MAX_CPB_CNT][2];
+};
+#endif
+#if SUPPORT_FOR_VUI
+class TComVUI
+{
+private:
+  Bool m_aspectRatioInfoPresentFlag;
+  Int  m_aspectRatioIdc;
+  Int  m_sarWidth;
+  Int  m_sarHeight;
+  Bool m_overscanInfoPresentFlag;
+  Bool m_overscanAppropriateFlag;
+  Bool m_videoSignalTypePresentFlag;
+  Int  m_videoFormat;
+  Bool m_videoFullRangeFlag;
+  Bool m_colourDescriptionPresentFlag;
+  Int  m_colourPrimaries;
+  Int  m_transferCharacteristics;
+  Int  m_matrixCoefficients;
+  Bool m_chromaLocInfoPresentFlag;
+  Int  m_chromaSampleLocTypeTopField;
+  Int  m_chromaSampleLocTypeBottomField;
+  Bool m_neutralChromaIndicationFlag;
+  Bool m_fieldSeqFlag;
+  Bool m_hrdParametersPresentFlag;
+  Bool m_bitstreamRestrictionFlag;
+  Bool m_tilesFixedStructureFlag;
+  Bool m_motionVectorsOverPicBoundariesFlag;
+  Int  m_maxBytesPerPicDenom;
+  Int  m_maxBitsPerMinCuDenom;
+  Int  m_log2MaxMvLengthHorizontal;
+  Int  m_log2MaxMvLengthVertical;
+#if BUFFERING_PERIOD_AND_TIMING_SEI
+  Bool m_timingInfoPresentFlag;
+  UInt m_numUnitsInTick;
+  UInt m_timeScale;
+  Bool m_nalHrdParametersPresentFlag;
+  Bool m_vclHrdParametersPresentFlag;
+  Bool m_subPicCpbParamsPresentFlag;
+  UInt m_tickDivisorMinus2;
+  UInt m_duCpbRemovalDelayLengthMinus1;
+  UInt m_bitRateScale;
+  UInt m_cpbSizeScale;
+  UInt m_initialCpbRemovalDelayLengthMinus1;
+  UInt m_cpbRemovalDelayLengthMinus1;
+  UInt m_dpbOutputDelayLengthMinus1;
+  UInt m_numDU;
+  HrdSubLayerInfo m_HRD[MAX_TLAYER];
+#endif
+public:
+  TComVUI()
+    :m_aspectRatioInfoPresentFlag(false)
+    ,m_aspectRatioIdc(0)
+    ,m_sarWidth(0)
+    ,m_sarHeight(0)
+    ,m_overscanInfoPresentFlag(false)
+    ,m_overscanAppropriateFlag(false)
+    ,m_videoSignalTypePresentFlag(false)
+    ,m_videoFormat(5)
+    ,m_videoFullRangeFlag(false)
+    ,m_colourDescriptionPresentFlag(false)
+    ,m_colourPrimaries(2)
+    ,m_transferCharacteristics(2)
+    ,m_matrixCoefficients(2)
+    ,m_chromaLocInfoPresentFlag(false)
+    ,m_chromaSampleLocTypeTopField(0)
+    ,m_chromaSampleLocTypeBottomField(0)
+    ,m_neutralChromaIndicationFlag(false)
+    ,m_fieldSeqFlag(false)
+    ,m_hrdParametersPresentFlag(false)
+    ,m_bitstreamRestrictionFlag(false)
+    ,m_tilesFixedStructureFlag(false)
+    ,m_motionVectorsOverPicBoundariesFlag(true)
+    ,m_maxBytesPerPicDenom(2)
+    ,m_maxBitsPerMinCuDenom(1)
+    ,m_log2MaxMvLengthHorizontal(15)
+    ,m_log2MaxMvLengthVertical(15)
+#if BUFFERING_PERIOD_AND_TIMING_SEI
+    ,m_timingInfoPresentFlag(false)
+    ,m_numUnitsInTick(1001)
+    ,m_timeScale(60000)
+    ,m_nalHrdParametersPresentFlag(0)
+    ,m_vclHrdParametersPresentFlag(0)
+    ,m_subPicCpbParamsPresentFlag(false)
+    ,m_tickDivisorMinus2(0)
+    ,m_duCpbRemovalDelayLengthMinus1(0)
+    ,m_bitRateScale(0)
+    ,m_cpbSizeScale(0)
+    ,m_initialCpbRemovalDelayLengthMinus1(0)
+    ,m_cpbRemovalDelayLengthMinus1(0)
+    ,m_dpbOutputDelayLengthMinus1(0)
+#endif
+  {}
+
+  virtual ~TComVUI() {}
+
+  Bool getAspectRatioInfoPresentFlag() { return m_aspectRatioInfoPresentFlag; }
+  Void setAspectRatioInfoPresentFlag(Bool i) { m_aspectRatioInfoPresentFlag = i; }
+
+  Int getAspectRatioIdc() { return m_aspectRatioIdc; }
+  Void setAspectRatioIdc(Int i) { m_aspectRatioIdc = i; }
+
+  Int getSarWidth() { return m_sarWidth; }
+  Void setSarWidth(Int i) { m_sarWidth = i; }
+
+  Int getSarHeight() { return m_sarHeight; }
+  Void setSarHeight(Int i) { m_sarHeight = i; }
+
+  Bool getOverscanInfoPresentFlag() { return m_overscanInfoPresentFlag; }
+  Void setOverscanInfoPresentFlag(Bool i) { m_overscanInfoPresentFlag = i; }
+
+  Bool getOverscanAppropriateFlag() { return m_overscanAppropriateFlag; }
+  Void setOverscanAppropriateFlag(Bool i) { m_overscanAppropriateFlag = i; }
+
+  Bool getVideoSignalTypePresentFlag() { return m_videoSignalTypePresentFlag; }
+  Void setVideoSignalTypePresentFlag(Bool i) { m_videoSignalTypePresentFlag = i; }
+
+  Int getVideoFormat() { return m_videoFormat; }
+  Void setVideoFormat(Int i) { m_videoFormat = i; }
+
+  Bool getVideoFullRangeFlag() { return m_videoFullRangeFlag; }
+  Void setVideoFullRangeFlag(Bool i) { m_videoFullRangeFlag = i; }
+
+  Bool getColourDescriptionPresentFlag() { return m_colourDescriptionPresentFlag; }
+  Void setColourDescriptionPresentFlag(Bool i) { m_colourDescriptionPresentFlag = i; }
+
+  Int getColourPrimaries() { return m_colourPrimaries; }
+  Void setColourPrimaries(Int i) { m_colourPrimaries = i; }
+
+  Int getTransferCharacteristics() { return m_transferCharacteristics; }
+  Void setTransferCharacteristics(Int i) { m_transferCharacteristics = i; }
+
+  Int getMatrixCoefficients() { return m_matrixCoefficients; }
+  Void setMatrixCoefficients(Int i) { m_matrixCoefficients = i; }
+
+  Bool getChromaLocInfoPresentFlag() { return m_chromaLocInfoPresentFlag; }
+  Void setChromaLocInfoPresentFlag(Bool i) { m_chromaLocInfoPresentFlag = i; }
+
+  Int getChromaSampleLocTypeTopField() { return m_chromaSampleLocTypeTopField; }
+  Void setChromaSampleLocTypeTopField(Int i) { m_chromaSampleLocTypeTopField = i; }
+
+  Int getChromaSampleLocTypeBottomField() { return m_chromaSampleLocTypeBottomField; }
+  Void setChromaSampleLocTypeBottomField(Int i) { m_chromaSampleLocTypeBottomField = i; }
+
+  Bool getNeutralChromaIndicationFlag() { return m_neutralChromaIndicationFlag; }
+  Void setNeutralChromaIndicationFlag(Bool i) { m_neutralChromaIndicationFlag = i; }
+
+  Bool getFieldSeqFlag() { return m_fieldSeqFlag; }
+  Void setFieldSeqFlag(Bool i) { m_fieldSeqFlag = i; }
+
+  Bool getHrdParametersPresentFlag() { return m_hrdParametersPresentFlag; }
+  Void setHrdParametersPresentFlag(Bool i) { m_hrdParametersPresentFlag = i; }
+
+  Bool getBitstreamRestrictionFlag() { return m_bitstreamRestrictionFlag; }
+  Void setBitstreamRestrictionFlag(Bool i) { m_bitstreamRestrictionFlag = i; }
+
+  Bool getTilesFixedStructureFlag() { return m_tilesFixedStructureFlag; }
+  Void setTilesFixedStructureFlag(Bool i) { m_tilesFixedStructureFlag = i; }
+
+  Bool getMotionVectorsOverPicBoundariesFlag() { return m_motionVectorsOverPicBoundariesFlag; }
+  Void setMotionVectorsOverPicBoundariesFlag(Bool i) { m_motionVectorsOverPicBoundariesFlag = i; }
+
+  Int getMaxBytesPerPicDenom() { return m_maxBytesPerPicDenom; }
+  Void setMaxBytesPerPicDenom(Int i) { m_maxBytesPerPicDenom = i; }
+
+  Int getMaxBitsPerMinCuDenom() { return m_maxBitsPerMinCuDenom; }
+  Void setMaxBitsPerMinCuDenom(Int i) { m_maxBitsPerMinCuDenom = i; }
+
+  Int getLog2MaxMvLengthHorizontal() { return m_log2MaxMvLengthHorizontal; }
+  Void setLog2MaxMvLengthHorizontal(Int i) { m_log2MaxMvLengthHorizontal = i; }
+
+  Int getLog2MaxMvLengthVertical() { return m_log2MaxMvLengthVertical; }
+  Void setLog2MaxMvLengthVertical(Int i) { m_log2MaxMvLengthVertical = i; }
+
+#if BUFFERING_PERIOD_AND_TIMING_SEI
+  Void setTimingInfoPresentFlag             ( Bool flag )  { m_timingInfoPresentFlag = flag;               }
+  Bool getTimingInfoPresentFlag             ( )            { return m_timingInfoPresentFlag;               }
+
+  Void setNumUnitsInTick                    ( UInt value ) { m_numUnitsInTick = value;                     }
+  UInt getNumUnitsInTick                    ( )            { return m_numUnitsInTick;                      }
+
+  Void setTimeScale                         ( UInt value ) { m_timeScale = value;                          }
+  UInt getTimeScale                         ( )            { return m_timeScale;                           }
+
+  Void setNalHrdParametersPresentFlag       ( Bool flag )  { m_nalHrdParametersPresentFlag = flag;         }
+  Bool getNalHrdParametersPresentFlag       ( )            { return m_nalHrdParametersPresentFlag;         }
+
+  Void setVclHrdParametersPresentFlag       ( Bool flag )  { m_vclHrdParametersPresentFlag = flag;         }
+  Bool getVclHrdParametersPresentFlag       ( )            { return m_vclHrdParametersPresentFlag;         }
+
+  Void setSubPicCpbParamsPresentFlag        ( Bool flag )  { m_subPicCpbParamsPresentFlag = flag;          }
+  Bool getSubPicCpbParamsPresentFlag        ( )            { return m_subPicCpbParamsPresentFlag;          }
+  
+  Void setTickDivisorMinus2                 ( UInt value ) { m_tickDivisorMinus2 = value;                  }
+  UInt getTickDivisorMinus2                 ( )            { return m_tickDivisorMinus2;                   }
+
+  Void setDuCpbRemovalDelayLengthMinus1     ( UInt value ) { m_duCpbRemovalDelayLengthMinus1 = value;      }
+  UInt getDuCpbRemovalDelayLengthMinus1     ( )            { return m_duCpbRemovalDelayLengthMinus1;       }
+
+  Void setBitRateScale                      ( UInt value ) { m_bitRateScale = value;                       }
+  UInt getBitRateScale                      ( )            { return m_bitRateScale;                        }
+
+  Void setCpbSizeScale                      ( UInt value ) { m_cpbSizeScale = value;                       }
+  UInt getCpbSizeScale                      ( )            { return m_cpbSizeScale;                        }
+
+  Void setInitialCpbRemovalDelayLengthMinus1( UInt value ) { m_initialCpbRemovalDelayLengthMinus1 = value; }
+  UInt getInitialCpbRemovalDelayLengthMinus1( )            { return m_initialCpbRemovalDelayLengthMinus1;  }
+
+  Void setCpbRemovalDelayLengthMinus1       ( UInt value ) { m_cpbRemovalDelayLengthMinus1 = value;        }
+  UInt getCpbRemovalDelayLengthMinus1       ( )            { return m_cpbRemovalDelayLengthMinus1;         }
+
+  Void setDpbOutputDelayLengthMinus1        ( UInt value ) { m_dpbOutputDelayLengthMinus1 = value;         }
+  UInt getDpbOutputDelayLengthMinus1        ( )            { return m_dpbOutputDelayLengthMinus1;          }
+
+  Void setFixedPicRateFlag       ( Int layer, Bool flag )  { m_HRD[layer].fixedPicRateFlag = flag;         }
+  Bool getFixedPicRateFlag       ( Int layer            )  { return m_HRD[layer].fixedPicRateFlag;         }
+
+  Void setPicDurationInTcMinus1  ( Int layer, UInt value ) { m_HRD[layer].picDurationInTcMinus1 = value;   }
+  UInt getPicDurationInTcMinus1  ( Int layer             ) { return m_HRD[layer].picDurationInTcMinus1;    }
+
+  Void setLowDelayHrdFlag        ( Int layer, Bool flag )  { m_HRD[layer].lowDelayHrdFlag = flag;          }
+  Bool getLowDelayHrdFlag        ( Int layer            )  { return m_HRD[layer].lowDelayHrdFlag;          }
+
+  Void setCpbCntMinus1           ( Int layer, UInt value ) { m_HRD[layer].cpbCntMinus1 = value; }
+  UInt getCpbCntMinus1           ( Int layer            )  { return m_HRD[layer].cpbCntMinus1; }
+
+  Void setBitRateValueMinus1     ( Int layer, Int cpbcnt, Int nalOrVcl, UInt value ) { m_HRD[layer].bitRateValueMinus1[cpbcnt][nalOrVcl] = value; }
+  UInt getBitRateValueMinus1     ( Int layer, Int cpbcnt, Int nalOrVcl             ) { return m_HRD[layer].bitRateValueMinus1[cpbcnt][nalOrVcl];  }
+
+  Void setCpbSizeValueMinus1     ( Int layer, Int cpbcnt, Int nalOrVcl, UInt value ) { m_HRD[layer].cpbSizeValue[cpbcnt][nalOrVcl] = value;       }
+  UInt getCpbSizeValueMinus1     ( Int layer, Int cpbcnt, Int nalOrVcl            )  { return m_HRD[layer].cpbSizeValue[cpbcnt][nalOrVcl];        }
+
+  Void setCbrFlag                ( Int layer, Int cpbcnt, Int nalOrVcl, UInt value ) { m_HRD[layer].cbrFlag[cpbcnt][nalOrVcl] = value;            }
+  Bool getCbrFlag                ( Int layer, Int cpbcnt, Int nalOrVcl             ) { return m_HRD[layer].cbrFlag[cpbcnt][nalOrVcl];             }
+
+  Void setNumDU                              ( UInt value ) { m_numDU = value;                            }
+  UInt getNumDU                              ( )            { return m_numDU;          }
+#endif
+};
+#endif
+
+/// SPS class
+class TComSPS
+{
+private:
+  Int         m_SPSId;
+#if !SPS_SYNTAX_CHANGES
+  Int         m_ProfileSpace;
+  Int         m_ProfileIdc;
+  Int         m_ReservedIndicatorFlags;
+  Int         m_LevelIdc;
+  UInt        m_ProfileCompatibility;
+#endif
+  Int         m_VPSId;
+  Int         m_chromaFormatIdc;
+
+  UInt        m_uiMaxTLayers;           // maximum number of temporal layers
+
+  // Structure
+  UInt        m_picWidthInLumaSamples;
+  UInt        m_picHeightInLumaSamples;
+  Bool        m_picCroppingFlag;
+  Int         m_picCropLeftOffset;
+  Int         m_picCropRightOffset;
+  Int         m_picCropTopOffset;
+  Int         m_picCropBottomOffset;
+  UInt        m_uiMaxCUWidth;
+  UInt        m_uiMaxCUHeight;
+  UInt        m_uiMaxCUDepth;
+  UInt        m_uiMinTrDepth;
+  UInt        m_uiMaxTrDepth;
+  TComRPSList m_RPSList;
+  Bool        m_bLongTermRefsPresent;
+  Bool        m_TMVPFlagsPresent;
+  Int         m_numReorderPics[MAX_TLAYER];
+  
+  // Tool list
+  UInt        m_uiQuadtreeTULog2MaxSize;
+  UInt        m_uiQuadtreeTULog2MinSize;
+  UInt        m_uiQuadtreeTUMaxDepthInter;
+  UInt        m_uiQuadtreeTUMaxDepthIntra;
+  Bool        m_usePCM;
+  UInt        m_pcmLog2MaxSize;
+  UInt        m_uiPCMLog2MinSize;
+  Bool        m_useAMP;
+#if !REMOVE_ALF
+  Bool        m_bUseALF;
+#endif
+#if !REMOVE_LMCHROMA
+  Bool        m_bUseLMChroma; // JL:
+#endif
+
+#if !PPS_TS_FLAG
+  Bool        m_useTransformSkip;
+  Bool        m_useTransformSkipFast;
+#endif
+
+  Bool        m_bUseLComb;
+#if !REMOVE_NSQT
+  Bool        m_useNSQT;
+#endif
+  
+  Bool        m_restrictedRefPicListsFlag;
+  Bool        m_listsModificationPresentFlag;
+
+  // Parameter
+#if !SPS_AMVP_CLEANUP
+  AMVP_MODE   m_aeAMVPMode[MAX_CU_DEPTH];
+#endif
+  UInt        m_uiBitDepth;
+  UInt        m_uiBitIncrement;
+  Int         m_qpBDOffsetY;
+  Int         m_qpBDOffsetC;
+
+  Bool        m_useLossless;
+
+  UInt        m_uiPCMBitDepthLuma;
+  UInt        m_uiPCMBitDepthChroma;
+  Bool        m_bPCMFilterDisableFlag;
+
+  UInt        m_uiBitsForPOC;
+#if LTRP_IN_SPS
+  UInt        m_numLongTermRefPicSPS;
+  UInt        m_ltRefPicPocLsbSps[33];
+  Bool        m_usedByCurrPicLtSPSFlag[33];
+#endif
+  // Max physical transform size
+  UInt        m_uiMaxTrSize;
+  
+  Int m_iAMPAcc[MAX_CU_DEPTH];
+#if !MOVE_LOOP_FILTER_SLICES_FLAG
+  Bool        m_bLFCrossSliceBoundaryFlag;
+#endif
+  Bool        m_bUseSAO; 
+
+  Bool        m_bTemporalIdNestingFlag; // temporal_id_nesting_flag
+
+  Bool        m_scalingListEnabledFlag;
+  Bool        m_scalingListPresentFlag;
+  TComScalingList*     m_scalingList;   //!< ScalingList class pointer
+  UInt        m_uiMaxDecPicBuffering[MAX_TLAYER]; 
+  UInt        m_uiMaxLatencyIncrease[MAX_TLAYER];
+
+  Bool        m_useDF;
+
+#if SUPPORT_FOR_VUI
+  Bool        m_vuiParametersPresentFlag;
+  TComVUI     m_vuiParameters;
+#endif
+
+  static const Int   m_cropUnitX[MAX_CHROMA_FORMAT_IDC+1];
+  static const Int   m_cropUnitY[MAX_CHROMA_FORMAT_IDC+1];
+#if SPS_SYNTAX_CHANGES
+  TComPTL     m_pcPTL;
+#endif
+#if SVC_EXTENSION
+  UInt m_layerId;
+#endif
+public:
+  TComSPS();
+  virtual ~TComSPS();
+
+  Int  getVPSId       ()         { return m_VPSId;          }
+  Void setVPSId       (Int i)    { m_VPSId = i;             }
+  Int  getSPSId       ()         { return m_SPSId;          }
+  Void setSPSId       (Int i)    { m_SPSId = i;             }
+#if !SPS_SYNTAX_CHANGES
+  Int  getProfileSpace  ()       { return m_ProfileSpace;   }
+  Void setProfileSpace  (Int i)  { m_ProfileSpace = i;      }
+  Int  getProfileIdc  ()         { return m_ProfileIdc;     }
+  Void setProfileIdc  (Int i)    { m_ProfileIdc = i; if (m_ProfileSpace == 0) m_ProfileCompatibility |= (1 << (i - 1));    }
+  Int  getRsvdIndFlags  ()       { return m_ReservedIndicatorFlags;     }
+  Void setRsvdIndFlags  (Int i)  { m_ReservedIndicatorFlags = i;        }
+  Int  getLevelIdc    ()         { return m_LevelIdc;       }
+  Void setLevelIdc    (Int i)    { m_LevelIdc = i;          }
+  UInt getProfileCompat ()       { return m_ProfileCompatibility;       }
+  Void setProfileCompat (UInt i) { m_ProfileCompatibility = i; if (m_ProfileIdc != 0 && m_ProfileSpace == 0) m_ProfileCompatibility |= (1 << (m_ProfileIdc - 1));          }
+#endif
+  Int  getChromaFormatIdc ()         { return m_chromaFormatIdc;       }
+  Void setChromaFormatIdc (Int i)    { m_chromaFormatIdc = i;          }
+
+  static Int getCropUnitX (Int chromaFormatIdc) { assert (chromaFormatIdc > 0 && chromaFormatIdc <= MAX_CHROMA_FORMAT_IDC); return m_cropUnitX[chromaFormatIdc];      }
+  static Int getCropUnitY (Int chromaFormatIdc) { assert (chromaFormatIdc > 0 && chromaFormatIdc <= MAX_CHROMA_FORMAT_IDC); return m_cropUnitY[chromaFormatIdc];      }
+  
+  // structure
+  Void setPicWidthInLumaSamples       ( UInt u ) { m_picWidthInLumaSamples = u;        }
+  UInt getPicWidthInLumaSamples       ()         { return  m_picWidthInLumaSamples;    }
+  Void setPicHeightInLumaSamples      ( UInt u ) { m_picHeightInLumaSamples = u;       }
+  UInt getPicHeightInLumaSamples      ()         { return  m_picHeightInLumaSamples;   }
+
+  Bool getPicCroppingFlag() const          { return m_picCroppingFlag; }
+  Void setPicCroppingFlag(Bool val)        { m_picCroppingFlag = val; }
+  Int  getPicCropLeftOffset() const        { return m_picCropLeftOffset; }
+  Void setPicCropLeftOffset(Int val)       { m_picCropLeftOffset = val; }
+  Int  getPicCropRightOffset() const       { return m_picCropRightOffset; }
+  Void setPicCropRightOffset(Int val)      { m_picCropRightOffset = val; }
+  Int  getPicCropTopOffset() const         { return m_picCropTopOffset; }
+  Void setPicCropTopOffset(Int val)        { m_picCropTopOffset = val; }
+  Int  getPicCropBottomOffset() const      { return m_picCropBottomOffset; }
+  Void setPicCropBottomOffset(Int val)     { m_picCropBottomOffset = val; }
+#if LTRP_IN_SPS
+  UInt  getNumLongTermRefPicSPS()             { return m_numLongTermRefPicSPS; }
+  Void  setNumLongTermRefPicSPS(UInt val)     { m_numLongTermRefPicSPS = val; }
+
+  UInt  getLtRefPicPocLsbSps(UInt index)             { return m_ltRefPicPocLsbSps[index]; }
+  Void  setLtRefPicPocLsbSps(UInt index, UInt val)     { m_ltRefPicPocLsbSps[index] = val; }
+
+  Bool getUsedByCurrPicLtSPSFlag(Int i)        {return m_usedByCurrPicLtSPSFlag[i];}
+  Void setUsedByCurrPicLtSPSFlag(Int i, Bool x)      { m_usedByCurrPicLtSPSFlag[i] = x;}
+#endif
+  Void setMaxCUWidth  ( UInt u ) { m_uiMaxCUWidth = u;      }
+  UInt getMaxCUWidth  ()         { return  m_uiMaxCUWidth;  }
+  Void setMaxCUHeight ( UInt u ) { m_uiMaxCUHeight = u;     }
+  UInt getMaxCUHeight ()         { return  m_uiMaxCUHeight; }
+  Void setMaxCUDepth  ( UInt u ) { m_uiMaxCUDepth = u;      }
+  UInt getMaxCUDepth  ()         { return  m_uiMaxCUDepth;  }
+  Void setUsePCM      ( Bool b ) { m_usePCM = b;           }
+  Bool getUsePCM      ()         { return m_usePCM;        }
+  Void setPCMLog2MaxSize  ( UInt u ) { m_pcmLog2MaxSize = u;      }
+  UInt getPCMLog2MaxSize  ()         { return  m_pcmLog2MaxSize;  }
+  Void setPCMLog2MinSize  ( UInt u ) { m_uiPCMLog2MinSize = u;      }
+  UInt getPCMLog2MinSize  ()         { return  m_uiPCMLog2MinSize;  }
+  Void setBitsForPOC  ( UInt u ) { m_uiBitsForPOC = u;      }
+  UInt getBitsForPOC  ()         { return m_uiBitsForPOC;   }
+  Bool getUseAMP() { return m_useAMP; }
+  Void setUseAMP( Bool b ) { m_useAMP = b; }
+  Void setMinTrDepth  ( UInt u ) { m_uiMinTrDepth = u;      }
+  UInt getMinTrDepth  ()         { return  m_uiMinTrDepth;  }
+  Void setMaxTrDepth  ( UInt u ) { m_uiMaxTrDepth = u;      }
+  UInt getMaxTrDepth  ()         { return  m_uiMaxTrDepth;  }
+  Void setQuadtreeTULog2MaxSize( UInt u ) { m_uiQuadtreeTULog2MaxSize = u;    }
+  UInt getQuadtreeTULog2MaxSize()         { return m_uiQuadtreeTULog2MaxSize; }
+  Void setQuadtreeTULog2MinSize( UInt u ) { m_uiQuadtreeTULog2MinSize = u;    }
+  UInt getQuadtreeTULog2MinSize()         { return m_uiQuadtreeTULog2MinSize; }
+  Void setQuadtreeTUMaxDepthInter( UInt u ) { m_uiQuadtreeTUMaxDepthInter = u;    }
+  Void setQuadtreeTUMaxDepthIntra( UInt u ) { m_uiQuadtreeTUMaxDepthIntra = u;    }
+  UInt getQuadtreeTUMaxDepthInter()         { return m_uiQuadtreeTUMaxDepthInter; }
+  UInt getQuadtreeTUMaxDepthIntra()         { return m_uiQuadtreeTUMaxDepthIntra; }
+  Void setNumReorderPics(Int i, UInt tlayer)              { m_numReorderPics[tlayer] = i;    }
+  Int  getNumReorderPics(UInt tlayer)                     { return m_numReorderPics[tlayer]; }
+  Void         createRPSList( Int numRPS );
+  TComRPSList* getRPSList()                      { return &m_RPSList;          }
+  Bool      getLongTermRefsPresent()         { return m_bLongTermRefsPresent; }
+  Void      setLongTermRefsPresent(Bool b)   { m_bLongTermRefsPresent=b;      }
+  Bool      getTMVPFlagsPresent()         { return m_TMVPFlagsPresent; }
+  Void      setTMVPFlagsPresent(Bool b)   { m_TMVPFlagsPresent=b;      }  
+  // physical transform
+  Void setMaxTrSize   ( UInt u ) { m_uiMaxTrSize = u;       }
+  UInt getMaxTrSize   ()         { return  m_uiMaxTrSize;   }
+  
+  // Tool list
+#if !REMOVE_ALF
+  Bool getUseALF      ()         { return m_bUseALF;        }
+  Void setUseALF      ( Bool b ) { m_bUseALF  = b;          }
+#endif
+  Void setUseLComb    (Bool b)   { m_bUseLComb = b;         }
+  Bool getUseLComb    ()         { return m_bUseLComb;      }
+#if !REMOVE_LMCHROMA
+  Bool getUseLMChroma ()         { return m_bUseLMChroma;        }
+  Void setUseLMChroma ( Bool b ) { m_bUseLMChroma  = b;          }
+#endif
+
+#if !PPS_TS_FLAG
+  Bool getUseTransformSkip       ()         { return m_useTransformSkip;     }
+  Void setUseTransformSkip       ( Bool b ) { m_useTransformSkip  = b;       }
+  Bool getUseTransformSkipFast   ()         { return m_useTransformSkipFast; }
+  Void setUseTransformSkipFast   ( Bool b ) { m_useTransformSkipFast  = b;   }
+#endif
+
+  Bool getUseLossless ()         { return m_useLossless; }
+  Void setUseLossless ( Bool b ) { m_useLossless  = b; }
+#if !REMOVE_NSQT
+  Bool getUseNSQT() { return m_useNSQT; }
+  Void setUseNSQT( Bool b ) { m_useNSQT = b; }
+#endif
+  
+  Bool getRestrictedRefPicListsFlag    ()          { return m_restrictedRefPicListsFlag;   }
+  Void setRestrictedRefPicListsFlag    ( Bool b )  { m_restrictedRefPicListsFlag = b;      }
+  Bool getListsModificationPresentFlag ()          { return m_listsModificationPresentFlag; }
+  Void setListsModificationPresentFlag ( Bool b )  { m_listsModificationPresentFlag = b;    }
+
+#if !SPS_AMVP_CLEANUP
+  // AMVP mode (for each depth)
+  AMVP_MODE getAMVPMode ( UInt uiDepth ) { assert(uiDepth < g_uiMaxCUDepth);  return m_aeAMVPMode[uiDepth]; }
+  Void      setAMVPMode ( UInt uiDepth, AMVP_MODE eMode) { assert(uiDepth < g_uiMaxCUDepth);  m_aeAMVPMode[uiDepth] = eMode; }
+#endif
+
+  // AMP accuracy
+  Int       getAMPAcc   ( UInt uiDepth ) { return m_iAMPAcc[uiDepth]; }
+  Void      setAMPAcc   ( UInt uiDepth, Int iAccu ) { assert( uiDepth < g_uiMaxCUDepth);  m_iAMPAcc[uiDepth] = iAccu; }
+
+  // Bit-depth
+  UInt      getBitDepth     ()         { return m_uiBitDepth;     }
+  Void      setBitDepth     ( UInt u ) { m_uiBitDepth = u;        }
+  UInt      getBitIncrement ()         { return m_uiBitIncrement; }
+  Void      setBitIncrement ( UInt u ) { m_uiBitIncrement = u;    }
+  Int       getQpBDOffsetY  ()             { return m_qpBDOffsetY;   }
+  Void      setQpBDOffsetY  ( Int value  ) { m_qpBDOffsetY = value;  }
+  Int       getQpBDOffsetC  ()             { return m_qpBDOffsetC;   }
+  Void      setQpBDOffsetC  ( Int value  ) { m_qpBDOffsetC = value;  }
+#if !MOVE_LOOP_FILTER_SLICES_FLAG
+  Void      setLFCrossSliceBoundaryFlag     ( Bool   bValue  )    { m_bLFCrossSliceBoundaryFlag = bValue; }
+  Bool      getLFCrossSliceBoundaryFlag     ()                    { return m_bLFCrossSliceBoundaryFlag;   } 
+#endif
+  Void setUseSAO                  (Bool bVal)  {m_bUseSAO = bVal;}
+  Bool getUseSAO                  ()           {return m_bUseSAO;}
+
+  UInt      getMaxTLayers()                           { return m_uiMaxTLayers; }
+  Void      setMaxTLayers( UInt uiMaxTLayers )        { assert( uiMaxTLayers <= MAX_TLAYER ); m_uiMaxTLayers = uiMaxTLayers; }
+
+  Bool      getTemporalIdNestingFlag()                { return m_bTemporalIdNestingFlag; }
+  Void      setTemporalIdNestingFlag( Bool bValue )   { m_bTemporalIdNestingFlag = bValue; }
+  UInt      getPCMBitDepthLuma     ()         { return m_uiPCMBitDepthLuma;     }
+  Void      setPCMBitDepthLuma     ( UInt u ) { m_uiPCMBitDepthLuma = u;        }
+  UInt      getPCMBitDepthChroma   ()         { return m_uiPCMBitDepthChroma;   }
+  Void      setPCMBitDepthChroma   ( UInt u ) { m_uiPCMBitDepthChroma = u;      }
+  Void      setPCMFilterDisableFlag     ( Bool   bValue  )    { m_bPCMFilterDisableFlag = bValue; }
+  Bool      getPCMFilterDisableFlag     ()                    { return m_bPCMFilterDisableFlag;   } 
+
+  Bool getScalingListFlag       ()         { return m_scalingListEnabledFlag;     }
+  Void setScalingListFlag       ( Bool b ) { m_scalingListEnabledFlag  = b;       }
+  Bool getScalingListPresentFlag()         { return m_scalingListPresentFlag;     }
+  Void setScalingListPresentFlag( Bool b ) { m_scalingListPresentFlag  = b;       }
+  Void setScalingList      ( TComScalingList *scalingList);
+  TComScalingList* getScalingList ()       { return m_scalingList; }               //!< get ScalingList class pointer in SPS
+  UInt getMaxDecPicBuffering  (UInt tlayer)            { return m_uiMaxDecPicBuffering[tlayer]; }
+  Void setMaxDecPicBuffering  ( UInt ui, UInt tlayer ) { m_uiMaxDecPicBuffering[tlayer] = ui;   }
+  UInt getMaxLatencyIncrease  (UInt tlayer)            { return m_uiMaxLatencyIncrease[tlayer];   }
+  Void setMaxLatencyIncrease  ( UInt ui , UInt tlayer) { m_uiMaxLatencyIncrease[tlayer] = ui;      }
+
+#if SUPPORT_FOR_VUI
+  Bool getVuiParametersPresentFlag() { return m_vuiParametersPresentFlag; }
+  Void setVuiParametersPresentFlag(Bool b) { m_vuiParametersPresentFlag = b; }
+  TComVUI* getVuiParameters() { return &m_vuiParameters; }
+#if BUFFERING_PERIOD_AND_TIMING_SEI
+  Void setHrdParameters( UInt frameRate, UInt numDU, UInt bitRate, Bool randomAccess );
+#endif
+#endif
+
+#if SPS_SYNTAX_CHANGES
+  TComPTL* getPTL()     { return &m_pcPTL; }
+#endif
+#if SVC_EXTENSION
+  Void     setLayerId(UInt layerId) { m_layerId = layerId; }
+  UInt     getLayerId() { return m_layerId; }
+#endif
+};
+
+/// Reference Picture Lists class
+class TComRefPicListModification
+{
+private:
+  UInt      m_bRefPicListModificationFlagL0;  
+  UInt      m_bRefPicListModificationFlagL1;  
+  UInt      m_RefPicSetIdxL0[32];
+  UInt      m_RefPicSetIdxL1[32];
+    
+public:
+  TComRefPicListModification();
+  virtual ~TComRefPicListModification();
+  
+  Void  create                    ();
+  Void  destroy                   ();
+
+  Bool       getRefPicListModificationFlagL0() { return m_bRefPicListModificationFlagL0; }
+  Void       setRefPicListModificationFlagL0(Bool flag) { m_bRefPicListModificationFlagL0 = flag; }
+  Bool       getRefPicListModificationFlagL1() { return m_bRefPicListModificationFlagL1; }
+  Void       setRefPicListModificationFlagL1(Bool flag) { m_bRefPicListModificationFlagL1 = flag; }
+  Void       setRefPicSetIdxL0(UInt idx, UInt refPicSetIdx) { m_RefPicSetIdxL0[idx] = refPicSetIdx; }
+  UInt       getRefPicSetIdxL0(UInt idx) { return m_RefPicSetIdxL0[idx]; }
+  Void       setRefPicSetIdxL1(UInt idx, UInt refPicSetIdx) { m_RefPicSetIdxL1[idx] = refPicSetIdx; }
+  UInt       getRefPicSetIdxL1(UInt idx) { return m_RefPicSetIdxL1[idx]; }
+};
+
+/// PPS class
+class TComPPS
+{
+private:
+  Int         m_PPSId;                    // pic_parameter_set_id
+  Int         m_SPSId;                    // seq_parameter_set_id
+  Int         m_picInitQPMinus26;
+  Bool        m_useDQP;
+  Bool        m_bConstrainedIntraPred;    // constrained_intra_pred_flag
+#if CHROMA_QP_EXTENSION
+  Bool        m_bSliceChromaQpFlag;       // slicelevel_chroma_qp_flag
+#endif
+
+  // access channel
+  TComSPS*    m_pcSPS;
+  UInt        m_uiMaxCuDQPDepth;
+  UInt        m_uiMinCuDQPSize;
+
+  Int         m_chromaCbQpOffset;
+  Int         m_chromaCrQpOffset;
+
+  UInt        m_numRefIdxL0DefaultActive;
+  UInt        m_numRefIdxL1DefaultActive;
+
+#if !REMOVE_FGS
+  Int         m_iSliceGranularity;
+#endif
+  
+  Bool        m_bUseWeightPred;           // Use of Weighting Prediction (P_SLICE)
+  Bool        m_useWeightedBiPred;        // Use of Weighting Bi-Prediction (B_SLICE)
+  Bool        m_OutputFlagPresentFlag;   // Indicates the presence of output_flag in slice header
+
+  Bool        m_TransquantBypassEnableFlag; // Indicates presence of cu_transquant_bypass_flag in CUs.
+#if PPS_TS_FLAG
+  Bool        m_useTransformSkip;
+#endif
+#if !TILES_WPP_ENTROPYSLICES_FLAGS
+#if DEPENDENT_SLICES
+  Bool        m_bDependentSliceEnabledFlag;   // Indicates the presence of dependent_slices_flag in slice header
+  Bool        m_bCabacIndependentFlag;   // Indicates the presence of dependent_slices_flag in slice header
+#endif
+  UInt        m_tilesOrEntropyCodingSyncIdc;
+#else
+  Bool        m_dependentSliceEnabledFlag;     //!< Indicates the presence of dependent slices
+  Bool        m_tilesEnabledFlag;              //!< Indicates the presence of tiles
+  Bool        m_entropyCodingSyncEnabledFlag;  //!< Indicates the presence of wavefronts
+  Bool        m_entropySliceEnabledFlag;       //!< Indicates the presence of entropy slices
+#endif
+
+  Bool     m_loopFilterAcrossTilesEnabledFlag;
+  Int      m_uniformSpacingFlag;
+  Int      m_iNumColumnsMinus1;
+  UInt*    m_puiColumnWidth;
+  Int      m_iNumRowsMinus1;
+  UInt*    m_puiRowHeight;
+
+  Int      m_iNumSubstreams;
+
+  Int      m_signHideFlag;
+
+  Bool     m_cabacInitPresentFlag;
+  UInt     m_encCABACTableIdx;           // Used to transmit table selection across slices
+
+#if SLICE_HEADER_EXTENSION
+  Bool     m_sliceHeaderExtensionPresentFlag;
+#endif
+#if MOVE_LOOP_FILTER_SLICES_FLAG
+  Bool        m_loopFilterAcrossSlicesEnabledFlag;
+#endif
+  Bool     m_deblockingFilterControlPresentFlag;
+  Bool     m_deblockingFilterOverrideEnabledFlag;
+  Bool     m_picDisableDeblockingFilterFlag;
+  Int      m_deblockingFilterBetaOffsetDiv2;    //< beta offset for deblocking filter
+  Int      m_deblockingFilterTcOffsetDiv2;      //< tc offset for deblocking filter
+  Bool     m_scalingListPresentFlag;
+  TComScalingList*     m_scalingList;   //!< ScalingList class pointer
+  UInt m_log2ParallelMergeLevelMinus2;
+public:
+  TComPPS();
+  virtual ~TComPPS();
+  
+  Int       getPPSId ()      { return m_PPSId; }
+  Void      setPPSId (Int i) { m_PPSId = i; }
+  Int       getSPSId ()      { return m_SPSId; }
+  Void      setSPSId (Int i) { m_SPSId = i; }
+  
+#if !REMOVE_FGS
+  Int       getSliceGranularity()        { return m_iSliceGranularity; }
+  Void      setSliceGranularity( Int i ) { m_iSliceGranularity = i;    }
+#endif
+  Int       getPicInitQPMinus26 ()         { return  m_picInitQPMinus26; }
+  Void      setPicInitQPMinus26 ( Int i )  { m_picInitQPMinus26 = i;     }
+  Bool      getUseDQP ()                   { return m_useDQP;        }
+  Void      setUseDQP ( Bool b )           { m_useDQP   = b;         }
+  Bool      getConstrainedIntraPred ()         { return  m_bConstrainedIntraPred; }
+  Void      setConstrainedIntraPred ( Bool b ) { m_bConstrainedIntraPred = b;     }
+#if CHROMA_QP_EXTENSION
+  Bool      getSliceChromaQpFlag ()         { return  m_bSliceChromaQpFlag; }
+  Void      setSliceChromaQpFlag ( Bool b ) { m_bSliceChromaQpFlag = b;     }
+#endif
+
+  Void      setSPS              ( TComSPS* pcSPS ) { m_pcSPS = pcSPS; }
+  TComSPS*  getSPS              ()         { return m_pcSPS;          }
+  Void      setMaxCuDQPDepth    ( UInt u ) { m_uiMaxCuDQPDepth = u;   }
+  UInt      getMaxCuDQPDepth    ()         { return m_uiMaxCuDQPDepth;}
+  Void      setMinCuDQPSize     ( UInt u ) { m_uiMinCuDQPSize = u;    }
+  UInt      getMinCuDQPSize     ()         { return m_uiMinCuDQPSize; }
+
+  Void      setChromaCbQpOffset( Int i ) { m_chromaCbQpOffset = i;    }
+  Int       getChromaCbQpOffset()        { return m_chromaCbQpOffset; }
+  Void      setChromaCrQpOffset( Int i ) { m_chromaCrQpOffset = i;    }
+  Int       getChromaCrQpOffset()        { return m_chromaCrQpOffset; }
+
+  Void      setNumRefIdxL0DefaultActive(UInt ui)    { m_numRefIdxL0DefaultActive=ui;     }
+  UInt      getNumRefIdxL0DefaultActive()           { return m_numRefIdxL0DefaultActive; }
+  Void      setNumRefIdxL1DefaultActive(UInt ui)    { m_numRefIdxL1DefaultActive=ui;     }
+  UInt      getNumRefIdxL1DefaultActive()           { return m_numRefIdxL1DefaultActive; }
+
+  Bool getUseWP                     ()          { return m_bUseWeightPred;  }
+  Bool getWPBiPred                  ()          { return m_useWeightedBiPred;     }
+  Void setUseWP                     ( Bool b )  { m_bUseWeightPred = b;     }
+  Void setWPBiPred                  ( Bool b )  { m_useWeightedBiPred = b;  }
+  Void      setOutputFlagPresentFlag( Bool b )  { m_OutputFlagPresentFlag = b;    }
+  Bool      getOutputFlagPresentFlag()          { return m_OutputFlagPresentFlag; }
+#if !TILES_WPP_ENTROPYSLICES_FLAGS
+#if DEPENDENT_SLICES
+  Void      setDependentSliceEnabledFlag( Bool b )  { m_bDependentSliceEnabledFlag = b;    }
+  Bool      getDependentSliceEnabledFlag()          { return m_bDependentSliceEnabledFlag; }
+  Void      setCabacIndependentFlag( Bool b )  { m_bCabacIndependentFlag = b;    }
+  Bool      getCabacIndependentFlag()          { return m_bCabacIndependentFlag; }
+#endif
+#endif
+  Void      setTransquantBypassEnableFlag( Bool b ) { m_TransquantBypassEnableFlag = b; }
+  Bool      getTransquantBypassEnableFlag()         { return m_TransquantBypassEnableFlag; }
+
+#if PPS_TS_FLAG
+  Bool      getUseTransformSkip       ()         { return m_useTransformSkip;     }
+  Void      setUseTransformSkip       ( Bool b ) { m_useTransformSkip  = b;       }
+#endif
+
+  Void    setLoopFilterAcrossTilesEnabledFlag  (Bool b)    { m_loopFilterAcrossTilesEnabledFlag = b; }
+  Bool    getLoopFilterAcrossTilesEnabledFlag  ()          { return m_loopFilterAcrossTilesEnabledFlag;   }
+#if TILES_WPP_ENTROPYSLICES_FLAGS
+  Bool    getDependentSliceEnabledFlag() const             { return m_dependentSliceEnabledFlag; }
+  Void    setDependentSliceEnabledFlag(Bool val)           { m_dependentSliceEnabledFlag = val; }
+  Bool    getTilesEnabledFlag() const                      { return m_tilesEnabledFlag; }
+  Void    setTilesEnabledFlag(Bool val)                    { m_tilesEnabledFlag = val; }
+  Bool    getEntropyCodingSyncEnabledFlag() const          { return m_entropyCodingSyncEnabledFlag; }
+  Void    setEntropyCodingSyncEnabledFlag(Bool val)        { m_entropyCodingSyncEnabledFlag = val; }
+  Bool    getEntropySliceEnabledFlag() const               { return m_entropySliceEnabledFlag; }
+  Void    setEntropySliceEnabledFlag(Bool val)             { m_entropySliceEnabledFlag = val; }
+#else
+  UInt     getTilesOrEntropyCodingSyncIdc   ()                  { return m_tilesOrEntropyCodingSyncIdc;   }
+  Void     setTilesOrEntropyCodingSyncIdc   ( UInt val )        { m_tilesOrEntropyCodingSyncIdc = val;    }
+#endif
+  Void     setUniformSpacingFlag            ( Bool b )          { m_uniformSpacingFlag = b; }
+  Bool     getUniformSpacingFlag            ()                  { return m_uniformSpacingFlag; }
+  Void     setNumColumnsMinus1              ( Int i )           { m_iNumColumnsMinus1 = i; }
+  Int      getNumColumnsMinus1              ()                  { return m_iNumColumnsMinus1; }
+  Void     setColumnWidth ( UInt* columnWidth )
+  {
+    if( m_uniformSpacingFlag == 0 && m_iNumColumnsMinus1 > 0 )
+    {
+      m_puiColumnWidth = new UInt[ m_iNumColumnsMinus1 ];
+
+      for(Int i=0; i<m_iNumColumnsMinus1; i++)
+      {
+        m_puiColumnWidth[i] = columnWidth[i];
+      }
+    }
+  }
+  UInt     getColumnWidth  (UInt columnIdx) { return *( m_puiColumnWidth + columnIdx ); }
+  Void     setNumRowsMinus1( Int i )        { m_iNumRowsMinus1 = i; }
+  Int      getNumRowsMinus1()               { return m_iNumRowsMinus1; }
+  Void     setRowHeight    ( UInt* rowHeight )
+  {
+    if( m_uniformSpacingFlag == 0 && m_iNumRowsMinus1 > 0 )
+    {
+      m_puiRowHeight = new UInt[ m_iNumRowsMinus1 ];
+
+      for(Int i=0; i<m_iNumRowsMinus1; i++)
+      {
+        m_puiRowHeight[i] = rowHeight[i];
+      }
+    }
+  }
+  UInt     getRowHeight           (UInt rowIdx)    { return *( m_puiRowHeight + rowIdx ); }
+  Void     setNumSubstreams(Int iNumSubstreams)               { m_iNumSubstreams = iNumSubstreams; }
+  Int      getNumSubstreams()                                 { return m_iNumSubstreams; }
+
+  Void      setSignHideFlag( Int signHideFlag ) { m_signHideFlag = signHideFlag; }
+  Int       getSignHideFlag()                    { return m_signHideFlag; }
+
+  Void     setCabacInitPresentFlag( Bool flag )     { m_cabacInitPresentFlag = flag;    }
+  Void     setEncCABACTableIdx( Int idx )           { m_encCABACTableIdx = idx;         }
+  Bool     getCabacInitPresentFlag()                { return m_cabacInitPresentFlag;    }
+  UInt     getEncCABACTableIdx()                    { return m_encCABACTableIdx;        }
+  Void     setDeblockingFilterControlPresentFlag( Bool val )  { m_deblockingFilterControlPresentFlag = val; }
+  Bool     getDeblockingFilterControlPresentFlag()            { return m_deblockingFilterControlPresentFlag; }
+  Void     setDeblockingFilterOverrideEnabledFlag( Bool val ) { m_deblockingFilterOverrideEnabledFlag = val; }
+  Bool     getDeblockingFilterOverrideEnabledFlag()           { return m_deblockingFilterOverrideEnabledFlag; }
+  Void     setPicDisableDeblockingFilterFlag(Bool val)        { m_picDisableDeblockingFilterFlag = val; }       //!< set offset for deblocking filter disabled
+  Bool     getPicDisableDeblockingFilterFlag()                { return m_picDisableDeblockingFilterFlag; }      //!< get offset for deblocking filter disabled
+  Void     setDeblockingFilterBetaOffsetDiv2(Int val)         { m_deblockingFilterBetaOffsetDiv2 = val; }       //!< set beta offset for deblocking filter
+  Int      getDeblockingFilterBetaOffsetDiv2()                { return m_deblockingFilterBetaOffsetDiv2; }      //!< get beta offset for deblocking filter
+  Void     setDeblockingFilterTcOffsetDiv2(Int val)           { m_deblockingFilterTcOffsetDiv2 = val; }               //!< set tc offset for deblocking filter
+  Int      getDeblockingFilterTcOffsetDiv2()                  { return m_deblockingFilterTcOffsetDiv2; }              //!< get tc offset for deblocking filter
+  Bool     getScalingListPresentFlag()         { return m_scalingListPresentFlag;     }
+  Void     setScalingListPresentFlag( Bool b ) { m_scalingListPresentFlag  = b;       }
+  Void     setScalingList      ( TComScalingList *scalingList);
+  TComScalingList* getScalingList ()          { return m_scalingList; }         //!< get ScalingList class pointer in PPS
+  UInt getLog2ParallelMergeLevelMinus2      ()                    { return m_log2ParallelMergeLevelMinus2; }
+  Void setLog2ParallelMergeLevelMinus2      (UInt mrgLevel)       { m_log2ParallelMergeLevelMinus2 = mrgLevel; }
+#if MOVE_LOOP_FILTER_SLICES_FLAG
+  Void      setLoopFilterAcrossSlicesEnabledFlag ( Bool   bValue  )    { m_loopFilterAcrossSlicesEnabledFlag = bValue; }
+  Bool      getLoopFilterAcrossSlicesEnabledFlag ()                    { return m_loopFilterAcrossSlicesEnabledFlag;   } 
+#endif
+#if SLICE_HEADER_EXTENSION
+  Bool getSliceHeaderExtensionPresentFlag   ()                    { return m_sliceHeaderExtensionPresentFlag; }
+  Void setSliceHeaderExtensionPresentFlag   (Bool val)            { m_sliceHeaderExtensionPresentFlag = val; }
+#endif
+};
+
+#if !REMOVE_APS
+/// APS class
+class TComAPS
+{
+public:
+  TComAPS();
+  virtual ~TComAPS();
+
+  Void      setAPSID      (Int iID)   {m_apsID = iID;            }  //!< set APS ID 
+  Int       getAPSID      ()          {return m_apsID;           }  //!< get APS ID
+#if !REMOVE_ALF
+  ALFParam** getAlfParam  ()                       { return m_alfParam;}
+  Bool       getAlfEnabled(Int compIdx)            { return (m_alfParam[compIdx] == NULL)?(false):(m_alfParam[compIdx]->alf_flag ==1);}
+  Void       setAlfEnabled(Bool bVal, Int compIdx) { m_alfParam[compIdx]->alf_flag= (bVal?1:0); }  //!< set ALF enabled/disabled in APS
+#endif
+  SAOParam* getSaoParam   ()          {return m_pSaoParam;       }  //!< get SAO parameters in APS
+
+  Void      createSaoParam();   //!< create SAO parameter object
+  Void      destroySaoParam();  //!< destroy SAO parameter object
+
+#if !REMOVE_ALF
+  Void      createAlfParam();   //!< create ALF parameter object
+  Void      destroyAlfParam();  //!< destroy ALF parameter object
+#endif
+private:
+  Int         m_apsID;        //!< APS ID
+  SAOParam*   m_pSaoParam;    //!< SAO parameter object pointer
+#if !REMOVE_ALF
+  ALFParam*   m_alfParam[3];
+#endif
+public:
+  TComAPS& operator= (const TComAPS& src);  //!< "=" operator for APS object
+};
+#endif
+
+typedef struct {
+  // Explicit weighted prediction parameters parsed in slice header,
+  // or Implicit weighted prediction parameters (8 bits depth values).
+  Bool        bPresentFlag;
+  UInt        uiLog2WeightDenom;
+  Int         iWeight;
+  Int         iOffset;
+
+  // Weighted prediction scaling values built from above parameters (bitdepth scaled):
+  Int         w, o, offset, shift, round;
+} wpScalingParam;
+
+typedef struct {
+  Int64 iAC;
+  Int64 iDC;
+} wpACDCParam;
+
+/// slice header class
+class TComSlice
+{
+  
+private:
+  //  Bitstream writing
+#if !REMOVE_APS
+  Int         m_iAPSId; //!< APS ID in slice header
+#endif
+#if !REMOVE_ALF
+  Bool       m_alfEnabledFlag[3];
+#endif
+  bool       m_saoEnabledFlag;
+#if SAO_TYPE_SHARING
+  bool       m_saoEnabledFlagChroma;      ///< SAO Cb&Cr enabled flag
+#else
+  bool       m_saoEnabledFlagCb;      ///< SAO Cb enabled flag
+  bool       m_saoEnabledFlagCr;      ///< SAO Cr enabled flag
+#endif
+  Int         m_iPPSId;               ///< picture parameter set ID
+  Bool        m_PicOutputFlag;        ///< pic_output_flag 
+  Int         m_iPOC;
+  Int         m_iLastIDR;
+#if PREVREFPIC_DEFN 
+  static Int  m_prevPOC[MAX_TLAYER];
+#else
+  static Int  m_prevPOC;
+#endif
+  TComReferencePictureSet *m_pcRPS;
+  TComReferencePictureSet m_LocalRPS;
+  Int         m_iBDidx; 
+  Int         m_iCombinationBDidx;
+  Bool        m_bCombineWithReferenceFlag;
+  TComRefPicListModification m_RefPicListModification;
+  NalUnitType m_eNalUnitType;         ///< Nal unit type for the slice
+  SliceType   m_eSliceType;
+  Int         m_iSliceQp;
+#if SLICEHEADER_SYNTAX_FIX
+  Bool        m_dependentSliceFlag;
+#endif
+#if ADAPTIVE_QP_SELECTION
+  Int         m_iSliceQpBase;
+#endif
+  Bool        m_deblockingFilterDisable;
+  Bool        m_deblockingFilterOverrideFlag;      //< offsets for deblocking filter inherit from PPS
+  Int         m_deblockingFilterBetaOffsetDiv2;    //< beta offset for deblocking filter
+  Int         m_deblockingFilterTcOffsetDiv2;      //< tc offset for deblocking filter
+  
+  Int         m_aiNumRefIdx   [3];    //  for multiple reference of current slice
+
+  Int         m_iRefIdxOfLC[2][MAX_NUM_REF_LC];
+  Int         m_eListIdFromIdxOfLC[MAX_NUM_REF_LC];
+  Int         m_iRefIdxFromIdxOfLC[MAX_NUM_REF_LC];
+  Int         m_iRefIdxOfL1FromRefIdxOfL0[MAX_NUM_REF_LC];
+  Int         m_iRefIdxOfL0FromRefIdxOfL1[MAX_NUM_REF_LC];
+  Bool        m_bRefPicListModificationFlagLC;
+  Bool        m_bRefPicListCombinationFlag;
+
+  Bool        m_bCheckLDC;
+
+  //  Data
+  Int         m_iSliceQpDelta;
+#if CHROMA_QP_EXTENSION
+  Int         m_iSliceQpDeltaCb;
+  Int         m_iSliceQpDeltaCr;
+#endif
+  TComPic*    m_apcRefPicList [2][MAX_NUM_REF+1];
+  Int         m_aiRefPOCList  [2][MAX_NUM_REF+1];
+  Int         m_iDepth;
+  
+  // referenced slice?
+  Bool        m_bRefenced;
+  
+  // access channel
+  TComVPS*    m_pcVPS;
+  TComSPS*    m_pcSPS;
+  TComPPS*    m_pcPPS;
+  TComPic*    m_pcPic;
+#if ADAPTIVE_QP_SELECTION
+  TComTrQuant* m_pcTrQuant;
+#endif  
+#if !REMOVE_APS
+  TComAPS*    m_pcAPS;  //!< pointer to APS parameter object
+#endif
+  UInt        m_colFromL0Flag;  // collocated picture from List0 flag
+  
+  UInt        m_colRefIdx;
+  UInt        m_maxNumMergeCand;
+
+
+#if ALF_CHROMA_LAMBDA || SAO_CHROMA_LAMBDA
+  Double      m_dLambdaLuma;
+  Double      m_dLambdaChroma;
+#else
+  Double      m_dLambda;
+#endif
+
+  Bool        m_abEqualRef  [2][MAX_NUM_REF][MAX_NUM_REF];
+  
+  Bool        m_bNoBackPredFlag;
+  UInt        m_uiTLayer;
+#if SVC_EXTENSION
+  UInt        m_layerId;
+  TComPic*    m_pcBaseColPic;
+  TComPicYuv* m_pcFullPelBaseRec;
+#endif 
+  Bool        m_bTLayerSwitchingFlag;
+
+  UInt        m_uiSliceMode;
+  UInt        m_uiSliceArgument;
+  UInt        m_uiSliceCurStartCUAddr;
+  UInt        m_uiSliceCurEndCUAddr;
+  UInt        m_uiSliceIdx;
+  UInt        m_uiDependentSliceMode;
+  UInt        m_uiDependentSliceArgument;
+  UInt        m_uiDependentSliceCurStartCUAddr;
+  UInt        m_uiDependentSliceCurEndCUAddr;
+  Bool        m_bNextSlice;
+  Bool        m_bNextDependentSlice;
+  UInt        m_uiSliceBits;
+  UInt        m_uiDependentSliceCounter;
+  Bool        m_bFinalized;
+
+  wpScalingParam  m_weightPredTable[2][MAX_NUM_REF][3]; // [REF_PIC_LIST_0 or REF_PIC_LIST_1][refIdx][0:Y, 1:U, 2:V]
+  wpACDCParam    m_weightACDCParam[3];                 // [0:Y, 1:U, 2:V]
+  wpScalingParam  m_weightPredTableLC[2*MAX_NUM_REF][3]; // [refIdxLC][0:Y, 1:U, 2:V]
+
+  std::vector<UInt> m_tileByteLocation;
+  UInt        m_uiTileOffstForMultES;
+
+  UInt*       m_puiSubstreamSizes;
+  TComScalingList*     m_scalingList;                 //!< pointer of quantization matrix
+  Bool        m_cabacInitFlag; 
+
+  Bool       m_bLMvdL1Zero;
+  Int         m_numEntryPointOffsets;
+#if TEMPORAL_LAYER_NON_REFERENCE
+  Bool       m_temporalLayerNonReferenceFlag;
+#endif
+#if !REMOVE_NAL_REF_FLAG
+  Bool        m_nalRefFlag;
+#endif
+  Bool       m_LFCrossSliceBoundaryFlag;
+
+  Bool       m_enableTMVPFlag;
+
+public:
+  TComSlice();
+  virtual ~TComSlice(); 
+  Void      initSlice       ();
+
+  Void      setVPS          ( TComVPS* pcVPS ) { m_pcVPS = pcVPS; }
+  TComVPS*  getVPS          () { return m_pcVPS; }
+  Void      setSPS          ( TComSPS* pcSPS ) { m_pcSPS = pcSPS; }
+  TComSPS*  getSPS          () { return m_pcSPS; }
+  
+  Void      setPPS          ( TComPPS* pcPPS )         { assert(pcPPS!=NULL); m_pcPPS = pcPPS; m_iPPSId = pcPPS->getPPSId(); }
+  TComPPS*  getPPS          () { return m_pcPPS; }
+
+#if ADAPTIVE_QP_SELECTION
+  Void          setTrQuant          ( TComTrQuant* pcTrQuant ) { m_pcTrQuant = pcTrQuant; }
+  TComTrQuant*  getTrQuant          () { return m_pcTrQuant; }
+#endif
+
+  Void      setPPSId        ( Int PPSId )         { m_iPPSId = PPSId; }
+  Int       getPPSId        () { return m_iPPSId; }
+#if !REMOVE_APS
+  Void      setAPS          ( TComAPS* pcAPS ) { m_pcAPS = pcAPS; } //!< set APS pointer
+  TComAPS*  getAPS          ()                 { return m_pcAPS;  } //!< get APS pointer
+  Void      setAPSId        ( Int Id)          { m_iAPSId =Id;    } //!< set APS ID
+  Int       getAPSId        ()                 { return m_iAPSId; } //!< get APS ID
+#endif
+  Void      setPicOutputFlag( Bool b )         { m_PicOutputFlag = b;    }
+  Bool      getPicOutputFlag()                 { return m_PicOutputFlag; }
+#if !REMOVE_ALF
+  Void      setAlfEnabledFlag(Bool b, Int compIdx) { m_alfEnabledFlag[compIdx] = b;    }
+  Bool      getAlfEnabledFlag(Int compIdx)         { return m_alfEnabledFlag[compIdx]; }
+#endif
+  Void      setSaoEnabledFlag(Bool s) {m_saoEnabledFlag =s; }
+  Bool      getSaoEnabledFlag() { return m_saoEnabledFlag; }
+#if SAO_TYPE_SHARING
+  Void      setSaoEnabledFlagChroma(Bool s) {m_saoEnabledFlagChroma =s; }       //!< set SAO Cb&Cr enabled flag
+  Bool      getSaoEnabledFlagChroma() { return m_saoEnabledFlagChroma; }        //!< get SAO Cb&Cr enabled flag
+#else
+  Void      setSaoEnabledFlagCb(Bool s) {m_saoEnabledFlagCb =s; }       //!< set SAO Cb enabled flag
+  Bool      getSaoEnabledFlagCb() { return m_saoEnabledFlagCb; }        //!< get SAO Cb enabled flag
+  Void      setSaoEnabledFlagCr(Bool s) {m_saoEnabledFlagCr =s; }       //!< set SAO Cr enabled flag
+  Bool      getSaoEnabledFlagCr() { return m_saoEnabledFlagCr; }        //!< get SAO Cr enabled flag
+#endif
+  Void      setRPS          ( TComReferencePictureSet *pcRPS ) { m_pcRPS = pcRPS; }
+  TComReferencePictureSet*  getRPS          () { return m_pcRPS; }
+  TComReferencePictureSet*  getLocalRPS     () { return &m_LocalRPS; }
+
+  Void      setRPSidx          ( Int iBDidx ) { m_iBDidx = iBDidx; }
+  Int       getRPSidx          () { return m_iBDidx; }
+  Void      setCombinationBDidx          ( Int iCombinationBDidx ) { m_iCombinationBDidx = iCombinationBDidx; }
+  Int       getCombinationBDidx          () { return m_iCombinationBDidx; }
+  Void      setCombineWithReferenceFlag          ( Bool bCombineWithReferenceFlag ) { m_bCombineWithReferenceFlag = bCombineWithReferenceFlag; }
+  Bool      getCombineWithReferenceFlag          () { return m_bCombineWithReferenceFlag; }
+#if PREVREFPIC_DEFN 
+  Int       getPrevPOC      ()                          { return  m_prevPOC[getTLayer()];       }
+#else
+  Int       getPrevPOC      ()                          { return  m_prevPOC;       }
+#endif
+  TComRefPicListModification* getRefPicListModification() { return &m_RefPicListModification; }
+  Void      setLastIDR(Int iIDRPOC)                       { m_iLastIDR = iIDRPOC; }
+  Int       getLastIDR()                                  { return m_iLastIDR; }
+  SliceType getSliceType    ()                          { return  m_eSliceType;         }
+  Int       getPOC          ()                          { return  m_iPOC;           }
+  Int       getSliceQp      ()                          { return  m_iSliceQp;           }
+#if SLICEHEADER_SYNTAX_FIX
+  Bool      getDependentSliceFlag() const               { return m_dependentSliceFlag; }
+  void      setDependentSliceFlag(Bool val)             { m_dependentSliceFlag = val; }
+#endif
+#if ADAPTIVE_QP_SELECTION
+  Int       getSliceQpBase  ()                          { return  m_iSliceQpBase;       }
+#endif
+  Int       getSliceQpDelta ()                          { return  m_iSliceQpDelta;      }
+#if CHROMA_QP_EXTENSION
+  Int       getSliceQpDeltaCb ()                          { return  m_iSliceQpDeltaCb;      }
+  Int       getSliceQpDeltaCr ()                          { return  m_iSliceQpDeltaCr;      }
+#endif
+  Bool      getDeblockingFilterDisable()                { return  m_deblockingFilterDisable; }
+  Bool      getDeblockingFilterOverrideFlag()           { return  m_deblockingFilterOverrideFlag; }
+  Int       getDeblockingFilterBetaOffsetDiv2()         { return  m_deblockingFilterBetaOffsetDiv2; }
+  Int       getDeblockingFilterTcOffsetDiv2()           { return  m_deblockingFilterTcOffsetDiv2; }
+
+  Int       getNumRefIdx        ( RefPicList e )                { return  m_aiNumRefIdx[e];             }
+  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];   }
+  Int       getDepth            ()                              { return  m_iDepth;                     }
+  UInt      getColFromL0Flag    ()                              { return  m_colFromL0Flag;              }
+  UInt      getColRefIdx        ()                              { return  m_colRefIdx;                  }
+  Void      checkColRefIdx      (UInt curSliceIdx, TComPic* pic);
+  Bool      getCheckLDC     ()                                  { return m_bCheckLDC; }
+  Bool      getMvdL1ZeroFlag ()                                  { return m_bLMvdL1Zero;    }
+  Int       getNumRpsCurrTempList();
+  Int       getRefIdxOfLC       (RefPicList e, Int iRefIdx)     { return m_iRefIdxOfLC[e][iRefIdx];           }
+  Int       getListIdFromIdxOfLC(Int iRefIdx)                   { return m_eListIdFromIdxOfLC[iRefIdx];       }
+  Int       getRefIdxFromIdxOfLC(Int iRefIdx)                   { return m_iRefIdxFromIdxOfLC[iRefIdx];       }
+  Int       getRefIdxOfL0FromRefIdxOfL1(Int iRefIdx)            { return m_iRefIdxOfL0FromRefIdxOfL1[iRefIdx];}
+  Int       getRefIdxOfL1FromRefIdxOfL0(Int iRefIdx)            { return m_iRefIdxOfL1FromRefIdxOfL0[iRefIdx];}
+  Bool      getRefPicListModificationFlagLC()                   {return m_bRefPicListModificationFlagLC;}
+  Void      setRefPicListModificationFlagLC(Bool bflag)         {m_bRefPicListModificationFlagLC=bflag;}     
+  Bool      getRefPicListCombinationFlag()                      {return m_bRefPicListCombinationFlag;}
+  Void      setRefPicListCombinationFlag(Bool bflag)            {m_bRefPicListCombinationFlag=bflag;}   
+  Void      setReferenced(Bool b)                               { m_bRefenced = b; }
+  Bool      isReferenced()                                      { return m_bRefenced; }
+#if PREVREFPIC_DEFN 
+  Void      setPOC              ( Int i )
+  {
+    m_iPOC = i;
+    if (isReferenced())
+    {
+      for (Int j = getTLayer(); j < (getSPS()->getMaxTLayers()); j++)
+      {
+        m_prevPOC[j] = i;
+      }
+    }
+  }
+#else  
+  Void      setPOC              ( Int i )                       { m_iPOC              = i; if(getTLayer()==0) m_prevPOC=i; }
+#endif
+  Void      setNalUnitType      ( NalUnitType e )               { m_eNalUnitType      = e;      }
+  NalUnitType getNalUnitType    ()                              { return m_eNalUnitType;        }
+  Bool      getRapPicFlag       ();  
+#if SUPPORT_FOR_RAP_N_LP
+  Bool      getIdrPicFlag       ()                              { return getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP; }
+#endif
+  Void      checkCRA(TComReferencePictureSet *pReferencePictureSet, Int& pocCRA, Bool& prevRAPisBLA, TComList<TComPic*>& rcListPic);
+  Void      decodingRefreshMarking(Int& pocCRA, Bool& bRefreshPending, TComList<TComPic*>& rcListPic);
+  Void      setSliceType        ( SliceType e )                 { m_eSliceType        = e;      }
+  Void      setSliceQp          ( Int i )                       { m_iSliceQp          = i;      }
+#if ADAPTIVE_QP_SELECTION
+  Void      setSliceQpBase      ( Int i )                       { m_iSliceQpBase      = i;      }
+#endif
+  Void      setSliceQpDelta     ( Int i )                       { m_iSliceQpDelta     = i;      }
+#if CHROMA_QP_EXTENSION
+  Void      setSliceQpDeltaCb   ( Int i )                       { m_iSliceQpDeltaCb   = i;      }
+  Void      setSliceQpDeltaCr   ( Int i )                       { m_iSliceQpDeltaCr   = i;      }
+#endif
+  Void      setDeblockingFilterDisable( Bool b )                { m_deblockingFilterDisable= b;      }
+  Void      setDeblockingFilterOverrideFlag( Bool b )           { m_deblockingFilterOverrideFlag = b; }
+  Void      setDeblockingFilterBetaOffsetDiv2( Int i )          { m_deblockingFilterBetaOffsetDiv2 = i; }
+  Void      setDeblockingFilterTcOffsetDiv2( Int i )            { m_deblockingFilterTcOffsetDiv2 = i; }
+  
+  Void      setRefPic           ( TComPic* p, RefPicList e, Int iRefIdx ) { m_apcRefPicList[e][iRefIdx] = p; }
+  Void      setRefPOC           ( Int i, RefPicList e, Int iRefIdx ) { m_aiRefPOCList[e][iRefIdx] = i; }
+  Void      setNumRefIdx        ( RefPicList e, Int i )         { m_aiNumRefIdx[e]    = i;      }
+  Void      setPic              ( TComPic* p )                  { m_pcPic             = p;      }
+  Void      setDepth            ( Int iDepth )                  { m_iDepth            = iDepth; }
+  
+#if SVC_EXTENSION  
+  Void      setBaseColPic       ( TComPic* p)                   { m_pcBaseColPic = p; }
+  Void      setBaseColPic       ( TComList<TComPic*>& rcListPic , UInt layerID );
+  TComPic*  getBaseColPic       ()  { return m_pcBaseColPic; }
+
+  Void      setLayerId (UInt layerId) { m_layerId = layerId; }
+  UInt      getLayerId ()               { return m_layerId; }
+
+  Void        setFullPelBaseRec   ( TComPicYuv* p) { m_pcFullPelBaseRec = p; }
+  TComPicYuv* getFullPelBaseRec   ()  { return  m_pcFullPelBaseRec;  }
+#endif
+  Void      setRefPicList       ( TComList<TComPic*>& rcListPic );
+  Void      setRefPOCList       ();
+  Void      setColFromL0Flag    ( UInt colFromL0 ) { m_colFromL0Flag = colFromL0; }
+  Void      setColRefIdx        ( UInt refIdx) { m_colRefIdx = refIdx; }
+  Void      setCheckLDC         ( Bool b )                      { m_bCheckLDC = b; }
+  Void      setMvdL1ZeroFlag     ( Bool b)                       { m_bLMvdL1Zero = b; }
+
+  Bool      isIntra         ()                          { return  m_eSliceType == I_SLICE;  }
+  Bool      isInterB        ()                          { return  m_eSliceType == B_SLICE;  }
+  Bool      isInterP        ()                          { return  m_eSliceType == P_SLICE;  }
+  
+#if ALF_CHROMA_LAMBDA || SAO_CHROMA_LAMBDA  
+  Void      setLambda( Double d, Double e ) { m_dLambdaLuma = d; m_dLambdaChroma = e;}
+  Double    getLambdaLuma() { return m_dLambdaLuma;        }
+  Double    getLambdaChroma() { return m_dLambdaChroma;        }
+#else
+  Void      setLambda( Double d ) { m_dLambda = d; }
+  Double    getLambda() { return m_dLambda;        }
+#endif
+  
+  Void      initEqualRef();
+  Bool      isEqualRef  ( RefPicList e, Int iRefIdx1, Int iRefIdx2 )
+  {
+    if (iRefIdx1 < 0 || iRefIdx2 < 0) return false;
+    return m_abEqualRef[e][iRefIdx1][iRefIdx2];
+  }
+  
+  Void setEqualRef( RefPicList e, Int iRefIdx1, Int iRefIdx2, Bool b)
+  {
+    m_abEqualRef[e][iRefIdx1][iRefIdx2] = m_abEqualRef[e][iRefIdx2][iRefIdx1] = b;
+  }
+  
+  static Void      sortPicList         ( TComList<TComPic*>& rcListPic );
+  
+  Bool getNoBackPredFlag() { return m_bNoBackPredFlag; }
+  Void setNoBackPredFlag( Bool b ) { m_bNoBackPredFlag = b; }
+  Void generateCombinedList       ();
+
+  UInt getTLayer             ()                            { return m_uiTLayer;                      }
+  Void setTLayer             ( UInt uiTLayer )             { m_uiTLayer = uiTLayer;                  }
+
+  Void setTLayerInfo( UInt uiTLayer );
+  Void decodingMarking( TComList<TComPic*>& rcListPic, Int iGOPSIze, Int& iMaxRefPicNum ); 
+  Void applyReferencePictureSet( TComList<TComPic*>& rcListPic, TComReferencePictureSet *RPSList);
+  Bool isTemporalLayerSwitchingPoint( TComList<TComPic*>& rcListPic, TComReferencePictureSet *RPSList);
+#if STSA
+  Bool isStepwiseTemporalLayerSwitchingPointCandidate( TComList<TComPic*>& rcListPic, TComReferencePictureSet *RPSList);
+#endif
+  Int       checkThatAllRefPicsAreAvailable( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool printErrors, Int pocRandomAccess = 0);
+  Void      createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet);
+
+  Void setMaxNumMergeCand               (UInt val )         { m_maxNumMergeCand = val;                    }
+  UInt getMaxNumMergeCand               ()                  { return m_maxNumMergeCand;                   }
+
+  Void setSliceMode                     ( UInt uiMode )     { m_uiSliceMode = uiMode;                     }
+  UInt getSliceMode                     ()                  { return m_uiSliceMode;                       }
+  Void setSliceArgument                 ( UInt uiArgument ) { m_uiSliceArgument = uiArgument;             }
+  UInt getSliceArgument                 ()                  { return m_uiSliceArgument;                   }
+  Void setSliceCurStartCUAddr           ( UInt uiAddr )     { m_uiSliceCurStartCUAddr = uiAddr;           }
+  UInt getSliceCurStartCUAddr           ()                  { return m_uiSliceCurStartCUAddr;             }
+  Void setSliceCurEndCUAddr             ( UInt uiAddr )     { m_uiSliceCurEndCUAddr = uiAddr;             }
+  UInt getSliceCurEndCUAddr             ()                  { return m_uiSliceCurEndCUAddr;               }
+  Void setSliceIdx                      ( UInt i)           { m_uiSliceIdx = i;                           }
+  UInt getSliceIdx                      ()                  { return  m_uiSliceIdx;                       }
+  Void copySliceInfo                    (TComSlice *pcSliceSrc);
+  Void setDependentSliceMode              ( UInt uiMode )     { m_uiDependentSliceMode = uiMode;              }
+  UInt getDependentSliceMode              ()                  { return m_uiDependentSliceMode;                }
+  Void setDependentSliceArgument          ( UInt uiArgument ) { m_uiDependentSliceArgument = uiArgument;      }
+  UInt getDependentSliceArgument          ()                  { return m_uiDependentSliceArgument;            }
+  Void setDependentSliceCurStartCUAddr    ( UInt uiAddr )     { m_uiDependentSliceCurStartCUAddr = uiAddr;    }
+  UInt getDependentSliceCurStartCUAddr    ()                  { return m_uiDependentSliceCurStartCUAddr;      }
+  Void setDependentSliceCurEndCUAddr      ( UInt uiAddr )     { m_uiDependentSliceCurEndCUAddr = uiAddr;      }
+  UInt getDependentSliceCurEndCUAddr      ()                  { return m_uiDependentSliceCurEndCUAddr;        }
+  Void setNextSlice                     ( Bool b )          { m_bNextSlice = b;                           }
+  Bool isNextSlice                      ()                  { return m_bNextSlice;                        }
+  Void setNextDependentSlice              ( Bool b )          { m_bNextDependentSlice = b;                    }
+  Bool isNextDependentSlice               ()                  { return m_bNextDependentSlice;                 }
+  Void setSliceBits                     ( UInt uiVal )      { m_uiSliceBits = uiVal;                      }
+  UInt getSliceBits                     ()                  { return m_uiSliceBits;                       }  
+  Void setDependentSliceCounter           ( UInt uiVal )      { m_uiDependentSliceCounter = uiVal;            }
+  UInt getDependentSliceCounter           ()                  { return m_uiDependentSliceCounter;             }
+  Void setFinalized                     ( Bool uiVal )      { m_bFinalized = uiVal;                       }
+  Bool getFinalized                     ()                  { return m_bFinalized;                        }
+  Void  setWpScaling    ( wpScalingParam  wp[2][MAX_NUM_REF][3] ) { memcpy(m_weightPredTable, wp, sizeof(wpScalingParam)*2*MAX_NUM_REF*3); }
+  Void  getWpScaling    ( RefPicList e, Int iRefIdx, wpScalingParam *&wp);
+
+  Void  resetWpScaling  (wpScalingParam  wp[2][MAX_NUM_REF][3]);
+  Void  initWpScaling    (wpScalingParam  wp[2][MAX_NUM_REF][3]);
+  Void  initWpScaling   ();
+  inline Bool applyWP   () { return( (m_eSliceType==P_SLICE && m_pcPPS->getUseWP()) || (m_eSliceType==B_SLICE && m_pcPPS->getWPBiPred()) ); }
+
+  Void  setWpAcDcParam  ( wpACDCParam wp[3] ) { memcpy(m_weightACDCParam, wp, sizeof(wpACDCParam)*3); }
+  Void  getWpAcDcParam  ( wpACDCParam *&wp );
+  Void  initWpAcDcParam ();
+  
+  Void setTileLocationCount             ( UInt cnt )               { return m_tileByteLocation.resize(cnt);    }
+  UInt getTileLocationCount             ()                         { return (UInt) m_tileByteLocation.size();  }
+  Void setTileLocation                  ( Int idx, UInt location ) { assert (idx<m_tileByteLocation.size());
+                                                                     m_tileByteLocation[idx] = location;       }
+  Void addTileLocation                  ( UInt location )          { m_tileByteLocation.push_back(location);   }
+  UInt getTileLocation                  ( Int idx )                { return m_tileByteLocation[idx];           }
+
+  Void setTileOffstForMultES            (UInt uiOffset )      { m_uiTileOffstForMultES = uiOffset;        }
+  UInt getTileOffstForMultES            ()                    { return m_uiTileOffstForMultES;            }
+  Void allocSubstreamSizes              ( UInt uiNumSubstreams );
+  UInt* getSubstreamSizes               ()                  { return m_puiSubstreamSizes; }
+  Void  setScalingList              ( TComScalingList* scalingList ) { m_scalingList = scalingList; }
+  TComScalingList*   getScalingList ()                               { return m_scalingList; }
+  Void  setDefaultScalingList       ();
+  Bool  checkDefaultScalingList     ();
+  Void      setCabacInitFlag  ( Bool val ) { m_cabacInitFlag = val;      }  //!< set CABAC initial flag 
+  Bool      getCabacInitFlag  ()           { return m_cabacInitFlag;     }  //!< get CABAC initial flag 
+  Void      setNumEntryPointOffsets(Int val)  { m_numEntryPointOffsets = val;     }
+  Int       getNumEntryPointOffsets()         { return m_numEntryPointOffsets;    }
+#if TEMPORAL_LAYER_NON_REFERENCE
+  Bool      getTemporalLayerNonReferenceFlag()       { return m_temporalLayerNonReferenceFlag;}
+  Void      setTemporalLayerNonReferenceFlag(Bool x) { m_temporalLayerNonReferenceFlag = x;}
+#endif
+#if !REMOVE_NAL_REF_FLAG
+  Bool      getNalRefFlag()       { return m_nalRefFlag;}
+  Void      setNalRefFlag(Bool x) { m_nalRefFlag = x;}
+#endif
+  Void      setLFCrossSliceBoundaryFlag     ( Bool   val )    { m_LFCrossSliceBoundaryFlag = val; }
+  Bool      getLFCrossSliceBoundaryFlag     ()                { return m_LFCrossSliceBoundaryFlag;} 
+
+  Void      setEnableTMVPFlag     ( Bool   b )    { m_enableTMVPFlag = b; }
+  Bool      getEnableTMVPFlag     ()              { return m_enableTMVPFlag;}
+#if REF_IDX_FRAMEWORK
+  Void      addRefPicList( TComPic **pIlpPicList, Int iRefPicNum, Int iInsertOffset=0 );
+#endif
+protected:
+  TComPic*  xGetRefPic  (TComList<TComPic*>& rcListPic,
+                         UInt                uiPOC);
+  TComPic*  xGetLongTermRefPic  (TComList<TComPic*>& rcListPic,
+                         UInt                uiPOC);
+};// END CLASS DEFINITION TComSlice
+
+
+template <class T> class ParameterSetMap
+{
+public:
+  ParameterSetMap(Int maxId)
+  :m_maxId (maxId)
+  {}
+
+  ~ParameterSetMap()
+  {
+    for (typename std::map<Int,T *>::iterator i = m_paramsetMap.begin(); i!= m_paramsetMap.end(); i++)
+    {
+      delete (*i).second;
+    }
+  }
+
+  Void storePS(Int psId, T *ps)
+  {
+    assert ( psId < m_maxId );
+    if ( m_paramsetMap.find(psId) != m_paramsetMap.end() )
+    {
+      delete m_paramsetMap[psId];
+    }
+    m_paramsetMap[psId] = ps; 
+  }
+
+  Void mergePSList(ParameterSetMap<T> &rPsList)
+  {
+    for (typename std::map<Int,T *>::iterator i = rPsList.m_paramsetMap.begin(); i!= rPsList.m_paramsetMap.end(); i++)
+    {
+      storePS(i->first, i->second);
+    }
+    rPsList.m_paramsetMap.clear();
+  }
+
+
+  T* getPS(Int psId)
+  {
+    return ( m_paramsetMap.find(psId) == m_paramsetMap.end() ) ? NULL : m_paramsetMap[psId];
+  }
+
+  T* getFirstPS()
+  {
+    return (m_paramsetMap.begin() == m_paramsetMap.end() ) ? NULL : m_paramsetMap.begin()->second;
+  }
+
+private:
+  std::map<Int,T *> m_paramsetMap;
+  Int               m_maxId;
+};
+
+class ParameterSetManager
+{
+public:
+  ParameterSetManager();
+  virtual ~ParameterSetManager();
+
+  //! store sequence parameter set and take ownership of it 
+  Void storeVPS(TComVPS *vps) { m_vpsMap.storePS( vps->getVPSId(), vps); };
+  //! get pointer to existing video parameter set  
+  TComVPS* getVPS(Int vpsId)  { return m_vpsMap.getPS(vpsId); };
+  TComVPS* getFirstVPS()      { return m_vpsMap.getFirstPS(); };
+  
+  //! store sequence parameter set and take ownership of it 
+  Void storeSPS(TComSPS *sps) { m_spsMap.storePS( sps->getSPSId(), sps); };
+  //! get pointer to existing sequence parameter set  
+  TComSPS* getSPS(Int spsId)  { return m_spsMap.getPS(spsId); };
+  TComSPS* getFirstSPS()      { return m_spsMap.getFirstPS(); };
+
+  //! store picture parameter set and take ownership of it 
+  Void storePPS(TComPPS *pps) { m_ppsMap.storePS( pps->getPPSId(), pps); };
+  //! get pointer to existing picture parameter set  
+  TComPPS* getPPS(Int ppsId)  { return m_ppsMap.getPS(ppsId); };
+  TComPPS* getFirstPPS()      { return m_ppsMap.getFirstPS(); };
+
+#if !REMOVE_APS
+  //! store adaptation parameter set and take ownership of it
+  Void storeAPS(TComAPS *aps) { m_apsMap.storePS( aps->getAPSID(), aps); };
+  //! getPointer to existing adaptation parameter set  
+  TComAPS* getAPS(Int apsId)  { return m_apsMap.getPS(apsId); };
+#endif
+protected:
+  
+  ParameterSetMap<TComVPS> m_vpsMap;
+  ParameterSetMap<TComSPS> m_spsMap; 
+  ParameterSetMap<TComPPS> m_ppsMap;
+#if !REMOVE_APS
+  ParameterSetMap<TComAPS> m_apsMap;
+#endif
+};
+
+//! \}
+
+#endif // __TCOMSLICE__
Index: /trunk/source/Lib/TLibCommon/TComTrQuant.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComTrQuant.cpp	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComTrQuant.cpp	(revision 2)
@@ -0,0 +1,3069 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComTrQuant.cpp
+    \brief    transform and quantization class
+*/
+
+#include <stdlib.h>
+#include <math.h>
+#include <memory.h>
+#include "TComTrQuant.h"
+#include "TComPic.h"
+#include "ContextTables.h"
+
+typedef struct
+{
+  Int    iNNZbeforePos0;
+  Double d64CodedLevelandDist; // distortion and level cost only
+  Double d64UncodedDist;    // all zero coded block distortion
+  Double d64SigCost;
+  Double d64SigCost_0;
+} coeffGroupRDStats;
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+#define RDOQ_CHROMA                 1           ///< use of RDOQ in chroma
+
+// ====================================================================================================================
+// Tables
+// ====================================================================================================================
+
+// RDOQ parameter
+
+// ====================================================================================================================
+// Qp class member functions
+// ====================================================================================================================
+
+QpParam::QpParam()
+{
+}
+
+// ====================================================================================================================
+// TComTrQuant class member functions
+// ====================================================================================================================
+
+TComTrQuant::TComTrQuant()
+{
+  m_cQP.clear();
+  
+  // allocate temporary buffers
+  m_plTempCoeff  = new Int[ MAX_CU_SIZE*MAX_CU_SIZE ];
+  
+  // allocate bit estimation class  (for RDOQ)
+  m_pcEstBitsSbac = new estBitsSbacStruct;
+  initScalingList();
+}
+
+TComTrQuant::~TComTrQuant()
+{
+  // delete temporary buffers
+  if ( m_plTempCoeff )
+  {
+    delete [] m_plTempCoeff;
+    m_plTempCoeff = NULL;
+  }
+  
+  // delete bit estimation class
+  if ( m_pcEstBitsSbac )
+  {
+    delete m_pcEstBitsSbac;
+  }
+  destroyScalingList();
+}
+
+#if ADAPTIVE_QP_SELECTION
+Void TComTrQuant::storeSliceQpNext(TComSlice* pcSlice)
+{
+  Int qpBase = pcSlice->getSliceQpBase();
+  Int sliceQpused = pcSlice->getSliceQp();
+  Int sliceQpnext;
+  Double alpha = qpBase < 17 ? 0.5 : 1;
+  
+  Int cnt=0;
+  for(int u=1; u<=LEVEL_RANGE; u++)
+  { 
+    cnt += m_sliceNsamples[u] ;
+  }
+
+  if( !m_bUseRDOQ )
+  {
+    sliceQpused = qpBase;
+    alpha = 0.5;
+  }
+
+  if( cnt > 120 )
+  {
+    Double sum = 0;
+    Int k = 0;
+    for(Int u=1; u<LEVEL_RANGE; u++)
+    {
+      sum += u*m_sliceSumC[u];
+      k += u*u*m_sliceNsamples[u];
+    }
+
+    Int v;
+    Double q[MAX_QP+1] ;
+    for(v=0; v<=MAX_QP; v++)
+    {
+      q[v] = (Double)(g_invQuantScales[v%6] * (1<<(v/6)))/64 ;
+    }
+
+    Double qnext = sum/k * q[sliceQpused] / (1<<ARL_C_PRECISION);
+
+    for(v=0; v<MAX_QP; v++)
+    {
+      if(qnext < alpha * q[v] + (1 - alpha) * q[v+1] )
+      {
+        break;
+      }
+    }
+    sliceQpnext = Clip3(sliceQpused - 3, sliceQpused + 3, v);
+  }
+  else
+  {
+    sliceQpnext = sliceQpused;
+  }
+
+  m_qpDelta[qpBase] = sliceQpnext - qpBase; 
+}
+
+Void TComTrQuant::initSliceQpDelta()
+{
+  for(Int qp=0; qp<=MAX_QP; qp++)
+  {
+    m_qpDelta[qp] = qp < 17 ? 0 : 1;
+  }
+}
+
+Void TComTrQuant::clearSliceARLCnt()
+{ 
+  memset(m_sliceSumC, 0, sizeof(Double)*(LEVEL_RANGE+1));
+  memset(m_sliceNsamples, 0, sizeof(Int)*(LEVEL_RANGE+1));
+}
+#endif
+
+
+/** Set qP for Quantization.
+ * \param qpy QPy
+ * \param bLowpass
+ * \param eSliceType
+ * \param eTxtType
+ * \param qpBdOffset
+ * \param chromaQPOffset
+ *
+ * return void  
+ */
+Void TComTrQuant::setQPforQuant( Int qpy, TextType eTxtType, Int qpBdOffset, Int chromaQPOffset)
+{
+  Int qpScaled;
+
+  if(eTxtType == TEXT_LUMA)
+  {
+    qpScaled = qpy + qpBdOffset;
+  }
+  else
+  {
+#if CHROMA_QP_EXTENSION
+    qpScaled = Clip3( -qpBdOffset, 57, qpy + chromaQPOffset );
+#else
+    qpScaled = Clip3( -qpBdOffset, 51, qpy + chromaQPOffset );
+#endif
+
+    if(qpScaled < 0)
+    {
+      qpScaled = qpScaled + qpBdOffset;
+    }
+    else
+    {
+#if CHROMA_QP_EXTENSION
+      qpScaled = g_aucChromaScale[ qpScaled ] + qpBdOffset;
+#else
+      qpScaled = g_aucChromaScale[ Clip3(0, 51, qpScaled) ] + qpBdOffset;
+#endif
+    }
+  }
+  m_cQP.setQpParam( qpScaled );
+}
+
+#if MATRIX_MULT
+/** NxN forward transform (2D) using brute force matrix multiplication (3 nested loops)
+ *  \param block pointer to input data (residual)
+ *  \param coeff pointer to output data (transform coefficients)
+ *  \param uiStride stride of input data
+ *  \param uiTrSize transform size (uiTrSize x uiTrSize)
+ *  \param uiMode is Intra Prediction mode used in Mode-Dependent DCT/DST only
+ */
+void xTr(Pel *block, Int *coeff, UInt uiStride, UInt uiTrSize, UInt uiMode)
+{
+  Int i,j,k,iSum;
+  Int tmp[32*32];
+  const short *iT;
+  UInt uiLog2TrSize = g_aucConvertToBit[ uiTrSize ] + 2;
+
+  if (uiTrSize==4)
+  {
+    iT  = g_aiT4[0];
+  }
+  else if (uiTrSize==8)
+  {
+    iT = g_aiT8[0];
+  }
+  else if (uiTrSize==16)
+  {
+    iT = g_aiT16[0];
+  }
+  else if (uiTrSize==32)
+  {
+    iT = g_aiT32[0];
+  }
+  else
+  {
+    assert(0);
+  }
+
+#if FULL_NBIT
+  int shift_1st = uiLog2TrSize - 1 + g_uiBitDepth - 8; // log2(N) - 1 + g_uiBitDepth - 8
+#else
+  int shift_1st = uiLog2TrSize - 1 + g_uiBitIncrement; // log2(N) - 1 + g_uiBitIncrement
+#endif
+
+  int add_1st = 1<<(shift_1st-1);
+  int shift_2nd = uiLog2TrSize + 6;
+  int add_2nd = 1<<(shift_2nd-1);
+
+  /* Horizontal transform */
+
+  if (uiTrSize==4)
+  {
+    if (uiMode != REG_DCT && g_aucDCTDSTMode_Hor[uiMode])
+    {
+      iT  =  g_as_DST_MAT_4[0];
+    }
+  }
+  for (i=0; i<uiTrSize; i++)
+  {
+    for (j=0; j<uiTrSize; j++)
+    {
+      iSum = 0;
+      for (k=0; k<uiTrSize; k++)
+      {
+        iSum += iT[i*uiTrSize+k]*block[j*uiStride+k];
+      }
+      tmp[i*uiTrSize+j] = (iSum + add_1st)>>shift_1st;
+    }
+  }
+  
+  /* Vertical transform */
+  if (uiTrSize==4)
+  {
+    if (uiMode != REG_DCT && g_aucDCTDSTMode_Vert[uiMode])
+    {
+      iT  =  g_as_DST_MAT_4[0];
+    }
+    else
+    {
+      iT  = g_aiT4[0];
+    }
+  }
+  for (i=0; i<uiTrSize; i++)
+  {                 
+    for (j=0; j<uiTrSize; j++)
+    {
+      iSum = 0;
+      for (k=0; k<uiTrSize; k++)
+      {
+        iSum += iT[i*uiTrSize+k]*tmp[j*uiTrSize+k];        
+      }
+      coeff[i*uiTrSize+j] = (iSum + add_2nd)>>shift_2nd; 
+    }
+  }
+}
+
+/** NxN inverse transform (2D) using brute force matrix multiplication (3 nested loops)
+ *  \param coeff pointer to input data (transform coefficients)
+ *  \param block pointer to output data (residual)
+ *  \param uiStride stride of output data
+ *  \param uiTrSize transform size (uiTrSize x uiTrSize)
+ *  \param uiMode is Intra Prediction mode used in Mode-Dependent DCT/DST only
+ */
+void xITr(Int *coeff, Pel *block, UInt uiStride, UInt uiTrSize, UInt uiMode)
+{
+  int i,j,k,iSum;
+  Int tmp[32*32];
+  const short *iT;
+  
+  if (uiTrSize==4)
+  {
+    iT  = g_aiT4[0];
+  }
+  else if (uiTrSize==8)
+  {
+    iT = g_aiT8[0];
+  }
+  else if (uiTrSize==16)
+  {
+    iT = g_aiT16[0];
+  }
+  else if (uiTrSize==32)
+  {
+    iT = g_aiT32[0];
+  }
+  else
+  {
+    assert(0);
+  }
+  
+  int shift_1st = SHIFT_INV_1ST;
+  int add_1st = 1<<(shift_1st-1);  
+#if FULL_NBIT
+  int shift_2nd = SHIFT_INV_2ND - ((short)g_uiBitDepth - 8);
+#else
+  int shift_2nd = SHIFT_INV_2ND - g_uiBitIncrement;
+#endif
+  int add_2nd = 1<<(shift_2nd-1);
+  if (uiTrSize==4)
+  {
+    if (uiMode != REG_DCT && g_aucDCTDSTMode_Vert[uiMode] ) // Check for DCT or DST
+    {
+      iT  =  g_as_DST_MAT_4[0];
+    }
+  }
+  
+  /* Horizontal transform */
+  for (i=0; i<uiTrSize; i++)
+  {    
+    for (j=0; j<uiTrSize; j++)
+    {
+      iSum = 0;
+      for (k=0; k<uiTrSize; k++)
+      {        
+        iSum += iT[k*uiTrSize+i]*coeff[k*uiTrSize+j]; 
+      }
+      tmp[i*uiTrSize+j] = Clip3(-32768, 32767, (iSum + add_1st)>>shift_1st); // Clipping is normative
+    }
+  }   
+  
+  if (uiTrSize==4)
+  {
+    if (uiMode != REG_DCT && g_aucDCTDSTMode_Hor[uiMode] )   // Check for DCT or DST
+    {
+      iT  =  g_as_DST_MAT_4[0];
+    }
+    else  
+    {
+      iT  = g_aiT4[0];
+    }
+  }
+  
+  /* Vertical transform */
+  for (i=0; i<uiTrSize; i++)
+  {   
+    for (j=0; j<uiTrSize; j++)
+    {
+      iSum = 0;
+      for (k=0; k<uiTrSize; k++)
+      {        
+        iSum += iT[k*uiTrSize+j]*tmp[i*uiTrSize+k];
+      }
+      block[i*uiStride+j] = Clip3(-32768, 32767, (iSum + add_2nd)>>shift_2nd); // Clipping is non-normative
+    }
+  }
+}
+
+#else //MATRIX_MULT
+
+/** 4x4 forward transform implemented using partial butterfly structure (1D)
+ *  \param src   input data (residual)
+ *  \param dst   output data (transform coefficients)
+ *  \param shift specifies right shift after 1D transform
+ */
+
+void partialButterfly4(short *src,short *dst,int shift, int line)
+{
+  int j;  
+  int E[2],O[2];
+  int add = 1<<(shift-1);
+
+  for (j=0; j<line; j++)
+  {    
+    /* E and O */
+    E[0] = src[0] + src[3];
+    O[0] = src[0] - src[3];
+    E[1] = src[1] + src[2];
+    O[1] = src[1] - src[2];
+
+    dst[0] = (g_aiT4[0][0]*E[0] + g_aiT4[0][1]*E[1] + add)>>shift;
+    dst[2*line] = (g_aiT4[2][0]*E[0] + g_aiT4[2][1]*E[1] + add)>>shift;
+    dst[line] = (g_aiT4[1][0]*O[0] + g_aiT4[1][1]*O[1] + add)>>shift;
+    dst[3*line] = (g_aiT4[3][0]*O[0] + g_aiT4[3][1]*O[1] + add)>>shift;
+
+    src += 4;
+    dst ++;
+  }
+}
+
+// Fast DST Algorithm. Full matrix multiplication for DST and Fast DST algorithm 
+// give identical results
+void fastForwardDst(short *block,short *coeff,int shift)  // input block, output coeff
+{
+  int i, c[4];
+  int rnd_factor = 1<<(shift-1);
+  for (i=0; i<4; i++)
+  {
+    // Intermediate Variables
+    c[0] = block[4*i+0] + block[4*i+3];
+    c[1] = block[4*i+1] + block[4*i+3];
+    c[2] = block[4*i+0] - block[4*i+1];
+    c[3] = 74* block[4*i+2];
+
+    coeff[   i] =  ( 29 * c[0] + 55 * c[1]         + c[3]               + rnd_factor ) >> shift;
+    coeff[ 4+i] =  ( 74 * (block[4*i+0]+ block[4*i+1] - block[4*i+3])   + rnd_factor ) >> shift;
+    coeff[ 8+i] =  ( 29 * c[2] + 55 * c[0]         - c[3]               + rnd_factor ) >> shift;
+    coeff[12+i] =  ( 55 * c[2] - 29 * c[1]         + c[3]               + rnd_factor ) >> shift;
+  }
+}
+
+void fastInverseDst(short *tmp,short *block,int shift)  // input tmp, output block
+{
+  int i, c[4];
+  int rnd_factor = 1<<(shift-1);
+  for (i=0; i<4; i++)
+  {  
+    // Intermediate Variables
+    c[0] = tmp[  i] + tmp[ 8+i];
+    c[1] = tmp[8+i] + tmp[12+i];
+    c[2] = tmp[  i] - tmp[12+i];
+    c[3] = 74* tmp[4+i];
+
+    block[4*i+0] = Clip3( -32768, 32767, ( 29 * c[0] + 55 * c[1]     + c[3]               + rnd_factor ) >> shift );
+    block[4*i+1] = Clip3( -32768, 32767, ( 55 * c[2] - 29 * c[1]     + c[3]               + rnd_factor ) >> shift );
+    block[4*i+2] = Clip3( -32768, 32767, ( 74 * (tmp[i] - tmp[8+i]  + tmp[12+i])      + rnd_factor ) >> shift );
+    block[4*i+3] = Clip3( -32768, 32767, ( 55 * c[0] + 29 * c[2]     - c[3]               + rnd_factor ) >> shift );
+  }
+}
+
+void partialButterflyInverse4(short *src,short *dst,int shift, int line)
+{
+  int j;    
+  int E[2],O[2];
+  int add = 1<<(shift-1);
+
+  for (j=0; j<line; j++)
+  {    
+    /* Utilizing symmetry properties to the maximum to minimize the number of multiplications */    
+    O[0] = g_aiT4[1][0]*src[line] + g_aiT4[3][0]*src[3*line];
+    O[1] = g_aiT4[1][1]*src[line] + g_aiT4[3][1]*src[3*line];
+    E[0] = g_aiT4[0][0]*src[0] + g_aiT4[2][0]*src[2*line];
+    E[1] = g_aiT4[0][1]*src[0] + g_aiT4[2][1]*src[2*line];
+
+    /* Combining even and odd terms at each hierarchy levels to calculate the final spatial domain vector */
+    dst[0] = Clip3( -32768, 32767, (E[0] + O[0] + add)>>shift );
+    dst[1] = Clip3( -32768, 32767, (E[1] + O[1] + add)>>shift );
+    dst[2] = Clip3( -32768, 32767, (E[1] - O[1] + add)>>shift );
+    dst[3] = Clip3( -32768, 32767, (E[0] - O[0] + add)>>shift );
+            
+    src   ++;
+    dst += 4;
+  }
+}
+
+
+void partialButterfly8(short *src,short *dst,int shift, int line)
+{
+  int j,k;  
+  int E[4],O[4];
+  int EE[2],EO[2];
+  int add = 1<<(shift-1);
+
+  for (j=0; j<line; j++)
+  {  
+    /* E and O*/
+    for (k=0;k<4;k++)
+    {
+      E[k] = src[k] + src[7-k];
+      O[k] = src[k] - src[7-k];
+    }    
+    /* EE and EO */
+    EE[0] = E[0] + E[3];    
+    EO[0] = E[0] - E[3];
+    EE[1] = E[1] + E[2];
+    EO[1] = E[1] - E[2];
+
+    dst[0] = (g_aiT8[0][0]*EE[0] + g_aiT8[0][1]*EE[1] + add)>>shift;
+    dst[4*line] = (g_aiT8[4][0]*EE[0] + g_aiT8[4][1]*EE[1] + add)>>shift; 
+    dst[2*line] = (g_aiT8[2][0]*EO[0] + g_aiT8[2][1]*EO[1] + add)>>shift;
+    dst[6*line] = (g_aiT8[6][0]*EO[0] + g_aiT8[6][1]*EO[1] + add)>>shift; 
+
+    dst[line] = (g_aiT8[1][0]*O[0] + g_aiT8[1][1]*O[1] + g_aiT8[1][2]*O[2] + g_aiT8[1][3]*O[3] + add)>>shift;
+    dst[3*line] = (g_aiT8[3][0]*O[0] + g_aiT8[3][1]*O[1] + g_aiT8[3][2]*O[2] + g_aiT8[3][3]*O[3] + add)>>shift;
+    dst[5*line] = (g_aiT8[5][0]*O[0] + g_aiT8[5][1]*O[1] + g_aiT8[5][2]*O[2] + g_aiT8[5][3]*O[3] + add)>>shift;
+    dst[7*line] = (g_aiT8[7][0]*O[0] + g_aiT8[7][1]*O[1] + g_aiT8[7][2]*O[2] + g_aiT8[7][3]*O[3] + add)>>shift;
+
+    src += 8;
+    dst ++;
+  }
+}
+
+
+void partialButterflyInverse8(short *src,short *dst,int shift, int line)
+{
+  int j,k;    
+  int E[4],O[4];
+  int EE[2],EO[2];
+  int add = 1<<(shift-1);
+
+  for (j=0; j<line; j++) 
+  {    
+    /* Utilizing symmetry properties to the maximum to minimize the number of multiplications */
+    for (k=0;k<4;k++)
+    {
+      O[k] = g_aiT8[ 1][k]*src[line] + g_aiT8[ 3][k]*src[3*line] + g_aiT8[ 5][k]*src[5*line] + g_aiT8[ 7][k]*src[7*line];
+    }
+
+    EO[0] = g_aiT8[2][0]*src[ 2*line ] + g_aiT8[6][0]*src[ 6*line ];
+    EO[1] = g_aiT8[2][1]*src[ 2*line ] + g_aiT8[6][1]*src[ 6*line ];
+    EE[0] = g_aiT8[0][0]*src[ 0      ] + g_aiT8[4][0]*src[ 4*line ];
+    EE[1] = g_aiT8[0][1]*src[ 0      ] + g_aiT8[4][1]*src[ 4*line ];
+
+    /* Combining even and odd terms at each hierarchy levels to calculate the final spatial domain vector */ 
+    E[0] = EE[0] + EO[0];
+    E[3] = EE[0] - EO[0];
+    E[1] = EE[1] + EO[1];
+    E[2] = EE[1] - EO[1];
+    for (k=0;k<4;k++)
+    {
+      dst[ k   ] = Clip3( -32768, 32767, (E[k] + O[k] + add)>>shift );
+      dst[ k+4 ] = Clip3( -32768, 32767, (E[3-k] - O[3-k] + add)>>shift );
+    }   
+    src ++;
+    dst += 8;
+  }
+}
+
+
+void partialButterfly16(short *src,short *dst,int shift, int line)
+{
+  int j,k;
+  int E[8],O[8];
+  int EE[4],EO[4];
+  int EEE[2],EEO[2];
+  int add = 1<<(shift-1);
+
+  for (j=0; j<line; j++) 
+  {    
+    /* E and O*/
+    for (k=0;k<8;k++)
+    {
+      E[k] = src[k] + src[15-k];
+      O[k] = src[k] - src[15-k];
+    } 
+    /* EE and EO */
+    for (k=0;k<4;k++)
+    {
+      EE[k] = E[k] + E[7-k];
+      EO[k] = E[k] - E[7-k];
+    }
+    /* EEE and EEO */
+    EEE[0] = EE[0] + EE[3];    
+    EEO[0] = EE[0] - EE[3];
+    EEE[1] = EE[1] + EE[2];
+    EEO[1] = EE[1] - EE[2];
+
+    dst[ 0      ] = (g_aiT16[ 0][0]*EEE[0] + g_aiT16[ 0][1]*EEE[1] + add)>>shift;        
+    dst[ 8*line ] = (g_aiT16[ 8][0]*EEE[0] + g_aiT16[ 8][1]*EEE[1] + add)>>shift;    
+    dst[ 4*line ] = (g_aiT16[ 4][0]*EEO[0] + g_aiT16[ 4][1]*EEO[1] + add)>>shift;        
+    dst[ 12*line] = (g_aiT16[12][0]*EEO[0] + g_aiT16[12][1]*EEO[1] + add)>>shift;
+
+    for (k=2;k<16;k+=4)
+    {
+      dst[ k*line ] = (g_aiT16[k][0]*EO[0] + g_aiT16[k][1]*EO[1] + g_aiT16[k][2]*EO[2] + g_aiT16[k][3]*EO[3] + add)>>shift;      
+    }
+
+    for (k=1;k<16;k+=2)
+    {
+      dst[ k*line ] = (g_aiT16[k][0]*O[0] + g_aiT16[k][1]*O[1] + g_aiT16[k][2]*O[2] + g_aiT16[k][3]*O[3] + 
+        g_aiT16[k][4]*O[4] + g_aiT16[k][5]*O[5] + g_aiT16[k][6]*O[6] + g_aiT16[k][7]*O[7] + add)>>shift;
+    }
+
+    src += 16;
+    dst ++; 
+
+  }
+}
+
+
+void partialButterflyInverse16(short *src,short *dst,int shift, int line)
+{
+  int j,k;  
+  int E[8],O[8];
+  int EE[4],EO[4];
+  int EEE[2],EEO[2];
+  int add = 1<<(shift-1);
+
+  for (j=0; j<line; j++)
+  {    
+    /* Utilizing symmetry properties to the maximum to minimize the number of multiplications */
+    for (k=0;k<8;k++)
+    {
+      O[k] = g_aiT16[ 1][k]*src[ line] + g_aiT16[ 3][k]*src[ 3*line] + g_aiT16[ 5][k]*src[ 5*line] + g_aiT16[ 7][k]*src[ 7*line] + 
+        g_aiT16[ 9][k]*src[ 9*line] + g_aiT16[11][k]*src[11*line] + g_aiT16[13][k]*src[13*line] + g_aiT16[15][k]*src[15*line];
+    }
+    for (k=0;k<4;k++)
+    {
+      EO[k] = g_aiT16[ 2][k]*src[ 2*line] + g_aiT16[ 6][k]*src[ 6*line] + g_aiT16[10][k]*src[10*line] + g_aiT16[14][k]*src[14*line];
+    }
+    EEO[0] = g_aiT16[4][0]*src[ 4*line ] + g_aiT16[12][0]*src[ 12*line ];
+    EEE[0] = g_aiT16[0][0]*src[ 0      ] + g_aiT16[ 8][0]*src[ 8*line  ];
+    EEO[1] = g_aiT16[4][1]*src[ 4*line ] + g_aiT16[12][1]*src[ 12*line ];
+    EEE[1] = g_aiT16[0][1]*src[ 0      ] + g_aiT16[ 8][1]*src[ 8*line  ];
+
+    /* Combining even and odd terms at each hierarchy levels to calculate the final spatial domain vector */ 
+    for (k=0;k<2;k++)
+    {
+      EE[k] = EEE[k] + EEO[k];
+      EE[k+2] = EEE[1-k] - EEO[1-k];
+    }    
+    for (k=0;k<4;k++)
+    {
+      E[k] = EE[k] + EO[k];
+      E[k+4] = EE[3-k] - EO[3-k];
+    }    
+    for (k=0;k<8;k++)
+    {
+      dst[k]   = Clip3( -32768, 32767, (E[k] + O[k] + add)>>shift );
+      dst[k+8] = Clip3( -32768, 32767, (E[7-k] - O[7-k] + add)>>shift );
+    }   
+    src ++; 
+    dst += 16;
+  }
+}
+
+
+void partialButterfly32(short *src,short *dst,int shift, int line)
+{
+  int j,k;
+  int E[16],O[16];
+  int EE[8],EO[8];
+  int EEE[4],EEO[4];
+  int EEEE[2],EEEO[2];
+  int add = 1<<(shift-1);
+
+  for (j=0; j<line; j++)
+  {    
+    /* E and O*/
+    for (k=0;k<16;k++)
+    {
+      E[k] = src[k] + src[31-k];
+      O[k] = src[k] - src[31-k];
+    } 
+    /* EE and EO */
+    for (k=0;k<8;k++)
+    {
+      EE[k] = E[k] + E[15-k];
+      EO[k] = E[k] - E[15-k];
+    }
+    /* EEE and EEO */
+    for (k=0;k<4;k++)
+    {
+      EEE[k] = EE[k] + EE[7-k];
+      EEO[k] = EE[k] - EE[7-k];
+    }
+    /* EEEE and EEEO */
+    EEEE[0] = EEE[0] + EEE[3];    
+    EEEO[0] = EEE[0] - EEE[3];
+    EEEE[1] = EEE[1] + EEE[2];
+    EEEO[1] = EEE[1] - EEE[2];
+
+    dst[ 0       ] = (g_aiT32[ 0][0]*EEEE[0] + g_aiT32[ 0][1]*EEEE[1] + add)>>shift;
+    dst[ 16*line ] = (g_aiT32[16][0]*EEEE[0] + g_aiT32[16][1]*EEEE[1] + add)>>shift;
+    dst[ 8*line  ] = (g_aiT32[ 8][0]*EEEO[0] + g_aiT32[ 8][1]*EEEO[1] + add)>>shift; 
+    dst[ 24*line ] = (g_aiT32[24][0]*EEEO[0] + g_aiT32[24][1]*EEEO[1] + add)>>shift;
+    for (k=4;k<32;k+=8)
+    {
+      dst[ k*line ] = (g_aiT32[k][0]*EEO[0] + g_aiT32[k][1]*EEO[1] + g_aiT32[k][2]*EEO[2] + g_aiT32[k][3]*EEO[3] + add)>>shift;
+    }       
+    for (k=2;k<32;k+=4)
+    {
+      dst[ k*line ] = (g_aiT32[k][0]*EO[0] + g_aiT32[k][1]*EO[1] + g_aiT32[k][2]*EO[2] + g_aiT32[k][3]*EO[3] + 
+        g_aiT32[k][4]*EO[4] + g_aiT32[k][5]*EO[5] + g_aiT32[k][6]*EO[6] + g_aiT32[k][7]*EO[7] + add)>>shift;
+    }       
+    for (k=1;k<32;k+=2)
+    {
+      dst[ k*line ] = (g_aiT32[k][ 0]*O[ 0] + g_aiT32[k][ 1]*O[ 1] + g_aiT32[k][ 2]*O[ 2] + g_aiT32[k][ 3]*O[ 3] + 
+        g_aiT32[k][ 4]*O[ 4] + g_aiT32[k][ 5]*O[ 5] + g_aiT32[k][ 6]*O[ 6] + g_aiT32[k][ 7]*O[ 7] +
+        g_aiT32[k][ 8]*O[ 8] + g_aiT32[k][ 9]*O[ 9] + g_aiT32[k][10]*O[10] + g_aiT32[k][11]*O[11] + 
+        g_aiT32[k][12]*O[12] + g_aiT32[k][13]*O[13] + g_aiT32[k][14]*O[14] + g_aiT32[k][15]*O[15] + add)>>shift;
+    }
+    src += 32;
+    dst ++;
+  }
+}
+
+
+void partialButterflyInverse32(short *src,short *dst,int shift, int line)
+{
+  int j,k;  
+  int E[16],O[16];
+  int EE[8],EO[8];
+  int EEE[4],EEO[4];
+  int EEEE[2],EEEO[2];
+  int add = 1<<(shift-1);
+
+  for (j=0; j<line; j++)
+  {    
+    /* Utilizing symmetry properties to the maximum to minimize the number of multiplications */
+    for (k=0;k<16;k++)
+    {
+      O[k] = g_aiT32[ 1][k]*src[ line  ] + g_aiT32[ 3][k]*src[ 3*line  ] + g_aiT32[ 5][k]*src[ 5*line  ] + g_aiT32[ 7][k]*src[ 7*line  ] + 
+        g_aiT32[ 9][k]*src[ 9*line  ] + g_aiT32[11][k]*src[ 11*line ] + g_aiT32[13][k]*src[ 13*line ] + g_aiT32[15][k]*src[ 15*line ] + 
+        g_aiT32[17][k]*src[ 17*line ] + g_aiT32[19][k]*src[ 19*line ] + g_aiT32[21][k]*src[ 21*line ] + g_aiT32[23][k]*src[ 23*line ] + 
+        g_aiT32[25][k]*src[ 25*line ] + g_aiT32[27][k]*src[ 27*line ] + g_aiT32[29][k]*src[ 29*line ] + g_aiT32[31][k]*src[ 31*line ];
+    }
+    for (k=0;k<8;k++)
+    {
+      EO[k] = g_aiT32[ 2][k]*src[ 2*line  ] + g_aiT32[ 6][k]*src[ 6*line  ] + g_aiT32[10][k]*src[ 10*line ] + g_aiT32[14][k]*src[ 14*line ] + 
+        g_aiT32[18][k]*src[ 18*line ] + g_aiT32[22][k]*src[ 22*line ] + g_aiT32[26][k]*src[ 26*line ] + g_aiT32[30][k]*src[ 30*line ];
+    }
+    for (k=0;k<4;k++)
+    {
+      EEO[k] = g_aiT32[4][k]*src[ 4*line ] + g_aiT32[12][k]*src[ 12*line ] + g_aiT32[20][k]*src[ 20*line ] + g_aiT32[28][k]*src[ 28*line ];
+    }
+    EEEO[0] = g_aiT32[8][0]*src[ 8*line ] + g_aiT32[24][0]*src[ 24*line ];
+    EEEO[1] = g_aiT32[8][1]*src[ 8*line ] + g_aiT32[24][1]*src[ 24*line ];
+    EEEE[0] = g_aiT32[0][0]*src[ 0      ] + g_aiT32[16][0]*src[ 16*line ];    
+    EEEE[1] = g_aiT32[0][1]*src[ 0      ] + g_aiT32[16][1]*src[ 16*line ];
+
+    /* Combining even and odd terms at each hierarchy levels to calculate the final spatial domain vector */
+    EEE[0] = EEEE[0] + EEEO[0];
+    EEE[3] = EEEE[0] - EEEO[0];
+    EEE[1] = EEEE[1] + EEEO[1];
+    EEE[2] = EEEE[1] - EEEO[1];    
+    for (k=0;k<4;k++)
+    {
+      EE[k] = EEE[k] + EEO[k];
+      EE[k+4] = EEE[3-k] - EEO[3-k];
+    }    
+    for (k=0;k<8;k++)
+    {
+      E[k] = EE[k] + EO[k];
+      E[k+8] = EE[7-k] - EO[7-k];
+    }    
+    for (k=0;k<16;k++)
+    {
+      dst[k]    = Clip3( -32768, 32767, (E[k] + O[k] + add)>>shift );
+      dst[k+16] = Clip3( -32768, 32767, (E[15-k] - O[15-k] + add)>>shift );
+    }
+    src ++;
+    dst += 32;
+  }
+}
+
+/** MxN forward transform (2D)
+*  \param block input data (residual)
+*  \param coeff output data (transform coefficients)
+*  \param iWidth input data (width of transform)
+*  \param iHeight input data (height of transform)
+*/
+void xTrMxN(short *block,short *coeff, int iWidth, int iHeight, UInt uiMode)
+{
+#if FULL_NBIT
+  int shift_1st = g_aucConvertToBit[iWidth]  + 1 + g_uiBitDepth - 8; // log2(iWidth) - 1 + g_uiBitDepth - 8
+#else
+  int shift_1st = g_aucConvertToBit[iWidth]  + 1 + g_uiBitIncrement; // log2(iWidth) - 1 + g_uiBitIncrement
+#endif
+  int shift_2nd = g_aucConvertToBit[iHeight]  + 8;                   // log2(iHeight) + 6
+
+  short tmp[ 64 * 64 ];
+
+#if !REMOVE_NSQT
+  if( iWidth == 16 && iHeight == 4)
+  {
+    partialButterfly16( block, tmp, shift_1st, iHeight );
+    partialButterfly4( tmp, coeff, shift_2nd, iWidth );
+  }
+  else if( iWidth == 32 && iHeight == 8 )
+  {
+    partialButterfly32( block, tmp, shift_1st, iHeight );
+    partialButterfly8( tmp, coeff, shift_2nd, iWidth );
+  }
+  else if( iWidth == 4 && iHeight == 16)
+  {
+    partialButterfly4( block, tmp, shift_1st, iHeight );
+    partialButterfly16( tmp, coeff, shift_2nd, iWidth );
+  }
+  else if( iWidth == 8 && iHeight == 32 )
+  {
+    partialButterfly8( block, tmp, shift_1st, iHeight );
+    partialButterfly32( tmp, coeff, shift_2nd, iWidth );
+  }
+  else
+#endif
+  if( iWidth == 4 && iHeight == 4)
+  {
+#if INTRA_TRANS_SIMP
+    if (uiMode != REG_DCT)
+    {
+      fastForwardDst(block,tmp,shift_1st); // Forward DST BY FAST ALGORITHM, block input, tmp output
+      fastForwardDst(tmp,coeff,shift_2nd); // Forward DST BY FAST ALGORITHM, tmp input, coeff output
+    }
+    else
+    {
+      partialButterfly4(block, tmp, shift_1st, iHeight);
+      partialButterfly4(tmp, coeff, shift_2nd, iWidth);
+    }
+
+#else
+    if (uiMode != REG_DCT && (!uiMode || (uiMode>=2 && uiMode <= 25)))    // Check for DCT or DST
+    {
+      fastForwardDst(block,tmp,shift_1st); // Forward DST BY FAST ALGORITHM, block input, tmp output
+    }
+    else  
+    {
+      partialButterfly4(block, tmp, shift_1st, iHeight);
+    }
+    if (uiMode != REG_DCT && (!uiMode || (uiMode>=11 && uiMode <= 34)))    // Check for DCT or DST
+    {
+      fastForwardDst(tmp,coeff,shift_2nd); // Forward DST BY FAST ALGORITHM, tmp input, coeff output
+    }
+    else  
+    {
+      partialButterfly4(tmp, coeff, shift_2nd, iWidth);
+    }
+#endif
+  }
+  else if( iWidth == 8 && iHeight == 8)
+  {
+    partialButterfly8( block, tmp, shift_1st, iHeight );
+    partialButterfly8( tmp, coeff, shift_2nd, iWidth );
+  }
+  else if( iWidth == 16 && iHeight == 16)
+  {
+    partialButterfly16( block, tmp, shift_1st, iHeight );
+    partialButterfly16( tmp, coeff, shift_2nd, iWidth );
+  }
+  else if( iWidth == 32 && iHeight == 32)
+  {
+    partialButterfly32( block, tmp, shift_1st, iHeight );
+    partialButterfly32( tmp, coeff, shift_2nd, iWidth );
+  }
+}
+/** MxN inverse transform (2D)
+*  \param coeff input data (transform coefficients)
+*  \param block output data (residual)
+*  \param iWidth input data (width of transform)
+*  \param iHeight input data (height of transform)
+*/
+void xITrMxN(short *coeff,short *block, int iWidth, int iHeight, UInt uiMode)
+{
+  int shift_1st = SHIFT_INV_1ST;
+#if FULL_NBIT
+  int shift_2nd = SHIFT_INV_2ND - ((short)g_uiBitDepth - 8);
+#else
+  int shift_2nd = SHIFT_INV_2ND - g_uiBitIncrement;
+#endif
+
+  short tmp[ 64*64];
+#if !REMOVE_NSQT
+  if( iWidth == 16 && iHeight == 4)
+  {
+    partialButterflyInverse4(coeff,tmp,shift_1st,iWidth);
+    partialButterflyInverse16(tmp,block,shift_2nd,iHeight);
+  }
+  else if( iWidth == 32 && iHeight == 8)
+  {
+    partialButterflyInverse8(coeff,tmp,shift_1st,iWidth);
+    partialButterflyInverse32(tmp,block,shift_2nd,iHeight);
+  }
+  else if( iWidth == 4 && iHeight == 16)
+  {
+    partialButterflyInverse16(coeff,tmp,shift_1st,iWidth);
+    partialButterflyInverse4(tmp,block,shift_2nd,iHeight);
+  }
+  else if( iWidth == 8 && iHeight == 32)
+  {
+    partialButterflyInverse32(coeff,tmp,shift_1st,iWidth);
+    partialButterflyInverse8(tmp,block,shift_2nd,iHeight);
+  }
+  else
+#endif
+  if( iWidth == 4 && iHeight == 4)
+  {
+#if INTRA_TRANS_SIMP
+    if (uiMode != REG_DCT)
+    {
+      fastInverseDst(coeff,tmp,shift_1st);    // Inverse DST by FAST Algorithm, coeff input, tmp output
+      fastInverseDst(tmp,block,shift_2nd); // Inverse DST by FAST Algorithm, tmp input, coeff output
+    }
+    else
+    {
+      partialButterflyInverse4(coeff,tmp,shift_1st,iWidth);
+      partialButterflyInverse4(tmp,block,shift_2nd,iHeight);
+    }
+#else
+    if (uiMode != REG_DCT && (!uiMode || (uiMode>=11 && uiMode <= 34)))    // Check for DCT or DST
+    {
+      fastInverseDst(coeff,tmp,shift_1st);    // Inverse DST by FAST Algorithm, coeff input, tmp output
+    }
+    else
+    {
+      partialButterflyInverse4(coeff,tmp,shift_1st,iWidth);    
+    } 
+    if (uiMode != REG_DCT && (!uiMode || (uiMode>=2 && uiMode <= 25)))    // Check for DCT or DST
+    {
+      fastInverseDst(tmp,block,shift_2nd); // Inverse DST by FAST Algorithm, tmp input, coeff output
+    }
+    else
+    {
+      partialButterflyInverse4(tmp,block,shift_2nd,iHeight);
+    } 
+#endif
+  }
+  else if( iWidth == 8 && iHeight == 8)
+  {
+    partialButterflyInverse8(coeff,tmp,shift_1st,iWidth);
+    partialButterflyInverse8(tmp,block,shift_2nd,iHeight);
+  }
+  else if( iWidth == 16 && iHeight == 16)
+  {
+    partialButterflyInverse16(coeff,tmp,shift_1st,iWidth);
+    partialButterflyInverse16(tmp,block,shift_2nd,iHeight);
+  }
+  else if( iWidth == 32 && iHeight == 32)
+  {
+    partialButterflyInverse32(coeff,tmp,shift_1st,iWidth);
+    partialButterflyInverse32(tmp,block,shift_2nd,iHeight);
+  }
+}
+
+#endif //MATRIX_MULT
+
+// To minimize the distortion only. No rate is considered. 
+Void TComTrQuant::signBitHidingHDQ( TComDataCU* pcCU, TCoeff* pQCoef, TCoeff* pCoef, UInt const *scan, Int* deltaU, Int width, Int height )
+{
+  Int lastCG = -1;
+  Int absSum = 0 ;
+  Int n ;
+
+  for( Int subSet = (width*height-1) >> LOG2_SCAN_SET_SIZE; subSet >= 0; subSet-- )
+  {
+    Int  subPos     = subSet << LOG2_SCAN_SET_SIZE;
+    Int  firstNZPosInCG=SCAN_SET_SIZE , lastNZPosInCG=-1 ;
+    absSum = 0 ;
+
+    for(n = SCAN_SET_SIZE-1; n >= 0; --n )
+    {
+      if( pQCoef[ scan[ n + subPos ]] )
+      {
+        lastNZPosInCG = n;
+        break;
+      }
+    }
+
+    for(n = 0; n <SCAN_SET_SIZE; n++ )
+    {
+      if( pQCoef[ scan[ n + subPos ]] )
+      {
+        firstNZPosInCG = n;
+        break;
+      }
+    }
+
+    for(n = firstNZPosInCG; n <=lastNZPosInCG; n++ )
+    {
+      absSum += pQCoef[ scan[ n + subPos ]];
+    }
+
+    if(lastNZPosInCG>=0 && lastCG==-1) 
+    {
+      lastCG = 1 ; 
+    }
+
+    if( lastNZPosInCG-firstNZPosInCG>=SBH_THRESHOLD )
+    {
+      UInt signbit = (pQCoef[scan[subPos+firstNZPosInCG]]>0?0:1) ;
+      if( signbit!=(absSum&0x1) )  //compare signbit with sum_parity
+      {
+        Int minCostInc = MAX_INT,  minPos =-1, finalChange=0, curCost=MAX_INT, curChange=0;
+        
+        for( n = (lastCG==1?lastNZPosInCG:SCAN_SET_SIZE-1) ; n >= 0; --n )
+        {
+          UInt blkPos   = scan[ n+subPos ];
+          if(pQCoef[ blkPos ] != 0 )
+          {
+            if(deltaU[blkPos]>0)
+            {
+              curCost = - deltaU[blkPos]; 
+              curChange=1 ;
+            }
+            else 
+            {
+              //curChange =-1;
+              if(n==firstNZPosInCG && abs(pQCoef[blkPos])==1)
+              {
+                curCost=MAX_INT ; 
+              }
+              else
+              {
+                curCost = deltaU[blkPos]; 
+                curChange =-1;
+              }
+            }
+          }
+          else
+          {
+            if(n<firstNZPosInCG)
+            {
+              UInt thisSignBit = (pCoef[blkPos]>=0?0:1);
+              if(thisSignBit != signbit )
+              {
+                curCost = MAX_INT;
+              }
+              else
+              { 
+                curCost = - (deltaU[blkPos])  ;
+                curChange = 1 ;
+              }
+            }
+            else
+            {
+              curCost = - (deltaU[blkPos])  ;
+              curChange = 1 ;
+            }
+          }
+
+          if( curCost<minCostInc)
+          {
+            minCostInc = curCost ;
+            finalChange = curChange ;
+            minPos = blkPos ;
+          }
+        } //CG loop
+
+        if(pQCoef[minPos] == 32767 || pQCoef[minPos] == -32768)
+        {
+          finalChange = -1;
+        }
+
+        if(pCoef[minPos]>=0)
+        {
+          pQCoef[minPos] += finalChange ; 
+        }
+        else 
+        { 
+          pQCoef[minPos] -= finalChange ;
+        }  
+      } // Hide
+    }
+    if(lastCG==1) 
+    {
+      lastCG=0 ;
+    }
+  } // TU loop
+
+  return;
+}
+
+Void TComTrQuant::xQuant( TComDataCU* pcCU, 
+                          Int*        pSrc, 
+                          TCoeff*     pDes, 
+#if ADAPTIVE_QP_SELECTION
+                          Int*&       pArlDes,
+#endif
+                          Int         iWidth, 
+                          Int         iHeight, 
+                          UInt&       uiAcSum, 
+                          TextType    eTType, 
+                          UInt        uiAbsPartIdx )
+{
+  Int*   piCoef    = pSrc;
+  TCoeff* piQCoef   = pDes;
+#if ADAPTIVE_QP_SELECTION
+  Int*   piArlCCoef = pArlDes;
+#endif
+  Int   iAdd = 0;
+ 
+  Bool useRDOQForTransformSkip = !(m_useTransformSkipFast && pcCU->getTransformSkip(uiAbsPartIdx,eTType));
+  if ( m_bUseRDOQ && (eTType == TEXT_LUMA || RDOQ_CHROMA) && useRDOQForTransformSkip)
+  {
+#if ADAPTIVE_QP_SELECTION
+    xRateDistOptQuant( pcCU, piCoef, pDes, pArlDes, iWidth, iHeight, uiAcSum, eTType, uiAbsPartIdx );
+#else
+    xRateDistOptQuant( pcCU, piCoef, pDes, iWidth, iHeight, uiAcSum, eTType, uiAbsPartIdx );
+#endif
+  }
+  else
+  {
+    const UInt   log2BlockSize   = g_aucConvertToBit[ iWidth ] + 2;
+
+    UInt scanIdx = pcCU->getCoefScanIdx(uiAbsPartIdx, iWidth, eTType==TEXT_LUMA, pcCU->isIntra(uiAbsPartIdx));
+    if (scanIdx == SCAN_ZIGZAG)
+    {
+      scanIdx = SCAN_DIAG;
+    }
+
+#if REMOVE_NSQT
+    const UInt *scan = g_auiSigLastScan[ scanIdx ][ log2BlockSize - 1 ];
+#else
+    if (iWidth != iHeight)
+    {
+      scanIdx = SCAN_DIAG;
+    }
+    
+    const UInt * scan;
+    if (iWidth == iHeight)
+    {
+      scan = g_auiSigLastScan[ scanIdx ][ log2BlockSize - 1 ];
+    }
+    else
+    {
+      scan = g_sigScanNSQT[ log2BlockSize - 2 ];
+    }
+#endif
+    
+    Int deltaU[32*32] ;
+
+#if ADAPTIVE_QP_SELECTION
+    QpParam cQpBase;
+    Int iQpBase = pcCU->getSlice()->getSliceQpBase();
+
+    Int qpScaled;
+    Int qpBDOffset = (eTType == TEXT_LUMA)? pcCU->getSlice()->getSPS()->getQpBDOffsetY() : pcCU->getSlice()->getSPS()->getQpBDOffsetC();
+
+    if(eTType == TEXT_LUMA)
+    {
+      qpScaled = iQpBase + qpBDOffset;
+    }
+    else
+    {
+#if CHROMA_QP_EXTENSION
+      qpScaled = Clip3( -qpBDOffset, 57, iQpBase);
+#else
+      qpScaled = Clip3( -qpBDOffset, 51, iQpBase);
+#endif
+
+      if(qpScaled < 0)
+      {
+        qpScaled = qpScaled +  qpBDOffset;
+      }
+      else
+      {
+#if CHROMA_QP_EXTENSION
+        qpScaled = g_aucChromaScale[ qpScaled ] + qpBDOffset;
+#else
+        qpScaled = g_aucChromaScale[ Clip3(0, 51, qpScaled) ] + qpBDOffset;
+#endif
+      }
+    }
+    cQpBase.setQpParam(qpScaled);
+#endif
+
+#if !REMOVE_NSQT
+    Bool bNonSqureFlag = ( iWidth != iHeight );
+#endif
+    UInt dir           = SCALING_LIST_SQT;
+#if !REMOVE_NSQT
+    if( bNonSqureFlag )
+    {
+      dir = ( iWidth < iHeight )?  SCALING_LIST_VER: SCALING_LIST_HOR;
+      UInt uiWidthBit  = g_aucConvertToBit[ iWidth ] + 2;
+      UInt uiHeightBit = g_aucConvertToBit[ iHeight ] + 2;
+      iWidth  = 1 << ( ( uiWidthBit + uiHeightBit) >> 1 );
+      iHeight = iWidth;
+    }    
+#endif
+    
+    UInt uiLog2TrSize = g_aucConvertToBit[ iWidth ] + 2;
+    Int scalingListType = (pcCU->isIntra(uiAbsPartIdx) ? 0 : 3) + g_eTTable[(Int)eTType];
+    assert(scalingListType < 6);
+    Int *piQuantCoeff = 0;
+    piQuantCoeff = getQuantCoeff(scalingListType,m_cQP.m_iRem,uiLog2TrSize-2, dir);
+
+#if FULL_NBIT
+    UInt uiBitDepth = g_uiBitDepth;
+#else
+    UInt uiBitDepth = g_uiBitDepth + g_uiBitIncrement;
+#endif
+    Int iTransformShift = MAX_TR_DYNAMIC_RANGE - uiBitDepth - uiLog2TrSize;  // Represents scaling through forward transform
+
+    Int iQBits = QUANT_SHIFT + m_cQP.m_iPer + iTransformShift;                // Right shift of non-RDOQ quantizer;  level = (coeff*uiQ + offset)>>q_bits
+
+    iAdd = (pcCU->getSlice()->getSliceType()==I_SLICE ? 171 : 85) << (iQBits-9);
+
+#if ADAPTIVE_QP_SELECTION
+    iQBits = QUANT_SHIFT + cQpBase.m_iPer + iTransformShift;
+    iAdd = (pcCU->getSlice()->getSliceType()==I_SLICE ? 171 : 85) << (iQBits-9);
+    Int iQBitsC = QUANT_SHIFT + cQpBase.m_iPer + iTransformShift - ARL_C_PRECISION;  
+    Int iAddC   = 1 << (iQBitsC-1);
+#endif
+
+    Int qBits8 = iQBits-8;
+    for( Int n = 0; n < iWidth*iHeight; n++ )
+    {
+      Int iLevel;
+      Int  iSign;
+      UInt uiBlockPos = n;
+      iLevel  = piCoef[uiBlockPos];
+      iSign   = (iLevel < 0 ? -1: 1);      
+
+#if ADAPTIVE_QP_SELECTION
+      Int64 tmpLevel = (Int64)abs(iLevel) * piQuantCoeff[uiBlockPos];
+      if( m_bUseAdaptQpSelect )
+      {
+        piArlCCoef[uiBlockPos] = (Int)((tmpLevel + iAddC ) >> iQBitsC);
+      }
+      iLevel = (Int)((tmpLevel + iAdd ) >> iQBits);
+      deltaU[uiBlockPos] = (Int)((tmpLevel - (iLevel<<iQBits) )>> qBits8);
+#else
+      iLevel = ((Int64)abs(iLevel) * piQuantCoeff[uiBlockPos] + iAdd ) >> iQBits;
+      deltaU[uiBlockPos] = (Int)( ((Int64)abs(iLevel) * piQuantCoeff[uiBlockPos] - (iLevel<<iQBits) )>> qBits8 );
+#endif
+      uiAcSum += iLevel;
+      iLevel *= iSign;        
+      piQCoef[uiBlockPos] = Clip3( -32768, 32767, iLevel );
+    } // for n
+    if( pcCU->getSlice()->getPPS()->getSignHideFlag() )
+    {
+      if(uiAcSum>=2)
+      {
+        signBitHidingHDQ( pcCU, piQCoef, piCoef, scan, deltaU, iWidth, iHeight ) ;
+      }
+    }
+  } //if RDOQ
+  //return;
+
+}
+
+Void TComTrQuant::xDeQuant( const TCoeff* pSrc, Int* pDes, Int iWidth, Int iHeight, Int scalingListType )
+{
+  
+  const TCoeff* piQCoef   = pSrc;
+  Int*   piCoef    = pDes;
+  UInt dir          = SCALING_LIST_SQT;
+#if !REMOVE_NSQT
+  if( iWidth != iHeight )
+  {
+    dir          = ( iWidth < iHeight )? SCALING_LIST_VER: SCALING_LIST_HOR;
+    UInt uiWidthBit  = g_aucConvertToBit[ iWidth ]  + 2;
+    UInt uiHeightBit = g_aucConvertToBit[ iHeight ] + 2;
+    iWidth  = 1 << ( ( uiWidthBit + uiHeightBit) >> 1 );
+    iHeight = iWidth;
+  }    
+#endif
+  
+  if ( iWidth > (Int)m_uiMaxTrSize )
+  {
+    iWidth  = m_uiMaxTrSize;
+    iHeight = m_uiMaxTrSize;
+  }
+  
+  Int iShift,iAdd,iCoeffQ;
+  UInt uiLog2TrSize = g_aucConvertToBit[ iWidth ] + 2;
+
+#if FULL_NBIT
+  UInt uiBitDepth = g_uiBitDepth;
+#else
+  UInt uiBitDepth = g_uiBitDepth + g_uiBitIncrement;
+#endif
+  Int iTransformShift = MAX_TR_DYNAMIC_RANGE - uiBitDepth - uiLog2TrSize; 
+
+  iShift = QUANT_IQUANT_SHIFT - QUANT_SHIFT - iTransformShift;
+
+  TCoeff clipQCoef;
+  const Int bitRange = min( 15, ( Int )( 12 + uiLog2TrSize + uiBitDepth - m_cQP.m_iPer) );
+  const Int levelLimit = 1 << bitRange;
+
+  if(getUseScalingList())
+  {
+    iShift += 4;
+    if(iShift > m_cQP.m_iPer)
+    {
+      iAdd = 1 << (iShift - m_cQP.m_iPer - 1);
+    }
+    else
+    {
+      iAdd = 0;
+    }
+    Int *piDequantCoef = getDequantCoeff(scalingListType,m_cQP.m_iRem,uiLog2TrSize-2,dir);
+
+    if(iShift > m_cQP.m_iPer)
+    {
+      for( Int n = 0; n < iWidth*iHeight; n++ )
+      {
+        clipQCoef = Clip3( -32768, 32767, piQCoef[n] );
+        iCoeffQ = ((clipQCoef * piDequantCoef[n]) + iAdd ) >> (iShift -  m_cQP.m_iPer);
+        piCoef[n] = Clip3(-32768,32767,iCoeffQ);
+      }
+    }
+    else
+    {
+      for( Int n = 0; n < iWidth*iHeight; n++ )
+      {
+        clipQCoef = Clip3( -levelLimit, levelLimit - 1, piQCoef[n] );
+        iCoeffQ = (clipQCoef * piDequantCoef[n]) << (m_cQP.m_iPer - iShift);
+        piCoef[n] = Clip3(-32768,32767,iCoeffQ);
+      }
+    }
+  }
+  else
+  {
+    iAdd = 1 << (iShift-1);
+    Int scale = g_invQuantScales[m_cQP.m_iRem] << m_cQP.m_iPer;
+
+    for( Int n = 0; n < iWidth*iHeight; n++ )
+    {
+      clipQCoef = Clip3( -32768, 32767, piQCoef[n] );
+      iCoeffQ = ( clipQCoef * scale + iAdd ) >> iShift;
+      piCoef[n] = Clip3(-32768,32767,iCoeffQ);
+    }
+  }
+}
+
+Void TComTrQuant::init( UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxTrSize, Int iSymbolMode, UInt *aTableLP4, UInt *aTableLP8, UInt *aTableLastPosVlcIndex,
+                       Bool bUseRDOQ,  Bool bEnc, Bool useTransformSkipFast
+#if ADAPTIVE_QP_SELECTION
+                       , Bool bUseAdaptQpSelect
+#endif
+                       )
+{
+  m_uiMaxTrSize  = uiMaxTrSize;
+  m_bEnc         = bEnc;
+  m_bUseRDOQ     = bUseRDOQ;
+#if ADAPTIVE_QP_SELECTION
+  m_bUseAdaptQpSelect = bUseAdaptQpSelect;
+#endif
+  m_useTransformSkipFast = useTransformSkipFast;
+}
+
+Void TComTrQuant::transformNxN( TComDataCU* pcCU, 
+                               Pel*        pcResidual, 
+                               UInt        uiStride, 
+                               TCoeff*     rpcCoeff, 
+#if ADAPTIVE_QP_SELECTION
+                               Int*&       rpcArlCoeff, 
+#endif
+                               UInt        uiWidth, 
+                               UInt        uiHeight, 
+                               UInt&       uiAbsSum, 
+                               TextType    eTType, 
+                               UInt        uiAbsPartIdx,
+                               Bool        useTransformSkip
+                               )
+{
+  if (pcCU->getCUTransquantBypass(uiAbsPartIdx))
+  {
+    uiAbsSum=0;
+    for (UInt k = 0; k<uiHeight; k++)
+    {
+      for (UInt j = 0; j<uiWidth; j++)
+      {
+        rpcCoeff[k*uiWidth+j]= pcResidual[k*uiStride+j];
+        uiAbsSum += abs(pcResidual[k*uiStride+j]);
+      }
+    }
+    return;
+  }
+  UInt uiMode;  //luma intra pred
+  if(eTType == TEXT_LUMA && pcCU->getPredictionMode(uiAbsPartIdx) == MODE_INTRA )
+  {
+    uiMode = pcCU->getLumaIntraDir( uiAbsPartIdx );
+  }
+  else
+  {
+    uiMode = REG_DCT;
+  }
+  
+  uiAbsSum = 0;
+  assert( (pcCU->getSlice()->getSPS()->getMaxTrSize() >= uiWidth) );
+  if(useTransformSkip)
+  {
+    xTransformSkip( pcResidual, uiStride, m_plTempCoeff, uiWidth, uiHeight );
+  }
+  else
+  {
+    xT( uiMode, pcResidual, uiStride, m_plTempCoeff, uiWidth, uiHeight );
+  }
+  xQuant( pcCU, m_plTempCoeff, rpcCoeff,
+#if ADAPTIVE_QP_SELECTION
+       rpcArlCoeff,
+#endif
+       uiWidth, uiHeight, uiAbsSum, eTType, uiAbsPartIdx );
+}
+
+Void TComTrQuant::invtransformNxN( Bool transQuantBypass, TextType eText, UInt uiMode,Pel* rpcResidual, UInt uiStride, TCoeff*   pcCoeff, UInt uiWidth, UInt uiHeight,  Int scalingListType, Bool useTransformSkip )
+{
+  if(transQuantBypass)
+  {
+    for (UInt k = 0; k<uiHeight; k++)
+    {
+      for (UInt j = 0; j<uiWidth; j++)
+      {
+        rpcResidual[k*uiStride+j] = pcCoeff[k*uiWidth+j];
+      }
+    } 
+    return;
+  }
+  xDeQuant( pcCoeff, m_plTempCoeff, uiWidth, uiHeight, scalingListType);
+  if(useTransformSkip == true)
+  {
+    xITransformSkip( m_plTempCoeff, rpcResidual, uiStride, uiWidth, uiHeight );
+  }
+  else
+  {
+    xIT( uiMode, m_plTempCoeff, rpcResidual, uiStride, uiWidth, uiHeight );
+  }
+}
+
+Void TComTrQuant::invRecurTransformNxN( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eTxt, Pel* rpcResidual, UInt uiAddr, UInt uiStride, UInt uiWidth, UInt uiHeight, UInt uiMaxTrMode, UInt uiTrMode, TCoeff* rpcCoeff )
+{
+  if( !pcCU->getCbf(uiAbsPartIdx, eTxt, uiTrMode) )
+  {
+    return;
+  }
+  
+  UInt uiLumaTrMode, uiChromaTrMode;
+  pcCU->convertTransIdx( uiAbsPartIdx, pcCU->getTransformIdx( uiAbsPartIdx ), uiLumaTrMode, uiChromaTrMode );
+  const UInt uiStopTrMode = eTxt == TEXT_LUMA ? uiLumaTrMode : uiChromaTrMode;
+  
+  if( uiTrMode == uiStopTrMode )
+  {
+    UInt uiDepth      = pcCU->getDepth( uiAbsPartIdx ) + uiTrMode;
+    UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiDepth ] + 2;
+    if( eTxt != TEXT_LUMA && uiLog2TrSize == 2 )
+    {
+      UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( uiDepth - 1 ) << 1 );
+      if( ( uiAbsPartIdx % uiQPDiv ) != 0 )
+      {
+        return;
+      }
+      uiWidth  <<= 1;
+      uiHeight <<= 1;
+    }
+    Pel* pResi = rpcResidual + uiAddr;
+#if !REMOVE_NSQT
+    if( pcCU->useNonSquareTrans( uiTrMode, uiAbsPartIdx ) )
+    {
+      Int trWidth  = uiWidth;
+      Int trHeight = uiHeight;
+      pcCU->getNSQTSize( uiTrMode, uiAbsPartIdx, trWidth, trHeight );
+
+      uiWidth  = trWidth;
+      uiHeight = trHeight;
+    }
+#endif
+    Int scalingListType = (pcCU->isIntra(uiAbsPartIdx) ? 0 : 3) + g_eTTable[(Int)eTxt];
+    assert(scalingListType < 6);
+#if INTER_TRANSFORMSKIP
+    invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), eTxt, REG_DCT, pResi, uiStride, rpcCoeff, uiWidth, uiHeight, scalingListType, pcCU->getTransformSkip(uiAbsPartIdx, eTxt) );
+#else
+    invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), eTxt, REG_DCT, pResi, uiStride, rpcCoeff, uiWidth, uiHeight, scalingListType );
+#endif
+  }
+  else
+  {
+    uiTrMode++;
+    uiWidth  >>= 1;
+    uiHeight >>= 1;
+    Int trWidth = uiWidth, trHeight = uiHeight;
+#if !REMOVE_NSQT
+    Int trLastWidth = uiWidth << 1, trLastHeight = uiHeight << 1;
+    pcCU->getNSQTSize ( uiTrMode, uiAbsPartIdx, trWidth, trHeight );
+    pcCU->getNSQTSize ( uiTrMode - 1, uiAbsPartIdx, trLastWidth, trLastHeight );
+#endif
+    UInt uiAddrOffset = trHeight * uiStride;
+    UInt uiCoefOffset = trWidth * trHeight;
+    UInt uiPartOffset = pcCU->getTotalNumPart() >> ( uiTrMode << 1 );
+#if !REMOVE_NSQT
+    UInt uiInterTUSplitDirection = pcCU->getInterTUSplitDirection ( trWidth, trHeight, trLastWidth, trLastHeight );
+    if( uiInterTUSplitDirection != 2 )
+    {
+      invRecurTransformNxN( pcCU, uiAbsPartIdx, eTxt, rpcResidual, uiAddr                                                                                            , uiStride, uiWidth, uiHeight, uiMaxTrMode, uiTrMode, rpcCoeff ); rpcCoeff += uiCoefOffset; uiAbsPartIdx += uiPartOffset;
+      invRecurTransformNxN( pcCU, uiAbsPartIdx, eTxt, rpcResidual, uiAddr +     trWidth * uiInterTUSplitDirection +     uiAddrOffset * ( 1 - uiInterTUSplitDirection), uiStride, uiWidth, uiHeight, uiMaxTrMode, uiTrMode, rpcCoeff ); rpcCoeff += uiCoefOffset; uiAbsPartIdx += uiPartOffset;
+      invRecurTransformNxN( pcCU, uiAbsPartIdx, eTxt, rpcResidual, uiAddr + 2 * trWidth * uiInterTUSplitDirection + 2 * uiAddrOffset * ( 1 - uiInterTUSplitDirection), uiStride, uiWidth, uiHeight, uiMaxTrMode, uiTrMode, rpcCoeff ); rpcCoeff += uiCoefOffset; uiAbsPartIdx += uiPartOffset;
+      invRecurTransformNxN( pcCU, uiAbsPartIdx, eTxt, rpcResidual, uiAddr + 3 * trWidth * uiInterTUSplitDirection + 3 * uiAddrOffset * ( 1 - uiInterTUSplitDirection), uiStride, uiWidth, uiHeight, uiMaxTrMode, uiTrMode, rpcCoeff );
+    }
+    else
+#endif
+    {
+      invRecurTransformNxN( pcCU, uiAbsPartIdx, eTxt, rpcResidual, uiAddr                         , uiStride, uiWidth, uiHeight, uiMaxTrMode, uiTrMode, rpcCoeff ); rpcCoeff += uiCoefOffset; uiAbsPartIdx += uiPartOffset;
+      invRecurTransformNxN( pcCU, uiAbsPartIdx, eTxt, rpcResidual, uiAddr + trWidth               , uiStride, uiWidth, uiHeight, uiMaxTrMode, uiTrMode, rpcCoeff ); rpcCoeff += uiCoefOffset; uiAbsPartIdx += uiPartOffset;
+      invRecurTransformNxN( pcCU, uiAbsPartIdx, eTxt, rpcResidual, uiAddr + uiAddrOffset          , uiStride, uiWidth, uiHeight, uiMaxTrMode, uiTrMode, rpcCoeff ); rpcCoeff += uiCoefOffset; uiAbsPartIdx += uiPartOffset;
+      invRecurTransformNxN( pcCU, uiAbsPartIdx, eTxt, rpcResidual, uiAddr + uiAddrOffset + trWidth, uiStride, uiWidth, uiHeight, uiMaxTrMode, uiTrMode, rpcCoeff );
+    }
+  }
+}
+
+// ------------------------------------------------------------------------------------------------
+// Logical transform
+// ------------------------------------------------------------------------------------------------
+
+/** Wrapper function between HM interface and core NxN forward transform (2D) 
+ *  \param piBlkResi input data (residual)
+ *  \param psCoeff output data (transform coefficients)
+ *  \param uiStride stride of input residual data
+ *  \param iSize transform size (iSize x iSize)
+ *  \param uiMode is Intra Prediction mode used in Mode-Dependent DCT/DST only
+ */
+Void TComTrQuant::xT( UInt uiMode, Pel* piBlkResi, UInt uiStride, Int* psCoeff, Int iWidth, Int iHeight )
+{
+#if MATRIX_MULT  
+  Int iSize = iWidth;
+#if !REMOVE_NSQT
+  if( iWidth != iHeight)
+  {
+    xTrMxN( piBlkResi, psCoeff, uiStride, (UInt)iWidth, (UInt)iHeight );
+    return;
+  }
+#endif
+  xTr(piBlkResi,psCoeff,uiStride,(UInt)iSize,uiMode);
+#else
+  Int j;
+  {
+    short block[ 64 * 64 ];
+    short coeff[ 64 * 64 ];
+    {
+      for (j = 0; j < iHeight; j++)
+      {    
+        memcpy( block + j * iWidth, piBlkResi + j * uiStride, iWidth * sizeof( short ) );      
+      }
+    }
+    xTrMxN( block, coeff, iWidth, iHeight, uiMode );
+    for ( j = 0; j < iHeight * iWidth; j++ )
+    {    
+      psCoeff[ j ] = coeff[ j ];
+    }
+    return ;
+  }
+#endif  
+}
+
+
+/** Wrapper function between HM interface and core NxN inverse transform (2D) 
+ *  \param plCoef input data (transform coefficients)
+ *  \param pResidual output data (residual)
+ *  \param uiStride stride of input residual data
+ *  \param iSize transform size (iSize x iSize)
+ *  \param uiMode is Intra Prediction mode used in Mode-Dependent DCT/DST only
+ */
+Void TComTrQuant::xIT( UInt uiMode, Int* plCoef, Pel* pResidual, UInt uiStride, Int iWidth, Int iHeight )
+{
+#if MATRIX_MULT  
+  Int iSize = iWidth;
+#if !REMOVE_NSQT
+  if( iWidth != iHeight )
+  {
+    xITrMxN( plCoef, pResidual, uiStride, (UInt)iWidth, (UInt)iHeight );
+    return;
+  }
+#endif
+  xITr(plCoef,pResidual,uiStride,(UInt)iSize,uiMode);
+#else
+  Int j;
+  {
+    short block[ 64 * 64 ];
+    short coeff[ 64 * 64 ];
+    for ( j = 0; j < iHeight * iWidth; j++ )
+    {    
+      coeff[j] = (short)plCoef[j];
+    }
+    xITrMxN( coeff, block, iWidth, iHeight, uiMode );
+    {
+      for ( j = 0; j < iHeight; j++ )
+      {    
+        memcpy( pResidual + j * uiStride, block + j * iWidth, iWidth * sizeof(short) );      
+      }
+    }
+    return ;
+  }
+#endif  
+}
+ 
+/** Wrapper function between HM interface and core 4x4 transform skipping
+ *  \param piBlkResi input data (residual)
+ *  \param psCoeff output data (transform coefficients)
+ *  \param uiStride stride of input residual data
+ *  \param iSize transform size (iSize x iSize)
+ */
+Void TComTrQuant::xTransformSkip( Pel* piBlkResi, UInt uiStride, Int* psCoeff, Int width, Int height )
+{
+  assert( width == height );
+  UInt uiLog2TrSize = g_aucConvertToBit[ width ] + 2;
+#if FULL_NBIT
+  UInt uiBitDepth = g_uiBitDepth;
+#else
+  UInt uiBitDepth = g_uiBitDepth + g_uiBitIncrement;
+#endif
+  Int  shift = MAX_TR_DYNAMIC_RANGE - uiBitDepth - uiLog2TrSize;
+  UInt transformSkipShift;
+  Int  j,k;
+  if(shift >= 0)
+  {
+    transformSkipShift = shift;
+    for (j = 0; j < height; j++)
+    {    
+      for(k = 0; k < width; k ++)
+      {
+        psCoeff[j*height + k] = piBlkResi[j * uiStride + k] << transformSkipShift;      
+      }
+    }
+  }
+  else
+  {
+    //The case when uiBitDepth > 13
+    Int offset;
+    transformSkipShift = -shift;
+    offset = (1 << (transformSkipShift - 1));
+    for (j = 0; j < height; j++)
+    {    
+      for(k = 0; k < width; k ++)
+      {
+        psCoeff[j*height + k] = (piBlkResi[j * uiStride + k] + offset) >> transformSkipShift;      
+      }
+    }
+  }
+}
+
+/** Wrapper function between HM interface and core NxN transform skipping 
+ *  \param plCoef input data (coefficients)
+ *  \param pResidual output data (residual)
+ *  \param uiStride stride of input residual data
+ *  \param iSize transform size (iSize x iSize)
+ */
+Void TComTrQuant::xITransformSkip( Int* plCoef, Pel* pResidual, UInt uiStride, Int width, Int height )
+{
+  assert( width == height );
+  UInt uiLog2TrSize = g_aucConvertToBit[ width ] + 2;
+#if FULL_NBIT
+  UInt uiBitDepth = g_uiBitDepth;
+#else
+  UInt uiBitDepth = g_uiBitDepth + g_uiBitIncrement;
+#endif
+  Int  shift = MAX_TR_DYNAMIC_RANGE - uiBitDepth - uiLog2TrSize; 
+  UInt transformSkipShift; 
+  Int  j,k;
+  if(shift > 0)
+  {
+    Int offset;
+    transformSkipShift = shift;
+    offset = (1 << (transformSkipShift -1));
+    for ( j = 0; j < height; j++ )
+    {    
+      for(k = 0; k < width; k ++)
+      {
+        pResidual[j * uiStride + k] =  (plCoef[j*width+k] + offset) >> transformSkipShift;
+      } 
+    }
+  }
+  else
+  {
+    //The case when uiBitDepth >= 13
+    transformSkipShift = - shift;
+    for ( j = 0; j < height; j++ )
+    {    
+      for(k = 0; k < width; k ++)
+      {
+        pResidual[j * uiStride + k] =  plCoef[j*width+k] << transformSkipShift;
+      }
+    }
+  }
+}
+
+/** RDOQ with CABAC
+ * \param pcCU pointer to coding unit structure
+ * \param plSrcCoeff pointer to input buffer
+ * \param piDstCoeff reference to pointer to output buffer
+ * \param uiWidth block width
+ * \param uiHeight block height
+ * \param uiAbsSum reference to absolute sum of quantized transform coefficient
+ * \param eTType plane type / luminance or chrominance
+ * \param uiAbsPartIdx absolute partition index
+ * \returns Void
+ * Rate distortion optimized quantization for entropy
+ * coding engines using probability models like CABAC
+ */
+Void TComTrQuant::xRateDistOptQuant                 ( TComDataCU*                     pcCU,
+                                                      Int*                            plSrcCoeff,
+                                                      TCoeff*                         piDstCoeff,
+#if ADAPTIVE_QP_SELECTION
+                                                      Int*&                           piArlDstCoeff,
+#endif
+                                                      UInt                            uiWidth,
+                                                      UInt                            uiHeight,
+                                                      UInt&                           uiAbsSum,
+                                                      TextType                        eTType,
+                                                      UInt                            uiAbsPartIdx )
+{
+  Int    iQBits      = m_cQP.m_iBits;
+  Double dTemp       = 0;
+  UInt dir         = SCALING_LIST_SQT;
+  UInt uiLog2TrSize = g_aucConvertToBit[ uiWidth ] + 2;
+  Int uiQ = g_quantScales[m_cQP.rem()];
+#if !REMOVE_NSQT
+  if (uiWidth != uiHeight)
+  {
+    uiLog2TrSize += (uiWidth > uiHeight) ? -1 : 1;
+    dir            = ( uiWidth < uiHeight )?  SCALING_LIST_VER: SCALING_LIST_HOR;
+  }
+#endif
+  
+#if FULL_NBIT
+  UInt uiBitDepth = g_uiBitDepth;
+#else
+  UInt uiBitDepth = g_uiBitDepth + g_uiBitIncrement;  
+#endif
+  Int iTransformShift = MAX_TR_DYNAMIC_RANGE - uiBitDepth - uiLog2TrSize;  // Represents scaling through forward transform
+  UInt       uiGoRiceParam       = 0;
+  Double     d64BlockUncodedCost = 0;
+  const UInt uiLog2BlkSize       = g_aucConvertToBit[ uiWidth ] + 2;
+  const UInt uiMaxNumCoeff       = uiWidth * uiHeight;
+  Int scalingListType = (pcCU->isIntra(uiAbsPartIdx) ? 0 : 3) + g_eTTable[(Int)eTType];
+  assert(scalingListType < 6);
+  
+  iQBits = QUANT_SHIFT + m_cQP.m_iPer + iTransformShift;                   // Right shift of non-RDOQ quantizer;  level = (coeff*uiQ + offset)>>q_bits
+  double dErrScale   = 0;
+  double *pdErrScaleOrg = getErrScaleCoeff(scalingListType,uiLog2TrSize-2,m_cQP.m_iRem,dir);
+  Int *piQCoefOrg = getQuantCoeff(scalingListType,m_cQP.m_iRem,uiLog2TrSize-2,dir);
+  Int *piQCoef = piQCoefOrg;
+  double *pdErrScale = pdErrScaleOrg;
+#if ADAPTIVE_QP_SELECTION
+  Int iQBitsC = iQBits - ARL_C_PRECISION;
+  Int iAddC =  1 << (iQBitsC-1);
+#endif
+  UInt uiScanIdx = pcCU->getCoefScanIdx(uiAbsPartIdx, uiWidth, eTType==TEXT_LUMA, pcCU->isIntra(uiAbsPartIdx));
+  if (uiScanIdx == SCAN_ZIGZAG)
+  {
+    // Map value zigzag to diagonal scan
+    uiScanIdx = SCAN_DIAG;
+  }
+  Int blockType = uiLog2BlkSize;
+#if !REMOVE_NSQT
+  if (uiWidth != uiHeight)
+  {
+    uiScanIdx = SCAN_DIAG;
+    blockType = 4;
+  }
+#endif
+  
+#if ADAPTIVE_QP_SELECTION
+  memset(piArlDstCoeff, 0, sizeof(Int) *  uiMaxNumCoeff);
+#endif
+  
+  Double pdCostCoeff [ 32 * 32 ];
+  Double pdCostSig   [ 32 * 32 ];
+  Double pdCostCoeff0[ 32 * 32 ];
+  ::memset( pdCostCoeff, 0, sizeof(Double) *  uiMaxNumCoeff );
+  ::memset( pdCostSig,   0, sizeof(Double) *  uiMaxNumCoeff );
+  Int rateIncUp   [ 32 * 32 ];
+  Int rateIncDown [ 32 * 32 ];
+  Int sigRateDelta[ 32 * 32 ];
+  Int deltaU      [ 32 * 32 ];
+  ::memset( rateIncUp,    0, sizeof(Int) *  uiMaxNumCoeff );
+  ::memset( rateIncDown,  0, sizeof(Int) *  uiMaxNumCoeff );
+  ::memset( sigRateDelta, 0, sizeof(Int) *  uiMaxNumCoeff );
+  ::memset( deltaU,       0, sizeof(Int) *  uiMaxNumCoeff );
+  
+  const UInt * scanCG;
+#if !REMOVE_NSQT
+  if (uiWidth == uiHeight)
+#endif
+  {
+    scanCG = g_auiSigLastScan[ uiScanIdx ][ uiLog2BlkSize > 3 ? uiLog2BlkSize-2-1 : 0  ];
+    if( uiLog2BlkSize == 3 )
+    {
+      scanCG = g_sigLastScan8x8[ uiScanIdx ];
+    }
+    else if( uiLog2BlkSize == 5 )
+    {
+      scanCG = g_sigLastScanCG32x32;
+    }
+  }
+#if !REMOVE_NSQT
+  else
+  {
+    scanCG = g_sigCGScanNSQT[ uiLog2BlkSize - 2 ];
+  }
+#endif
+  const UInt uiCGSize = (1 << MLS_CG_SIZE);         // 16
+  Double pdCostCoeffGroupSig[ MLS_GRP_NUM ];
+  UInt uiSigCoeffGroupFlag[ MLS_GRP_NUM ];
+  UInt uiNumBlkSide = uiWidth / MLS_CG_SIZE;
+  Int iCGLastScanPos = -1;
+  
+  UInt    uiCtxSet            = 0;
+  Int     c1                  = 1;
+  Int     c2                  = 0;
+#if !REMOVE_NUM_GREATER1
+  UInt    uiNumOne            = 0;
+#endif
+  Double  d64BaseCost         = 0;
+  Int     iLastScanPos        = -1;
+  dTemp                       = dErrScale;
+  
+  UInt    c1Idx     = 0;
+  UInt    c2Idx     = 0;
+  Int     baseLevel;
+  
+#if REMOVE_NSQT
+  const UInt *scan = g_auiSigLastScan[ uiScanIdx ][ uiLog2BlkSize - 1 ];
+#else
+  const UInt * scan;
+  if (uiWidth == uiHeight)
+  {
+    scan = g_auiSigLastScan[ uiScanIdx ][ uiLog2BlkSize - 1 ];    
+  }
+  else
+  {
+    scan = g_sigScanNSQT[ uiLog2BlkSize - 2 ];
+  }
+#endif
+  
+  ::memset( pdCostCoeffGroupSig,   0, sizeof(Double) * MLS_GRP_NUM );
+  ::memset( uiSigCoeffGroupFlag,   0, sizeof(UInt) * MLS_GRP_NUM );
+  
+  UInt uiCGNum = uiWidth * uiHeight >> MLS_CG_SIZE;
+  Int iScanPos;
+  coeffGroupRDStats rdStats;     
+  
+  for (Int iCGScanPos = uiCGNum-1; iCGScanPos >= 0; iCGScanPos--)
+  {
+    UInt uiCGBlkPos = scanCG[ iCGScanPos ];
+    UInt uiCGPosY   = uiCGBlkPos / uiNumBlkSide;
+    UInt uiCGPosX   = uiCGBlkPos - (uiCGPosY * uiNumBlkSide);
+#if !REMOVAL_8x2_2x8_CG
+    if( uiWidth == 8 && uiHeight == 8 && (uiScanIdx == SCAN_HOR || uiScanIdx == SCAN_VER) )
+    {
+      uiCGPosY = (uiScanIdx == SCAN_HOR ? uiCGBlkPos : 0);
+      uiCGPosX = (uiScanIdx == SCAN_VER ? uiCGBlkPos : 0);
+    }
+#endif
+    ::memset( &rdStats, 0, sizeof (coeffGroupRDStats));
+    
+    const Int patternSigCtx = TComTrQuant::calcPatternSigCtx(uiSigCoeffGroupFlag, uiCGPosX, uiCGPosY, uiWidth, uiHeight);
+    for (Int iScanPosinCG = uiCGSize-1; iScanPosinCG >= 0; iScanPosinCG--)
+    {
+      iScanPos = iCGScanPos*uiCGSize + iScanPosinCG;
+      //===== quantization =====
+      UInt    uiBlkPos          = scan[iScanPos];
+      // set coeff
+      uiQ  = piQCoef[uiBlkPos];
+      dTemp = pdErrScale[uiBlkPos];
+      Int lLevelDouble          = plSrcCoeff[ uiBlkPos ];
+      lLevelDouble              = (Int)min<Int64>((Int64)abs((Int)lLevelDouble) * uiQ , MAX_INT - (1 << (iQBits - 1)));
+#if ADAPTIVE_QP_SELECTION
+      if( m_bUseAdaptQpSelect )
+      {
+        piArlDstCoeff[uiBlkPos]   = (Int)(( lLevelDouble + iAddC) >> iQBitsC );
+      }
+#endif
+      UInt uiMaxAbsLevel        = (lLevelDouble + (1 << (iQBits - 1))) >> iQBits;
+      
+      Double dErr               = Double( lLevelDouble );
+      pdCostCoeff0[ iScanPos ]  = dErr * dErr * dTemp;
+      d64BlockUncodedCost      += pdCostCoeff0[ iScanPos ];
+      piDstCoeff[ uiBlkPos ]    = uiMaxAbsLevel;
+      
+      if ( uiMaxAbsLevel > 0 && iLastScanPos < 0 )
+      {
+        iLastScanPos            = iScanPos;
+        uiCtxSet                = (iScanPos < SCAN_SET_SIZE || eTType!=TEXT_LUMA) ? 0 : 2;
+        iCGLastScanPos          = iCGScanPos;
+      }
+      
+      if ( iLastScanPos >= 0 )
+      {
+        //===== coefficient level estimation =====
+        UInt  uiLevel;
+        UInt  uiOneCtx         = 4 * uiCtxSet + c1;
+        UInt  uiAbsCtx         = uiCtxSet + c2;
+        
+        if( iScanPos == iLastScanPos )
+        {
+          uiLevel              = xGetCodedLevel( pdCostCoeff[ iScanPos ], pdCostCoeff0[ iScanPos ], pdCostSig[ iScanPos ], 
+                                                lLevelDouble, uiMaxAbsLevel, 0, uiOneCtx, uiAbsCtx, uiGoRiceParam, 
+                                                c1Idx, c2Idx, iQBits, dTemp, 1 );
+        }
+        else
+        {
+          UInt   uiPosY        = uiBlkPos >> uiLog2BlkSize;
+          UInt   uiPosX        = uiBlkPos - ( uiPosY << uiLog2BlkSize );
+#if REMOVAL_8x2_2x8_CG
+          UShort uiCtxSig      = getSigCtxInc( patternSigCtx, uiScanIdx, uiPosX, uiPosY, blockType, uiWidth, uiHeight, eTType );
+#else
+          UShort uiCtxSig      = getSigCtxInc( patternSigCtx, uiPosX, uiPosY, blockType, uiWidth, uiHeight, eTType );
+#endif
+          uiLevel              = xGetCodedLevel( pdCostCoeff[ iScanPos ], pdCostCoeff0[ iScanPos ], pdCostSig[ iScanPos ],
+                                                lLevelDouble, uiMaxAbsLevel, uiCtxSig, uiOneCtx, uiAbsCtx, uiGoRiceParam, 
+                                                c1Idx, c2Idx, iQBits, dTemp, 0 );
+          sigRateDelta[ uiBlkPos ] = m_pcEstBitsSbac->significantBits[ uiCtxSig ][ 1 ] - m_pcEstBitsSbac->significantBits[ uiCtxSig ][ 0 ];
+        }
+        deltaU[ uiBlkPos ]        = (lLevelDouble - ((Int)uiLevel << iQBits)) >> (iQBits-8);
+        if( uiLevel > 0 )
+        {
+          Int rateNow = xGetICRate( uiLevel, uiOneCtx, uiAbsCtx, uiGoRiceParam, c1Idx, c2Idx );
+          rateIncUp   [ uiBlkPos ] = xGetICRate( uiLevel+1, uiOneCtx, uiAbsCtx, uiGoRiceParam, c1Idx, c2Idx ) - rateNow;
+          rateIncDown [ uiBlkPos ] = xGetICRate( uiLevel-1, uiOneCtx, uiAbsCtx, uiGoRiceParam, c1Idx, c2Idx ) - rateNow;
+        }
+        else // uiLevel == 0
+        {
+          rateIncUp   [ uiBlkPos ] = m_pcEstBitsSbac->m_greaterOneBits[ uiOneCtx ][ 0 ];
+        }
+        piDstCoeff[ uiBlkPos ] = uiLevel;
+        d64BaseCost           += pdCostCoeff [ iScanPos ];
+        
+        
+        baseLevel = (c1Idx < C1FLAG_NUMBER) ? (2 + (c2Idx < C2FLAG_NUMBER)) : 1;
+        if( uiLevel >= baseLevel )
+        {
+          if(uiLevel  > 3*(1<<uiGoRiceParam))
+          {
+            uiGoRiceParam = min<UInt>(uiGoRiceParam+ 1, 4);
+          }
+        }
+        if ( uiLevel >= 1)
+        {
+          c1Idx ++;
+        }
+        
+        //===== update bin model =====
+        if( uiLevel > 1 )
+        {
+          c1 = 0; 
+          c2 += (c2 < 2);
+#if !REMOVE_NUM_GREATER1
+          uiNumOne++;
+#endif
+          c2Idx ++;
+        }
+        else if( (c1 < 3) && (c1 > 0) && uiLevel)
+        {
+          c1++;
+        }
+        
+        //===== context set update =====
+        if( ( iScanPos % SCAN_SET_SIZE == 0 ) && ( iScanPos > 0 ) )
+        {
+#if !REMOVE_NUM_GREATER1
+          c1                = 1;
+#endif
+          c2                = 0;
+          uiGoRiceParam     = 0;
+          
+          c1Idx   = 0;
+          c2Idx   = 0; 
+          uiCtxSet          = (iScanPos == SCAN_SET_SIZE || eTType!=TEXT_LUMA) ? 0 : 2;
+#if REMOVE_NUM_GREATER1
+          if( c1 == 0 )
+#else
+          if( uiNumOne > 0 )
+#endif
+          {
+            uiCtxSet++;
+          }
+#if REMOVE_NUM_GREATER1
+          c1 = 1;
+#else
+          uiNumOne    >>= 1;
+#endif
+        }
+      }
+      else
+      {
+        d64BaseCost    += pdCostCoeff0[ iScanPos ];
+      }
+      rdStats.d64SigCost += pdCostSig[ iScanPos ];
+      if (iScanPosinCG == 0 )
+      {
+        rdStats.d64SigCost_0 = pdCostSig[ iScanPos ];
+      }
+      if (piDstCoeff[ uiBlkPos ] )
+      {
+        uiSigCoeffGroupFlag[ uiCGBlkPos ] = 1;
+        rdStats.d64CodedLevelandDist += pdCostCoeff[ iScanPos ] - pdCostSig[ iScanPos ];
+        rdStats.d64UncodedDist += pdCostCoeff0[ iScanPos ];
+        if ( iScanPosinCG != 0 )
+        {
+          rdStats.iNNZbeforePos0++;
+        }
+      }
+    } //end for (iScanPosinCG)
+    
+    if (iCGLastScanPos >= 0) 
+    {
+      if( iCGScanPos )
+      {
+        if (uiSigCoeffGroupFlag[ uiCGBlkPos ] == 0)
+        {
+          UInt  uiCtxSig = getSigCoeffGroupCtxInc( uiSigCoeffGroupFlag, uiCGPosX, uiCGPosY, uiScanIdx, uiWidth, uiHeight);
+          d64BaseCost += xGetRateSigCoeffGroup(0, uiCtxSig) - rdStats.d64SigCost;;  
+          pdCostCoeffGroupSig[ iCGScanPos ] = xGetRateSigCoeffGroup(0, uiCtxSig);  
+        } 
+        else
+        {
+          if (iCGScanPos < iCGLastScanPos) //skip the last coefficient group, which will be handled together with last position below.
+          {
+            if ( rdStats.iNNZbeforePos0 == 0 ) 
+            {
+              d64BaseCost -= rdStats.d64SigCost_0;
+              rdStats.d64SigCost -= rdStats.d64SigCost_0;
+            }
+            // rd-cost if SigCoeffGroupFlag = 0, initialization
+            Double d64CostZeroCG = d64BaseCost;
+            
+            // add SigCoeffGroupFlag cost to total cost
+            UInt  uiCtxSig = getSigCoeffGroupCtxInc( uiSigCoeffGroupFlag, uiCGPosX, uiCGPosY, uiScanIdx, uiWidth, uiHeight);
+            if (iCGScanPos < iCGLastScanPos)
+            {
+              d64BaseCost  += xGetRateSigCoeffGroup(1, uiCtxSig); 
+              d64CostZeroCG += xGetRateSigCoeffGroup(0, uiCtxSig);  
+              pdCostCoeffGroupSig[ iCGScanPos ] = xGetRateSigCoeffGroup(1, uiCtxSig); 
+            }
+            
+            // try to convert the current coeff group from non-zero to all-zero
+            d64CostZeroCG += rdStats.d64UncodedDist;  // distortion for resetting non-zero levels to zero levels
+            d64CostZeroCG -= rdStats.d64CodedLevelandDist;   // distortion and level cost for keeping all non-zero levels
+            d64CostZeroCG -= rdStats.d64SigCost;     // sig cost for all coeffs, including zero levels and non-zerl levels
+            
+            // if we can save cost, change this block to all-zero block
+            if ( d64CostZeroCG < d64BaseCost )      
+            {
+              uiSigCoeffGroupFlag[ uiCGBlkPos ] = 0;
+              d64BaseCost = d64CostZeroCG;
+              if (iCGScanPos < iCGLastScanPos)
+              {
+                pdCostCoeffGroupSig[ iCGScanPos ] = xGetRateSigCoeffGroup(0, uiCtxSig); 
+              }
+              // reset coeffs to 0 in this block                
+              for (Int iScanPosinCG = uiCGSize-1; iScanPosinCG >= 0; iScanPosinCG--)
+              {
+                iScanPos      = iCGScanPos*uiCGSize + iScanPosinCG;
+                UInt uiBlkPos = scan[ iScanPos ];
+                
+                if (piDstCoeff[ uiBlkPos ])
+                {
+                  piDstCoeff [ uiBlkPos ] = 0;
+                  pdCostCoeff[ iScanPos ] = pdCostCoeff0[ iScanPos ];
+                  pdCostSig  [ iScanPos ] = 0;
+                }
+              }
+            } // end if ( d64CostAllZeros < d64BaseCost )      
+          }
+        } // end if if (uiSigCoeffGroupFlag[ uiCGBlkPos ] == 0)
+      }
+      else
+      {
+        uiSigCoeffGroupFlag[ uiCGBlkPos ] = 1;
+      }
+    }
+  } //end for (iCGScanPos)
+  
+  //===== estimate last position =====
+  if ( iLastScanPos < 0 )
+  {
+    return;
+  }
+  
+  Double  d64BestCost         = 0;
+  Int     ui16CtxCbf          = 0;
+  Int     iBestLastIdxP1      = 0;
+  if( !pcCU->isIntra( uiAbsPartIdx ) && eTType == TEXT_LUMA && pcCU->getTransformIdx( uiAbsPartIdx ) == 0 )
+  {
+    ui16CtxCbf   = 0;
+    d64BestCost  = d64BlockUncodedCost + xGetICost( m_pcEstBitsSbac->blockRootCbpBits[ ui16CtxCbf ][ 0 ] );
+    d64BaseCost += xGetICost( m_pcEstBitsSbac->blockRootCbpBits[ ui16CtxCbf ][ 1 ] );
+  }
+  else
+  {
+    ui16CtxCbf   = pcCU->getCtxQtCbf( uiAbsPartIdx, eTType, pcCU->getTransformIdx( uiAbsPartIdx ) );
+    ui16CtxCbf   = ( eTType ? TEXT_CHROMA : eTType ) * NUM_QT_CBF_CTX + ui16CtxCbf;
+    d64BestCost  = d64BlockUncodedCost + xGetICost( m_pcEstBitsSbac->blockCbpBits[ ui16CtxCbf ][ 0 ] );
+    d64BaseCost += xGetICost( m_pcEstBitsSbac->blockCbpBits[ ui16CtxCbf ][ 1 ] );
+  }
+  
+  Bool bFoundLast = false;
+  for (Int iCGScanPos = iCGLastScanPos; iCGScanPos >= 0; iCGScanPos--)
+  {
+    UInt uiCGBlkPos = scanCG[ iCGScanPos ];
+    
+    d64BaseCost -= pdCostCoeffGroupSig [ iCGScanPos ]; 
+    if (uiSigCoeffGroupFlag[ uiCGBlkPos ])
+    {     
+      for (Int iScanPosinCG = uiCGSize-1; iScanPosinCG >= 0; iScanPosinCG--)
+      {
+        iScanPos = iCGScanPos*uiCGSize + iScanPosinCG;
+        if (iScanPos > iLastScanPos) continue;
+        UInt   uiBlkPos     = scan[iScanPos];
+        
+        if( piDstCoeff[ uiBlkPos ] )
+        {
+          UInt   uiPosY       = uiBlkPos >> uiLog2BlkSize;
+          UInt   uiPosX       = uiBlkPos - ( uiPosY << uiLog2BlkSize );
+          
+          Double d64CostLast= uiScanIdx == SCAN_VER ? xGetRateLast( uiPosY, uiPosX, uiWidth ) : xGetRateLast( uiPosX, uiPosY, uiWidth );
+          Double totalCost = d64BaseCost + d64CostLast - pdCostSig[ iScanPos ];
+          
+          if( totalCost < d64BestCost )
+          {
+            iBestLastIdxP1  = iScanPos + 1;
+            d64BestCost     = totalCost;
+          }
+          if( piDstCoeff[ uiBlkPos ] > 1 )
+          {
+            bFoundLast = true;
+            break;
+          }
+          d64BaseCost      -= pdCostCoeff[ iScanPos ];
+          d64BaseCost      += pdCostCoeff0[ iScanPos ];
+        }
+        else
+        {
+          d64BaseCost      -= pdCostSig[ iScanPos ];
+        }
+      } //end for 
+      if (bFoundLast)
+      {
+        break;
+      }
+    } // end if (uiSigCoeffGroupFlag[ uiCGBlkPos ])
+  } // end for 
+  
+  for ( Int scanPos = 0; scanPos < iBestLastIdxP1; scanPos++ )
+  {
+    Int blkPos = scan[ scanPos ];
+    Int level  = piDstCoeff[ blkPos ];
+    uiAbsSum += level;
+    piDstCoeff[ blkPos ] = ( plSrcCoeff[ blkPos ] < 0 ) ? -level : level;
+  }
+  
+  //===== clean uncoded coefficients =====
+  for ( Int scanPos = iBestLastIdxP1; scanPos <= iLastScanPos; scanPos++ )
+  {
+    piDstCoeff[ scan[ scanPos ] ] = 0;
+  }
+  
+  if( pcCU->getSlice()->getPPS()->getSignHideFlag() && uiAbsSum>=2)
+  {
+    Int64 rdFactor = (Int64)((Double)(g_invQuantScales[m_cQP.rem()])*(Double)(g_invQuantScales[m_cQP.rem()])*(Double)(1<<(2*m_cQP.m_iPer))/m_dLambda/16/(Double)(1<<(2*g_uiBitIncrement)) + 0.5);
+    Int lastCG = -1;
+    Int absSum = 0 ;
+    Int n ;
+    
+    for( Int subSet = (uiWidth*uiHeight-1) >> LOG2_SCAN_SET_SIZE; subSet >= 0; subSet-- )
+    {
+      Int  subPos     = subSet << LOG2_SCAN_SET_SIZE;
+      Int  firstNZPosInCG=SCAN_SET_SIZE , lastNZPosInCG=-1 ;
+      absSum = 0 ;
+      
+      for(n = SCAN_SET_SIZE-1; n >= 0; --n )
+      {
+        if( piDstCoeff[ scan[ n + subPos ]] )
+        {
+          lastNZPosInCG = n;
+          break;
+        }
+      }
+      
+      for(n = 0; n <SCAN_SET_SIZE; n++ )
+      {
+        if( piDstCoeff[ scan[ n + subPos ]] )
+        {
+          firstNZPosInCG = n;
+          break;
+        }
+      }
+      
+      for(n = firstNZPosInCG; n <=lastNZPosInCG; n++ )
+      {
+        absSum += piDstCoeff[ scan[ n + subPos ]];
+      }
+      
+      if(lastNZPosInCG>=0 && lastCG==-1)
+      {
+        lastCG = 1; 
+      } 
+      
+      if( lastNZPosInCG-firstNZPosInCG>=SBH_THRESHOLD )
+      {
+        UInt signbit = (piDstCoeff[scan[subPos+firstNZPosInCG]]>0?0:1);
+        if( signbit!=(absSum&0x1) )  // hide but need tune
+        {
+          // calculate the cost 
+          Int64 minCostInc = MAX_INT64, curCost=MAX_INT64;
+          Int minPos =-1, finalChange=0, curChange=0;
+          
+          for( n = (lastCG==1?lastNZPosInCG:SCAN_SET_SIZE-1) ; n >= 0; --n )
+          {
+            UInt uiBlkPos   = scan[ n + subPos ];
+            if(piDstCoeff[ uiBlkPos ] != 0 )
+            {
+              Int64 costUp   = rdFactor * ( - deltaU[uiBlkPos] ) + rateIncUp[uiBlkPos] ;
+              Int64 costDown = rdFactor * (   deltaU[uiBlkPos] ) + rateIncDown[uiBlkPos] 
+              -   ( abs(piDstCoeff[uiBlkPos])==1?((1<<15)+sigRateDelta[uiBlkPos]):0 );
+              
+              if(lastCG==1 && lastNZPosInCG==n && abs(piDstCoeff[uiBlkPos])==1)
+              {
+                costDown -= (4<<15) ;
+              }
+              
+              if(costUp<costDown)
+              {  
+                curCost = costUp;
+                curChange =  1 ;
+              }
+              else               
+              {
+                curChange = -1 ;
+                if(n==firstNZPosInCG && abs(piDstCoeff[uiBlkPos])==1)
+                {
+                  curCost = MAX_INT64 ;
+                }
+                else
+                {
+                  curCost = costDown ; 
+                }
+              }
+            }
+            else
+            {
+              curCost = rdFactor * ( - (abs(deltaU[uiBlkPos])) ) + (1<<15) + rateIncUp[uiBlkPos] + sigRateDelta[uiBlkPos] ; 
+              curChange = 1 ;
+              
+              if(n<firstNZPosInCG)
+              {
+                UInt thissignbit = (plSrcCoeff[uiBlkPos]>=0?0:1);
+                if(thissignbit != signbit )
+                {
+                  curCost = MAX_INT64;
+                }
+              }
+            }
+            
+            if( curCost<minCostInc)
+            {
+              minCostInc = curCost ;
+              finalChange = curChange ;
+              minPos = uiBlkPos ;
+            }
+          }
+          
+          if(piQCoef[minPos] == 32767 || piQCoef[minPos] == -32768)
+          {
+            finalChange = -1;
+          }
+          
+          if(plSrcCoeff[minPos]>=0)
+          {
+            piDstCoeff[minPos] += finalChange ;
+          }
+          else
+          {
+            piDstCoeff[minPos] -= finalChange ; 
+          }          
+        }
+      }
+      
+      if(lastCG==1)
+      {
+        lastCG=0 ;  
+      }
+    }
+  }
+}
+
+/** Pattern decision for context derivation process of significant_coeff_flag
+ * \param sigCoeffGroupFlag pointer to prior coded significant coeff group
+ * \param posXCG column of current coefficient group
+ * \param posYCG row of current coefficient group
+ * \param width width of the block
+ * \param height height of the block
+ * \returns pattern for current coefficient group
+ */
+Int  TComTrQuant::calcPatternSigCtx( const UInt* sigCoeffGroupFlag, UInt posXCG, UInt posYCG, Int width, Int height )
+{
+#if REMOVAL_8x2_2x8_CG
+  if( width == 4 && height == 4 ) return -1;
+#else
+  if( width == height && width <= 8 ) return -1;
+#endif
+
+  UInt sigRight = 0;
+  UInt sigLower = 0;
+
+  width >>= 2;
+  height >>= 2;
+  if( posXCG < width - 1 )
+  {
+    sigRight = (sigCoeffGroupFlag[ posYCG * width + posXCG + 1 ] != 0);
+  }
+  if (posYCG < height - 1 )
+  {
+    sigLower = (sigCoeffGroupFlag[ (posYCG  + 1 ) * width + posXCG ] != 0);
+  }
+  return sigRight + (sigLower<<1);
+}
+
+/** Context derivation process of coeff_abs_significant_flag
+ * \param patternSigCtx pattern for current coefficient group
+ * \param posX column of current scan position
+ * \param posY row of current scan position
+ * \param blockType log2 value of block size if square block, or 4 otherwise
+ * \param width width of the block
+ * \param height height of the block
+ * \param textureType texture type (TEXT_LUMA...)
+ * \returns ctxInc for current scan position
+ */
+Int TComTrQuant::getSigCtxInc    (
+                                   Int                             patternSigCtx,
+#if REMOVAL_8x2_2x8_CG
+                                   UInt                            scanIdx,
+#endif
+                                   Int                             posX,
+                                   Int                             posY,
+                                   Int                             blockType,
+                                   Int                             width
+                                  ,Int                             height
+                                  ,TextType                        textureType
+                                  )
+{
+  const Int ctxIndMap[16] =
+  {
+    0, 1, 4, 5,
+    2, 3, 4, 5,
+    6, 6, 8, 8,
+    7, 7, 8, 8
+  };
+
+  if( posX + posY == 0 )
+  {
+    return 0;
+  }
+
+  if ( blockType == 2 )
+  {
+    return ctxIndMap[ 4 * posY + posX ];
+  }
+
+#if !REMOVAL_8x2_2x8_CG
+  if ( blockType == 3 )
+  {
+    return 9 + ctxIndMap[ 4 * (posY >> 1) + (posX >> 1) ];
+  }
+
+  Int offset = 18;
+#else
+  Int offset = blockType == 3 ? (scanIdx==SCAN_DIAG ? 9 : 15) : (textureType == TEXT_LUMA ? 21 : 12);
+#endif
+
+  Int posXinSubset = posX-((posX>>2)<<2);
+  Int posYinSubset = posY-((posY>>2)<<2);
+  Int cnt = 0;
+  if(patternSigCtx==0)
+  {
+#if REMOVAL_8x2_2x8_CG
+    cnt = posXinSubset+posYinSubset<=2 ? (posXinSubset+posYinSubset==0 ? 2 : 1) : 0;
+#else
+    cnt = posXinSubset+posYinSubset<=2 ? 1 : 0;
+#endif
+  }
+  else if(patternSigCtx==1)
+  {
+#if REMOVAL_8x2_2x8_CG
+    cnt = posYinSubset<=1 ? (posYinSubset==0 ? 2 : 1) : 0;
+#else
+    cnt = posYinSubset<=1 ? 1 : 0;
+#endif
+  }
+  else if(patternSigCtx==2)
+  {
+#if REMOVAL_8x2_2x8_CG
+    cnt = posXinSubset<=1 ? (posXinSubset==0 ? 2 : 1) : 0;
+#else
+    cnt = posXinSubset<=1 ? 1 : 0;
+#endif
+  }
+  else
+  {
+#if REMOVAL_8x2_2x8_CG
+    cnt = 2;
+#else
+    cnt = posXinSubset+posYinSubset<=4 ? 2 : 1;
+#endif
+  }
+
+  return (( textureType == TEXT_LUMA && ((posX>>2) + (posY>>2)) > 0 ) ? 3 : 0) + offset + cnt;
+}
+
+/** Get the best level in RD sense
+ * \param rd64CodedCost reference to coded cost
+ * \param rd64CodedCost0 reference to cost when coefficient is 0
+ * \param rd64CodedCostSig reference to cost of significant coefficient
+ * \param lLevelDouble reference to unscaled quantized level
+ * \param uiMaxAbsLevel scaled quantized level
+ * \param ui16CtxNumSig current ctxInc for coeff_abs_significant_flag
+ * \param ui16CtxNumOne current ctxInc for coeff_abs_level_greater1 (1st bin of coeff_abs_level_minus1 in AVC)
+ * \param ui16CtxNumAbs current ctxInc for coeff_abs_level_greater2 (remaining bins of coeff_abs_level_minus1 in AVC)
+ * \param ui16AbsGoRice current Rice parameter for coeff_abs_level_minus3
+ * \param iQBits quantization step size
+ * \param dTemp correction factor
+ * \param bLast indicates if the coefficient is the last significant
+ * \returns best quantized transform level for given scan position
+ * This method calculates the best quantized transform level for a given scan position.
+ */
+__inline UInt TComTrQuant::xGetCodedLevel ( Double&                         rd64CodedCost,
+                                            Double&                         rd64CodedCost0,
+                                            Double&                         rd64CodedCostSig,
+                                            Int                             lLevelDouble,
+                                            UInt                            uiMaxAbsLevel,
+                                            UShort                          ui16CtxNumSig,
+                                            UShort                          ui16CtxNumOne,
+                                            UShort                          ui16CtxNumAbs,
+                                            UShort                          ui16AbsGoRice,
+                                            UInt                            c1Idx,
+                                            UInt                            c2Idx,
+                                            Int                             iQBits,
+                                            Double                          dTemp,
+                                            Bool                            bLast        ) const
+{
+  Double dCurrCostSig   = 0; 
+  UInt   uiBestAbsLevel = 0;
+  
+  if( !bLast && uiMaxAbsLevel < 3 )
+  {
+    rd64CodedCostSig    = xGetRateSigCoef( 0, ui16CtxNumSig ); 
+    rd64CodedCost       = rd64CodedCost0 + rd64CodedCostSig;
+    if( uiMaxAbsLevel == 0 )
+    {
+      return uiBestAbsLevel;
+    }
+  }
+  else
+  {
+    rd64CodedCost       = MAX_DOUBLE;
+  }
+
+  if( !bLast )
+  {
+    dCurrCostSig        = xGetRateSigCoef( 1, ui16CtxNumSig );
+  }
+
+  UInt uiMinAbsLevel    = ( uiMaxAbsLevel > 1 ? uiMaxAbsLevel - 1 : 1 );
+  for( Int uiAbsLevel  = uiMaxAbsLevel; uiAbsLevel >= uiMinAbsLevel ; uiAbsLevel-- )
+  {
+    Double dErr         = Double( lLevelDouble  - ( uiAbsLevel << iQBits ) );
+    Double dCurrCost    = dErr * dErr * dTemp + xGetICRateCost( uiAbsLevel, ui16CtxNumOne, ui16CtxNumAbs, ui16AbsGoRice, c1Idx, c2Idx );
+    dCurrCost          += dCurrCostSig;
+
+    if( dCurrCost < rd64CodedCost )
+    {
+      uiBestAbsLevel    = uiAbsLevel;
+      rd64CodedCost     = dCurrCost;
+      rd64CodedCostSig  = dCurrCostSig;
+    }
+  }
+
+  return uiBestAbsLevel;
+}
+
+/** Calculates the cost for specific absolute transform level
+ * \param uiAbsLevel scaled quantized level
+ * \param ui16CtxNumOne current ctxInc for coeff_abs_level_greater1 (1st bin of coeff_abs_level_minus1 in AVC)
+ * \param ui16CtxNumAbs current ctxInc for coeff_abs_level_greater2 (remaining bins of coeff_abs_level_minus1 in AVC)
+ * \param ui16AbsGoRice Rice parameter for coeff_abs_level_minus3
+ * \returns cost of given absolute transform level
+ */
+__inline Double TComTrQuant::xGetICRateCost  ( UInt                            uiAbsLevel,
+                                               UShort                          ui16CtxNumOne,
+                                               UShort                          ui16CtxNumAbs,
+                                               UShort                          ui16AbsGoRice
+                                            ,  UInt                            c1Idx,
+                                               UInt                            c2Idx
+                                               ) const
+{
+  Double iRate = xGetIEPRate();
+  UInt baseLevel  =  (c1Idx < C1FLAG_NUMBER)? (2 + (c2Idx < C2FLAG_NUMBER)) : 1;
+
+  if ( uiAbsLevel >= baseLevel )
+  {    
+    UInt symbol     = uiAbsLevel - baseLevel;
+    UInt length;
+#if COEF_REMAIN_BIN_REDUCTION
+    if (symbol < (COEF_REMAIN_BIN_REDUCTION << ui16AbsGoRice))
+#else
+    if (symbol < (8 << ui16AbsGoRice))
+#endif
+    {
+      length = symbol>>ui16AbsGoRice;
+      iRate += (length+1+ui16AbsGoRice)<< 15;
+    }
+    else
+    {
+      length = ui16AbsGoRice;
+#if COEF_REMAIN_BIN_REDUCTION
+      symbol  = symbol - ( COEF_REMAIN_BIN_REDUCTION << ui16AbsGoRice); 
+#else
+      symbol  = symbol - ( 8 << ui16AbsGoRice);    
+#endif
+      while (symbol >= (1<<length))
+      {
+        symbol -=  (1<<(length++));    
+      }
+#if COEF_REMAIN_BIN_REDUCTION
+      iRate += (COEF_REMAIN_BIN_REDUCTION+length+1-ui16AbsGoRice+length)<< 15;
+#else
+      iRate += (8+length+1-ui16AbsGoRice+length)<< 15;
+#endif
+    }
+    if (c1Idx < C1FLAG_NUMBER)
+    {
+      iRate += m_pcEstBitsSbac->m_greaterOneBits[ ui16CtxNumOne ][ 1 ];
+
+      if (c2Idx < C2FLAG_NUMBER)
+      {
+        iRate += m_pcEstBitsSbac->m_levelAbsBits[ ui16CtxNumAbs ][ 1 ];
+      }
+    }
+  }
+  else
+  if( uiAbsLevel == 1 )
+  {
+    iRate += m_pcEstBitsSbac->m_greaterOneBits[ ui16CtxNumOne ][ 0 ];
+  }
+  else if( uiAbsLevel == 2 )
+  {
+    iRate += m_pcEstBitsSbac->m_greaterOneBits[ ui16CtxNumOne ][ 1 ];
+    iRate += m_pcEstBitsSbac->m_levelAbsBits[ ui16CtxNumAbs ][ 0 ];
+  }
+  else
+  {
+    assert (0);
+  }
+  return xGetICost( iRate );
+}
+
+__inline Int TComTrQuant::xGetICRate  ( UInt                            uiAbsLevel,
+                                       UShort                          ui16CtxNumOne,
+                                       UShort                          ui16CtxNumAbs,
+                                       UShort                          ui16AbsGoRice
+                                     , UInt                            c1Idx,
+                                       UInt                            c2Idx
+                                       ) const
+{
+  Int iRate = 0;
+  UInt baseLevel  =  (c1Idx < C1FLAG_NUMBER)? (2 + (c2Idx < C2FLAG_NUMBER)) : 1;
+
+  if ( uiAbsLevel >= baseLevel )
+  {
+    UInt uiSymbol     = uiAbsLevel - baseLevel;
+    UInt uiMaxVlc     = g_auiGoRiceRange[ ui16AbsGoRice ];
+    Bool bExpGolomb   = ( uiSymbol > uiMaxVlc );
+
+    if( bExpGolomb )
+    {
+      uiAbsLevel  = uiSymbol - uiMaxVlc;
+      int iEGS    = 1;  for( UInt uiMax = 2; uiAbsLevel >= uiMax; uiMax <<= 1, iEGS += 2 );
+      iRate      += iEGS << 15;
+      uiSymbol    = min<UInt>( uiSymbol, ( uiMaxVlc + 1 ) );
+    }
+
+    UShort ui16PrefLen = UShort( uiSymbol >> ui16AbsGoRice ) + 1;
+    UShort ui16NumBins = min<UInt>( ui16PrefLen, g_auiGoRicePrefixLen[ ui16AbsGoRice ] ) + ui16AbsGoRice;
+
+    iRate += ui16NumBins << 15;
+
+    if (c1Idx < C1FLAG_NUMBER)
+    {
+      iRate += m_pcEstBitsSbac->m_greaterOneBits[ ui16CtxNumOne ][ 1 ];
+
+      if (c2Idx < C2FLAG_NUMBER)
+      {
+        iRate += m_pcEstBitsSbac->m_levelAbsBits[ ui16CtxNumAbs ][ 1 ];
+      }
+    }
+  }
+  else
+  if( uiAbsLevel == 0 )
+  {
+    return 0;
+  }
+  else if( uiAbsLevel == 1 )
+  {
+    iRate += m_pcEstBitsSbac->m_greaterOneBits[ ui16CtxNumOne ][ 0 ];
+  }
+  else if( uiAbsLevel == 2 )
+  {
+    iRate += m_pcEstBitsSbac->m_greaterOneBits[ ui16CtxNumOne ][ 1 ];
+    iRate += m_pcEstBitsSbac->m_levelAbsBits[ ui16CtxNumAbs ][ 0 ];
+  }
+  else
+  {
+    assert(0);
+  }
+  return iRate;
+}
+
+__inline Double TComTrQuant::xGetRateSigCoeffGroup  ( UShort                    uiSignificanceCoeffGroup,
+                                                UShort                          ui16CtxNumSig ) const
+{
+  return xGetICost( m_pcEstBitsSbac->significantCoeffGroupBits[ ui16CtxNumSig ][ uiSignificanceCoeffGroup ] );
+}
+
+/** Calculates the cost of signaling the last significant coefficient in the block
+ * \param uiPosX X coordinate of the last significant coefficient
+ * \param uiPosY Y coordinate of the last significant coefficient
+ * \returns cost of last significant coefficient
+ */
+/*
+ * \param uiWidth width of the transform unit (TU)
+*/
+__inline Double TComTrQuant::xGetRateLast   ( const UInt                      uiPosX,
+                                              const UInt                      uiPosY,
+                                              const UInt                      uiBlkWdth     ) const
+{
+  UInt uiCtxX   = g_uiGroupIdx[uiPosX];
+  UInt uiCtxY   = g_uiGroupIdx[uiPosY];
+  Double uiCost = m_pcEstBitsSbac->lastXBits[ uiCtxX ] + m_pcEstBitsSbac->lastYBits[ uiCtxY ];
+  if( uiCtxX > 3 )
+  {
+    uiCost += xGetIEPRate() * ((uiCtxX-2)>>1);
+  }
+  if( uiCtxY > 3 )
+  {
+    uiCost += xGetIEPRate() * ((uiCtxY-2)>>1);
+  }
+  return xGetICost( uiCost );
+}
+
+ /** Calculates the cost for specific absolute transform level
+ * \param uiAbsLevel scaled quantized level
+ * \param ui16CtxNumOne current ctxInc for coeff_abs_level_greater1 (1st bin of coeff_abs_level_minus1 in AVC)
+ * \param ui16CtxNumAbs current ctxInc for coeff_abs_level_greater2 (remaining bins of coeff_abs_level_minus1 in AVC)
+ * \param ui16CtxBase current global offset for coeff_abs_level_greater1 and coeff_abs_level_greater2
+ * \returns cost of given absolute transform level
+ */
+__inline Double TComTrQuant::xGetRateSigCoef  ( UShort                          uiSignificance,
+                                                UShort                          ui16CtxNumSig ) const
+{
+  return xGetICost( m_pcEstBitsSbac->significantBits[ ui16CtxNumSig ][ uiSignificance ] );
+}
+
+/** Get the cost for a specific rate
+ * \param dRate rate of a bit
+ * \returns cost at the specific rate
+ */
+__inline Double TComTrQuant::xGetICost        ( Double                          dRate         ) const
+{
+  return m_dLambda * dRate;
+}
+
+/** Get the cost of an equal probable bit
+ * \returns cost of equal probable bit
+ */
+__inline Double TComTrQuant::xGetIEPRate      (                                               ) const
+{
+  return 32768;
+}
+
+/** Context derivation process of coeff_abs_significant_flag
+ * \param uiSigCoeffGroupFlag significance map of L1
+ * \param uiBlkX column of current scan position
+ * \param uiBlkY row of current scan position
+ * \param uiLog2BlkSize log2 value of block size
+ * \returns ctxInc for current scan position
+ */
+UInt TComTrQuant::getSigCoeffGroupCtxInc  ( const UInt*               uiSigCoeffGroupFlag,
+                                           const UInt                      uiCGPosX,
+                                           const UInt                      uiCGPosY,
+                                           const UInt                      scanIdx,
+                                           Int width, Int height)
+{
+  UInt uiRight = 0;
+  UInt uiLower = 0;
+
+  width >>= 2;
+  height >>= 2;
+#if !REMOVAL_8x2_2x8_CG
+  if( width == 2 && height == 2 ) // 8x8
+  {
+    if( scanIdx == SCAN_HOR )  
+    {
+      width = 1;
+      height = 4;
+    }
+    else if( scanIdx == SCAN_VER )
+    {
+      width = 4;
+      height = 1;
+    }
+  }
+#endif
+  if( uiCGPosX < width - 1 )
+  {
+    uiRight = (uiSigCoeffGroupFlag[ uiCGPosY * width + uiCGPosX + 1 ] != 0);
+  }
+  if (uiCGPosY < height - 1 )
+  {
+    uiLower = (uiSigCoeffGroupFlag[ (uiCGPosY  + 1 ) * width + uiCGPosX ] != 0);
+  }
+  return (uiRight || uiLower);
+
+}
+/** set quantized matrix coefficient for encode
+ * \param scalingList quantaized matrix address
+ */
+Void TComTrQuant::setScalingList(TComScalingList *scalingList)
+{
+  UInt size,list;
+  UInt qp;
+
+  for(size=0;size<SCALING_LIST_SIZE_NUM;size++)
+  {
+    for(list = 0; list < g_scalingListNum[size]; list++)
+    {
+      for(qp=0;qp<SCALING_LIST_REM_NUM;qp++)
+      {
+        xSetScalingListEnc(scalingList,list,size,qp);
+        xSetScalingListDec(scalingList,list,size,qp);
+        setErrScaleCoeff(list,size,qp,SCALING_LIST_SQT);
+        if(size == SCALING_LIST_32x32 || size == SCALING_LIST_16x16)
+        {
+          setErrScaleCoeff(list,size-1,qp,SCALING_LIST_HOR);
+          setErrScaleCoeff(list,size-1,qp,SCALING_LIST_VER);
+        }
+      }
+    }
+  }
+}
+/** set quantized matrix coefficient for decode
+ * \param scalingList quantaized matrix address
+ */
+Void TComTrQuant::setScalingListDec(TComScalingList *scalingList)
+{
+  UInt size,list;
+  UInt qp;
+
+  for(size=0;size<SCALING_LIST_SIZE_NUM;size++)
+  {
+    for(list = 0; list < g_scalingListNum[size]; list++)
+    {
+      for(qp=0;qp<SCALING_LIST_REM_NUM;qp++)
+      {
+        xSetScalingListDec(scalingList,list,size,qp);
+      }
+    }
+  }
+}
+/** set error scale coefficients
+ * \param list List ID
+ * \param uiSize Size
+ * \param uiQP Quantization parameter
+ */
+Void TComTrQuant::setErrScaleCoeff(UInt list,UInt size, UInt qp, UInt dir)
+{
+
+  UInt uiLog2TrSize = g_aucConvertToBit[ g_scalingListSizeX[size] ] + 2;
+#if FULL_NBIT
+  UInt uiBitDepth = g_uiBitDepth;
+#else
+  UInt uiBitDepth = g_uiBitDepth + g_uiBitIncrement;  
+#endif
+
+  Int iTransformShift = MAX_TR_DYNAMIC_RANGE - uiBitDepth - uiLog2TrSize;  // Represents scaling through forward transform
+
+  UInt i,uiMaxNumCoeff = g_scalingListSize[size];
+  Int *piQuantcoeff;
+  double *pdErrScale;
+  piQuantcoeff   = getQuantCoeff(list, qp,size,dir);
+  pdErrScale     = getErrScaleCoeff(list, size, qp,dir);
+
+  double dErrScale = (double)(1<<SCALE_BITS);                              // Compensate for scaling of bitcount in Lagrange cost function
+  dErrScale = dErrScale*pow(2.0,-2.0*iTransformShift);                     // Compensate for scaling through forward transform
+  for(i=0;i<uiMaxNumCoeff;i++)
+  {
+    pdErrScale[i] =  dErrScale/(double)piQuantcoeff[i]/(double)piQuantcoeff[i]/(double)(1<<(2*g_uiBitIncrement));
+  }
+}
+
+/** set quantized matrix coefficient for encode
+ * \param scalingList quantaized matrix address
+ * \param listId List index
+ * \param sizeId size index
+ * \param uiQP Quantization parameter
+ */
+Void TComTrQuant::xSetScalingListEnc(TComScalingList *scalingList, UInt listId, UInt sizeId, UInt qp)
+{
+  UInt width = g_scalingListSizeX[sizeId];
+  UInt height = g_scalingListSizeX[sizeId];
+  UInt ratio = g_scalingListSizeX[sizeId]/min(MAX_MATRIX_SIZE_NUM,(Int)g_scalingListSizeX[sizeId]);
+  Int *quantcoeff;
+  Int *coeff = scalingList->getScalingListAddress(sizeId,listId);
+  quantcoeff   = getQuantCoeff(listId, qp, sizeId, SCALING_LIST_SQT);
+
+  processScalingListEnc(coeff,quantcoeff,g_quantScales[qp]<<4,height,width,ratio,min(MAX_MATRIX_SIZE_NUM,(Int)g_scalingListSizeX[sizeId]),scalingList->getScalingListDC(sizeId,listId));
+
+  if(sizeId == SCALING_LIST_32x32 || sizeId == SCALING_LIST_16x16) //for NSQT
+  {
+    quantcoeff   = getQuantCoeff(listId, qp, sizeId-1,SCALING_LIST_VER);
+    processScalingListEnc(coeff,quantcoeff,g_quantScales[qp]<<4,height,width>>2,ratio,min(MAX_MATRIX_SIZE_NUM,(Int)g_scalingListSizeX[sizeId]),scalingList->getScalingListDC(sizeId,listId));
+
+    quantcoeff   = getQuantCoeff(listId, qp, sizeId-1,SCALING_LIST_HOR);
+    processScalingListEnc(coeff,quantcoeff,g_quantScales[qp]<<4,height>>2,width,ratio,min(MAX_MATRIX_SIZE_NUM,(Int)g_scalingListSizeX[sizeId]),scalingList->getScalingListDC(sizeId,listId));
+  }
+}
+/** set quantized matrix coefficient for decode
+ * \param scalingList quantaized matrix address
+ * \param list List index
+ * \param size size index
+ * \param uiQP Quantization parameter
+ */
+Void TComTrQuant::xSetScalingListDec(TComScalingList *scalingList, UInt listId, UInt sizeId, UInt qp)
+{
+  UInt width = g_scalingListSizeX[sizeId];
+  UInt height = g_scalingListSizeX[sizeId];
+  UInt ratio = g_scalingListSizeX[sizeId]/min(MAX_MATRIX_SIZE_NUM,(Int)g_scalingListSizeX[sizeId]);
+  Int *dequantcoeff;
+  Int *coeff = scalingList->getScalingListAddress(sizeId,listId);
+
+  dequantcoeff = getDequantCoeff(listId, qp, sizeId,SCALING_LIST_SQT);
+  processScalingListDec(coeff,dequantcoeff,g_invQuantScales[qp],height,width,ratio,min(MAX_MATRIX_SIZE_NUM,(Int)g_scalingListSizeX[sizeId]),scalingList->getScalingListDC(sizeId,listId));
+
+  if(sizeId == SCALING_LIST_32x32 || sizeId == SCALING_LIST_16x16)
+  {
+    dequantcoeff   = getDequantCoeff(listId, qp, sizeId-1,SCALING_LIST_VER);
+    processScalingListDec(coeff,dequantcoeff,g_invQuantScales[qp],height,width>>2,ratio,min(MAX_MATRIX_SIZE_NUM,(Int)g_scalingListSizeX[sizeId]),scalingList->getScalingListDC(sizeId,listId));
+
+    dequantcoeff   = getDequantCoeff(listId, qp, sizeId-1,SCALING_LIST_HOR);
+
+    processScalingListDec(coeff,dequantcoeff,g_invQuantScales[qp],height>>2,width,ratio,min(MAX_MATRIX_SIZE_NUM,(Int)g_scalingListSizeX[sizeId]),scalingList->getScalingListDC(sizeId,listId));
+  }
+}
+
+/** set flat matrix value to quantized coefficient
+ */
+Void TComTrQuant::setFlatScalingList()
+{
+  UInt size,list;
+  UInt qp;
+
+  for(size=0;size<SCALING_LIST_SIZE_NUM;size++)
+  {
+    for(list = 0; list <  g_scalingListNum[size]; list++)
+    {
+      for(qp=0;qp<SCALING_LIST_REM_NUM;qp++)
+      {
+        xsetFlatScalingList(list,size,qp);
+        setErrScaleCoeff(list,size,qp,SCALING_LIST_SQT);
+        if(size == SCALING_LIST_32x32 || size == SCALING_LIST_16x16)
+        {
+          setErrScaleCoeff(list,size-1,qp,SCALING_LIST_HOR);
+          setErrScaleCoeff(list,size-1,qp,SCALING_LIST_VER);
+        }
+      }
+    }
+  }
+}
+
+/** set flat matrix value to quantized coefficient
+ * \param list List ID
+ * \param uiQP Quantization parameter
+ * \param uiSize Size
+ */
+Void TComTrQuant::xsetFlatScalingList(UInt list, UInt size, UInt qp)
+{
+  UInt i,num = g_scalingListSize[size];
+  UInt numDiv4 = num>>2;
+  Int *quantcoeff;
+  Int *dequantcoeff;
+  Int quantScales = g_quantScales[qp];
+  Int invQuantScales = g_invQuantScales[qp]<<4;
+
+  quantcoeff   = getQuantCoeff(list, qp, size,SCALING_LIST_SQT);
+  dequantcoeff = getDequantCoeff(list, qp, size,SCALING_LIST_SQT);
+
+  for(i=0;i<num;i++)
+  { 
+    *quantcoeff++ = quantScales;
+    *dequantcoeff++ = invQuantScales;
+  }
+
+  if(size == SCALING_LIST_32x32 || size == SCALING_LIST_16x16)
+  {
+    quantcoeff   = getQuantCoeff(list, qp, size-1, SCALING_LIST_HOR);
+    dequantcoeff = getDequantCoeff(list, qp, size-1, SCALING_LIST_HOR);
+
+    for(i=0;i<numDiv4;i++)
+    {
+      *quantcoeff++ = quantScales;
+      *dequantcoeff++ = invQuantScales;
+    }
+    quantcoeff   = getQuantCoeff(list, qp, size-1 ,SCALING_LIST_VER);
+    dequantcoeff = getDequantCoeff(list, qp, size-1 ,SCALING_LIST_VER);
+
+    for(i=0;i<numDiv4;i++)
+    {
+      *quantcoeff++ = quantScales;
+      *dequantcoeff++ = invQuantScales;
+    }
+  }
+}
+
+/** set quantized matrix coefficient for encode
+ * \param coeff quantaized matrix address
+ * \param quantcoeff quantaized matrix address
+ * \param quantScales Q(QP%6)
+ * \param height height
+ * \param width width
+ * \param ratio ratio for upscale
+ * \param sizuNum matrix size
+ * \param dc dc parameter
+ */
+Void TComTrQuant::processScalingListEnc( Int *coeff, Int *quantcoeff, Int quantScales, UInt height, UInt width, UInt ratio, Int sizuNum, UInt dc)
+{
+  Int nsqth = (height < width) ? 4: 1; //height ratio for NSQT
+  Int nsqtw = (width < height) ? 4: 1; //width ratio for NSQT
+  for(UInt j=0;j<height;j++)
+  {
+    for(UInt i=0;i<width;i++)
+    {
+      quantcoeff[j*width + i] = quantScales / coeff[sizuNum * (j * nsqth / ratio) + i * nsqtw /ratio];
+    }
+  }
+  if(ratio > 1)
+  {
+    quantcoeff[0] = quantScales / dc;
+  }
+}
+/** set quantized matrix coefficient for decode
+ * \param coeff quantaized matrix address
+ * \param dequantcoeff quantaized matrix address
+ * \param invQuantScales IQ(QP%6))
+ * \param height height
+ * \param width width
+ * \param ratio ratio for upscale
+ * \param sizuNum matrix size
+ * \param dc dc parameter
+ */
+Void TComTrQuant::processScalingListDec( Int *coeff, Int *dequantcoeff, Int invQuantScales, UInt height, UInt width, UInt ratio, Int sizuNum, UInt dc)
+{
+#if !REMOVE_NSQT
+  Int nsqth = (height < width) ? 4: 1; //height ratio for NSQT
+  Int nsqtw = (width < height) ? 4: 1; //width ratio for NSQT
+#endif
+  for(UInt j=0;j<height;j++)
+  {
+    for(UInt i=0;i<width;i++)
+    {
+#if REMOVE_NSQT
+      dequantcoeff[j*width + i] = invQuantScales * coeff[sizuNum * (j / ratio) + i / ratio];
+#else
+      dequantcoeff[j*width + i] = invQuantScales * coeff[sizuNum * (j * nsqth / ratio) + i * nsqtw /ratio];
+#endif
+    }
+  }
+  if(ratio > 1)
+  {
+    dequantcoeff[0] = invQuantScales * dc;
+  }
+}
+
+/** initialization process of scaling list array
+ */
+Void TComTrQuant::initScalingList()
+{
+  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
+  {
+    for(UInt listId = 0; listId < g_scalingListNum[sizeId]; listId++)
+    {
+      for(UInt qp = 0; qp < SCALING_LIST_REM_NUM; qp++)
+      {
+        m_quantCoef   [sizeId][listId][qp][SCALING_LIST_SQT] = new Int [g_scalingListSize[sizeId]];
+        m_dequantCoef [sizeId][listId][qp][SCALING_LIST_SQT] = new Int [g_scalingListSize[sizeId]];
+        m_errScale    [sizeId][listId][qp][SCALING_LIST_SQT] = new double [g_scalingListSize[sizeId]];
+        
+        if(sizeId == SCALING_LIST_8x8 || (sizeId == SCALING_LIST_16x16 && listId < 2))
+        {
+          for(UInt dir = SCALING_LIST_VER; dir < SCALING_LIST_DIR_NUM; dir++)
+          {
+            m_quantCoef   [sizeId][listId][qp][dir] = new Int [g_scalingListSize[sizeId]];
+            m_dequantCoef [sizeId][listId][qp][dir] = new Int [g_scalingListSize[sizeId]];
+            m_errScale    [sizeId][listId][qp][dir] = new double [g_scalingListSize[sizeId]];
+          }
+        }
+      }
+    }
+  }
+  //copy for NSQT
+  for(UInt qp = 0; qp < SCALING_LIST_REM_NUM; qp++)
+  {
+    for(UInt dir = SCALING_LIST_VER; dir < SCALING_LIST_DIR_NUM; dir++)
+    {
+      m_quantCoef   [SCALING_LIST_16x16][3][qp][dir] = m_quantCoef   [SCALING_LIST_16x16][1][qp][dir];
+      m_dequantCoef [SCALING_LIST_16x16][3][qp][dir] = m_dequantCoef [SCALING_LIST_16x16][1][qp][dir];
+      m_errScale    [SCALING_LIST_16x16][3][qp][dir] = m_errScale    [SCALING_LIST_16x16][1][qp][dir];
+    }
+    m_quantCoef   [SCALING_LIST_32x32][3][qp][SCALING_LIST_SQT] = m_quantCoef   [SCALING_LIST_32x32][1][qp][SCALING_LIST_SQT];
+    m_dequantCoef [SCALING_LIST_32x32][3][qp][SCALING_LIST_SQT] = m_dequantCoef [SCALING_LIST_32x32][1][qp][SCALING_LIST_SQT];
+    m_errScale    [SCALING_LIST_32x32][3][qp][SCALING_LIST_SQT] = m_errScale    [SCALING_LIST_32x32][1][qp][SCALING_LIST_SQT];
+  }
+}
+/** destroy quantization matrix array
+ */
+Void TComTrQuant::destroyScalingList()
+{
+  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
+  {
+    for(UInt listId = 0; listId < g_scalingListNum[sizeId]; listId++)
+    {
+      for(UInt qp = 0; qp < SCALING_LIST_REM_NUM; qp++)
+      {
+        if(m_quantCoef   [sizeId][listId][qp][SCALING_LIST_SQT]) delete [] m_quantCoef   [sizeId][listId][qp][SCALING_LIST_SQT];
+        if(m_dequantCoef [sizeId][listId][qp][SCALING_LIST_SQT]) delete [] m_dequantCoef [sizeId][listId][qp][SCALING_LIST_SQT];
+        if(m_errScale    [sizeId][listId][qp][SCALING_LIST_SQT]) delete [] m_errScale    [sizeId][listId][qp][SCALING_LIST_SQT];
+        if(sizeId == SCALING_LIST_8x8 || (sizeId == SCALING_LIST_16x16 && listId < 2))
+        {
+          for(UInt dir = SCALING_LIST_VER; dir < SCALING_LIST_DIR_NUM; dir++)
+          {
+            if(m_quantCoef   [sizeId][listId][qp][dir]) delete [] m_quantCoef   [sizeId][listId][qp][dir];
+            if(m_dequantCoef [sizeId][listId][qp][dir]) delete [] m_dequantCoef [sizeId][listId][qp][dir];
+            if(m_errScale    [sizeId][listId][qp][dir]) delete [] m_errScale    [sizeId][listId][qp][dir];
+          }
+        }
+      }
+    }
+  }
+}
+
+//! \}
Index: /trunk/source/Lib/TLibCommon/TComTrQuant.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComTrQuant.h	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComTrQuant.h	(revision 2)
@@ -0,0 +1,316 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComTrQuant.h
+    \brief    transform and quantization class (header)
+*/
+
+#ifndef __TCOMTRQUANT__
+#define __TCOMTRQUANT__
+
+#include "CommonDef.h"
+#include "TComYuv.h"
+#include "TComDataCU.h"
+#include "ContextTables.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+#define QP_BITS                 15
+
+// ====================================================================================================================
+// Type definition
+// ====================================================================================================================
+
+typedef struct
+{
+  Int significantCoeffGroupBits[NUM_SIG_CG_FLAG_CTX][2];
+  Int significantBits[NUM_SIG_FLAG_CTX][2];
+  Int lastXBits[32];
+  Int lastYBits[32];
+  Int m_greaterOneBits[NUM_ONE_FLAG_CTX][2];
+  Int m_levelAbsBits[NUM_ABS_FLAG_CTX][2];
+
+  Int blockCbpBits[3*NUM_QT_CBF_CTX][2];
+  Int blockRootCbpBits[4][2];
+  Int scanZigzag[2];            ///< flag for zigzag scan
+  Int scanNonZigzag[2];         ///< flag for non zigzag scan
+} estBitsSbacStruct;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// QP class
+class QpParam
+{
+public:
+  QpParam();
+  
+  Int m_iQP;
+  Int m_iPer;
+  Int m_iRem;
+  
+public:
+  Int m_iBits;
+    
+  Void setQpParam( Int qpScaled )
+  {
+    m_iQP   = qpScaled;
+    m_iPer  = qpScaled / 6;
+    m_iRem  = qpScaled % 6;
+    m_iBits = QP_BITS + m_iPer;
+  }
+  
+  Void clear()
+  {
+    m_iQP   = 0;
+    m_iPer  = 0;
+    m_iRem  = 0;
+    m_iBits = 0;
+  }
+  
+  
+  Int per()   const { return m_iPer; }
+  Int rem()   const { return m_iRem; }
+  Int bits()  const { return m_iBits; }
+  
+  Int qp() {return m_iQP;}
+}; // END CLASS DEFINITION QpParam
+
+/// transform and quantization class
+class TComTrQuant
+{
+public:
+  TComTrQuant();
+  ~TComTrQuant();
+  
+  // initialize class
+  Void init                 ( UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxTrSize, Int iSymbolMode = 0, UInt *aTable4 = NULL, UInt *aTable8 = NULL, UInt *aTableLastPosVlcIndex=NULL, Bool bUseRDOQ = false,  Bool bEnc = false, Bool useTransformSkipFast = false
+#if ADAPTIVE_QP_SELECTION
+    , Bool bUseAdaptQpSelect = false
+#endif 
+    );
+  
+  // transform & inverse transform functions
+  Void transformNxN( TComDataCU* pcCU, 
+                     Pel*        pcResidual, 
+                     UInt        uiStride, 
+                     TCoeff*     rpcCoeff, 
+#if ADAPTIVE_QP_SELECTION
+                     Int*&       rpcArlCoeff, 
+#endif
+                     UInt        uiWidth, 
+                     UInt        uiHeight, 
+                     UInt&       uiAbsSum, 
+                     TextType    eTType, 
+                     UInt        uiAbsPartIdx,
+                     Bool        useTransformSkip = false );
+
+  Void invtransformNxN( Bool transQuantBypass, TextType eText, UInt uiMode,Pel* rpcResidual, UInt uiStride, TCoeff*   pcCoeff, UInt uiWidth, UInt uiHeight,  Int scalingListType, Bool useTransformSkip = false );
+  Void invRecurTransformNxN ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eTxt, Pel* rpcResidual, UInt uiAddr,   UInt uiStride, UInt uiWidth, UInt uiHeight,
+                             UInt uiMaxTrMode,  UInt uiTrMode, TCoeff* rpcCoeff );
+  
+  // Misc functions
+  Void setQPforQuant( Int qpy, TextType eTxtType, Int qpBdOffset, Int chromaQPOffset);
+
+#if RDOQ_CHROMA_LAMBDA 
+  Void setLambda(Double dLambdaLuma, Double dLambdaChroma) { m_dLambdaLuma = dLambdaLuma; m_dLambdaChroma = dLambdaChroma; }
+  Void selectLambda(TextType eTType) { m_dLambda = (eTType == TEXT_LUMA) ? m_dLambdaLuma : m_dLambdaChroma; }
+#else
+  Void setLambda(Double dLambda) { m_dLambda = dLambda;}
+#endif
+  Void setRDOQOffset( UInt uiRDOQOffset ) { m_uiRDOQOffset = uiRDOQOffset; }
+  
+  estBitsSbacStruct* m_pcEstBitsSbac;
+  
+  static Int      calcPatternSigCtx( const UInt* sigCoeffGroupFlag, UInt posXCG, UInt posYCG, Int width, Int height );
+
+  static Int      getSigCtxInc     (
+                                     Int                             patternSigCtx,
+#if REMOVAL_8x2_2x8_CG
+                                     UInt                            scanIdx,
+#endif
+                                     Int                             posX,
+                                     Int                             posY,
+                                     Int                             blockType,
+                                     Int                             width
+                                    ,Int                             height
+                                    ,TextType                        textureType
+                                    );
+  static UInt getSigCoeffGroupCtxInc  ( const UInt*                   uiSigCoeffGroupFlag,
+                                       const UInt                       uiCGPosX,
+                                       const UInt                       uiCGPosY,
+                                       const UInt                     scanIdx,
+                                       Int width, Int height);
+  Void initScalingList                      ();
+  Void destroyScalingList                   ();
+  Void setErrScaleCoeff    ( UInt list, UInt size, UInt qp, UInt dir);
+  double* getErrScaleCoeff ( UInt list, UInt size, UInt qp, UInt dir) {return m_errScale[size][list][qp][dir];};    //!< get Error Scale Coefficent
+  Int* getQuantCoeff       ( UInt list, UInt qp, UInt size, UInt dir) {return m_quantCoef[size][list][qp][dir];};   //!< get Quant Coefficent
+  Int* getDequantCoeff     ( UInt list, UInt qp, UInt size, UInt dir) {return m_dequantCoef[size][list][qp][dir];}; //!< get DeQuant Coefficent
+  Void setUseScalingList   ( Bool bUseScalingList){ m_scalingListEnabledFlag = bUseScalingList; };
+  Bool getUseScalingList   (){ return m_scalingListEnabledFlag; };
+  Void setFlatScalingList  ();
+  Void xsetFlatScalingList ( UInt list, UInt size, UInt qp);
+  Void xSetScalingListEnc  ( TComScalingList *scalingList, UInt list, UInt size, UInt qp);
+  Void xSetScalingListDec  ( TComScalingList *scalingList, UInt list, UInt size, UInt qp);
+  Void setScalingList      ( TComScalingList *scalingList);
+  Void setScalingListDec   ( TComScalingList *scalingList);
+  Void processScalingListEnc( Int *coeff, Int *quantcoeff, Int quantScales, UInt height, UInt width, UInt ratio, Int sizuNum, UInt dc);
+  Void processScalingListDec( Int *coeff, Int *dequantcoeff, Int invQuantScales, UInt height, UInt width, UInt ratio, Int sizuNum, UInt dc);
+#if ADAPTIVE_QP_SELECTION
+  Void    initSliceQpDelta() ;
+  Void    storeSliceQpNext(TComSlice* pcSlice);
+  Void    clearSliceARLCnt();
+  Int     getQpDelta(Int qp) { return m_qpDelta[qp]; } 
+  Int*    getSliceNSamples(){ return m_sliceNsamples ;} 
+  Double* getSliceSumC()    { return m_sliceSumC; }
+#endif
+protected:
+#if ADAPTIVE_QP_SELECTION
+  Int     m_qpDelta[MAX_QP+1]; 
+  Int     m_sliceNsamples[LEVEL_RANGE+1];  
+  Double  m_sliceSumC[LEVEL_RANGE+1] ;  
+#endif
+  Int*    m_plTempCoeff;
+  
+  QpParam  m_cQP;
+#if RDOQ_CHROMA_LAMBDA
+  Double   m_dLambdaLuma;
+  Double   m_dLambdaChroma;
+#endif
+  Double   m_dLambda;
+  UInt     m_uiRDOQOffset;
+  UInt     m_uiMaxTrSize;
+  Bool     m_bEnc;
+  Bool     m_bUseRDOQ;
+#if ADAPTIVE_QP_SELECTION
+  Bool     m_bUseAdaptQpSelect;
+#endif
+  Bool     m_useTransformSkipFast;
+  Bool     m_scalingListEnabledFlag;
+  Int      *m_quantCoef      [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM][SCALING_LIST_REM_NUM][SCALING_LIST_DIR_NUM]; ///< array of quantization matrix coefficient 4x4
+  Int      *m_dequantCoef    [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM][SCALING_LIST_REM_NUM][SCALING_LIST_DIR_NUM]; ///< array of dequantization matrix coefficient 4x4
+  double   *m_errScale       [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM][SCALING_LIST_REM_NUM][SCALING_LIST_DIR_NUM]; ///< array of quantization matrix coefficient 4x4
+private:
+  // forward Transform
+  Void xT   ( UInt uiMode,Pel* pResidual, UInt uiStride, Int* plCoeff, Int iWidth, Int iHeight );
+  
+  // skipping Transform
+  Void xTransformSkip ( Pel* piBlkResi, UInt uiStride, Int* psCoeff, Int width, Int height );
+
+  Void signBitHidingHDQ( TComDataCU* pcCU, TCoeff* pQCoef, TCoeff* pCoef, UInt const *scan, Int* deltaU, Int width, Int height );
+
+  // quantization
+  Void xQuant( TComDataCU* pcCU, 
+               Int*        pSrc, 
+               TCoeff*     pDes, 
+#if ADAPTIVE_QP_SELECTION
+               Int*&       pArlDes,
+#endif
+               Int         iWidth, 
+               Int         iHeight, 
+               UInt&       uiAcSum, 
+               TextType    eTType, 
+               UInt        uiAbsPartIdx );
+
+  // RDOQ functions
+  
+  Void           xRateDistOptQuant ( TComDataCU*                     pcCU,
+                                     Int*                            plSrcCoeff,
+                                     TCoeff*                         piDstCoeff,
+#if ADAPTIVE_QP_SELECTION
+                                     Int*&                           piArlDstCoeff,
+#endif
+                                     UInt                            uiWidth,
+                                     UInt                            uiHeight,
+                                     UInt&                           uiAbsSum,
+                                     TextType                        eTType,
+                                     UInt                            uiAbsPartIdx );
+__inline UInt              xGetCodedLevel  ( Double&                         rd64CodedCost,
+                                             Double&                         rd64CodedCost0,
+                                             Double&                         rd64CodedCostSig,
+                                             Int                             lLevelDouble,
+                                             UInt                            uiMaxAbsLevel,
+                                             UShort                          ui16CtxNumSig,
+                                             UShort                          ui16CtxNumOne,
+                                             UShort                          ui16CtxNumAbs,
+                                             UShort                          ui16AbsGoRice,
+                                             UInt                            c1Idx,  
+                                             UInt                            c2Idx,  
+                                             Int                             iQBits,
+                                             Double                          dTemp,
+                                             Bool                            bLast        ) const;
+  __inline Double xGetICRateCost   ( UInt                            uiAbsLevel,
+                                     UShort                          ui16CtxNumOne,
+                                     UShort                          ui16CtxNumAbs,
+                                     UShort                          ui16AbsGoRice 
+                                   , UInt                            c1Idx,
+                                     UInt                            c2Idx
+                                     ) const;
+__inline Int xGetICRate  ( UInt                            uiAbsLevel,
+                           UShort                          ui16CtxNumOne,
+                           UShort                          ui16CtxNumAbs,
+                           UShort                          ui16AbsGoRice
+                         , UInt                            c1Idx,
+                           UInt                            c2Idx
+                         ) const;
+  __inline Double xGetRateLast     ( const UInt                      uiPosX,
+                                     const UInt                      uiPosY,
+                                     const UInt                      uiBlkWdth     ) const;
+  __inline Double xGetRateSigCoeffGroup (  UShort                    uiSignificanceCoeffGroup,
+                                     UShort                          ui16CtxNumSig ) const;
+  __inline Double xGetRateSigCoef (  UShort                          uiSignificance,
+                                     UShort                          ui16CtxNumSig ) const;
+  __inline Double xGetICost        ( Double                          dRate         ) const; 
+  __inline Double xGetIEPRate      (                                               ) const;
+  
+  
+  // dequantization
+  Void xDeQuant( const TCoeff* pSrc, Int* pDes, Int iWidth, Int iHeight, Int scalingListType );
+  
+  // inverse transform
+  Void xIT    ( UInt uiMode, Int* plCoef, Pel* pResidual, UInt uiStride, Int iWidth, Int iHeight );
+  
+  // inverse skipping transform
+  Void xITransformSkip ( Int* plCoef, Pel* pResidual, UInt uiStride, Int width, Int height );
+};// END CLASS DEFINITION TComTrQuant
+
+//! \}
+
+#endif // __TCOMTRQUANT__
Index: /trunk/source/Lib/TLibCommon/TComUpsampleFilter.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComUpsampleFilter.cpp	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComUpsampleFilter.cpp	(revision 2)
@@ -0,0 +1,389 @@
+
+#include "TComUpsampleFilter.h"
+#include "TypeDef.h"
+
+#if SVC_EXTENSION
+// ====================================================================================================================
+// Tables:
+// 1. PHASE_DERIVATION_IN_INTEGER = 0 is the implementation using 2 multi-phase (12 phase and 8 phase) filter sets 
+//    by following K0378.
+// 2. PHASE_DERIVATION_IN_INTEGER = 1 is the implemetation using a 16-phase filter set just for speed up. Some phases 
+//    is approximated to x/16 (e.g. 1/3 -> 5/16). 
+// 3. It was confirmed that two implementations provides the identical result. 
+// 4. By default, PHASE_DERIVATION_IN_INTEGER is set to 1. 
+// ====================================================================================================================
+#define CNU -1 ///< Coefficients Not Used
+
+#if PHASE_DERIVATION_IN_INTEGER
+const Int TComUpsampleFilter::m_lumaFixedFilter[16][NTAPS_US_LUMA] =
+{
+  {  0,  0,  0, 64,  0,  0,  0,  0}, //
+  {CNU,CNU,CNU,CNU,CNU,CNU,CNU,CNU}, //
+  {CNU,CNU,CNU,CNU,CNU,CNU,CNU,CNU}, //
+  {CNU,CNU,CNU,CNU,CNU,CNU,CNU,CNU}, // 
+  {CNU,CNU,CNU,CNU,CNU,CNU,CNU,CNU}, //
+  { -1, 4, -11, 52, 26,  -8, 3, -1}, // <-> actual phase shift 1/3, used for spatial scalability x1.5      
+  {CNU,CNU,CNU,CNU,CNU,CNU,CNU,CNU}, //       
+  {CNU,CNU,CNU,CNU,CNU,CNU,CNU,CNU}, // 
+  { -1, 4, -11, 40, 40, -11, 4, -1}, // <-> actual phase shift 1/2, equal to HEVC MC, used for spatial scalability x2
+  {CNU,CNU,CNU,CNU,CNU,CNU,CNU,CNU}, // 
+  {CNU,CNU,CNU,CNU,CNU,CNU,CNU,CNU}, // 
+  { -1, 3,  -8, 26, 52, -11, 4, -1}, // <-> actual phase shift 2/3, used for spatial scalability x1.5
+  {CNU,CNU,CNU,CNU,CNU,CNU,CNU,CNU}, // 
+  {CNU,CNU,CNU,CNU,CNU,CNU,CNU,CNU}, // 
+  {CNU,CNU,CNU,CNU,CNU,CNU,CNU,CNU}, // 
+  {CNU,CNU,CNU,CNU,CNU,CNU,CNU,CNU}  // 
+};
+
+const Int TComUpsampleFilter::m_chromaFixedFilter[16][NTAPS_US_CHROMA] =
+{
+  {  0, 64,  0,  0},//
+  {CNU,CNU,CNU,CNU},//
+  {CNU,CNU,CNU,CNU},//
+  {CNU,CNU,CNU,CNU},// 
+  { -4, 54, 16, -2},// <-> actual phase shift 1/4,equal to HEVC MC, used for spatial scalability x1.5 (only for accurate Chroma alignement)
+  { -5, 50, 22, -3},// <-> actual phase shift 1/3, used for spatial scalability x1.5   
+  { -6, 46, 28, -4},// <-> actual phase shift 3/8,equal to HEVC MC, used for spatial scalability x2 (only for accurate Chroma alignement)      
+  {CNU,CNU,CNU,CNU},// 
+  { -4, 36, 36, -4},// <-> actual phase shift 1/2,equal to HEVC MC, used for spatial scalability x2
+  { -4, 30, 43, -5},// <-> actual phase shift 7/12, used for spatial scalability x1.5 (only for accurate Chroma alignement)
+  {CNU,CNU,CNU,CNU},// 
+  { -3, 22, 50, -5},// <-> actual phase shift 2/3, used for spatial scalability x1.5
+  {CNU,CNU,CNU,CNU},// 
+  {CNU,CNU,CNU,CNU},// 
+  { -2, 10, 58, -2},// <-> actual phase shift 7/8,equal to HEVC MC, used for spatial scalability x2 (only for accurate Chroma alignement)  
+  { -1,  5, 62, -2} // <-> actual phase shift 11/12, used for spatial scalability x1.5 (only for accurate Chroma alignement)
+};
+#else
+const Int TComUpsampleFilter::m_lumaFixedFilter[12][NTAPS_US_LUMA] =
+{
+  { 0,  0,   0, 64,  0,   0, 0,  0},
+  {CNU,CNU,CNU,CNU,CNU,CNU,CNU,CNU},//1/12 
+  {CNU,CNU,CNU,CNU,CNU,CNU,CNU,CNU},//2/12 
+  {CNU,CNU,CNU,CNU,CNU,CNU,CNU,CNU},//3/12 
+  { -1, 4, -11, 52, 26,  -8, 3, -1},//4/12 
+  {CNU,CNU,CNU,CNU,CNU,CNU,CNU,CNU},//5/12 
+  { -1, 4, -11, 40, 40, -11, 4, -1},//6/12       
+  {CNU,CNU,CNU,CNU,CNU,CNU,CNU,CNU},//7/12 
+  { -1, 3,  -8, 26, 52, -11, 4, -1},//8/12 
+  {CNU,CNU,CNU,CNU,CNU,CNU,CNU,CNU},//9/12 
+  {CNU,CNU,CNU,CNU,CNU,CNU,CNU,CNU},//10/12
+  {CNU,CNU,CNU,CNU,CNU,CNU,CNU,CNU},//11/12
+};
+
+const Int TComUpsampleFilter::m_chromaFixedFilter15[12][NTAPS_US_CHROMA] =
+{
+  {  0, 64,  0,  0},
+  {CNU,CNU,CNU,CNU},//1/12 
+  {CNU,CNU,CNU,CNU},//2/12 
+  { -4, 54, 16, -2},//3/12 
+  { -5, 50, 22, -3},//4/12 
+  {CNU,CNU,CNU,CNU},//5/12 
+  {CNU,CNU,CNU,CNU},//6/12 
+  { -4, 30, 43, -5},//7/12 
+  { -3, 22, 50, -5},//8/12 
+  {CNU,CNU,CNU,CNU},//9/12 
+  {CNU,CNU,CNU,CNU},//10/12
+  { -1,  5, 62, -2} //11/12
+};
+
+const Int TComUpsampleFilter::m_chromaFixedFilter20[8][NTAPS_US_CHROMA] =
+{
+  {  0, 64,  0,  0},
+  {CNU,CNU,CNU,CNU},//1/8 
+  {CNU,CNU,CNU,CNU},//2/8 
+  { -6, 46, 28, -4},//3/8 
+  { -4, 36, 36, -4},//4/8 
+  {CNU,CNU,CNU,CNU},//5/8 
+  {CNU,CNU,CNU,CNU},//6/8 
+  { -2, 10, 58, -2},//7/8 
+};
+#endif
+
+TComUpsampleFilter::TComUpsampleFilter(void)
+{
+}
+
+TComUpsampleFilter::~TComUpsampleFilter(void)
+{
+}
+
+Void TComUpsampleFilter::upsampleBasePic( TComPicYuv* pcUsPic, TComPicYuv* pcBasePic, TComPicYuv* pcTempPic )
+{
+  assert ( NTAPS_US_LUMA == 8 );
+  assert ( NTAPS_US_CHROMA == 4 );
+
+  Int i, j;
+
+  //========== Y component upsampling ===========
+  Int iBWidth   = pcBasePic->getWidth () - pcBasePic->getPicCropLeftOffset() - pcBasePic->getPicCropRightOffset();
+  Int iBHeight  = pcBasePic->getHeight() - pcBasePic->getPicCropTopOffset() - pcBasePic->getPicCropBottomOffset();
+  Int iBStride  = pcBasePic->getStride();
+
+  Int iEWidth   = pcUsPic->getWidth () - pcUsPic->getPicCropLeftOffset() - pcUsPic->getPicCropRightOffset();
+  Int iEHeight  = pcUsPic->getHeight() - pcUsPic->getPicCropTopOffset() - pcUsPic->getPicCropBottomOffset();
+  Int iEStride  = pcUsPic->getStride();
+
+#if PHASE_DERIVATION_IN_INTEGER
+  Int iRefPos16 = 0;
+  Int phase    = 0;
+  Int refPos   = 0; 
+  Int* coeff = m_chromaFilter[phase];
+  for ( i = 0; i < 16; i++)
+  {
+    memcpy(   m_lumaFilter[i],   m_lumaFixedFilter[i], sizeof(Int) * NTAPS_US_LUMA   );
+    memcpy( m_chromaFilter[i], m_chromaFixedFilter[i], sizeof(Int) * NTAPS_US_CHROMA );
+  }
+#else
+  for ( i = 0; i < 12; i++)
+  {
+    memcpy( m_lumaFilter[i], m_lumaFixedFilter[i], sizeof(Int) * NTAPS_US_LUMA );
+  }
+
+  Int chromaPhaseDenominator;
+  if (iEWidth == 2*iBWidth) // 2x scalability
+  {
+    for ( i = 0; i < 8; i++)
+    {
+      memcpy( m_chromaFilter[i], m_chromaFixedFilter20[i], sizeof(Int) * NTAPS_US_CHROMA );
+    }
+    chromaPhaseDenominator = 8;
+  }
+  else
+  {
+    for ( i = 0; i < 12; i++) // 1.5x scalability
+    {
+      memcpy( m_chromaFilter[i], m_chromaFixedFilter15[i], sizeof(Int) * NTAPS_US_CHROMA );
+    }
+    chromaPhaseDenominator = 12;
+  }
+#endif
+
+  Pel* piTempBufY = pcTempPic->getLumaAddr();
+  Pel* piSrcBufY  = pcBasePic->getLumaAddr();
+  Pel* piDstBufY  = pcUsPic->getLumaAddr();
+
+  Pel* piSrcY;
+  Pel* piDstY;
+
+  assert ( iEWidth == 2*iBWidth || 2*iEWidth == 3*iBWidth );
+  assert ( iEHeight == 2*iBHeight || 2*iEHeight == 3*iBHeight );
+
+  pcBasePic->setBorderExtension(false);
+  pcBasePic->extendPicBorder   (); // extend the border.
+
+#if PHASE_DERIVATION_IN_INTEGER
+  Int   iShiftX = 16;
+  Int   iShiftY = 16;
+
+  Int   iPhaseX = 0;
+  Int   iPhaseY = 0;
+
+  Int   iAddX       = ( ( ( iBWidth * iPhaseX ) << ( iShiftX - 2 ) ) + ( iEWidth >> 1 ) ) / iEWidth + ( 1 << ( iShiftX - 5 ) );
+  Int   iAddY       = ( ( ( iBHeight * iPhaseY ) << ( iShiftY - 2 ) ) + ( iEHeight >> 1 ) ) / iEHeight+ ( 1 << ( iShiftY - 5 ) );
+
+  Int   iDeltaX     = 4 * iPhaseX;
+  Int   iDeltaY     = 4 * iPhaseY;  
+
+
+  Int iShiftXM4 = iShiftX - 4;
+  Int iShiftYM4 = iShiftY - 4;
+
+  Int   iScaleX     = ( ( iBWidth << iShiftX ) + ( iEWidth >> 1 ) ) / iEWidth;
+  Int   iScaleY     = ( ( iBHeight << iShiftY ) + ( iEHeight >> 1 ) ) / iEHeight;
+#else
+  const Double sFactor = 1.0 * iBWidth / iEWidth;
+  const Double sFactor12 = sFactor * 12;
+#endif
+
+  //========== horizontal upsampling ===========
+  for( i = 0; i < iEWidth; i++ )
+  {
+#if PHASE_DERIVATION_IN_INTEGER
+    iRefPos16 = ((i*iScaleX + iAddX) >> iShiftXM4) - iDeltaX;
+    phase    = iRefPos16 & 15;
+    refPos   = iRefPos16 >> 4;
+    coeff = m_lumaFilter[phase];
+#else
+    Int refPos12 = (Int) ( i * sFactor12 );
+    Int refPos = (Int)( i * sFactor );
+    Int phase = (refPos12 + 12) % 12; 
+    Int* coeff = m_lumaFilter[phase];
+#endif
+
+    piSrcY = piSrcBufY + refPos -((NTAPS_US_LUMA>>1) - 1);
+    piDstY = piTempBufY + i;
+
+    for( j = 0; j < iBHeight ; j++ )
+    {
+      *piDstY = sumLumaHor(piSrcY, coeff);
+      piSrcY += iBStride;
+      piDstY += iEStride;
+    }
+  }
+
+
+  //========== vertical upsampling ===========
+  pcTempPic->setBorderExtension(false);
+  pcTempPic->setHeight(iBHeight);
+  pcTempPic->extendPicBorder   (); // extend the border.
+  pcTempPic->setHeight(iEHeight);
+
+  const Int nShift = US_FILTER_PREC*2;
+  Int iOffset = 1 << (nShift - 1); 
+
+  for( j = 0; j < iEHeight; j++ )
+  {
+#if PHASE_DERIVATION_IN_INTEGER
+    iRefPos16 = ((j*iScaleY + iAddY) >> iShiftYM4) - iDeltaY;
+    phase    = iRefPos16 & 15;
+    refPos   = iRefPos16 >> 4;
+    coeff = m_lumaFilter[phase];
+#else
+    Int refPos12 = (Int) (j * sFactor12 );
+    Int refPos = (Int)( j * sFactor );
+    Int phase = (refPos12 + 12) % 12;
+    Int* coeff = m_lumaFilter[phase];
+#endif
+
+    piSrcY = piTempBufY + (refPos -((NTAPS_US_LUMA>>1) - 1))*iEStride;
+    piDstY = piDstBufY + j * iEStride;
+
+    for( i = 0; i < iEWidth; i++ )
+    {
+      *piDstY = Clip( (sumLumaVer(piSrcY, coeff, iEStride) + iOffset) >> (nShift));
+      piSrcY++;
+      piDstY++;
+    }
+  }
+
+  //========== UV component upsampling ===========
+  Pel* piTempBufU = pcTempPic->getCbAddr();
+  Pel* piSrcBufU  = pcBasePic->getCbAddr();
+  Pel* piDstBufU  = pcUsPic->getCbAddr();
+
+  Pel* piTempBufV = pcTempPic->getCrAddr();
+  Pel* piSrcBufV  = pcBasePic->getCrAddr();
+  Pel* piDstBufV  = pcUsPic->getCrAddr();
+
+  Pel* piSrcU;
+  Pel* piDstU;
+  Pel* piSrcV;
+  Pel* piDstV;
+
+  iEWidth  >>= 1;
+  iEHeight >>= 1;
+
+  iBWidth  >>= 1;
+  iBHeight >>= 1;
+
+  iBStride  = pcBasePic->getCStride();
+  iEStride  = pcUsPic->getCStride();
+
+#if PHASE_DERIVATION_IN_INTEGER
+  iShiftX = 16;
+  iShiftY = 16;
+
+  iPhaseX = 0;
+  iPhaseY = 1;
+
+  iAddX       = ( ( ( iBWidth * iPhaseX ) << ( iShiftX - 2 ) ) + ( iEWidth >> 1 ) ) / iEWidth + ( 1 << ( iShiftX - 5 ) );
+  iAddY       = ( ( ( iBHeight * iPhaseY ) << ( iShiftY - 2 ) ) + ( iEHeight >> 1 ) ) / iEHeight+ ( 1 << ( iShiftY - 5 ) );
+
+  iDeltaX     = 4 * iPhaseX;
+  iDeltaY     = 4 * iPhaseY;
+
+  iShiftXM4 = iShiftX - 4;
+  iShiftYM4 = iShiftY - 4;
+
+  iScaleX     = ( ( iBWidth << iShiftX ) + ( iEWidth >> 1 ) ) / iEWidth;
+  iScaleY     = ( ( iBHeight << iShiftY ) + ( iEHeight >> 1 ) ) / iEHeight;
+#endif
+
+  //========== horizontal upsampling ===========
+  for( i = 0; i < iEWidth; i++ )
+  {
+#if PHASE_DERIVATION_IN_INTEGER
+    iRefPos16 = ((i*iScaleX + iAddX) >> iShiftXM4) - iDeltaX;
+    phase    = iRefPos16 & 15;
+    refPos   = iRefPos16 >> 4;
+    coeff = m_chromaFilter[phase];
+#else
+    Int refPosM = (Int) ( i * chromaPhaseDenominator * sFactor );
+    Int refPos = (Int)( i * sFactor );
+    Int phase = (refPosM + chromaPhaseDenominator) % chromaPhaseDenominator;
+    Int* coeff = m_chromaFilter[phase];
+#endif
+
+    piSrcU = piSrcBufU + refPos -((NTAPS_US_CHROMA>>1) - 1);
+    piSrcV = piSrcBufV + refPos -((NTAPS_US_CHROMA>>1) - 1);
+    piDstU = piTempBufU + i;
+    piDstV = piTempBufV + i;
+
+    for( j = 0; j < iBHeight ; j++ )
+    {
+      *piDstU = sumChromaHor(piSrcU, coeff);
+      *piDstV = sumChromaHor(piSrcV, coeff);
+
+      piSrcU += iBStride;
+      piSrcV += iBStride;
+      piDstU += iEStride;
+      piDstV += iEStride;
+    }
+  }
+
+  //========== vertical upsampling ===========
+  pcTempPic->setBorderExtension(false);
+  pcTempPic->setHeight(iBHeight << 1);
+  pcTempPic->extendPicBorder   (); // extend the border.
+  pcTempPic->setHeight(iEHeight << 1);
+
+  for( j = 0; j < iEHeight; j++ )
+  {
+#if PHASE_DERIVATION_IN_INTEGER
+    iRefPos16 = ((j*iScaleY + iAddY) >> iShiftYM4) - iDeltaY;
+    phase    = iRefPos16 & 15;
+    refPos   = iRefPos16 >> 4; 
+    coeff = m_chromaFilter[phase];
+#else
+    Int refPosM = (Int) (j * chromaPhaseDenominator * sFactor) - 1;
+    Int refPos; 
+    if ( refPosM < 0 )
+    {
+      refPos = (Int)( j * sFactor ) - 1;
+    }
+    else
+    {
+      refPos = refPosM / chromaPhaseDenominator;
+    }
+    Int phase = (refPosM + chromaPhaseDenominator) % chromaPhaseDenominator;
+    Int* coeff = m_chromaFilter[phase];
+#endif
+
+    piSrcU = piTempBufU  + (refPos -((NTAPS_US_CHROMA>>1) - 1))*iEStride;
+    piSrcV = piTempBufV  + (refPos -((NTAPS_US_CHROMA>>1) - 1))*iEStride;
+
+    piDstU = piDstBufU + j*iEStride;
+    piDstV = piDstBufV + j*iEStride;
+
+    for( i = 0; i < iEWidth; i++ )
+    {
+      *piDstU = Clip( (sumChromaVer(piSrcU, coeff, iEStride) + iOffset) >> (nShift));
+      *piDstV = Clip( (sumChromaVer(piSrcV, coeff, iEStride) + iOffset) >> (nShift));
+
+      piSrcU++;
+      piSrcV++;
+      piDstU++;
+      piDstV++;
+    }
+  }
+
+  pcUsPic->setBorderExtension(false);
+  pcUsPic->extendPicBorder   (); // extend the border.
+
+  //Reset the Border extension flag
+  pcUsPic->setBorderExtension(false);
+  pcTempPic->setBorderExtension(false);
+  pcBasePic->setBorderExtension(false);
+}
+#endif //SVC_EXTENSION
Index: /trunk/source/Lib/TLibCommon/TComUpsampleFilter.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComUpsampleFilter.h	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComUpsampleFilter.h	(revision 2)
@@ -0,0 +1,57 @@
+#ifndef __TCOMUPSAMPLEFILTER__
+#define __TCOMUPSAMPLEFILTER__
+
+#include "TComPic.h"
+#include "TComYuv.h"
+#include "TComDataCU.h"
+
+#define NTAPS_US_LUMA        8 ///< Number of taps for luma upsampling filter
+#define NTAPS_US_CHROMA      4 ///< Number of taps for chroma upsampling filter
+#define US_FILTER_PREC       6 ///< Log2 of sum of filter taps
+
+class TComUpsampleFilter
+{
+private:
+#if PHASE_DERIVATION_IN_INTEGER
+  static const Int m_lumaFixedFilter[16][NTAPS_US_LUMA];     ///< Luma filter taps for both 1.5x and 2x scalability
+  static const Int m_chromaFixedFilter[16][NTAPS_US_CHROMA]; ///< Chroma filter taps for 1.5x scalability
+
+  Int m_lumaFilter[16][NTAPS_US_LUMA];
+  Int m_chromaFilter[16][NTAPS_US_CHROMA];
+#else
+  static const Int m_lumaFixedFilter[12][NTAPS_US_LUMA];     ///< Luma filter taps for both 1.5x and 2x scalability
+  static const Int m_chromaFixedFilter20[8][NTAPS_US_CHROMA]; ///< Chroma filter taps for 2x scalability
+  static const Int m_chromaFixedFilter15[12][NTAPS_US_CHROMA]; ///< Chroma filter taps for 1.5x scalability
+
+  Int m_lumaFilter[12][NTAPS_US_LUMA];
+  Int m_chromaFilter[12][NTAPS_US_CHROMA];
+#endif
+
+  static inline Int sumLumaHor( Pel* pel, Int* coeff )
+  {
+    return ( pel[0]*coeff[0] + pel[1]*coeff[1] + pel[2]*coeff[2] + pel[3]*coeff[3] + pel[4]*coeff[4] + pel[5]*coeff[5] + pel[6]*coeff[6] + pel[7]*coeff[7]);
+  }
+
+  static inline Int sumChromaHor( Pel* pel, Int* coeff )
+  {
+    return ( pel[0]*coeff[0] + pel[1]*coeff[1] + pel[2]*coeff[2] + pel[3]*coeff[3] );
+  }
+
+  static inline Int sumLumaVer( Pel* pel, Int* coeff, Int stride )
+  {
+    return ( pel[0]*coeff[0] + pel[stride]*coeff[1] + pel[2*stride]*coeff[2] + pel[3*stride]*coeff[3] + pel[4*stride]*coeff[4] + pel[5*stride]*coeff[5] + pel[6*stride]*coeff[6] + pel[7*stride]*coeff[7]);
+  }
+
+  static inline Int sumChromaVer( Pel* pel, Int* coeff, Int stride )
+  {
+    return ( pel[0]*coeff[0] + pel[stride]*coeff[1] + pel[2*stride]*coeff[2] + pel[3*stride]*coeff[3] );
+  }
+
+public:
+  TComUpsampleFilter(void);
+  ~TComUpsampleFilter(void);
+
+ Void upsampleBasePic( TComPicYuv* pcUsPic, TComPicYuv* pcBasePic, TComPicYuv* pcTempPic );
+};
+
+#endif //__TCOMUPSAMPLEFILTER__
Index: /trunk/source/Lib/TLibCommon/TComWeightPrediction.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComWeightPrediction.cpp	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComWeightPrediction.cpp	(revision 2)
@@ -0,0 +1,388 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComWeightPrediction.h
+    \brief    weighting prediction class (header)
+*/
+
+// Include files
+#include "TComSlice.h"
+#include "TComWeightPrediction.h"
+#include "TComInterpolationFilter.h"
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+TComWeightPrediction::TComWeightPrediction()
+{
+}
+
+/** weighted averaging for bi-pred
+ * \param TComYuv* pcYuvSrc0
+ * \param TComYuv* pcYuvSrc1
+ * \param iPartUnitIdx
+ * \param iWidth
+ * \param iHeight
+ * \param wpScalingParam *wp0
+ * \param wpScalingParam *wp1
+ * \param TComYuv* rpcYuvDst
+ * \returns Void
+ */
+Void TComWeightPrediction::addWeightBi( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt iPartUnitIdx, UInt iWidth, UInt iHeight, wpScalingParam *wp0, wpScalingParam *wp1, TComYuv* rpcYuvDst, Bool bRound )
+{
+  Int x, y;
+
+  Pel* pSrcY0  = pcYuvSrc0->getLumaAddr( iPartUnitIdx );
+  Pel* pSrcU0  = pcYuvSrc0->getCbAddr  ( iPartUnitIdx );
+  Pel* pSrcV0  = pcYuvSrc0->getCrAddr  ( iPartUnitIdx );
+  
+  Pel* pSrcY1  = pcYuvSrc1->getLumaAddr( iPartUnitIdx );
+  Pel* pSrcU1  = pcYuvSrc1->getCbAddr  ( iPartUnitIdx );
+  Pel* pSrcV1  = pcYuvSrc1->getCrAddr  ( iPartUnitIdx );
+  
+  Pel* pDstY   = rpcYuvDst->getLumaAddr( iPartUnitIdx );
+  Pel* pDstU   = rpcYuvDst->getCbAddr  ( iPartUnitIdx );
+  Pel* pDstV   = rpcYuvDst->getCrAddr  ( iPartUnitIdx );
+  
+  // Luma : --------------------------------------------
+  Int w0      = wp0[0].w;
+  Int offset  = wp0[0].offset;
+  Int shiftNum = IF_INTERNAL_PREC - ( g_uiBitDepth + g_uiBitIncrement );
+  Int shift   = wp0[0].shift + shiftNum;
+  Int round   = shift?(1<<(shift-1)) * bRound:0;
+  Int w1      = wp1[0].w;
+
+  UInt  iSrc0Stride = pcYuvSrc0->getStride();
+  UInt  iSrc1Stride = pcYuvSrc1->getStride();
+  UInt  iDstStride  = rpcYuvDst->getStride();
+  for ( y = iHeight-1; y >= 0; y-- )
+  {
+    for ( x = iWidth-1; x >= 0; )
+    {
+      // note: luma min width is 4
+      pDstY[x] = weightBidir(w0,pSrcY0[x], w1,pSrcY1[x], round, shift, offset); x--;
+      pDstY[x] = weightBidir(w0,pSrcY0[x], w1,pSrcY1[x], round, shift, offset); x--;
+      pDstY[x] = weightBidir(w0,pSrcY0[x], w1,pSrcY1[x], round, shift, offset); x--;
+      pDstY[x] = weightBidir(w0,pSrcY0[x], w1,pSrcY1[x], round, shift, offset); x--;
+    }
+    pSrcY0 += iSrc0Stride;
+    pSrcY1 += iSrc1Stride;
+    pDstY  += iDstStride;
+  }
+
+  
+  // Chroma U : --------------------------------------------
+  w0      = wp0[1].w;
+  offset  = wp0[1].offset;
+  shift   = wp0[1].shift + shiftNum;
+  round   = shift?(1<<(shift-1)):0;
+  w1      = wp1[1].w;
+
+  iSrc0Stride = pcYuvSrc0->getCStride();
+  iSrc1Stride = pcYuvSrc1->getCStride();
+  iDstStride  = rpcYuvDst->getCStride();
+  
+  iWidth  >>=1;
+  iHeight >>=1;
+  
+  for ( y = iHeight-1; y >= 0; y-- )
+  {
+    for ( x = iWidth-1; x >= 0; )
+    {
+      // note: chroma min width is 2
+      pDstU[x] = weightBidir(w0,pSrcU0[x], w1,pSrcU1[x], round, shift, offset); x--;
+      pDstU[x] = weightBidir(w0,pSrcU0[x], w1,pSrcU1[x], round, shift, offset); x--;
+    }
+    pSrcU0 += iSrc0Stride;
+    pSrcU1 += iSrc1Stride;
+    pDstU  += iDstStride;
+  }
+
+  // Chroma V : --------------------------------------------
+  w0      = wp0[2].w;
+  offset  = wp0[2].offset;
+  shift   = wp0[2].shift + shiftNum;
+  round   = shift?(1<<(shift-1)):0;
+  w1      = wp1[2].w;
+
+  for ( y = iHeight-1; y >= 0; y-- )
+  {
+    for ( x = iWidth-1; x >= 0; )
+    {
+      // note: chroma min width is 2
+      pDstV[x] = weightBidir(w0,pSrcV0[x], w1,pSrcV1[x], round, shift, offset); x--;
+      pDstV[x] = weightBidir(w0,pSrcV0[x], w1,pSrcV1[x], round, shift, offset); x--;
+    }
+    pSrcV0 += iSrc0Stride;
+    pSrcV1 += iSrc1Stride;
+    pDstV  += iDstStride;
+  }
+}
+
+/** weighted averaging for uni-pred
+ * \param TComYuv* pcYuvSrc0
+ * \param iPartUnitIdx
+ * \param iWidth
+ * \param iHeight
+ * \param wpScalingParam *wp0
+ * \param TComYuv* rpcYuvDst
+ * \returns Void
+ */
+Void TComWeightPrediction::addWeightUni( TComYuv* pcYuvSrc0, UInt iPartUnitIdx, UInt iWidth, UInt iHeight, wpScalingParam *wp0, TComYuv* rpcYuvDst )
+{
+  Int x, y;
+  
+  Pel* pSrcY0  = pcYuvSrc0->getLumaAddr( iPartUnitIdx );
+  Pel* pSrcU0  = pcYuvSrc0->getCbAddr  ( iPartUnitIdx );
+  Pel* pSrcV0  = pcYuvSrc0->getCrAddr  ( iPartUnitIdx );
+  
+  Pel* pDstY   = rpcYuvDst->getLumaAddr( iPartUnitIdx );
+  Pel* pDstU   = rpcYuvDst->getCbAddr  ( iPartUnitIdx );
+  Pel* pDstV   = rpcYuvDst->getCrAddr  ( iPartUnitIdx );
+  
+  // Luma : --------------------------------------------
+  Int w0      = wp0[0].w;
+  Int offset  = wp0[0].offset;
+  Int shiftNum = IF_INTERNAL_PREC - ( g_uiBitDepth + g_uiBitIncrement );
+  Int shift   = wp0[0].shift + shiftNum;
+  Int round   = shift?(1<<(shift-1)):0;
+  UInt  iSrc0Stride = pcYuvSrc0->getStride();
+  UInt  iDstStride  = rpcYuvDst->getStride();
+  
+  for ( y = iHeight-1; y >= 0; y-- )
+  {
+    for ( x = iWidth-1; x >= 0; )
+    {
+      // note: luma min width is 4
+      pDstY[x] = weightUnidir(w0,pSrcY0[x], round, shift, offset); x--;
+      pDstY[x] = weightUnidir(w0,pSrcY0[x], round, shift, offset); x--;
+      pDstY[x] = weightUnidir(w0,pSrcY0[x], round, shift, offset); x--;
+      pDstY[x] = weightUnidir(w0,pSrcY0[x], round, shift, offset); x--;
+    }
+    pSrcY0 += iSrc0Stride;
+    pDstY  += iDstStride;
+  }
+  
+  // Chroma U : --------------------------------------------
+  w0      = wp0[1].w;
+  offset  = wp0[1].offset;
+  shift   = wp0[1].shift + shiftNum;
+  round   = shift?(1<<(shift-1)):0;
+
+  iSrc0Stride = pcYuvSrc0->getCStride();
+  iDstStride  = rpcYuvDst->getCStride();
+  
+  iWidth  >>=1;
+  iHeight >>=1;
+  
+  for ( y = iHeight-1; y >= 0; y-- )
+  {
+    for ( x = iWidth-1; x >= 0; )
+    {
+      // note: chroma min width is 2
+      pDstU[x] = weightUnidir(w0,pSrcU0[x], round, shift, offset); x--;
+      pDstU[x] = weightUnidir(w0,pSrcU0[x], round, shift, offset); x--;
+    }
+    pSrcU0 += iSrc0Stride;
+    pDstU  += iDstStride;
+  }
+
+  // Chroma V : --------------------------------------------
+  w0      = wp0[2].w;
+  offset  = wp0[2].offset;
+  shift   = wp0[2].shift + shiftNum;
+  round   = shift?(1<<(shift-1)):0;
+
+  for ( y = iHeight-1; y >= 0; y-- )
+  {
+    for ( x = iWidth-1; x >= 0; )
+    {
+      // note: chroma min width is 2
+      pDstV[x] = weightUnidir(w0,pSrcV0[x], round, shift, offset); x--;
+      pDstV[x] = weightUnidir(w0,pSrcV0[x], round, shift, offset); x--;
+    }
+    pSrcV0 += iSrc0Stride;
+    pDstV  += iDstStride;
+  }
+}
+
+//=======================================================
+//  getWpScaling()
+//=======================================================
+/** derivation of wp tables
+ * \param TComDataCU* pcCU
+ * \param iRefIdx0
+ * \param iRefIdx1
+ * \param wpScalingParam *&wp0
+ * \param wpScalingParam *&wp1
+ * \param ibdi
+ * \returns Void
+ */
+Void TComWeightPrediction::getWpScaling( TComDataCU* pcCU, Int iRefIdx0, Int iRefIdx1, wpScalingParam *&wp0, wpScalingParam *&wp1, Int ibdi)
+{
+  TComSlice*      pcSlice       = pcCU->getSlice();
+  TComPPS*        pps           = pcCU->getSlice()->getPPS();
+  Bool            wpBiPred = pps->getWPBiPred();
+  wpScalingParam* pwp;
+  Bool            bBiDir        = (iRefIdx0>=0 && iRefIdx1>=0);
+  Bool            bUniDir       = !bBiDir;
+
+  m_ibdi = ibdi;
+  if ( bUniDir || wpBiPred )
+  { // explicit --------------------
+    if ( iRefIdx0 >= 0 )
+    {
+      pcSlice->getWpScaling(REF_PIC_LIST_0, iRefIdx0, wp0);
+    }
+    if ( iRefIdx1 >= 0 )
+    {
+      pcSlice->getWpScaling(REF_PIC_LIST_1, iRefIdx1, wp1);
+    }
+  }
+  else
+  {
+    assert(0);
+  }
+
+  if ( iRefIdx0 < 0 )
+  {
+    wp0 = NULL;
+  }
+  if ( iRefIdx1 < 0 )
+  {
+    wp1 = NULL;
+  }
+
+  if ( bBiDir )
+  { // Bi-Dir case
+    for ( int yuv=0 ; yuv<3 ; yuv++ )
+    {
+      wp0[yuv].w      = wp0[yuv].iWeight;
+      wp0[yuv].o      = wp0[yuv].iOffset * (1 << (m_ibdi-8));
+      wp1[yuv].w      = wp1[yuv].iWeight;
+      wp1[yuv].o      = wp1[yuv].iOffset * (1 << (m_ibdi-8));
+      wp0[yuv].offset = wp0[yuv].o + wp1[yuv].o;
+      wp0[yuv].shift  = wp0[yuv].uiLog2WeightDenom + 1;
+      wp0[yuv].round  = (1 << wp0[yuv].uiLog2WeightDenom);
+      wp1[yuv].offset = wp0[yuv].offset;
+      wp1[yuv].shift  = wp0[yuv].shift;
+      wp1[yuv].round  = wp0[yuv].round;
+    }
+  }
+  else
+  {  // Unidir
+    pwp = (iRefIdx0>=0) ? wp0 : wp1 ;
+    for ( int yuv=0 ; yuv<3 ; yuv++ )
+    {
+      pwp[yuv].w      = pwp[yuv].iWeight;
+      pwp[yuv].offset = pwp[yuv].iOffset * (1 << (m_ibdi-8));
+      pwp[yuv].shift  = pwp[yuv].uiLog2WeightDenom;
+      pwp[yuv].round  = (pwp[yuv].uiLog2WeightDenom>=1) ? (1 << (pwp[yuv].uiLog2WeightDenom-1)) : (0);
+    }
+  }
+}
+
+/** weighted prediction for bi-pred
+ * \param TComDataCU* pcCU
+ * \param TComYuv* pcYuvSrc0
+ * \param TComYuv* pcYuvSrc1
+ * \param iRefIdx0
+ * \param iRefIdx1
+ * \param uiPartIdx
+ * \param iWidth
+ * \param iHeight
+ * \param TComYuv* rpcYuvDst
+ * \returns Void
+ */
+Void TComWeightPrediction::xWeightedPredictionBi( TComDataCU* pcCU, TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, Int iRefIdx0, Int iRefIdx1, UInt uiPartIdx, Int iWidth, Int iHeight, TComYuv* rpcYuvDst )
+{
+  wpScalingParam  *pwp0, *pwp1;
+  TComPPS         *pps = pcCU->getSlice()->getPPS();
+  assert( pps->getWPBiPred());
+
+  Int ibdi = (g_uiBitDepth+g_uiBitIncrement);
+  getWpScaling(pcCU, iRefIdx0, iRefIdx1, pwp0, pwp1, ibdi);
+
+  if( iRefIdx0 >= 0 && iRefIdx1 >= 0 )
+  {
+    addWeightBi(pcYuvSrc0, pcYuvSrc1, uiPartIdx, iWidth, iHeight, pwp0, pwp1, rpcYuvDst );
+  }
+  else if ( iRefIdx0 >= 0 && iRefIdx1 <  0 )
+  {
+    addWeightUni( pcYuvSrc0, uiPartIdx, iWidth, iHeight, pwp0, rpcYuvDst );
+  }
+  else if ( iRefIdx0 <  0 && iRefIdx1 >= 0 )
+  {
+    addWeightUni( pcYuvSrc1, uiPartIdx, iWidth, iHeight, pwp1, rpcYuvDst );
+  }
+  else
+  {
+    assert (0);
+  }
+}
+
+/** weighted prediction for uni-pred
+ * \param TComDataCU* pcCU
+ * \param TComYuv* pcYuvSrc
+ * \param uiPartAddr
+ * \param iWidth
+ * \param iHeight
+ * \param eRefPicList
+ * \param TComYuv*& rpcYuvPred
+ * \param iPartIdx
+ * \param iRefIdx
+ * \returns Void
+ */
+Void TComWeightPrediction::xWeightedPredictionUni( TComDataCU* pcCU, TComYuv* pcYuvSrc, UInt uiPartAddr, Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Int iPartIdx, Int iRefIdx)
+{ 
+  wpScalingParam  *pwp, *pwpTmp;
+  if ( iRefIdx < 0 )
+  {
+    iRefIdx   = pcCU->getCUMvField( eRefPicList )->getRefIdx( uiPartAddr );
+  }
+  assert (iRefIdx >= 0);
+
+  Int ibdi = (g_uiBitDepth+g_uiBitIncrement);
+
+  if ( eRefPicList == REF_PIC_LIST_0 )
+  {
+    getWpScaling(pcCU, iRefIdx, -1, pwp, pwpTmp, ibdi);
+  }
+  else
+  {
+    getWpScaling(pcCU, -1, iRefIdx, pwpTmp, pwp, ibdi);
+  }
+  addWeightUni( pcYuvSrc, uiPartAddr, iWidth, iHeight, pwp, rpcYuvPred );
+}
+
+
Index: /trunk/source/Lib/TLibCommon/TComWeightPrediction.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComWeightPrediction.h	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComWeightPrediction.h	(revision 2)
@@ -0,0 +1,91 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComWeightPrediction.h
+    \brief    weighting prediction class (header)
+*/
+
+#ifndef __TCOMWEIGHTPREDICTION__
+#define __TCOMWEIGHTPREDICTION__
+
+
+// Include files
+#include "TComPic.h"
+#include "TComMotionInfo.h"
+#include "TComPattern.h"
+#include "TComTrQuant.h"
+#include "TComInterpolationFilter.h"
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+/// weighting prediction class
+class TComWeightPrediction
+{
+  wpScalingParam  m_wp0[3], m_wp1[3];
+  Int             m_ibdi;
+
+public:
+  TComWeightPrediction();
+
+  Void  getWpScaling( TComDataCU* pcCU, Int iRefIdx0, Int iRefIdx1, wpScalingParam *&wp0 , wpScalingParam *&wp1 , Int ibdi=(g_uiBitDepth+g_uiBitIncrement));
+
+  Void  addWeightBi( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt iPartUnitIdx, UInt iWidth, UInt iHeight, wpScalingParam *wp0, wpScalingParam *wp1, TComYuv* rpcYuvDst, Bool bRound=true );
+  Void  addWeightUni( TComYuv* pcYuvSrc0, UInt iPartUnitIdx, UInt iWidth, UInt iHeight, wpScalingParam *wp0, TComYuv* rpcYuvDst );
+
+  Void  xWeightedPredictionUni( TComDataCU* pcCU, TComYuv* pcYuvSrc, UInt uiPartAddr, Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Int iPartIdx, Int iRefIdx=-1 );
+  Void  xWeightedPredictionBi( TComDataCU* pcCU, TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, Int iRefIdx0, Int iRefIdx1, UInt uiPartIdx, Int iWidth, Int iHeight, TComYuv* rpcYuvDst );
+
+  __inline  Pel   xClip  ( Int x );
+  __inline  Pel   weightBidir( Int w0, Pel P0, Int w1, Pel P1, Int round, Int shift, Int offset);
+  __inline  Pel   weightUnidir( Int w0, Pel P0, Int round, Int shift, Int offset);
+
+};
+
+inline  Pel TComWeightPrediction::xClip( Int x )
+{ 
+  Int max = (Int)g_uiIBDI_MAX;
+  Pel pel = (Pel)( (x < 0) ? 0 : (x > max) ? max : x );
+  return( pel );
+}
+
+inline  Pel TComWeightPrediction::weightBidir( Int w0, Pel P0, Int w1, Pel P1, Int round, Int shift, Int offset)
+{
+  return xClip( ( (w0*(P0 + IF_INTERNAL_OFFS) + w1*(P1 + IF_INTERNAL_OFFS) + round + (offset << (shift-1))) >> shift ) );
+}
+inline  Pel TComWeightPrediction::weightUnidir( Int w0, Pel P0, Int round, Int shift, Int offset) 
+{
+  return xClip( ( (w0*(P0 + IF_INTERNAL_OFFS) + round) >> shift ) + offset );
+}
+
+#endif 
Index: /trunk/source/Lib/TLibCommon/TComYuv.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComYuv.cpp	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComYuv.cpp	(revision 2)
@@ -0,0 +1,636 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComYuv.cpp
+    \brief    general YUV buffer class
+    \todo     this should be merged with TComPicYuv
+*/
+
+#include <stdlib.h>
+#include <memory.h>
+#include <assert.h>
+#include <math.h>
+
+#include "CommonDef.h"
+#include "TComYuv.h"
+#include "TComInterpolationFilter.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+TComYuv::TComYuv()
+{
+  m_apiBufY = NULL;
+  m_apiBufU = NULL;
+  m_apiBufV = NULL;
+}
+
+TComYuv::~TComYuv()
+{
+}
+
+Void TComYuv::create( UInt iWidth, UInt iHeight )
+{
+  // memory allocation
+  m_apiBufY  = (Pel*)xMalloc( Pel, iWidth*iHeight    );
+  m_apiBufU  = (Pel*)xMalloc( Pel, iWidth*iHeight >> 2 );
+  m_apiBufV  = (Pel*)xMalloc( Pel, iWidth*iHeight >> 2 );
+  
+  // set width and height
+  m_iWidth   = iWidth;
+  m_iHeight  = iHeight;
+  m_iCWidth  = iWidth  >> 1;
+  m_iCHeight = iHeight >> 1;
+}
+
+Void TComYuv::destroy()
+{
+  // memory free
+  xFree( m_apiBufY ); m_apiBufY = NULL;
+  xFree( m_apiBufU ); m_apiBufU = NULL;
+  xFree( m_apiBufV ); m_apiBufV = NULL;
+}
+
+Void TComYuv::clear()
+{
+  ::memset( m_apiBufY, 0, ( m_iWidth  * m_iHeight  )*sizeof(Pel) );
+  ::memset( m_apiBufU, 0, ( m_iCWidth * m_iCHeight )*sizeof(Pel) );
+  ::memset( m_apiBufV, 0, ( m_iCWidth * m_iCHeight )*sizeof(Pel) );
+}
+
+Void TComYuv::copyToPicYuv   ( TComPicYuv* pcPicYuvDst, UInt iCuAddr, UInt uiAbsZorderIdx, UInt uiPartDepth, UInt uiPartIdx )
+{
+  copyToPicLuma  ( pcPicYuvDst, iCuAddr, uiAbsZorderIdx, uiPartDepth, uiPartIdx );
+  copyToPicChroma( pcPicYuvDst, iCuAddr, uiAbsZorderIdx, uiPartDepth, uiPartIdx );
+}
+
+Void TComYuv::copyToPicLuma  ( TComPicYuv* pcPicYuvDst, UInt iCuAddr, UInt uiAbsZorderIdx, UInt uiPartDepth, UInt uiPartIdx )
+{
+  Int  y, iWidth, iHeight;
+  iWidth  = m_iWidth >>uiPartDepth;
+  iHeight = m_iHeight>>uiPartDepth;
+  
+  Pel* pSrc     = getLumaAddr(uiPartIdx, iWidth);
+  Pel* pDst     = pcPicYuvDst->getLumaAddr ( iCuAddr, uiAbsZorderIdx );
+  
+  UInt  iSrcStride  = getStride();
+  UInt  iDstStride  = pcPicYuvDst->getStride();
+  
+  for ( y = iHeight; y != 0; y-- )
+  {
+    ::memcpy( pDst, pSrc, sizeof(Pel)*iWidth);
+    pDst += iDstStride;
+    pSrc += iSrcStride;
+  }
+}
+
+Void TComYuv::copyToPicChroma( TComPicYuv* pcPicYuvDst, UInt iCuAddr, UInt uiAbsZorderIdx, UInt uiPartDepth, UInt uiPartIdx )
+{
+  Int  y, iWidth, iHeight;
+  iWidth  = m_iCWidth >>uiPartDepth;
+  iHeight = m_iCHeight>>uiPartDepth;
+  
+  Pel* pSrcU      = getCbAddr(uiPartIdx, iWidth);
+  Pel* pSrcV      = getCrAddr(uiPartIdx, iWidth);
+  Pel* pDstU      = pcPicYuvDst->getCbAddr( iCuAddr, uiAbsZorderIdx );
+  Pel* pDstV      = pcPicYuvDst->getCrAddr( iCuAddr, uiAbsZorderIdx );
+  
+  UInt  iSrcStride = getCStride();
+  UInt  iDstStride = pcPicYuvDst->getCStride();
+  for ( y = iHeight; y != 0; y-- )
+  {
+    ::memcpy( pDstU, pSrcU, sizeof(Pel)*(iWidth) );
+    ::memcpy( pDstV, pSrcV, sizeof(Pel)*(iWidth) );
+    pSrcU += iSrcStride;
+    pSrcV += iSrcStride;
+    pDstU += iDstStride;
+    pDstV += iDstStride;
+  }
+}
+
+Void TComYuv::copyFromPicYuv   ( TComPicYuv* pcPicYuvSrc, UInt iCuAddr, UInt uiAbsZorderIdx )
+{
+  copyFromPicLuma  ( pcPicYuvSrc, iCuAddr, uiAbsZorderIdx );
+  copyFromPicChroma( pcPicYuvSrc, iCuAddr, uiAbsZorderIdx );
+}
+
+Void TComYuv::copyFromPicLuma  ( TComPicYuv* pcPicYuvSrc, UInt iCuAddr, UInt uiAbsZorderIdx )
+{
+  Int  y;
+  
+  Pel* pDst     = m_apiBufY;
+  Pel* pSrc     = pcPicYuvSrc->getLumaAddr ( iCuAddr, uiAbsZorderIdx );
+  
+  UInt  iDstStride  = getStride();
+  UInt  iSrcStride  = pcPicYuvSrc->getStride();
+  for ( y = m_iHeight; y != 0; y-- )
+  {
+    ::memcpy( pDst, pSrc, sizeof(Pel)*m_iWidth);
+    pDst += iDstStride;
+    pSrc += iSrcStride;
+  }
+}
+
+Void TComYuv::copyFromPicChroma( TComPicYuv* pcPicYuvSrc, UInt iCuAddr, UInt uiAbsZorderIdx )
+{
+  Int  y;
+  
+  Pel* pDstU      = m_apiBufU;
+  Pel* pDstV      = m_apiBufV;
+  Pel* pSrcU      = pcPicYuvSrc->getCbAddr( iCuAddr, uiAbsZorderIdx );
+  Pel* pSrcV      = pcPicYuvSrc->getCrAddr( iCuAddr, uiAbsZorderIdx );
+  
+  UInt  iDstStride = getCStride();
+  UInt  iSrcStride = pcPicYuvSrc->getCStride();
+  for ( y = m_iCHeight; y != 0; y-- )
+  {
+    ::memcpy( pDstU, pSrcU, sizeof(Pel)*(m_iCWidth) );
+    ::memcpy( pDstV, pSrcV, sizeof(Pel)*(m_iCWidth) );
+    pSrcU += iSrcStride;
+    pSrcV += iSrcStride;
+    pDstU += iDstStride;
+    pDstV += iDstStride;
+  }
+}
+
+Void TComYuv::copyToPartYuv( TComYuv* pcYuvDst, UInt uiDstPartIdx )
+{
+  copyToPartLuma  ( pcYuvDst, uiDstPartIdx );
+  copyToPartChroma( pcYuvDst, uiDstPartIdx );
+}
+
+Void TComYuv::copyToPartLuma( TComYuv* pcYuvDst, UInt uiDstPartIdx )
+{
+  Int  y;
+  
+  Pel* pSrc     = m_apiBufY;
+  Pel* pDst     = pcYuvDst->getLumaAddr( uiDstPartIdx );
+  
+  UInt  iSrcStride  = getStride();
+  UInt  iDstStride  = pcYuvDst->getStride();
+  for ( y = m_iHeight; y != 0; y-- )
+  {
+    ::memcpy( pDst, pSrc, sizeof(Pel)*m_iWidth);
+    pDst += iDstStride;
+    pSrc += iSrcStride;
+  }
+}
+
+Void TComYuv::copyToPartChroma( TComYuv* pcYuvDst, UInt uiDstPartIdx )
+{
+  Int  y;
+  
+  Pel* pSrcU      = m_apiBufU;
+  Pel* pSrcV      = m_apiBufV;
+  Pel* pDstU      = pcYuvDst->getCbAddr( uiDstPartIdx );
+  Pel* pDstV      = pcYuvDst->getCrAddr( uiDstPartIdx );
+  
+  UInt  iSrcStride = getCStride();
+  UInt  iDstStride = pcYuvDst->getCStride();
+  for ( y = m_iCHeight; y != 0; y-- )
+  {
+    ::memcpy( pDstU, pSrcU, sizeof(Pel)*(m_iCWidth) );
+    ::memcpy( pDstV, pSrcV, sizeof(Pel)*(m_iCWidth) );
+    pSrcU += iSrcStride;
+    pSrcV += iSrcStride;
+    pDstU += iDstStride;
+    pDstV += iDstStride;
+  }
+}
+
+Void TComYuv::copyPartToYuv( TComYuv* pcYuvDst, UInt uiSrcPartIdx )
+{
+  copyPartToLuma  ( pcYuvDst, uiSrcPartIdx );
+  copyPartToChroma( pcYuvDst, uiSrcPartIdx );
+}
+
+Void TComYuv::copyPartToLuma( TComYuv* pcYuvDst, UInt uiSrcPartIdx )
+{
+  Int  y;
+  
+  Pel* pSrc     = getLumaAddr(uiSrcPartIdx);
+  Pel* pDst     = pcYuvDst->getLumaAddr( 0 );
+  
+  UInt  iSrcStride  = getStride();
+  UInt  iDstStride  = pcYuvDst->getStride();
+  
+  UInt uiHeight = pcYuvDst->getHeight();
+  UInt uiWidth = pcYuvDst->getWidth();
+  
+  for ( y = uiHeight; y != 0; y-- )
+  {
+    ::memcpy( pDst, pSrc, sizeof(Pel)*uiWidth);
+    pDst += iDstStride;
+    pSrc += iSrcStride;
+  }
+}
+
+Void TComYuv::copyPartToChroma( TComYuv* pcYuvDst, UInt uiSrcPartIdx )
+{
+  Int  y;
+  
+  Pel* pSrcU      = getCbAddr( uiSrcPartIdx );
+  Pel* pSrcV      = getCrAddr( uiSrcPartIdx );
+  Pel* pDstU      = pcYuvDst->getCbAddr( 0 );
+  Pel* pDstV      = pcYuvDst->getCrAddr( 0 );
+  
+  UInt  iSrcStride = getCStride();
+  UInt  iDstStride = pcYuvDst->getCStride();
+  
+  UInt uiCHeight = pcYuvDst->getCHeight();
+  UInt uiCWidth = pcYuvDst->getCWidth();
+  
+  for ( y = uiCHeight; y != 0; y-- )
+  {
+    ::memcpy( pDstU, pSrcU, sizeof(Pel)*(uiCWidth) );
+    ::memcpy( pDstV, pSrcV, sizeof(Pel)*(uiCWidth) );
+    pSrcU += iSrcStride;
+    pSrcV += iSrcStride;
+    pDstU += iDstStride;
+    pDstV += iDstStride;
+  }
+}
+
+Void TComYuv::copyPartToPartYuv   ( TComYuv* pcYuvDst, UInt uiPartIdx, UInt iWidth, UInt iHeight )
+{
+  copyPartToPartLuma   (pcYuvDst, uiPartIdx, iWidth, iHeight );
+  copyPartToPartChroma (pcYuvDst, uiPartIdx, iWidth>>1, iHeight>>1 );
+}
+
+Void TComYuv::copyPartToPartLuma  ( TComYuv* pcYuvDst, UInt uiPartIdx, UInt iWidth, UInt iHeight )
+{
+  Pel* pSrc =           getLumaAddr(uiPartIdx);
+  Pel* pDst = pcYuvDst->getLumaAddr(uiPartIdx);
+  if( pSrc == pDst )
+  {
+    //th not a good idea
+    //th best would be to fix the caller 
+    return ;
+  }
+  
+  UInt  iSrcStride = getStride();
+  UInt  iDstStride = pcYuvDst->getStride();
+  for ( UInt y = iHeight; y != 0; y-- )
+  {
+    ::memcpy( pDst, pSrc, iWidth * sizeof(Pel) );
+    pSrc += iSrcStride;
+    pDst += iDstStride;
+  }
+}
+
+Void TComYuv::copyPartToPartChroma( TComYuv* pcYuvDst, UInt uiPartIdx, UInt iWidth, UInt iHeight )
+{
+  Pel*  pSrcU =           getCbAddr(uiPartIdx);
+  Pel*  pSrcV =           getCrAddr(uiPartIdx);
+  Pel*  pDstU = pcYuvDst->getCbAddr(uiPartIdx);
+  Pel*  pDstV = pcYuvDst->getCrAddr(uiPartIdx);
+  
+  if( pSrcU == pDstU && pSrcV == pDstV)
+  {
+    //th not a good idea
+    //th best would be to fix the caller 
+    return ;
+  }
+  
+  UInt   iSrcStride = getCStride();
+  UInt   iDstStride = pcYuvDst->getCStride();
+  for ( UInt y = iHeight; y != 0; y-- )
+  {
+    ::memcpy( pDstU, pSrcU, iWidth * sizeof(Pel) );
+    ::memcpy( pDstV, pSrcV, iWidth * sizeof(Pel) );
+    pSrcU += iSrcStride;
+    pSrcV += iSrcStride;
+    pDstU += iDstStride;
+    pDstV += iDstStride;
+  }
+}
+
+Void TComYuv::copyPartToPartChroma( TComYuv* pcYuvDst, UInt uiPartIdx, UInt iWidth, UInt iHeight, UInt chromaId)
+{
+  if(chromaId == 0)
+  {
+    Pel*  pSrcU =           getCbAddr(uiPartIdx);
+    Pel*  pDstU = pcYuvDst->getCbAddr(uiPartIdx);
+    if( pSrcU == pDstU)
+    {
+      return ;
+    }
+    UInt   iSrcStride = getCStride();
+    UInt   iDstStride = pcYuvDst->getCStride();
+    for ( UInt y = iHeight; y != 0; y-- )
+    {
+      ::memcpy( pDstU, pSrcU, iWidth * sizeof(Pel) );
+      pSrcU += iSrcStride;
+      pDstU += iDstStride;
+    }
+  }
+  else if (chromaId == 1)
+  {
+    Pel*  pSrcV =           getCrAddr(uiPartIdx);
+    Pel*  pDstV = pcYuvDst->getCrAddr(uiPartIdx);
+    if( pSrcV == pDstV)
+    {
+      return;
+    }
+    UInt   iSrcStride = getCStride();
+    UInt   iDstStride = pcYuvDst->getCStride();
+    for ( UInt y = iHeight; y != 0; y-- )
+    { 
+      ::memcpy( pDstV, pSrcV, iWidth * sizeof(Pel) );
+      pSrcV += iSrcStride;
+      pDstV += iDstStride;
+    }
+  }
+  else
+  {
+    Pel*  pSrcU =           getCbAddr(uiPartIdx);
+    Pel*  pSrcV =           getCrAddr(uiPartIdx);
+    Pel*  pDstU = pcYuvDst->getCbAddr(uiPartIdx);
+    Pel*  pDstV = pcYuvDst->getCrAddr(uiPartIdx);
+    
+    if( pSrcU == pDstU && pSrcV == pDstV)
+    {
+      //th not a good idea
+      //th best would be to fix the caller 
+      return ;
+    }
+    UInt   iSrcStride = getCStride();
+    UInt   iDstStride = pcYuvDst->getCStride();
+    for ( UInt y = iHeight; y != 0; y-- )
+    {
+      ::memcpy( pDstU, pSrcU, iWidth * sizeof(Pel) );
+      ::memcpy( pDstV, pSrcV, iWidth * sizeof(Pel) );
+      pSrcU += iSrcStride;
+      pSrcV += iSrcStride;
+      pDstU += iDstStride;
+      pDstV += iDstStride;
+    }
+  }
+}
+
+Void TComYuv::addClip( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize )
+{
+  addClipLuma   ( pcYuvSrc0, pcYuvSrc1, uiTrUnitIdx, uiPartSize     );
+  addClipChroma ( pcYuvSrc0, pcYuvSrc1, uiTrUnitIdx, uiPartSize>>1  );
+}
+
+Void TComYuv::addClipLuma( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize )
+{
+  Int x, y;
+  
+  Pel* pSrc0 = pcYuvSrc0->getLumaAddr( uiTrUnitIdx, uiPartSize );
+  Pel* pSrc1 = pcYuvSrc1->getLumaAddr( uiTrUnitIdx, uiPartSize );
+  Pel* pDst  = getLumaAddr( uiTrUnitIdx, uiPartSize );
+  
+  UInt iSrc0Stride = pcYuvSrc0->getStride();
+  UInt iSrc1Stride = pcYuvSrc1->getStride();
+  UInt iDstStride  = getStride();
+  for ( y = uiPartSize-1; y >= 0; y-- )
+  {
+    for ( x = uiPartSize-1; x >= 0; x-- )
+    {
+      pDst[x] = Clip( pSrc0[x] + pSrc1[x] );
+    }
+    pSrc0 += iSrc0Stride;
+    pSrc1 += iSrc1Stride;
+    pDst  += iDstStride;
+  }
+}
+
+Void TComYuv::addClipChroma( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize )
+{
+  Int x, y;
+  
+  Pel* pSrcU0 = pcYuvSrc0->getCbAddr( uiTrUnitIdx, uiPartSize );
+  Pel* pSrcU1 = pcYuvSrc1->getCbAddr( uiTrUnitIdx, uiPartSize );
+  Pel* pSrcV0 = pcYuvSrc0->getCrAddr( uiTrUnitIdx, uiPartSize );
+  Pel* pSrcV1 = pcYuvSrc1->getCrAddr( uiTrUnitIdx, uiPartSize );
+  Pel* pDstU = getCbAddr( uiTrUnitIdx, uiPartSize );
+  Pel* pDstV = getCrAddr( uiTrUnitIdx, uiPartSize );
+  
+  UInt  iSrc0Stride = pcYuvSrc0->getCStride();
+  UInt  iSrc1Stride = pcYuvSrc1->getCStride();
+  UInt  iDstStride  = getCStride();
+  for ( y = uiPartSize-1; y >= 0; y-- )
+  {
+    for ( x = uiPartSize-1; x >= 0; x-- )
+    {
+      pDstU[x] = Clip( pSrcU0[x] + pSrcU1[x] );
+      pDstV[x] = Clip( pSrcV0[x] + pSrcV1[x] );
+    }
+    
+    pSrcU0 += iSrc0Stride;
+    pSrcU1 += iSrc1Stride;
+    pSrcV0 += iSrc0Stride;
+    pSrcV1 += iSrc1Stride;
+    pDstU  += iDstStride;
+    pDstV  += iDstStride;
+  }
+}
+
+Void TComYuv::subtract( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize )
+{
+  subtractLuma  ( pcYuvSrc0, pcYuvSrc1,  uiTrUnitIdx, uiPartSize    );
+  subtractChroma( pcYuvSrc0, pcYuvSrc1,  uiTrUnitIdx, uiPartSize>>1 );
+}
+
+Void TComYuv::subtractLuma( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize )
+{
+  Int x, y;
+  
+  Pel* pSrc0 = pcYuvSrc0->getLumaAddr( uiTrUnitIdx, uiPartSize );
+  Pel* pSrc1 = pcYuvSrc1->getLumaAddr( uiTrUnitIdx, uiPartSize );
+  Pel* pDst  = getLumaAddr( uiTrUnitIdx, uiPartSize );
+  
+  Int  iSrc0Stride = pcYuvSrc0->getStride();
+  Int  iSrc1Stride = pcYuvSrc1->getStride();
+  Int  iDstStride  = getStride();
+  for ( y = uiPartSize-1; y >= 0; y-- )
+  {
+    for ( x = uiPartSize-1; x >= 0; x-- )
+    {
+      pDst[x] = pSrc0[x] - pSrc1[x];
+    }
+    pSrc0 += iSrc0Stride;
+    pSrc1 += iSrc1Stride;
+    pDst  += iDstStride;
+  }
+}
+
+Void TComYuv::subtractChroma( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize )
+{
+  Int x, y;
+  
+  Pel* pSrcU0 = pcYuvSrc0->getCbAddr( uiTrUnitIdx, uiPartSize );
+  Pel* pSrcU1 = pcYuvSrc1->getCbAddr( uiTrUnitIdx, uiPartSize );
+  Pel* pSrcV0 = pcYuvSrc0->getCrAddr( uiTrUnitIdx, uiPartSize );
+  Pel* pSrcV1 = pcYuvSrc1->getCrAddr( uiTrUnitIdx, uiPartSize );
+  Pel* pDstU  = getCbAddr( uiTrUnitIdx, uiPartSize );
+  Pel* pDstV  = getCrAddr( uiTrUnitIdx, uiPartSize );
+  
+  Int  iSrc0Stride = pcYuvSrc0->getCStride();
+  Int  iSrc1Stride = pcYuvSrc1->getCStride();
+  Int  iDstStride  = getCStride();
+  for ( y = uiPartSize-1; y >= 0; y-- )
+  {
+    for ( x = uiPartSize-1; x >= 0; x-- )
+    {
+      pDstU[x] = pSrcU0[x] - pSrcU1[x];
+      pDstV[x] = pSrcV0[x] - pSrcV1[x];
+    }
+    pSrcU0 += iSrc0Stride;
+    pSrcU1 += iSrc1Stride;
+    pSrcV0 += iSrc0Stride;
+    pSrcV1 += iSrc1Stride;
+    pDstU  += iDstStride;
+    pDstV  += iDstStride;
+  }
+}
+
+Void TComYuv::addAvg( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt iPartUnitIdx, UInt iWidth, UInt iHeight )
+{
+  Int x, y;
+  
+  Pel* pSrcY0  = pcYuvSrc0->getLumaAddr( iPartUnitIdx );
+  Pel* pSrcU0  = pcYuvSrc0->getCbAddr  ( iPartUnitIdx );
+  Pel* pSrcV0  = pcYuvSrc0->getCrAddr  ( iPartUnitIdx );
+  
+  Pel* pSrcY1  = pcYuvSrc1->getLumaAddr( iPartUnitIdx );
+  Pel* pSrcU1  = pcYuvSrc1->getCbAddr  ( iPartUnitIdx );
+  Pel* pSrcV1  = pcYuvSrc1->getCrAddr  ( iPartUnitIdx );
+  
+  Pel* pDstY   = getLumaAddr( iPartUnitIdx );
+  Pel* pDstU   = getCbAddr  ( iPartUnitIdx );
+  Pel* pDstV   = getCrAddr  ( iPartUnitIdx );
+  
+  UInt  iSrc0Stride = pcYuvSrc0->getStride();
+  UInt  iSrc1Stride = pcYuvSrc1->getStride();
+  UInt  iDstStride  = getStride();
+  Int shiftNum = IF_INTERNAL_PREC + 1 - ( g_uiBitDepth + g_uiBitIncrement );
+  Int offset = ( 1 << ( shiftNum - 1 ) ) + 2 * IF_INTERNAL_OFFS;
+  
+  for ( y = 0; y < iHeight; y++ )
+  {
+    for ( x = 0; x < iWidth; x += 4 )
+    {
+      pDstY[ x + 0 ] = Clip( ( pSrcY0[ x + 0 ] + pSrcY1[ x + 0 ] + offset ) >> shiftNum );
+      pDstY[ x + 1 ] = Clip( ( pSrcY0[ x + 1 ] + pSrcY1[ x + 1 ] + offset ) >> shiftNum );
+      pDstY[ x + 2 ] = Clip( ( pSrcY0[ x + 2 ] + pSrcY1[ x + 2 ] + offset ) >> shiftNum );
+      pDstY[ x + 3 ] = Clip( ( pSrcY0[ x + 3 ] + pSrcY1[ x + 3 ] + offset ) >> shiftNum );
+    }
+    pSrcY0 += iSrc0Stride;
+    pSrcY1 += iSrc1Stride;
+    pDstY  += iDstStride;
+  }
+  
+  iSrc0Stride = pcYuvSrc0->getCStride();
+  iSrc1Stride = pcYuvSrc1->getCStride();
+  iDstStride  = getCStride();
+  
+  iWidth  >>=1;
+  iHeight >>=1;
+  
+  for ( y = iHeight-1; y >= 0; y-- )
+  {
+    for ( x = iWidth-1; x >= 0; )
+    {
+      // note: chroma min width is 2
+      pDstU[x] = Clip((pSrcU0[x] + pSrcU1[x] + offset) >> shiftNum);
+      pDstV[x] = Clip((pSrcV0[x] + pSrcV1[x] + offset) >> shiftNum); x--;
+      pDstU[x] = Clip((pSrcU0[x] + pSrcU1[x] + offset) >> shiftNum);
+      pDstV[x] = Clip((pSrcV0[x] + pSrcV1[x] + offset) >> shiftNum); x--;
+    }
+    
+    pSrcU0 += iSrc0Stride;
+    pSrcU1 += iSrc1Stride;
+    pSrcV0 += iSrc0Stride;
+    pSrcV1 += iSrc1Stride;
+    pDstU  += iDstStride;
+    pDstV  += iDstStride;
+  }
+}
+
+Void TComYuv::removeHighFreq( TComYuv* pcYuvSrc, UInt uiPartIdx, UInt uiWidht, UInt uiHeight )
+{
+  Int x, y;
+  
+  Pel* pSrc  = pcYuvSrc->getLumaAddr(uiPartIdx);
+  Pel* pSrcU = pcYuvSrc->getCbAddr(uiPartIdx);
+  Pel* pSrcV = pcYuvSrc->getCrAddr(uiPartIdx);
+  
+  Pel* pDst  = getLumaAddr(uiPartIdx);
+  Pel* pDstU = getCbAddr(uiPartIdx);
+  Pel* pDstV = getCrAddr(uiPartIdx);
+  
+  Int  iSrcStride = pcYuvSrc->getStride();
+  Int  iDstStride = getStride();
+  
+  for ( y = uiHeight-1; y >= 0; y-- )
+  {
+    for ( x = uiWidht-1; x >= 0; x-- )
+    {
+#if DISABLING_CLIP_FOR_BIPREDME
+      pDst[x ] = (pDst[x ]<<1) - pSrc[x ] ;
+#else
+      pDst[x ] = Clip( (pDst[x ]<<1) - pSrc[x ] );
+#endif
+    }
+    pSrc += iSrcStride;
+    pDst += iDstStride;
+  }
+  
+  iSrcStride = pcYuvSrc->getCStride();
+  iDstStride = getCStride();
+  
+  uiHeight >>= 1;
+  uiWidht  >>= 1;
+  
+  for ( y = uiHeight-1; y >= 0; y-- )
+  {
+    for ( x = uiWidht-1; x >= 0; x-- )
+    {
+#if DISABLING_CLIP_FOR_BIPREDME
+      pDstU[x ] = (pDstU[x ]<<1) - pSrcU[x ] ;
+      pDstV[x ] = (pDstV[x ]<<1) - pSrcV[x ] ;
+#else
+      pDstU[x ] = Clip( (pDstU[x ]<<1) - pSrcU[x ] );
+      pDstV[x ] = Clip( (pDstV[x ]<<1) - pSrcV[x ] );
+#endif
+    }
+    pSrcU += iSrcStride;
+    pSrcV += iSrcStride;
+    pDstU += iDstStride;
+    pDstV += iDstStride;
+  }
+}
+//! \}
Index: /trunk/source/Lib/TLibCommon/TComYuv.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComYuv.h	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TComYuv.h	(revision 2)
@@ -0,0 +1,186 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComYuv.h
+    \brief    general YUV buffer class (header)
+    \todo     this should be merged with TComPicYuv \n
+              check usage of removeHighFreq function
+*/
+
+#ifndef __TCOMYUV__
+#define __TCOMYUV__
+#include <assert.h>
+#include "CommonDef.h"
+#include "TComPicYuv.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// general YUV buffer class
+class TComYuv
+{
+private:
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  //  YUV buffer
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  Pel*    m_apiBufY;
+  Pel*    m_apiBufU;
+  Pel*    m_apiBufV;
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  //  Parameter for general YUV buffer usage
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  UInt     m_iWidth;
+  UInt     m_iHeight;
+  UInt     m_iCWidth;
+  UInt     m_iCHeight;
+  
+  static Int getAddrOffset( UInt uiPartUnitIdx, UInt width )
+  {
+    Int blkX = g_auiRasterToPelX[ g_auiZscanToRaster[ uiPartUnitIdx ] ];
+    Int blkY = g_auiRasterToPelY[ g_auiZscanToRaster[ uiPartUnitIdx ] ];
+    
+    return blkX + blkY * width;
+  }
+
+  static Int getAddrOffset( UInt iTransUnitIdx, UInt iBlkSize, UInt width )
+  {
+    Int blkX = ( iTransUnitIdx * iBlkSize ) &  ( width - 1 );
+    Int blkY = ( iTransUnitIdx * iBlkSize ) &~ ( width - 1 );
+    
+    return blkX + blkY * iBlkSize;
+  }
+  
+public:
+  
+  TComYuv();
+  virtual ~TComYuv();
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  //  Memory management
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  Void    create            ( UInt iWidth, UInt iHeight );  ///< Create  YUV buffer
+  Void    destroy           ();                             ///< Destroy YUV buffer
+  Void    clear             ();                             ///< clear   YUV buffer
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  //  Copy, load, store YUV buffer
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  //  Copy YUV buffer to picture buffer
+  Void    copyToPicYuv         ( TComPicYuv* pcPicYuvDst, UInt iCuAddr, UInt uiAbsZorderIdx, UInt uiPartDepth = 0, UInt uiPartIdx = 0 );
+  Void    copyToPicLuma        ( TComPicYuv* pcPicYuvDst, UInt iCuAddr, UInt uiAbsZorderIdx, UInt uiPartDepth = 0, UInt uiPartIdx = 0 );
+  Void    copyToPicChroma      ( TComPicYuv* pcPicYuvDst, UInt iCuAddr, UInt uiAbsZorderIdx, UInt uiPartDepth = 0, UInt uiPartIdx = 0 );
+  
+  //  Copy YUV buffer from picture buffer
+  Void    copyFromPicYuv       ( TComPicYuv* pcPicYuvSrc, UInt iCuAddr, UInt uiAbsZorderIdx );
+  Void    copyFromPicLuma      ( TComPicYuv* pcPicYuvSrc, UInt iCuAddr, UInt uiAbsZorderIdx );
+  Void    copyFromPicChroma    ( TComPicYuv* pcPicYuvSrc, UInt iCuAddr, UInt uiAbsZorderIdx );
+  
+  //  Copy Small YUV buffer to the part of other Big YUV buffer
+  Void    copyToPartYuv         ( TComYuv*    pcYuvDst,    UInt uiDstPartIdx );
+  Void    copyToPartLuma        ( TComYuv*    pcYuvDst,    UInt uiDstPartIdx );
+  Void    copyToPartChroma      ( TComYuv*    pcYuvDst,    UInt uiDstPartIdx );
+  
+  //  Copy the part of Big YUV buffer to other Small YUV buffer
+  Void    copyPartToYuv         ( TComYuv*    pcYuvDst,    UInt uiSrcPartIdx );
+  Void    copyPartToLuma        ( TComYuv*    pcYuvDst,    UInt uiSrcPartIdx );
+  Void    copyPartToChroma      ( TComYuv*    pcYuvDst,    UInt uiSrcPartIdx );
+  
+  //  Copy YUV partition buffer to other YUV partition buffer
+  Void    copyPartToPartYuv     ( TComYuv*    pcYuvDst, UInt uiPartIdx, UInt uiWidth, UInt uiHeight );
+  Void    copyPartToPartLuma    ( TComYuv*    pcYuvDst, UInt uiPartIdx, UInt uiWidth, UInt uiHeight );
+  Void    copyPartToPartChroma  ( TComYuv*    pcYuvDst, UInt uiPartIdx, UInt uiWidth, UInt uiHeight );
+  
+  Void    copyPartToPartChroma  ( TComYuv*    pcYuvDst, UInt uiPartIdx, UInt iWidth, UInt iHeight, UInt chromaId);
+
+  // ------------------------------------------------------------------------------------------------------------------
+  //  Algebraic operation for YUV buffer
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  //  Clip(pcYuvSrc0 + pcYuvSrc1) -> m_apiBuf
+  Void    addClip           ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize );
+  Void    addClipLuma       ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize );
+  Void    addClipChroma     ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize );
+  
+  //  pcYuvSrc0 - pcYuvSrc1 -> m_apiBuf
+  Void    subtract          ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize );
+  Void    subtractLuma      ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize );
+  Void    subtractChroma    ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize );
+  
+  //  (pcYuvSrc0 + pcYuvSrc1)/2 for YUV partition
+  Void    addAvg            ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt iPartUnitIdx, UInt iWidth, UInt iHeight );
+
+  //   Remove High frequency
+  Void    removeHighFreq    ( TComYuv* pcYuvSrc, UInt uiPartIdx, UInt uiWidht, UInt uiHeight );
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  //  Access function for YUV buffer
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  //  Access starting position of YUV buffer
+  Pel*    getLumaAddr ()    { return m_apiBufY; }
+  Pel*    getCbAddr   ()    { return m_apiBufU; }
+  Pel*    getCrAddr   ()    { return m_apiBufV; }
+  
+  //  Access starting position of YUV partition unit buffer
+  Pel* getLumaAddr( UInt iPartUnitIdx ) { return m_apiBufY +   getAddrOffset( iPartUnitIdx, m_iWidth  )       ; }
+  Pel* getCbAddr  ( UInt iPartUnitIdx ) { return m_apiBufU + ( getAddrOffset( iPartUnitIdx, m_iCWidth ) >> 1 ); }
+  Pel* getCrAddr  ( UInt iPartUnitIdx ) { return m_apiBufV + ( getAddrOffset( iPartUnitIdx, m_iCWidth ) >> 1 ); }
+  
+  //  Access starting position of YUV transform unit buffer
+  Pel* getLumaAddr( UInt iTransUnitIdx, UInt iBlkSize ) { return m_apiBufY + getAddrOffset( iTransUnitIdx, iBlkSize, m_iWidth  ); }
+  Pel* getCbAddr  ( UInt iTransUnitIdx, UInt iBlkSize ) { return m_apiBufU + getAddrOffset( iTransUnitIdx, iBlkSize, m_iCWidth ); }
+  Pel* getCrAddr  ( UInt iTransUnitIdx, UInt iBlkSize ) { return m_apiBufV + getAddrOffset( iTransUnitIdx, iBlkSize, m_iCWidth ); }
+
+  //  Get stride value of YUV buffer
+  UInt    getStride   ()    { return  m_iWidth;   }
+  UInt    getCStride  ()    { return  m_iCWidth;  }
+  UInt    getHeight   ()    { return  m_iHeight;  }
+  
+  UInt    getWidth    ()    { return  m_iWidth;   }
+  UInt    getCHeight  ()    { return  m_iCHeight; }
+  UInt    getCWidth   ()    { return  m_iCWidth;  }  
+};// END CLASS DEFINITION TComYuv
+
+//! \}
+
+#endif // __TCOMYUV__
Index: /trunk/source/Lib/TLibCommon/TypeDef.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TypeDef.h	(revision 2)
+++ /trunk/source/Lib/TLibCommon/TypeDef.h	(revision 2)
@@ -0,0 +1,638 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TypeDef.h
+    \brief    Define basic types, new types and enumerations
+*/
+
+#ifndef _TYPEDEF__
+#define _TYPEDEF__
+
+#define SVC_EXTENSION                    1
+#if SVC_EXTENSION
+#define MAX_LAYERS                       8      ///< max number of layers the codec is supposed to handle
+
+#define SVC_COL_BLK                      1      ///< get co-located block
+#define SVC_UPSAMPLING                   1      ///< upsampling filters
+#define PHASE_DERIVATION_IN_INTEGER      1      ///< upsampling filters implementation using only integer arithmetic
+
+#define AVC_BASE                         0      ///< YUV BL reading for AVC base SVC
+
+#define REF_IDX_FRAMEWORK                0      ///< inter-layer reference framework
+
+#if REF_IDX_FRAMEWORK
+#define REF_IDX_ME_AROUND_ZEROMV         0      ///< added ME around zero MV for inter-layer reference picture
+#else
+#define INTRA_BL                         1      ///< inter-layer texture prediction
+// Hooks
+#if !AVC_BASE
+#define SVC_MVP                          0      ///< motion hook for merge mode as an example
+#define SVC_BL_CAND_INTRA                0      ///< Intra Base Mode Prediction hook as an example 
+#endif
+#endif
+
+#endif
+
+//! \ingroup TLibCommon
+//! \{
+#define RECOVERY_POINT_SEI               1  ///< I0044/J0107, Recovery point SEI
+#define SPS_AMVP_CLEANUP                 1  ///< remove old AMVP related code for alignment with draft text
+#define SUPPORT_FOR_VUI                  1  ///< new: add support for VUI and hrd_parameters
+#if SUPPORT_FOR_VUI
+#define BUFFERING_PERIOD_AND_TIMING_SEI  1  ///< Buffering period SEI and Picture timing SEI
+#if BUFFERING_PERIOD_AND_TIMING_SEI
+#define MAX_CPB_CNT                     32  ///< Upper bound of (cpb_cnt_minus1 + 1)
+#endif
+#endif
+#define TARGET_DECLAYERID_SET            1  ///< J0074:  targetDecLayerIdSet for sub-bitstream extraction process
+#if TARGET_DECLAYERID_SET
+#define MAX_NUM_LAYER_IDS                64
+#endif
+
+#define TILES_WPP_ENTROPYSLICES_FLAGS    1  ///< J0123: Introduce tiles_enabled_flag, entropy_coding_sync_enabled_flag, entropy_slice_enabled_flag
+                                            ///<        and remove tiles_or_entropy_coding_sync_idc
+#define SLICEHEADER_SYNTAX_FIX           1  ///< fixes for aligning slice header syntax with HM8 text
+#define NAL_UNIT_TYPES_J1003_D7          1  ///< J1003: Implements the new mapping for NAL unit types as defined in Table 7-1 of J1003-d7
+#if NAL_UNIT_TYPES_J1003_D7
+// Place macro definitions that deal with new NAL unit types introduced in J1003-d7 (as opposed to I1003-d7) here
+#define SUPPORT_FOR_RAP_N_LP             1  ///< J0344: Add support for IDR_N_LP and BLA_N_LP NAL unit types
+#define STSA                             1        ///STSA (GTLA) pictures labeling
+#define TEMPORAL_LAYER_NON_REFERENCE     1  ///< J0549: Nal unit types for indicating non-reference pictures in the same temporal sub-layer
+#endif
+
+#define SPS_SYNTAX_CHANGES               1  ///< J0550: changes to SPS syntax
+#define VPS_SYNTAX_CHANGES               1  ///< J0550/J0562: changes to VPS syntax
+#define PROFILE_TIER_LEVEL_SYNTAX        1  ///< J0562: Include profile_tier_level() syntax structure; not used for now
+#define SAO_LUM_CHROMA_ONOFF_FLAGS       1  ///< J0087: slice-level independent luma/chroma SAO on/off flag 
+#define LTRP_IN_SPS                      1  ///< J0116: Include support for signalling LTRP LSBs in the SPS, and index them in the slice header.
+#define CHROMA_QP_EXTENSION              1  ///< J0342: Extend mapping table from luma QP to chroma QP, introduce slice-level chroma offsets, apply limits on offset values
+#define SIMPLE_LUMA_CBF_CTX_DERIVATION   1  ///< J0303: simplified luma_CBF context derivation
+
+#define COEF_REMAIN_BIN_REDUCTION        3 ///< J0142: Maximum codeword length of coeff_abs_level_remaining reduced to 32.
+                                           ///< COEF_REMAIN_BIN_REDUCTION is also used to indicate the level at which the VLC 
+                                
+///< transitions from Golomb-Rice to TU+EG(k)
+
+#define CU_DQP_TU_EG                     1 ///< J0089: Bin reduction for delta QP coding
+#if (CU_DQP_TU_EG)
+#define CU_DQP_TU_CMAX 5 //max number bins for truncated unary
+#define CU_DQP_EG_k 0 //expgolomb order
+#endif
+
+#define NAL_UNIT_HEADER                  1  ///< J0550: Define nal_unit_header() method
+#define TEMPORAL_ID_PLUS1                1  ///< J0550: Signal temporal_id_plus1 instead of temporal_id in NAL unit, and change reserved_one_5bits
+                                            ///<        value to zero
+#define REFERENCE_PICTURE_DEFN           1  ///< J0118: Reflect change of defn. of referece picture in semantics of delta_poc_msb_present_flag
+#if REFERENCE_PICTURE_DEFN
+#define REMOVE_NAL_REF_FLAG              1  ///< J0550: Remove nal_ref_flag, and allocate extra bit to reserved bits, and re-order syntax to put reserved bits after nal_unit_type
+#endif
+#define MOVE_LOOP_FILTER_SLICES_FLAG     1  ///< J0288: Move seq_loop_filter_across_slices_enabled_flag from SPS to PPS
+#define SPLICING_FRIENDLY_PARAMS         1  ///< J0108: Remove rap_pic_id and move no_output_prior_pic_flag
+
+#define  SKIP_FLAG                       1  ///< J0336: store skip flag
+
+#define PPS_TS_FLAG                      1  ///< J0184: move transform_skip_enabled_flag from SPS to PPS
+#if PPS_TS_FLAG
+#define TS_FLAT_QUANTIZATION_MATRIX      1  ///< I0408: set default quantization matrix to be flat if TS is enabled in PPS
+#endif
+#define INTER_TRANSFORMSKIP              1  ///< J0237: inter transform skipping (inter-TS)
+#define INTRA_TRANSFORMSKIP_FAST         1  ///< J0572: fast encoding for intra transform skipping
+
+#define REMOVAL_8x2_2x8_CG               1  ///< J0256: removal of 8x2 / 2x8 coefficient groups
+#define REF_IDX_BYPASS                   1  ///< J0098: bypass coding starting from the second bin for reference index
+
+#define RECALCULATE_QP_ACCORDING_LAMBDA  1  ///< J0242: recalculate QP value according to lambda value
+#define TU_ZERO_CBF_RDO                  1  ///< J0241: take the bits to represent zero cbf into consideration when doing TU RDO
+#define REMOVE_NUM_GREATER1              1  ///< J0408: numGreater1 removal and ctxset decision with c1 
+
+#define INTRA_TRANS_SIMP                 1  ///< J0035: Use DST for 4x4 luma intra TU's (regardless of the intra prediction direction)
+
+#define J0234_INTER_RPS_SIMPL            1  ///< J0234: Do not signal delta_idx_minus1 when building the RPS-list in SPS
+#define NUM_WP_LIMIT                     1  ///< J0571: number of total signalled weight flags <=24
+#define DISALLOW_BIPRED_IN_8x4_4x8PUS    1  ///< J0086: disallow bi-pred for 8x4 and 4x8 inter PUs
+#define SAO_SINGLE_MERGE                 1  ///< J0355: Single SAO merge flag for all color components (per Left and Up merge)
+#define SAO_TYPE_SHARING                 1  ///< J0045: SAO types, merge left/up flags are shared between Cr and Cb
+#define SAO_TYPE_CODING                  1  ///< J0268: SAO type signalling using 1 ctx on/off flag + 1 bp BO/EO flag + 2 bp bins for EO class
+#define SAO_MERGE_ONE_CTX                1  ///< J0041: SAO merge left/up flags share the same ctx
+#define SAO_ABS_BY_PASS                  1  ///< J0043: by pass coding for SAO magnitudes 
+#define SAO_LCU_BOUNDARY                 1  ///< J0139: SAO parameter estimation using non-deblocked pixels for LCU bottom and right boundary areas
+#define MODIFIED_CROSS_SLICE             1  ///< J0266: SAO slice boundary control for GDR
+#define CU_DQP_ENABLE_FLAG               1  ///< J0220: cu_qp_delta_enabled_flag in PPS
+#define REMOVE_ZIGZAG_SCAN               1  ///< J0150: removal of zigzag scan
+
+#define TRANS_SPLIT_FLAG_CTX_REDUCTION   1  ///< J0133: Reduce the context number of transform split flag to 3
+
+#define WP_PARAM_RANGE_LIMIT             1  ///< J0221: Range limit of delta_weight and delta_offset for chroma.
+#define J0260 1 ///< Fix in rate control equations
+
+#define NO_MV_PRED_IF_DIFFERENT_TERM     1  ///< J0071/J0121: No MVP is used when cur:short-term and pred:long-term or vice-versa
+
+#define ACTIVE_PARAMETER_SETS_SEI_MESSAGE    1  ///< J0261: Signaling of VPS Activation
+#define SLICE_HEADER_EXTENSION           1  ///< II0235: Slice header extension mechanism
+
+#define REMOVE_NSQT 1 ///< Disable NSQT-related code
+#define REMOVE_LMCHROMA 1 ///< Disable LM_Chroma-related code
+#define REMOVE_FGS 1 ///< Disable fine-granularity slices code
+#define REMOVE_ALF 1 ///< Disable ALF-related code
+#define REMOVE_APS 1 ///< Disable APS-related code
+
+#define PREVREFPIC_DEFN                  0  ///< J0248: Shall be set equal to 0! (prevRefPic definition reverted to CD definition)
+#define BYTE_ALIGNMENT                   1  ///< I0330: Add byte_alignment() procedure to end of slice header
+
+#define SBH_THRESHOLD                    4  ///< I0156: value of the fixed SBH controlling threshold
+  
+#define SEQUENCE_LEVEL_LOSSLESS           0  ///< H0530: used only for sequence or frame-level lossless coding
+
+#define DISABLING_CLIP_FOR_BIPREDME         1  ///< Ticket #175
+  
+#define C1FLAG_NUMBER               8 // maximum number of largerThan1 flag coded in one chunk :  16 in HM5
+#define C2FLAG_NUMBER               1 // maximum number of largerThan2 flag coded in one chunk:  16 in HM5 
+
+#define REMOVE_SAO_LCU_ENC_CONSTRAINTS_3 1  ///< disable the encoder constraint that conditionally disable SAO for chroma for entire slice in interleaved mode
+
+#define SAO_SKIP_RIGHT                   1  ///< H1101: disallow using unavailable pixel during RDO
+
+#define SAO_ENCODING_CHOICE              1  ///< I0184: picture early termination
+#define PICTURE_SAO_RDO_FIX              0  ///< J0097: picture-based SAO optimization fix
+#if SAO_ENCODING_CHOICE
+#define SAO_ENCODING_RATE                0.75
+#define SAO_ENCODING_CHOICE_CHROMA       1 ///< J0044: picture early termination Luma and Chroma are handled separatenly
+#if SAO_ENCODING_CHOICE_CHROMA
+#define SAO_ENCODING_RATE_CHROMA         0.5
+#endif
+#endif
+
+#define MAX_NUM_SPS                32
+#define MAX_NUM_PPS                256
+#define MAX_NUM_APS                32         //< !!!KS: number not defined in WD yet
+
+
+#define WEIGHTED_CHROMA_DISTORTION  1   ///< F386: weighting of chroma for RDO
+#define RDOQ_CHROMA_LAMBDA          1   ///< F386: weighting of chroma for RDOQ
+#define ALF_CHROMA_LAMBDA           1   ///< F386: weighting of chroma for ALF
+#define SAO_CHROMA_LAMBDA           1   ///< F386: weighting of chroma for SAO
+
+#define MIN_SCAN_POS_CROSS          4
+
+#define FAST_BIT_EST                1   ///< G763: Table-based bit estimation for CABAC
+
+#define MLS_GRP_NUM                         64     ///< G644 : Max number of coefficient groups, max(16, 64)
+#define MLS_CG_SIZE                         4      ///< G644 : Coefficient group size of 4x4
+
+#define ADAPTIVE_QP_SELECTION               1      ///< G382: Adaptive reconstruction levels, non-normative part for adaptive QP selection
+#if ADAPTIVE_QP_SELECTION
+#define ARL_C_PRECISION                     7      ///< G382: 7-bit arithmetic precision
+#define LEVEL_RANGE                         30     ///< G382: max coefficient level in statistics collection
+#endif
+
+#if REMOVE_NSQT
+#define NS_HAD                               0
+#else
+#define NS_HAD                               1
+#endif
+
+#define APS_BITS_FOR_SAO_BYTE_LENGTH 12           
+#define APS_BITS_FOR_ALF_BYTE_LENGTH 8
+
+#define HHI_RQT_INTRA_SPEEDUP             1           ///< tests one best mode with full rqt
+#define HHI_RQT_INTRA_SPEEDUP_MOD         0           ///< tests two best modes with full rqt
+
+#if HHI_RQT_INTRA_SPEEDUP_MOD && !HHI_RQT_INTRA_SPEEDUP
+#error
+#endif
+
+#define VERBOSE_RATE 0 ///< Print additional rate information in encoder
+
+#define AMVP_DECIMATION_FACTOR            4
+
+#define SCAN_SET_SIZE                     16
+#define LOG2_SCAN_SET_SIZE                4
+
+#define FAST_UDI_MAX_RDMODE_NUM               35          ///< maximum number of RD comparison in fast-UDI estimation loop 
+
+#define ZERO_MVD_EST                          0           ///< Zero Mvd Estimation in normal mode
+
+#define NUM_INTRA_MODE 36
+#if !REMOVE_LM_CHROMA
+#define LM_CHROMA_IDX  35
+#endif
+
+#define IBDI_DISTORTION                0           ///< enable/disable SSE modification when IBDI is used (JCTVC-D152)
+#define FIXED_ROUNDING_FRAME_MEMORY    0           ///< enable/disable fixed rounding to 8-bitdepth of frame memory when IBDI is used  
+
+#define WRITE_BACK                      1           ///< Enable/disable the encoder to replace the deltaPOC and Used by current from the config file with the values derived by the refIdc parameter.
+#define AUTO_INTER_RPS                  1           ///< Enable/disable the automatic generation of refIdc from the deltaPOC and Used by current from the config file.
+#define PRINT_RPS_INFO                  0           ///< Enable/disable the printing of bits used to send the RPS.
+                                                    // using one nearest frame as reference frame, and the other frames are high quality (POC%4==0) frames (1+X)
+                                                    // this should be done with encoder only decision
+                                                    // but because of the absence of reference frame management, the related code was hard coded currently
+
+#define RVM_VCEGAM10_M 4
+
+#define PLANAR_IDX             0
+#define VER_IDX                26                    // index for intra VERTICAL   mode
+#define HOR_IDX                10                    // index for intra HORIZONTAL mode
+#define DC_IDX                 1                     // index for intra DC mode
+#if REMOVE_LMCHROMA
+#define NUM_CHROMA_MODE        5                     // total number of chroma modes
+#else
+#define NUM_CHROMA_MODE        6                     // total number of chroma modes
+#endif
+#define DM_CHROMA_IDX          36                    // chroma mode index for derived from luma intra mode
+
+
+#define FAST_UDI_USE_MPM 1
+
+#define RDO_WITHOUT_DQP_BITS              0           ///< Disable counting dQP bits in RDO-based mode decision
+
+#define FULL_NBIT 0 ///< When enabled, does not use g_uiBitIncrement anymore to support > 8 bit data
+
+#define AD_HOC_SLICES_FIXED_NUMBER_OF_LCU_IN_SLICE      1          ///< OPTION IDENTIFIER. mode==1 -> Limit maximum number of largest coding tree blocks in a slice
+#define AD_HOC_SLICES_FIXED_NUMBER_OF_BYTES_IN_SLICE    2          ///< OPTION IDENTIFIER. mode==2 -> Limit maximum number of bins/bits in a slice
+#define AD_HOC_SLICES_FIXED_NUMBER_OF_TILES_IN_SLICE    3
+
+#define DEPENDENT_SLICES       1 ///< JCTVC-I0229
+// Dependent slice options
+#define SHARP_FIXED_NUMBER_OF_LCU_IN_DEPENDENT_SLICE            1          ///< OPTION IDENTIFIER. Limit maximum number of largest coding tree blocks in an dependent slice
+#define SHARP_MULTIPLE_CONSTRAINT_BASED_DEPENDENT_SLICE         2          ///< OPTION IDENTIFIER. Limit maximum number of bins/bits in an dependent slice
+#if DEPENDENT_SLICES
+#define FIXED_NUMBER_OF_TILES_IN_DEPENDENT_SLICE          3 // JCTVC-I0229
+#endif
+
+#define LOG2_MAX_NUM_COLUMNS_MINUS1        7
+#define LOG2_MAX_NUM_ROWS_MINUS1           7
+#define LOG2_MAX_COLUMN_WIDTH              13
+#define LOG2_MAX_ROW_HEIGHT                13
+
+#define MATRIX_MULT                             0   // Brute force matrix multiplication instead of partial butterfly
+
+#define REG_DCT 65535
+
+#define AMP_SAD                               1           ///< dedicated SAD functions for AMP
+#define AMP_ENC_SPEEDUP                       1           ///< encoder only speed-up by AMP mode skipping
+#if AMP_ENC_SPEEDUP
+#define AMP_MRG                               1           ///< encoder only force merge for AMP partition (no motion search for AMP)
+#endif
+
+#define SCALING_LIST_OUTPUT_RESULT    0 //JCTVC-G880/JCTVC-G1016 quantization matrices
+
+#define CABAC_INIT_PRESENT_FLAG     1
+
+// ====================================================================================================================
+// VPS constants
+// ====================================================================================================================
+#define MAX_LAYER_NUM                     10
+#define MAX_NUM_VPS                16
+
+// ====================================================================================================================
+// Basic type redefinition
+// ====================================================================================================================
+
+typedef       void                Void;
+typedef       bool                Bool;
+
+typedef       char                Char;
+typedef       unsigned char       UChar;
+typedef       short               Short;
+typedef       unsigned short      UShort;
+typedef       int                 Int;
+typedef       unsigned int        UInt;
+typedef       double              Double;
+
+// ====================================================================================================================
+// 64-bit integer type
+// ====================================================================================================================
+
+#ifdef _MSC_VER
+typedef       __int64             Int64;
+
+#if _MSC_VER <= 1200 // MS VC6
+typedef       __int64             UInt64;   // MS VC6 does not support unsigned __int64 to double conversion
+#else
+typedef       unsigned __int64    UInt64;
+#endif
+
+#else
+
+typedef       long long           Int64;
+typedef       unsigned long long  UInt64;
+
+#endif
+
+// ====================================================================================================================
+// Type definition
+// ====================================================================================================================
+
+typedef       UChar           Pxl;        ///< 8-bit pixel type
+typedef       Short           Pel;        ///< 16-bit pixel type
+typedef       Int             TCoeff;     ///< transform coefficient
+
+/// parameters for adaptive loop filter
+class TComPicSym;
+
+#define NUM_DOWN_PART 4
+
+enum SAOTypeLen
+{
+  SAO_EO_LEN    = 4, 
+  SAO_BO_LEN    = 4,
+  SAO_MAX_BO_CLASSES = 32
+};
+
+enum SAOType
+{
+  SAO_EO_0 = 0, 
+  SAO_EO_1,
+  SAO_EO_2, 
+  SAO_EO_3,
+  SAO_BO,
+  MAX_NUM_SAO_TYPE
+};
+
+typedef struct _SaoQTPart
+{
+  Int         iBestType;
+  Int         iLength;
+#if SAO_TYPE_CODING
+  Int         subTypeIdx ;                 ///< indicates EO class or BO band position
+#else
+  Int         bandPosition ;
+#endif
+  Int         iOffset[4];
+  Int         StartCUX;
+  Int         StartCUY;
+  Int         EndCUX;
+  Int         EndCUY;
+
+  Int         PartIdx;
+  Int         PartLevel;
+  Int         PartCol;
+  Int         PartRow;
+
+  Int         DownPartsIdx[NUM_DOWN_PART];
+  Int         UpPartIdx;
+
+  Bool        bSplit;
+
+  //---- encoder only start -----//
+  Bool        bProcessed;
+  Double      dMinCost;
+  Int64       iMinDist;
+  Int         iMinRate;
+  //---- encoder only end -----//
+} SAOQTPart;
+
+typedef struct _SaoLcuParam
+{
+  Bool       mergeUpFlag;
+  Bool       mergeLeftFlag;
+  Int        typeIdx;
+#if SAO_TYPE_CODING
+  Int        subTypeIdx;                  ///< indicates EO class or BO band position
+#else
+  Int        bandPosition;
+#endif
+  Int        offset[4];
+  Int        partIdx;
+  Int        partIdxTmp;
+  Int        length;
+} SaoLcuParam;
+
+struct SAOParam
+{
+#if SAO_TYPE_SHARING
+  Bool       bSaoFlag[2];
+#else
+  Bool       bSaoFlag[3];
+#endif
+  SAOQTPart* psSaoPart[3];
+  Int        iMaxSplitLevel;
+  Bool         oneUnitFlag[3];
+  SaoLcuParam* saoLcuParam[3];
+  Int          numCuInHeight;
+  Int          numCuInWidth;
+  ~SAOParam();
+};
+
+#if !REMOVE_ALF
+struct ALFParam
+{
+  Int alf_flag;                           ///< indicates use of ALF
+  Int num_coeff;                          ///< number of filter coefficients
+  Int filter_shape;
+  Int *filterPattern;
+  Int startSecondFilter;
+  Int filters_per_group;
+  Int **coeffmulti;
+  Int componentID;
+  //constructor, operator
+  ALFParam():componentID(-1){}
+  ALFParam(Int cID){create(cID);}
+  ALFParam(const ALFParam& src) {*this = src;}
+  ~ALFParam(){destroy();}
+  const ALFParam& operator= (const ALFParam& src);
+private:
+  Void create(Int cID);
+  Void destroy();
+  Void copy(const ALFParam& src);
+};
+#endif
+
+/// parameters for deblocking filter
+typedef struct _LFCUParam
+{
+  Bool bInternalEdge;                     ///< indicates internal edge
+  Bool bLeftEdge;                         ///< indicates left edge
+  Bool bTopEdge;                          ///< indicates top edge
+} LFCUParam;
+
+// ====================================================================================================================
+// Enumeration
+// ====================================================================================================================
+
+/// supported slice type
+enum SliceType
+{
+  B_SLICE,
+  P_SLICE,
+  I_SLICE
+};
+
+/// chroma formats (according to semantics of chroma_format_idc)
+enum ChromaFormat
+{
+  CHROMA_400  = 0,
+  CHROMA_420  = 1,
+  CHROMA_422  = 2,
+  CHROMA_444  = 3
+};
+
+/// supported partition shape
+enum PartSize
+{
+  SIZE_2Nx2N,           ///< symmetric motion partition,  2Nx2N
+  SIZE_2NxN,            ///< symmetric motion partition,  2Nx N
+  SIZE_Nx2N,            ///< symmetric motion partition,   Nx2N
+  SIZE_NxN,             ///< symmetric motion partition,   Nx N
+  SIZE_2NxnU,           ///< asymmetric motion partition, 2Nx( N/2) + 2Nx(3N/2)
+  SIZE_2NxnD,           ///< asymmetric motion partition, 2Nx(3N/2) + 2Nx( N/2)
+  SIZE_nLx2N,           ///< asymmetric motion partition, ( N/2)x2N + (3N/2)x2N
+  SIZE_nRx2N,           ///< asymmetric motion partition, (3N/2)x2N + ( N/2)x2N
+  SIZE_NONE = 15
+};
+
+/// supported prediction type
+enum PredMode
+{
+  MODE_INTER,           ///< inter-prediction mode
+  MODE_INTRA,           ///< intra-prediction mode
+#if INTRA_BL
+  MODE_INTRA_BL,        ///< inter-layer intra-prediction mode
+#endif
+  MODE_NONE = 15
+};
+
+/// texture component type
+enum TextType
+{
+  TEXT_LUMA,            ///< luma
+  TEXT_CHROMA,          ///< chroma (U+V)
+  TEXT_CHROMA_U,        ///< chroma U
+  TEXT_CHROMA_V,        ///< chroma V
+  TEXT_ALL,             ///< Y+U+V
+  TEXT_NONE = 15
+};
+
+/// reference list index
+enum RefPicList
+{
+  REF_PIC_LIST_0 = 0,   ///< reference list 0
+  REF_PIC_LIST_1 = 1,   ///< reference list 1
+  REF_PIC_LIST_C = 2,   ///< combined reference list for uni-prediction in B-Slices
+  REF_PIC_LIST_X = 100  ///< special mark
+};
+
+/// distortion function index
+enum DFunc
+{
+  DF_DEFAULT  = 0,
+  DF_SSE      = 1,      ///< general size SSE
+  DF_SSE4     = 2,      ///<   4xM SSE
+  DF_SSE8     = 3,      ///<   8xM SSE
+  DF_SSE16    = 4,      ///<  16xM SSE
+  DF_SSE32    = 5,      ///<  32xM SSE
+  DF_SSE64    = 6,      ///<  64xM SSE
+  DF_SSE16N   = 7,      ///< 16NxM SSE
+  
+  DF_SAD      = 8,      ///< general size SAD
+  DF_SAD4     = 9,      ///<   4xM SAD
+  DF_SAD8     = 10,     ///<   8xM SAD
+  DF_SAD16    = 11,     ///<  16xM SAD
+  DF_SAD32    = 12,     ///<  32xM SAD
+  DF_SAD64    = 13,     ///<  64xM SAD
+  DF_SAD16N   = 14,     ///< 16NxM SAD
+  
+  DF_SADS     = 15,     ///< general size SAD with step
+  DF_SADS4    = 16,     ///<   4xM SAD with step
+  DF_SADS8    = 17,     ///<   8xM SAD with step
+  DF_SADS16   = 18,     ///<  16xM SAD with step
+  DF_SADS32   = 19,     ///<  32xM SAD with step
+  DF_SADS64   = 20,     ///<  64xM SAD with step
+  DF_SADS16N  = 21,     ///< 16NxM SAD with step
+  
+  DF_HADS     = 22,     ///< general size Hadamard with step
+  DF_HADS4    = 23,     ///<   4xM HAD with step
+  DF_HADS8    = 24,     ///<   8xM HAD with step
+  DF_HADS16   = 25,     ///<  16xM HAD with step
+  DF_HADS32   = 26,     ///<  32xM HAD with step
+  DF_HADS64   = 27,     ///<  64xM HAD with step
+  DF_HADS16N  = 28,     ///< 16NxM HAD with step
+  
+#if AMP_SAD
+  DF_SAD12    = 43,
+  DF_SAD24    = 44,
+  DF_SAD48    = 45,
+
+  DF_SADS12   = 46,
+  DF_SADS24   = 47,
+  DF_SADS48   = 48,
+
+  DF_SSE_FRAME = 50     ///< Frame-based SSE
+#else
+  DF_SSE_FRAME = 33     ///< Frame-based SSE
+#endif
+};
+
+/// index for SBAC based RD optimization
+enum CI_IDX
+{
+  CI_CURR_BEST = 0,     ///< best mode index
+  CI_NEXT_BEST,         ///< next best index
+  CI_TEMP_BEST,         ///< temporal index
+  CI_CHROMA_INTRA,      ///< chroma intra index
+  CI_QT_TRAFO_TEST,
+  CI_QT_TRAFO_ROOT,
+  CI_NUM,               ///< total number
+};
+
+/// motion vector predictor direction used in AMVP
+enum MVP_DIR
+{
+  MD_LEFT = 0,          ///< MVP of left block
+  MD_ABOVE,             ///< MVP of above block
+  MD_ABOVE_RIGHT,       ///< MVP of above right block
+  MD_BELOW_LEFT,        ///< MVP of below left block
+  MD_ABOVE_LEFT         ///< MVP of above left block
+};
+
+#if !SPS_AMVP_CLEANUP
+/// motion vector prediction mode used in AMVP
+enum AMVP_MODE
+{
+  AM_NONE = 0,          ///< no AMVP mode
+  AM_EXPL,              ///< explicit signalling of motion vector index
+};
+#endif
+
+/// coefficient scanning type used in ACS
+enum COEFF_SCAN_TYPE
+{
+  SCAN_ZIGZAG = 0,      ///< typical zigzag scan
+  SCAN_HOR,             ///< horizontal first scan
+  SCAN_VER,              ///< vertical first scan
+  SCAN_DIAG              ///< up-right diagonal scan
+};
+
+//! \}
+
+#endif
Index: /trunk/source/Lib/TLibDecoder/AnnexBread.cpp
===================================================================
--- /trunk/source/Lib/TLibDecoder/AnnexBread.cpp	(revision 2)
+++ /trunk/source/Lib/TLibDecoder/AnnexBread.cpp	(revision 2)
@@ -0,0 +1,167 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <stdint.h>
+#include <cassert>
+#include <vector>
+#include "AnnexBread.h"
+
+using namespace std;
+
+//! \ingroup TLibDecoder
+//! \{
+
+/**
+ * Parse an AVC AnnexB Bytestream bs to extract a single nalUnit
+ * while accumulating bytestream statistics into stats.
+ *
+ * If EOF occurs while trying to extract a NALunit, an exception
+ * of std::ios_base::failure is thrown.  The contsnts of stats will
+ * be correct at this point.
+ */
+static void
+_byteStreamNALUnit(
+  InputByteStream& bs,
+  vector<uint8_t>& nalUnit,
+  AnnexBStats& stats)
+{
+  /* At the beginning of the decoding process, the decoder initialises its
+   * current position in the byte stream to the beginning of the byte stream.
+   * It then extracts and discards each leading_zero_8bits syntax element (if
+   * present), moving the current position in the byte stream forward one
+   * byte at a time, until the current position in the byte stream is such
+   * that the next four bytes in the bitstream form the four-byte sequence
+   * 0x00000001.
+   */
+  while ((bs.eofBeforeNBytes(24/8) || bs.peekBytes(24/8) != 0x000001)
+  &&     (bs.eofBeforeNBytes(32/8) || bs.peekBytes(32/8) != 0x00000001))
+  {
+    uint8_t leading_zero_8bits = bs.readByte();
+    assert(leading_zero_8bits == 0);
+    stats.m_numLeadingZero8BitsBytes++;
+  }
+
+  /* 1. When the next four bytes in the bitstream form the four-byte sequence
+   * 0x00000001, the next byte in the byte stream (which is a zero_byte
+   * syntax element) is extracted and discarded and the current position in
+   * the byte stream is set equal to the position of the byte following this
+   * discarded byte.
+   */
+  /* NB, the previous step guarantees this will succeed -- if EOF was
+   * encountered, an exception will stop execution getting this far */
+  if (bs.peekBytes(24/8) != 0x000001)
+  {
+    uint8_t zero_byte = bs.readByte();
+    assert(zero_byte == 0);
+    stats.m_numZeroByteBytes++;
+  }
+
+  /* 2. The next three-byte sequence in the byte stream (which is a
+   * start_code_prefix_one_3bytes) is extracted and discarded and the current
+   * position in the byte stream is set equal to the position of the byte
+   * following this three-byte sequence.
+   */
+  /* NB, (1) guarantees that the next three bytes are 0x00 00 01 */
+  uint32_t start_code_prefix_one_3bytes = bs.readBytes(24/8);
+  assert(start_code_prefix_one_3bytes == 0x000001);
+  stats.m_numStartCodePrefixBytes += 3;
+
+  /* 3. NumBytesInNALunit is set equal to the number of bytes starting with
+   * the byte at the current position in the byte stream up to and including
+   * the last byte that precedes the location of any of the following
+   * conditions:
+   *   a. A subsequent byte-aligned three-byte sequence equal to 0x000000, or
+   *   b. A subsequent byte-aligned three-byte sequence equal to 0x000001, or
+   *   c. The end of the byte stream, as determined by unspecified means.
+   */
+  /* 4. NumBytesInNALunit bytes are removed from the bitstream and the
+   * current position in the byte stream is advanced by NumBytesInNALunit
+   * bytes. This sequence of bytes is nal_unit( NumBytesInNALunit ) and is
+   * decoded using the NAL unit decoding process
+   */
+  /* NB, (unsigned)x > 2 implies n!=0 && n!=1 */
+  while (bs.eofBeforeNBytes(24/8) || bs.peekBytes(24/8) > 2) 
+  {
+    nalUnit.push_back(bs.readByte());
+  }
+  
+  /* 5. When the current position in the byte stream is:
+   *  - not at the end of the byte stream (as determined by unspecified means)
+   *  - and the next bytes in the byte stream do not start with a three-byte
+   *    sequence equal to 0x000001
+   *  - and the next bytes in the byte stream do not start with a four byte
+   *    sequence equal to 0x00000001,
+   * the decoder extracts and discards each trailing_zero_8bits syntax
+   * element, moving the current position in the byte stream forward one byte
+   * at a time, until the current position in the byte stream is such that:
+   *  - the next bytes in the byte stream form the four-byte sequence
+   *    0x00000001 or
+   *  - the end of the byte stream has been encountered (as determined by
+   *    unspecified means).
+   */
+  /* NB, (3) guarantees there are at least three bytes available or none */
+  while ((bs.eofBeforeNBytes(24/8) || bs.peekBytes(24/8) != 0x000001)
+  &&     (bs.eofBeforeNBytes(32/8) || bs.peekBytes(32/8) != 0x00000001))
+  {
+    uint8_t trailing_zero_8bits = bs.readByte();
+    assert(trailing_zero_8bits == 0);
+    stats.m_numTrailingZero8BitsBytes++;
+  }
+}
+
+/**
+ * Parse an AVC AnnexB Bytestream bs to extract a single nalUnit
+ * while accumulating bytestream statistics into stats.
+ *
+ * Returns false if EOF was reached (NB, nalunit data may be valid),
+ *         otherwise true.
+ */
+bool
+byteStreamNALUnit(
+  InputByteStream& bs,
+  vector<uint8_t>& nalUnit,
+  AnnexBStats& stats)
+{
+  bool eof = false;
+  try
+  {
+    _byteStreamNALUnit(bs, nalUnit, stats);
+  }
+  catch (...)
+  {
+    eof = true;
+  }
+  stats.m_numBytesInNALUnit = unsigned(nalUnit.size());
+  return eof;
+}
+//! \}
Index: /trunk/source/Lib/TLibDecoder/AnnexBread.h
===================================================================
--- /trunk/source/Lib/TLibDecoder/AnnexBread.h	(revision 2)
+++ /trunk/source/Lib/TLibDecoder/AnnexBread.h	(revision 2)
@@ -0,0 +1,179 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#pragma once
+
+#include <stdint.h>
+#include <istream>
+#include <vector>
+
+//! \ingroup TLibDecoder
+//! \{
+
+class InputByteStream
+{
+public:
+  /**
+   * Create a bytestream reader that will extract bytes from
+   * istream.
+   *
+   * NB, it isn't safe to access istream while in use by a
+   * InputByteStream.
+   *
+   * Side-effects: the exception mask of istream is set to eofbit
+   */
+  InputByteStream(std::istream& istream)
+  : m_NumFutureBytes(0)
+  , m_FutureBytes(0)
+  , m_Input(istream)
+  {
+    istream.exceptions(std::istream::eofbit);
+  }
+
+  /**
+   * Reset the internal state.  Must be called if input stream is
+   * modified externally to this class
+   */
+  void reset()
+  {
+    m_NumFutureBytes = 0;
+    m_FutureBytes = 0;
+  }
+
+  /**
+   * returns true if an EOF will be encountered within the next
+   * n bytes.
+   */
+  bool eofBeforeNBytes(unsigned n)
+  {
+    assert(n <= 4);
+    if (m_NumFutureBytes >= n)
+      return false;
+
+    n -= m_NumFutureBytes;
+    try
+    {
+      for (unsigned i = 0; i < n; i++)
+      {
+        m_FutureBytes = (m_FutureBytes << 8) | m_Input.get();
+        m_NumFutureBytes++;
+      }
+    }
+    catch (...)
+    {
+      return true;
+    }
+    return false;
+  }
+
+  /**
+   * return the next n bytes in the stream without advancing
+   * the stream pointer.
+   *
+   * Returns: an unsigned integer representing an n byte bigendian
+   * word.
+   *
+   * If an attempt is made to read past EOF, an n-byte word is
+   * returned, but the portion that required input bytes beyond EOF
+   * is undefined.
+   *
+   */
+  uint32_t peekBytes(unsigned n)
+  {
+    eofBeforeNBytes(n);
+    return m_FutureBytes >> 8*(m_NumFutureBytes - n);
+  }
+
+  /**
+   * consume and return one byte from the input.
+   *
+   * If bytestream is already at EOF prior to a call to readByte(),
+   * an exception std::ios_base::failure is thrown.
+   */
+  uint8_t readByte()
+  {
+    if (!m_NumFutureBytes)
+    {
+      uint8_t byte = m_Input.get();
+      return byte;
+    }
+    m_NumFutureBytes--;
+    uint8_t wanted_byte = m_FutureBytes >> 8*m_NumFutureBytes;
+    m_FutureBytes &= ~(0xff << 8*m_NumFutureBytes);
+    return wanted_byte;
+  }
+
+  /**
+   * consume and return n bytes from the input.  n bytes from
+   * bytestream are interpreted as bigendian when assembling
+   * the return value.
+   */
+  uint32_t readBytes(unsigned n)
+  {
+    uint32_t val = 0;
+    for (unsigned i = 0; i < n; i++)
+      val = (val << 8) | readByte();
+    return val;
+  }
+
+private:
+  unsigned m_NumFutureBytes; /* number of valid bytes in m_FutureBytes */
+  uint32_t m_FutureBytes; /* bytes that have been peeked */
+  std::istream& m_Input; /* Input stream to read from */
+};
+
+/**
+ * Statistics associated with AnnexB bytestreams
+ */
+struct AnnexBStats
+{
+  unsigned m_numLeadingZero8BitsBytes;
+  unsigned m_numZeroByteBytes;
+  unsigned m_numStartCodePrefixBytes;
+  unsigned m_numBytesInNALUnit;
+  unsigned m_numTrailingZero8BitsBytes;
+
+  AnnexBStats& operator+=(const AnnexBStats& rhs)
+  {
+    this->m_numLeadingZero8BitsBytes += rhs.m_numLeadingZero8BitsBytes;
+    this->m_numZeroByteBytes += rhs.m_numZeroByteBytes;
+    this->m_numStartCodePrefixBytes += rhs.m_numStartCodePrefixBytes;
+    this->m_numBytesInNALUnit += rhs.m_numBytesInNALUnit;
+    this->m_numTrailingZero8BitsBytes += rhs.m_numTrailingZero8BitsBytes;
+    return *this;
+  }
+};
+
+bool byteStreamNALUnit(InputByteStream& bs, std::vector<uint8_t>& nalUnit, AnnexBStats& stats);
+
+//! \}
Index: /trunk/source/Lib/TLibDecoder/NALread.cpp
===================================================================
--- /trunk/source/Lib/TLibDecoder/NALread.cpp	(revision 2)
+++ /trunk/source/Lib/TLibDecoder/NALread.cpp	(revision 2)
@@ -0,0 +1,186 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <vector>
+#include <algorithm>
+#include <ostream>
+
+#include "NALread.h"
+#include "TLibCommon/NAL.h"
+#include "TLibCommon/TComBitStream.h"
+
+using namespace std;
+
+//! \ingroup TLibDecoder
+//! \{
+static void convertPayloadToRBSP(vector<uint8_t>& nalUnitBuf, TComInputBitstream *pcBitstream)
+{
+  unsigned zeroCount = 0;
+  vector<uint8_t>::iterator it_read, it_write;
+
+  for (it_read = it_write = nalUnitBuf.begin(); it_read != nalUnitBuf.end(); it_read++, it_write++)
+  {
+    if (zeroCount == 2 && *it_read == 0x03)
+    {
+      it_read++;
+      zeroCount = 0;
+    }
+    zeroCount = (*it_read == 0x00) ? zeroCount+1 : 0;
+    *it_write = *it_read;
+  }
+
+  nalUnitBuf.resize(it_write - nalUnitBuf.begin());
+}
+
+#if NAL_UNIT_HEADER
+Void readNalUnitHeader(InputNALUnit& nalu)
+{
+  TComInputBitstream& bs = *nalu.m_Bitstream;
+
+  bool forbidden_zero_bit = bs.read(1);           // forbidden_zero_bit
+  assert(forbidden_zero_bit == 0);
+  nalu.m_nalUnitType = (NalUnitType) bs.read(6);  // nal_unit_type
+#if SVC_EXTENSION
+  nalu.m_reservedZero6Bits = bs.read(6);       // nuh_reserved_zero_6bits
+  nalu.m_layerId = nalu.m_reservedZero6Bits;
+#else
+#if TARGET_DECLAYERID_SET
+  nalu.m_reservedZero6Bits = bs.read(6);       // nuh_reserved_zero_6bits
+  assert(nalu.m_reservedZero6Bits == 0);
+#else
+  unsigned reserved_one_6bits = bs.read(6);       // nuh_reserved_zero_6bits
+  assert(reserved_one_6bits == 0);
+#endif
+#endif
+  nalu.m_temporalId = bs.read(3) - 1;             // nuh_temporal_id_plus1
+
+  if ( nalu.m_temporalId )
+  {
+#if NAL_UNIT_TYPES_J1003_D7
+    assert( nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_BLA
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_BLANT
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_BLA_N_LP
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_IDR
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_IDR_N_LP
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_CRA
+         && nalu.m_nalUnitType != NAL_UNIT_VPS
+         && nalu.m_nalUnitType != NAL_UNIT_SPS
+         && nalu.m_nalUnitType != NAL_UNIT_EOS
+         && nalu.m_nalUnitType != NAL_UNIT_EOB );
+#else
+    assert( nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_CRA
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_CRANT
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_BLA
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_BLANT
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_IDR
+         && nalu.m_nalUnitType != NAL_UNIT_VPS
+         && nalu.m_nalUnitType != NAL_UNIT_SPS );
+#endif
+  }
+  else
+  {
+#if NAL_UNIT_TYPES_J1003_D7
+    assert( nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_TLA
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_TSA_N
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_STSA_R
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_STSA_N );
+#else
+    assert( nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_TLA );
+#endif
+  }
+}
+#endif
+/**
+ * create a NALunit structure with given header values and storage for
+ * a bitstream
+ */
+void read(InputNALUnit& nalu, vector<uint8_t>& nalUnitBuf)
+{
+  /* perform anti-emulation prevention */
+  TComInputBitstream *pcBitstream = new TComInputBitstream(NULL);
+  convertPayloadToRBSP(nalUnitBuf, pcBitstream);
+
+  nalu.m_Bitstream = new TComInputBitstream(&nalUnitBuf);
+  delete pcBitstream;
+#if NAL_UNIT_HEADER
+  readNalUnitHeader(nalu);
+#else
+  TComInputBitstream& bs = *nalu.m_Bitstream;
+
+  bool forbidden_zero_bit = bs.read(1);
+  assert(forbidden_zero_bit == 0);
+#if !REMOVE_NAL_REF_FLAG
+  nalu.m_nalRefFlag  = (bs.read(1) != 0 );
+#endif
+  nalu.m_nalUnitType = (NalUnitType) bs.read(6);
+#if REMOVE_NAL_REF_FLAG
+  unsigned reserved_one_6bits = bs.read(6);
+  assert(reserved_one_6bits == 0);
+#endif
+#if TEMPORAL_ID_PLUS1
+  nalu.m_temporalId = bs.read(3) - 1;
+#if !REMOVE_NAL_REF_FLAG
+  unsigned reserved_one_5bits = bs.read(5);
+  assert(reserved_one_5bits == 0);
+#endif
+#else
+  nalu.m_temporalId = bs.read(3);
+  unsigned reserved_one_5bits = bs.read(5);
+#if SVC_EXTENSION
+  assert(reserved_one_5bits >= 1);
+  nalu.m_layerId = reserved_one_5bits - 1;
+#else
+  assert(reserved_one_5bits == 1);
+#endif
+#endif
+
+  if ( nalu.m_temporalId )
+  {
+#if NAL_UNIT_TYPES_J1003_D7
+    assert( nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_BLA
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_BLANT
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_BLA_N_LP
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_IDR
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_IDR_N_LP
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_CRA );
+#else
+    assert( nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_CRA
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_CRANT
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_BLA
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_BLANT
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_IDR );
+#endif
+  }
+#endif
+}
+//! \}
Index: /trunk/source/Lib/TLibDecoder/NALread.h
===================================================================
--- /trunk/source/Lib/TLibDecoder/NALread.h	(revision 2)
+++ /trunk/source/Lib/TLibDecoder/NALread.h	(revision 2)
@@ -0,0 +1,57 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#pragma once
+
+#include "TLibCommon/TypeDef.h"
+#include "TLibCommon/TComBitStream.h"
+#include "TLibCommon/NAL.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+/**
+ * A convenience wrapper to NALUnit that also provides a
+ * bitstream object.
+ */
+struct InputNALUnit : public NALUnit
+{
+  InputNALUnit() : m_Bitstream(0) {};
+  ~InputNALUnit() { delete m_Bitstream; }
+
+  TComInputBitstream* m_Bitstream;
+};
+
+void read(InputNALUnit& nalu, std::vector<uint8_t>& nalUnitBuf);
+
+//! \}
Index: /trunk/source/Lib/TLibDecoder/SEIread.cpp
===================================================================
--- /trunk/source/Lib/TLibDecoder/SEIread.cpp	(revision 2)
+++ /trunk/source/Lib/TLibDecoder/SEIread.cpp	(revision 2)
@@ -0,0 +1,363 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComBitStream.h"
+#include "TLibCommon/SEI.h"
+#include "TLibCommon/TComSlice.h"
+#include "SyntaxElementParser.h"
+#include "SEIread.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+#if ENC_DEC_TRACE
+Void  xTraceSEIHeader()
+{
+  fprintf( g_hTrace, "=========== SEI message ===========\n");
+}
+
+Void  xTraceSEIMessageType(SEI::PayloadType payloadType)
+{
+  switch (payloadType)
+  {
+  case SEI::DECODED_PICTURE_HASH:
+    fprintf( g_hTrace, "=========== Decoded picture hash SEI message ===========\n");
+    break;
+#if ACTIVE_PARAMETER_SETS_SEI_MESSAGE 
+  case SEI::ACTIVE_PARAMETER_SETS:
+    fprintf( g_hTrace, "=========== Active Parameter Sets SEI message ===========\n");
+    break;
+#endif
+  case SEI::USER_DATA_UNREGISTERED:
+    fprintf( g_hTrace, "=========== User Data Unregistered SEI message ===========\n");
+    break;
+  default:
+    fprintf( g_hTrace, "=========== Unknown SEI message ===========\n");
+    break;
+  }
+}
+#endif
+
+/**
+ * unmarshal a single SEI message from bitstream bs
+ */
+void SEIReader::parseSEImessage(TComInputBitstream* bs, SEImessages& seis)
+{
+  setBitstream(bs);
+
+  assert(!m_pcBitstream->getNumBitsUntilByteAligned());
+  do
+  {
+    xReadSEImessage(seis);
+    /* SEI messages are an integer number of bytes, something has failed
+    * in the parsing if bitstream not byte-aligned */
+    assert(!m_pcBitstream->getNumBitsUntilByteAligned());
+  } while (0x80 != m_pcBitstream->peekBits(8));
+  assert(m_pcBitstream->getNumBitsLeft() == 8); /* rsbp_trailing_bits */
+}
+
+Void SEIReader::xReadSEImessage(SEImessages& seis)
+{
+#if ENC_DEC_TRACE
+  xTraceSEIHeader();
+#endif
+  Int payloadType = 0;
+  UInt val = 0;
+
+  do
+  {
+    READ_CODE (8, val, "payload_type");
+    payloadType += val;
+  } while (val==0xFF);
+
+  UInt payloadSize = 0;
+  do
+  {
+    READ_CODE (8, val, "payload_size");
+    payloadSize += val;
+  } while (val==0xFF);
+
+#if ENC_DEC_TRACE
+  xTraceSEIMessageType((SEI::PayloadType)payloadType);
+#endif
+
+  switch (payloadType)
+  {
+  case SEI::USER_DATA_UNREGISTERED:
+    seis.user_data_unregistered = new SEIuserDataUnregistered;
+    xParseSEIuserDataUnregistered(*seis.user_data_unregistered, payloadSize);
+    break;
+#if ACTIVE_PARAMETER_SETS_SEI_MESSAGE    
+  case SEI::ACTIVE_PARAMETER_SETS:
+    seis.active_parameter_sets = new SEIActiveParameterSets; 
+    xParseSEIActiveParameterSets(*seis.active_parameter_sets, payloadSize); 
+    break; 
+#endif 
+  case SEI::DECODED_PICTURE_HASH:
+    seis.picture_digest = new SEIDecodedPictureHash;
+    xParseSEIDecodedPictureHash(*seis.picture_digest, payloadSize);
+    break;
+#if BUFFERING_PERIOD_AND_TIMING_SEI
+  case SEI::BUFFERING_PERIOD:
+    seis.buffering_period = new SEIBufferingPeriod;
+    seis.buffering_period->m_sps = seis.m_pSPS;
+    xParseSEIBufferingPeriod(*seis.buffering_period, payloadSize);
+    break;
+  case SEI::PICTURE_TIMING:
+    seis.picture_timing = new SEIPictureTiming;
+    seis.picture_timing->m_sps = seis.m_pSPS;
+    xParseSEIPictureTiming(*seis.picture_timing, payloadSize);
+    break;
+#endif
+#if RECOVERY_POINT_SEI
+  case SEI::RECOVERY_POINT:
+    seis.recovery_point = new SEIRecoveryPoint;
+    xParseSEIRecoveryPoint(*seis.recovery_point, payloadSize);
+    break;
+#endif
+  default:
+    assert(!"Unhandled SEI message");
+  }
+}
+
+/**
+ * parse bitstream bs and unpack a user_data_unregistered SEI message
+ * of payloasSize bytes into sei.
+ */
+Void SEIReader::xParseSEIuserDataUnregistered(SEIuserDataUnregistered &sei, UInt payloadSize)
+{
+  assert(payloadSize >= 16);
+  UInt val;
+
+  for (UInt i = 0; i < 16; i++)
+  {
+    READ_CODE (8, val, "uuid_iso_iec_11578");
+    sei.uuid_iso_iec_11578[i] = val;
+  }
+
+  sei.userDataLength = payloadSize - 16;
+  if (!sei.userDataLength)
+  {
+    sei.userData = 0;
+    return;
+  }
+
+  sei.userData = new UChar[sei.userDataLength];
+  for (UInt i = 0; i < sei.userDataLength; i++)
+  {
+    READ_CODE (8, val, "user_data" );
+    sei.userData[i] = val;
+  }
+}
+
+/**
+ * parse bitstream bs and unpack a decoded picture hash SEI message
+ * of payloadSize bytes into sei.
+ */
+Void SEIReader::xParseSEIDecodedPictureHash(SEIDecodedPictureHash& sei, UInt payloadSize)
+{
+  UInt val;
+  READ_CODE (8, val, "hash_type");
+  sei.method = static_cast<SEIDecodedPictureHash::Method>(val);
+  for(int yuvIdx = 0; yuvIdx < 3; yuvIdx++)
+  {
+    if(SEIDecodedPictureHash::MD5 == sei.method)
+    {
+      for (unsigned i = 0; i < 16; i++)
+      {
+        READ_CODE(8, val, "picture_md5");
+        sei.digest[yuvIdx][i] = val;
+      }
+    }
+    else if(SEIDecodedPictureHash::CRC == sei.method)
+    {
+      READ_CODE(16, val, "picture_crc");
+      sei.digest[yuvIdx][0] = val >> 8 & 0xFF;
+      sei.digest[yuvIdx][1] = val & 0xFF;
+    }
+    else if(SEIDecodedPictureHash::CHECKSUM == sei.method)
+    {
+      READ_CODE(32, val, "picture_checksum");
+      sei.digest[yuvIdx][0] = (val>>24) & 0xff;
+      sei.digest[yuvIdx][1] = (val>>16) & 0xff;
+      sei.digest[yuvIdx][2] = (val>>8)  & 0xff;
+      sei.digest[yuvIdx][3] =  val      & 0xff;
+    }
+  }
+}
+#if ACTIVE_PARAMETER_SETS_SEI_MESSAGE 
+Void SEIReader::xParseSEIActiveParameterSets(SEIActiveParameterSets& sei, unsigned payloadSize)
+{
+  UInt val; 
+  READ_CODE(4, val, "active_vps_id");
+  sei.activeVPSId = val; 
+
+  READ_CODE(1, val, "active_sps_id_present_flag");
+  sei.activeSPSIdPresentFlag = val; 
+
+  if(sei.activeSPSIdPresentFlag)
+  {
+    READ_UVLC(val, "active_seq_param_set_id");
+    sei.activeSeqParamSetId = val; 
+  }
+
+  READ_CODE(1, val, "active_param_set_sei_extension_flag");
+  sei.activeParamSetSEIExtensionFlag = val; 
+  
+  UInt uibits = m_pcBitstream->getNumBitsUntilByteAligned(); 
+  
+  while(uibits--)
+  {
+    READ_FLAG(val, "alignment_bit");
+  }
+}
+#endif
+
+#if BUFFERING_PERIOD_AND_TIMING_SEI
+Void SEIReader::xParseSEIBufferingPeriod(SEIBufferingPeriod& sei, UInt payloadSize)
+{
+  Int i, nalOrVcl;
+  UInt code;
+
+  TComVUI *pVUI = sei.m_sps->getVuiParameters();
+
+  READ_UVLC( code, "seq_parameter_set_id" );                            sei.m_seqParameterSetId     = code;
+  if( !pVUI->getSubPicCpbParamsPresentFlag() )
+  {
+    READ_FLAG( code, "alt_cpb_params_present_flag" );                   sei.m_altCpbParamsPresentFlag = code;
+  }
+
+  for( nalOrVcl = 0; nalOrVcl < 2; nalOrVcl ++ )
+  {
+    if( ( ( nalOrVcl == 0 ) && ( pVUI->getNalHrdParametersPresentFlag() ) ) ||
+        ( ( nalOrVcl == 1 ) && ( pVUI->getVclHrdParametersPresentFlag() ) ) )
+    {
+      for( i = 0; i < ( pVUI->getCpbCntMinus1( 0 ) + 1 ); i ++ )
+      {
+        READ_CODE( ( pVUI->getInitialCpbRemovalDelayLengthMinus1() + 1 ) , code, "initial_cpb_removal_delay" );
+        sei.m_initialCpbRemovalDelay[i][nalOrVcl] = code;
+        READ_CODE( ( pVUI->getInitialCpbRemovalDelayLengthMinus1() + 1 ) , code, "initial_cpb_removal_delay_offset" );
+        sei.m_initialCpbRemovalDelayOffset[i][nalOrVcl] = code;
+        if( pVUI->getSubPicCpbParamsPresentFlag() || sei.m_altCpbParamsPresentFlag )
+        {
+          READ_CODE( ( pVUI->getInitialCpbRemovalDelayLengthMinus1() + 1 ) , code, "initial_alt_cpb_removal_delay" );
+          sei.m_initialAltCpbRemovalDelay[i][nalOrVcl] = code;
+          READ_CODE( ( pVUI->getInitialCpbRemovalDelayLengthMinus1() + 1 ) , code, "initial_alt_cpb_removal_delay_offset" );
+          sei.m_initialAltCpbRemovalDelayOffset[i][nalOrVcl] = code;
+        }
+      }
+    }
+  }
+  xParseByteAlign();
+}
+Void SEIReader::xParseSEIPictureTiming(SEIPictureTiming& sei, UInt payloadSize)
+{
+  Int i;
+  UInt code;
+
+  TComVUI *vui = sei.m_sps->getVuiParameters();
+
+  if( !vui->getNalHrdParametersPresentFlag() && !vui->getVclHrdParametersPresentFlag() )
+  {
+    return;
+  }
+
+  READ_CODE( ( vui->getCpbRemovalDelayLengthMinus1() + 1 ), code, "au_cpb_removal_delay" );
+  sei.m_auCpbRemovalDelay = code;
+  READ_CODE( ( vui->getDpbOutputDelayLengthMinus1() + 1 ), code, "pic_dpb_output_delay" );
+  sei.m_picDpbOutputDelay = code;
+
+  if( sei.m_sps->getVuiParameters()->getSubPicCpbParamsPresentFlag() )
+  {
+    READ_UVLC( code, "num_decoding_units_minus1");
+    sei.m_numDecodingUnitsMinus1 = code;
+    READ_FLAG( code, "du_common_cpb_removal_delay_flag" );
+    sei.m_duCommonCpbRemovalDelayFlag = code;
+    if( sei.m_duCommonCpbRemovalDelayFlag )
+    {
+      READ_CODE( ( vui->getDuCpbRemovalDelayLengthMinus1() + 1 ), code, "du_common_cpb_removal_delay_minus1" );
+      sei.m_duCommonCpbRemovalDelayMinus1 = code;
+    }
+    else
+    {
+      if( sei.m_numNalusInDuMinus1 != NULL )
+      {
+        delete sei.m_numNalusInDuMinus1;
+      }
+      sei.m_numNalusInDuMinus1 = new UInt[ ( sei.m_numDecodingUnitsMinus1 + 1 ) ];
+      if( sei.m_duCpbRemovalDelayMinus1  != NULL )
+      {
+        delete sei.m_duCpbRemovalDelayMinus1;
+      }
+      sei.m_duCpbRemovalDelayMinus1  = new UInt[ ( sei.m_numDecodingUnitsMinus1 + 1 ) ];
+
+      for( i = 0; i < ( sei.m_numDecodingUnitsMinus1 + 1 ); i ++ )
+      {
+        READ_UVLC( code, "num_nalus_in_du_minus1");
+        sei.m_numNalusInDuMinus1[ i ] = code;
+        READ_CODE( ( vui->getDuCpbRemovalDelayLengthMinus1() + 1 ), code, "du_cpb_removal_delay_minus1" );
+        sei.m_duCpbRemovalDelayMinus1[ i ] = code;
+      }
+    }
+  }
+  xParseByteAlign();
+}
+#endif
+#if RECOVERY_POINT_SEI
+Void SEIReader::xParseSEIRecoveryPoint(SEIRecoveryPoint& sei, UInt payloadSize)
+{
+  Int  iCode;
+  UInt uiCode;
+  READ_SVLC( iCode,  "recovery_poc_cnt" );      sei.m_recoveryPocCnt     = iCode;
+  READ_FLAG( uiCode, "exact_matching_flag" );   sei.m_exactMatchingFlag  = uiCode;
+  READ_FLAG( uiCode, "broken_link_flag" );      sei.m_brokenLinkFlag     = uiCode;
+  xParseByteAlign();
+}
+#endif
+
+#if RECOVERY_POINT_SEI || BUFFERING_PERIOD_AND_TIMING_SEI
+Void SEIReader::xParseByteAlign()
+{
+  UInt code;
+  if( m_pcBitstream->getNumBitsRead() % 8 != 0 )
+  {
+    READ_FLAG( code, "bit_equal_to_one" );          assert( code == 1 );
+  }
+  while( m_pcBitstream->getNumBitsRead() % 8 != 0 )
+  {
+    READ_FLAG( code, "bit_equal_to_zero" );         assert( code == 0 );
+  }
+}
+#endif
+//! \}
Index: /trunk/source/Lib/TLibDecoder/SEIread.h
===================================================================
--- /trunk/source/Lib/TLibDecoder/SEIread.h	(revision 2)
+++ /trunk/source/Lib/TLibDecoder/SEIread.h	(revision 2)
@@ -0,0 +1,77 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef __SEIREAD__
+#define __SEIREAD__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+//! \ingroup TLibDecoder
+//! \{
+
+#include "TLibCommon/SEI.h"
+class TComInputBitstream;
+class SEImessages;
+
+
+class SEIReader: public SyntaxElementParser
+{
+public:
+  SEIReader() {};
+  virtual ~SEIReader() {};
+  Void parseSEImessage(TComInputBitstream* bs, SEImessages& seis);
+protected:
+  Void xReadSEImessage                (SEImessages& seis);
+  Void xParseSEIuserDataUnregistered  (SEIuserDataUnregistered &sei, UInt payloadSize);
+#if ACTIVE_PARAMETER_SETS_SEI_MESSAGE 
+  Void xParseSEIActiveParameterSets    (SEIActiveParameterSets& sei, UInt payloadSize);
+#endif
+  Void xParseSEIDecodedPictureHash    (SEIDecodedPictureHash& sei, UInt payloadSize);
+#if BUFFERING_PERIOD_AND_TIMING_SEI
+  Void xParseSEIBufferingPeriod       (SEIBufferingPeriod& sei, UInt payloadSize);
+  Void xParseSEIPictureTiming         (SEIPictureTiming& sei, UInt payloadSize);
+#endif
+#if RECOVERY_POINT_SEI
+  Void xParseSEIRecoveryPoint         (SEIRecoveryPoint& sei, UInt payloadSize);
+#endif
+#if RECOVERY_POINT_SEI || BUFFERING_PERIOD_AND_TIMING_SEI
+  Void xParseByteAlign();
+#endif
+};
+
+
+//! \}
+
+#endif
Index: /trunk/source/Lib/TLibDecoder/SyntaxElementParser.cpp
===================================================================
--- /trunk/source/Lib/TLibDecoder/SyntaxElementParser.cpp	(revision 2)
+++ /trunk/source/Lib/TLibDecoder/SyntaxElementParser.cpp	(revision 2)
@@ -0,0 +1,157 @@
+/* The copyright in this software is being made available under the BSD
+* License, included below. This software may be subject to other third party
+* and contributor rights, including patent rights, and no such rights are
+* granted under this license.  
+*
+* Copyright (c) 2010-2012, ITU/ISO/IEC
+* All rights reserved.
+*
+* Redistribution and use in source and binary forms, with or without
+* modification, are permitted provided that the following conditions are met:
+*
+*  * Redistributions of source code must retain the above copyright notice,
+*    this list of conditions and the following disclaimer.
+*  * Redistributions in binary form must reproduce the above copyright notice,
+*    this list of conditions and the following disclaimer in the documentation
+*    and/or other materials provided with the distribution.
+*  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+*    be used to endorse or promote products derived from this software without
+*    specific prior written permission.
+*
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+* THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/** \file     SyntaxElementParser.cpp
+    \brief    Parsing functionality high level syntax
+*/
+
+//! \ingroup TLibDecoder
+//! \{
+
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComRom.h"
+#include "TLibCommon/TComBitStream.h"
+#include "SyntaxElementParser.h"
+
+#if ENC_DEC_TRACE
+
+Void  SyntaxElementParser::xReadCodeTr           (UInt length, UInt& rValue, const Char *pSymbolName)
+{
+  xReadCode (length, rValue);
+  fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+  if (length < 10)
+  {
+    fprintf( g_hTrace, "%-50s u(%d)  : %d\n", pSymbolName, length, rValue ); 
+  }
+  else
+  {
+    fprintf( g_hTrace, "%-50s u(%d) : %d\n", pSymbolName, length, rValue ); 
+  }
+  fflush ( g_hTrace );
+}
+
+Void  SyntaxElementParser::xReadUvlcTr           (UInt& rValue, const Char *pSymbolName)
+{
+  xReadUvlc (rValue);
+  fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+  fprintf( g_hTrace, "%-50s ue(v) : %d\n", pSymbolName, rValue ); 
+  fflush ( g_hTrace );
+}
+
+Void  SyntaxElementParser::xReadSvlcTr           (Int& rValue, const Char *pSymbolName)
+{
+  xReadSvlc(rValue);
+  fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+  fprintf( g_hTrace, "%-50s se(v) : %d\n", pSymbolName, rValue ); 
+  fflush ( g_hTrace );
+}
+
+Void  SyntaxElementParser::xReadFlagTr           (UInt& rValue, const Char *pSymbolName)
+{
+  xReadFlag(rValue);
+  fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+  fprintf( g_hTrace, "%-50s u(1)  : %d\n", pSymbolName, rValue ); 
+  fflush ( g_hTrace );
+}
+
+#endif
+
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+Void SyntaxElementParser::xReadCode (UInt uiLength, UInt& ruiCode)
+{
+  assert ( uiLength > 0 );
+  m_pcBitstream->read (uiLength, ruiCode);
+}
+
+Void SyntaxElementParser::xReadUvlc( UInt& ruiVal)
+{
+  UInt uiVal = 0;
+  UInt uiCode = 0;
+  UInt uiLength;
+  m_pcBitstream->read( 1, uiCode );
+
+  if( 0 == uiCode )
+  {
+    uiLength = 0;
+
+    while( ! ( uiCode & 1 ))
+    {
+      m_pcBitstream->read( 1, uiCode );
+      uiLength++;
+    }
+
+    m_pcBitstream->read( uiLength, uiVal );
+
+    uiVal += (1 << uiLength)-1;
+  }
+
+  ruiVal = uiVal;
+}
+
+Void SyntaxElementParser::xReadSvlc( Int& riVal)
+{
+  UInt uiBits = 0;
+  m_pcBitstream->read( 1, uiBits );
+  if( 0 == uiBits )
+  {
+    UInt uiLength = 0;
+
+    while( ! ( uiBits & 1 ))
+    {
+      m_pcBitstream->read( 1, uiBits );
+      uiLength++;
+    }
+
+    m_pcBitstream->read( uiLength, uiBits );
+
+    uiBits += (1 << uiLength);
+    riVal = ( uiBits & 1) ? -(Int)(uiBits>>1) : (Int)(uiBits>>1);
+  }
+  else
+  {
+    riVal = 0;
+  }
+}
+
+Void SyntaxElementParser::xReadFlag (UInt& ruiCode)
+{
+  m_pcBitstream->read( 1, ruiCode );
+}
+
+
+//! \}
+
Index: /trunk/source/Lib/TLibDecoder/SyntaxElementParser.h
===================================================================
--- /trunk/source/Lib/TLibDecoder/SyntaxElementParser.h	(revision 2)
+++ /trunk/source/Lib/TLibDecoder/SyntaxElementParser.h	(revision 2)
@@ -0,0 +1,97 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     SyntaxElementParser.h
+    \brief    Parsing functionality high level syntax
+*/
+
+#ifndef __SYNTAXELEMENTPARSER__
+#define __SYNTAXELEMENTPARSER__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TLibCommon/TComRom.h"
+
+#if ENC_DEC_TRACE
+
+#define READ_CODE(length, code, name)     xReadCodeTr ( length, code, name )
+#define READ_UVLC(        code, name)     xReadUvlcTr (         code, name )
+#define READ_SVLC(        code, name)     xReadSvlcTr (         code, name )
+#define READ_FLAG(        code, name)     xReadFlagTr (         code, name )
+
+#else
+
+#define READ_CODE(length, code, name)     xReadCode ( length, code )
+#define READ_UVLC(        code, name)     xReadUvlc (         code )
+#define READ_SVLC(        code, name)     xReadSvlc (         code )
+#define READ_FLAG(        code, name)     xReadFlag (         code )
+
+#endif
+
+//! \ingroup TLibDecoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+class SyntaxElementParser
+{
+protected:
+  TComInputBitstream*   m_pcBitstream;
+
+  SyntaxElementParser()
+  : m_pcBitstream (NULL)
+  {};
+  virtual ~SyntaxElementParser() {};
+
+  Void  xReadCode    ( UInt   length, UInt& val );
+  Void  xReadUvlc    ( UInt&  val );
+  Void  xReadSvlc    ( Int&   val );
+  Void  xReadFlag    ( UInt&  val );
+#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);
+#endif
+public:
+  Void  setBitstream ( TComInputBitstream* p )   { m_pcBitstream = p; }
+};
+
+//! \}
+
+#endif // !defined(__SYNTAXELEMENTPARSER__)
+
Index: /trunk/source/Lib/TLibDecoder/TDecBinCoder.h
===================================================================
--- /trunk/source/Lib/TLibDecoder/TDecBinCoder.h	(revision 2)
+++ /trunk/source/Lib/TLibDecoder/TDecBinCoder.h	(revision 2)
@@ -0,0 +1,76 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TDecBinCoder.h
+    \brief    binary entropy decoder interface
+*/
+
+#ifndef __TDEC_BIN_CODER__
+#define __TDEC_BIN_CODER__
+
+#include "TLibCommon/ContextModel.h"
+#include "TLibCommon/TComBitStream.h"
+
+//! \ingroup TLibDecoder
+//! \{
+class TDecBinCABAC;
+
+class TDecBinIf
+{
+public:
+  virtual Void  init              ( TComInputBitstream* pcTComBitstream )     = 0;
+  virtual Void  uninit            ()                                          = 0;
+
+  virtual Void  start             ()                                          = 0;
+  virtual Void  finish            ()                                          = 0;
+  virtual Void  flush            ()                                           = 0;
+
+  virtual Void  decodeBin         ( UInt& ruiBin, ContextModel& rcCtxModel )  = 0;
+  virtual Void  decodeBinEP       ( UInt& ruiBin                           )  = 0;
+  virtual Void  decodeBinsEP      ( UInt& ruiBins, Int numBins             )  = 0;
+  virtual Void  decodeBinTrm      ( UInt& ruiBin                           )  = 0;
+  
+  virtual Void  resetBac          ()                                          = 0;
+  virtual Void  decodeNumSubseqIPCM( Int& numSubseqIPCM )                  = 0;
+  virtual Void  decodePCMAlignBits()                                          = 0;
+  virtual Void  xReadPCMCode      ( UInt uiLength, UInt& ruiCode)              = 0;
+
+  virtual ~TDecBinIf() {}
+
+  virtual Void  copyState         ( TDecBinIf* pcTDecBinIf )                  = 0;
+  virtual TDecBinCABAC*   getTDecBinCABAC   ()  { return 0; }
+};
+
+//! \}
+
+#endif
Index: /trunk/source/Lib/TLibDecoder/TDecBinCoderCABAC.cpp
===================================================================
--- /trunk/source/Lib/TLibDecoder/TDecBinCoderCABAC.cpp	(revision 2)
+++ /trunk/source/Lib/TLibDecoder/TDecBinCoderCABAC.cpp	(revision 2)
@@ -0,0 +1,305 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TDecBinCoderCABAC.cpp
+    \brief    binary entropy decoder of CABAC
+*/
+
+#include "TDecBinCoderCABAC.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+TDecBinCABAC::TDecBinCABAC()
+: m_pcTComBitstream( 0 )
+{
+}
+
+TDecBinCABAC::~TDecBinCABAC()
+{
+}
+
+Void
+TDecBinCABAC::init( TComInputBitstream* pcTComBitstream )
+{
+  m_pcTComBitstream = pcTComBitstream;
+}
+
+Void
+TDecBinCABAC::uninit()
+{
+  m_pcTComBitstream = 0;
+}
+
+Void
+TDecBinCABAC::start()
+{
+  assert( m_pcTComBitstream->getNumBitsUntilByteAligned() == 0 );
+  m_uiRange    = 510;
+  m_bitsNeeded = -8;
+  m_uiValue    = (m_pcTComBitstream->readByte() << 8);
+  m_uiValue   |= m_pcTComBitstream->readByte();
+}
+
+Void
+TDecBinCABAC::finish()
+{
+}
+
+Void 
+TDecBinCABAC::flush()
+{
+  while (m_pcTComBitstream->getNumBitsLeft() > 0 && m_pcTComBitstream->getNumBitsUntilByteAligned() != 0)
+  {
+    UInt uiBits;
+    m_pcTComBitstream->read ( 1, uiBits );
+  }
+  start();
+}
+
+/**
+ - Copy CABAC state.
+ .
+ \param pcTDecBinIf The source CABAC engine.
+ */
+Void
+TDecBinCABAC::copyState( TDecBinIf* pcTDecBinIf )
+{
+  TDecBinCABAC* pcTDecBinCABAC = pcTDecBinIf->getTDecBinCABAC();
+  m_uiRange   = pcTDecBinCABAC->m_uiRange;
+  m_uiValue   = pcTDecBinCABAC->m_uiValue;
+  m_bitsNeeded= pcTDecBinCABAC->m_bitsNeeded;
+}
+
+
+Void
+TDecBinCABAC::decodeBin( UInt& ruiBin, ContextModel &rcCtxModel )
+{
+  UInt uiLPS = TComCABACTables::sm_aucLPSTable[ rcCtxModel.getState() ][ ( m_uiRange >> 6 ) - 4 ];
+  m_uiRange -= uiLPS;
+  UInt scaledRange = m_uiRange << 7;
+  
+  if( m_uiValue < scaledRange )
+  {
+    // MPS path
+    ruiBin = rcCtxModel.getMps();
+    rcCtxModel.updateMPS();
+    
+    if ( scaledRange >= ( 256 << 7 ) )
+    {
+      return;
+    }
+    
+    m_uiRange = scaledRange >> 6;
+    m_uiValue += m_uiValue;
+    
+    if ( ++m_bitsNeeded == 0 )
+    {
+      m_bitsNeeded = -8;
+      m_uiValue += m_pcTComBitstream->readByte();      
+    }
+  }
+  else
+  {
+    // LPS path
+    Int numBits = TComCABACTables::sm_aucRenormTable[ uiLPS >> 3 ];
+    m_uiValue   = ( m_uiValue - scaledRange ) << numBits;
+    m_uiRange   = uiLPS << numBits;
+    ruiBin      = 1 - rcCtxModel.getMps();
+    rcCtxModel.updateLPS();
+    
+    m_bitsNeeded += numBits;
+    
+    if ( m_bitsNeeded >= 0 )
+    {
+      m_uiValue += m_pcTComBitstream->readByte() << m_bitsNeeded;
+      m_bitsNeeded -= 8;
+    }
+  }
+}
+
+Void
+TDecBinCABAC::decodeBinEP( UInt& ruiBin )
+{
+  m_uiValue += m_uiValue;
+  
+  if ( ++m_bitsNeeded >= 0 )
+  {
+    m_bitsNeeded = -8;
+    m_uiValue += m_pcTComBitstream->readByte();
+  }
+  
+  ruiBin = 0;
+  UInt scaledRange = m_uiRange << 7;
+  if ( m_uiValue >= scaledRange )
+  {
+    ruiBin = 1;
+    m_uiValue -= scaledRange;
+  }
+}
+
+Void TDecBinCABAC::decodeBinsEP( UInt& ruiBin, Int numBins )
+{
+  UInt bins = 0;
+  
+  while ( numBins > 8 )
+  {
+    m_uiValue = ( m_uiValue << 8 ) + ( m_pcTComBitstream->readByte() << ( 8 + m_bitsNeeded ) );
+    
+    UInt scaledRange = m_uiRange << 15;
+    for ( Int i = 0; i < 8; i++ )
+    {
+      bins += bins;
+      scaledRange >>= 1;
+      if ( m_uiValue >= scaledRange )
+      {
+        bins++;
+        m_uiValue -= scaledRange;
+      }
+    }
+    numBins -= 8;
+  }
+  
+  m_bitsNeeded += numBins;
+  m_uiValue <<= numBins;
+  
+  if ( m_bitsNeeded >= 0 )
+  {
+    m_uiValue += m_pcTComBitstream->readByte() << m_bitsNeeded;
+    m_bitsNeeded -= 8;
+  }
+  
+  UInt scaledRange = m_uiRange << ( numBins + 7 );
+  for ( Int i = 0; i < numBins; i++ )
+  {
+    bins += bins;
+    scaledRange >>= 1;
+    if ( m_uiValue >= scaledRange )
+    {
+      bins++;
+      m_uiValue -= scaledRange;
+    }
+  }
+  
+  ruiBin = bins;
+}
+
+Void
+TDecBinCABAC::decodeBinTrm( UInt& ruiBin )
+{
+  m_uiRange -= 2;
+  UInt scaledRange = m_uiRange << 7;
+  if( m_uiValue >= scaledRange )
+  {
+    ruiBin = 1;
+  }
+  else
+  {
+    ruiBin = 0;
+    if ( scaledRange < ( 256 << 7 ) )
+    {
+      m_uiRange = scaledRange >> 6;
+      m_uiValue += m_uiValue;
+      
+      if ( ++m_bitsNeeded == 0 )
+      {
+        m_bitsNeeded = -8;
+        m_uiValue += m_pcTComBitstream->readByte();      
+      }
+    }
+  }
+}
+
+/** Reset BAC register values.
+ * \returns Void
+ */
+Void TDecBinCABAC::resetBac()
+{
+  m_uiRange    = 510;
+  m_bitsNeeded = -8;
+  m_uiValue    = m_pcTComBitstream->read( 16 );
+}
+
+/** Decode subsequent_pcm_num.
+ * \param numSubseqIPCM
+ * \returns Void
+ */
+Void TDecBinCABAC::decodeNumSubseqIPCM( Int& numSubseqIPCM )
+{
+  UInt bit = 0;
+
+  numSubseqIPCM = 0;
+
+  do
+  {
+    m_uiValue += m_uiValue;
+    if ( ++m_bitsNeeded >= 0 )
+    {
+      m_bitsNeeded = -8;
+      m_uiValue += m_pcTComBitstream->readByte();
+    }
+    bit = ((m_uiValue&128)>>7);
+    numSubseqIPCM++;
+  }
+  while( bit && (numSubseqIPCM < 3 ));
+
+  if( bit && (numSubseqIPCM == 3 ))
+  {
+    numSubseqIPCM++;
+  }
+
+  numSubseqIPCM --;
+}
+
+/** Decode PCM alignment zero bits.
+ * \returns Void
+ */
+Void TDecBinCABAC::decodePCMAlignBits()
+{
+  Int iNum = m_pcTComBitstream->getNumBitsUntilByteAligned();
+  
+  UInt uiBit = 0;
+  m_pcTComBitstream->read( iNum, uiBit );
+}
+
+/** Read a PCM code.
+ * \param uiLength code bit-depth
+ * \param ruiCode pointer to PCM code value
+ * \returns Void
+ */
+Void  TDecBinCABAC::xReadPCMCode(UInt uiLength, UInt& ruiCode)
+{
+  assert ( uiLength > 0 );
+  m_pcTComBitstream->read (uiLength, ruiCode);
+}
+//! \}
Index: /trunk/source/Lib/TLibDecoder/TDecBinCoderCABAC.h
===================================================================
--- /trunk/source/Lib/TLibDecoder/TDecBinCoderCABAC.h	(revision 2)
+++ /trunk/source/Lib/TLibDecoder/TDecBinCoderCABAC.h	(revision 2)
@@ -0,0 +1,83 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TDecBinCoderCABAC.h
+    \brief    binary entropy decoder of CABAC
+*/
+
+#ifndef __TDEC_BIN_CODER_CABAC__
+#define __TDEC_BIN_CODER_CABAC__
+
+#include "TLibCommon/TComCABACTables.h"
+#include "TDecBinCoder.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+class TDecBinCABAC : public TDecBinIf
+{
+public:
+  TDecBinCABAC ();
+  virtual ~TDecBinCABAC();
+  
+  Void  init              ( TComInputBitstream* pcTComBitstream );
+  Void  uninit            ();
+  
+  Void  start             ();
+  Void  finish            ();
+  Void  flush             ();
+  
+  Void  decodeBin         ( UInt& ruiBin, ContextModel& rcCtxModel );
+  Void  decodeBinEP       ( UInt& ruiBin                           );
+  Void  decodeBinsEP      ( UInt& ruiBin, Int numBins              );
+  Void  decodeBinTrm      ( UInt& ruiBin                           );
+  
+  Void  resetBac          ();
+  Void  decodeNumSubseqIPCM( Int& numSubseqIPCM ) ;
+  Void  decodePCMAlignBits();
+  Void  xReadPCMCode      ( UInt uiLength, UInt& ruiCode );
+  
+  Void  copyState         ( TDecBinIf* pcTDecBinIf );
+  TDecBinCABAC* getTDecBinCABAC()  { return this; }
+
+private:
+  TComInputBitstream* m_pcTComBitstream;
+  UInt                m_uiRange;
+  UInt                m_uiValue;
+  Int                 m_bitsNeeded;
+};
+
+//! \}
+
+#endif
+
Index: /trunk/source/Lib/TLibDecoder/TDecCAVLC.cpp
===================================================================
--- /trunk/source/Lib/TLibDecoder/TDecCAVLC.cpp	(revision 2)
+++ /trunk/source/Lib/TLibDecoder/TDecCAVLC.cpp	(revision 2)
@@ -0,0 +1,2222 @@
+/* The copyright in this software is being made available under the BSD
+* License, included below. This software may be subject to other third party
+* and contributor rights, including patent rights, and no such rights are
+* granted under this license.  
+*
+* Copyright (c) 2010-2012, ITU/ISO/IEC
+* All rights reserved.
+*
+* Redistribution and use in source and binary forms, with or without
+* modification, are permitted provided that the following conditions are met:
+*
+*  * Redistributions of source code must retain the above copyright notice,
+*    this list of conditions and the following disclaimer.
+*  * Redistributions in binary form must reproduce the above copyright notice,
+*    this list of conditions and the following disclaimer in the documentation
+*    and/or other materials provided with the distribution.
+*  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+*    be used to endorse or promote products derived from this software without
+*    specific prior written permission.
+*
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+* THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/** \file     TDecCAVLC.cpp
+\brief    CAVLC decoder class
+*/
+
+#include "TDecCAVLC.h"
+#include "SEIread.h"
+#include "TDecSlice.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+#if ENC_DEC_TRACE
+
+Void  xTraceSPSHeader (TComSPS *pSPS)
+{
+  fprintf( g_hTrace, "=========== Sequence Parameter Set ID: %d ===========\n", pSPS->getSPSId() );
+}
+
+Void  xTracePPSHeader (TComPPS *pPPS)
+{
+  fprintf( g_hTrace, "=========== Picture Parameter Set ID: %d ===========\n", pPPS->getPPSId() );
+}
+
+#if !REMOVE_APS
+Void  xTraceAPSHeader (TComAPS *pAPS)
+{
+  fprintf( g_hTrace, "=========== Adaptation Parameter Set ===========\n");
+}
+#endif
+
+Void  xTraceSliceHeader (TComSlice *pSlice)
+{
+  fprintf( g_hTrace, "=========== Slice ===========\n");
+}
+
+#endif
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TDecCavlc::TDecCavlc()
+{
+#if !REMOVE_FGS
+  m_iSliceGranularity = 0;
+#endif
+}
+
+TDecCavlc::~TDecCavlc()
+{
+
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+void TDecCavlc::parseShortTermRefPicSet( TComSPS* sps, TComReferencePictureSet* rps, Int idx )
+{
+  UInt code;
+  UInt interRPSPred;
+  READ_FLAG(interRPSPred, "inter_ref_pic_set_prediction_flag");  rps->setInterRPSPrediction(interRPSPred);
+  if (interRPSPred) 
+  {
+    UInt bit;
+#if J0234_INTER_RPS_SIMPL
+    if(idx == sps->getRPSList()->getNumberOfReferencePictureSets())
+    {
+      READ_UVLC(code, "delta_idx_minus1" ); // delta index of the Reference Picture Set used for prediction minus 1
+    }
+    else
+    {
+      code = 0;
+    }
+    assert(code <= idx-1); // delta_idx_minus1 shall not be larger than idx-1, otherwise we will predict from a negative row position that does not exist. When idx equals 0 there is no legal value and interRPSPred must be zero. See J0185-r2
+#else
+    READ_UVLC(code, "delta_idx_minus1" ); // delta index of the Reference Picture Set used for prediction minus 1
+#endif
+    Int rIdx =  idx - 1 - code;
+#if J0234_INTER_RPS_SIMPL
+    assert (rIdx <= idx-1 && rIdx >= 0); // Made assert tighter; if rIdx = idx then prediction is done from itself. rIdx must belong to range 0, idx-1, inclusive, see J0185-r2
+#else
+    assert (rIdx <= idx && rIdx >= 0);
+#endif
+    TComReferencePictureSet*   rpsRef = sps->getRPSList()->getReferencePictureSet(rIdx);
+    Int k = 0, k0 = 0, k1 = 0;
+    READ_CODE(1, bit, "delta_rps_sign"); // delta_RPS_sign
+    READ_UVLC(code, "abs_delta_rps_minus1");  // absolute delta RPS minus 1
+    Int deltaRPS = (1 - (bit<<1)) * (code + 1); // delta_RPS
+    for(Int j=0 ; j <= rpsRef->getNumberOfPictures(); j++)
+    {
+      READ_CODE(1, bit, "used_by_curr_pic_flag" ); //first bit is "1" if Idc is 1 
+      Int refIdc = bit;
+      if (refIdc == 0) 
+      {
+        READ_CODE(1, bit, "use_delta_flag" ); //second bit is "1" if Idc is 2, "0" otherwise.
+        refIdc = bit<<1; //second bit is "1" if refIdc is 2, "0" if refIdc = 0.
+      }
+      if (refIdc == 1 || refIdc == 2)
+      {
+        Int deltaPOC = deltaRPS + ((j < rpsRef->getNumberOfPictures())? rpsRef->getDeltaPOC(j) : 0);
+        rps->setDeltaPOC(k, deltaPOC);
+        rps->setUsed(k, (refIdc == 1));
+
+        if (deltaPOC < 0) {
+          k0++;
+        }
+        else 
+        {
+          k1++;
+        }
+        k++;
+      }  
+      rps->setRefIdc(j,refIdc);  
+    }
+    rps->setNumRefIdc(rpsRef->getNumberOfPictures()+1);  
+    rps->setNumberOfPictures(k);
+    rps->setNumberOfNegativePictures(k0);
+    rps->setNumberOfPositivePictures(k1);
+    rps->sortDeltaPOC();
+  }
+  else
+  {
+    READ_UVLC(code, "num_negative_pics");           rps->setNumberOfNegativePictures(code);
+    READ_UVLC(code, "num_positive_pics");           rps->setNumberOfPositivePictures(code);
+    Int prev = 0;
+    Int poc;
+    for(Int j=0 ; j < rps->getNumberOfNegativePictures(); j++)
+    {
+      READ_UVLC(code, "delta_poc_s0_minus1");
+      poc = prev-code-1;
+      prev = poc;
+      rps->setDeltaPOC(j,poc);
+      READ_FLAG(code, "used_by_curr_pic_s0_flag");  rps->setUsed(j,code);
+    }
+    prev = 0;
+    for(Int j=rps->getNumberOfNegativePictures(); j < rps->getNumberOfNegativePictures()+rps->getNumberOfPositivePictures(); j++)
+    {
+      READ_UVLC(code, "delta_poc_s1_minus1");
+      poc = prev+code+1;
+      prev = poc;
+      rps->setDeltaPOC(j,poc);
+      READ_FLAG(code, "used_by_curr_pic_s1_flag");  rps->setUsed(j,code);
+    }
+    rps->setNumberOfPictures(rps->getNumberOfNegativePictures()+rps->getNumberOfPositivePictures());
+  }
+#if PRINT_RPS_INFO
+  rps->printDeltaPOC();
+#endif
+}
+
+#if !REMOVE_APS
+Void TDecCavlc::parseAPS(TComAPS* aps)
+{
+#if ENC_DEC_TRACE  
+  xTraceAPSHeader(aps);
+#endif
+
+  UInt uiCode;
+  READ_UVLC(uiCode, "aps_id");                             aps->setAPSID(uiCode);
+#if !REMOVE_ALF
+  for(Int compIdx=0; compIdx< 3; compIdx++)
+  {
+    xParseAlfParam( (aps->getAlfParam())[compIdx]);
+  }
+#endif
+  READ_FLAG( uiCode, "aps_extension_flag");
+  if (uiCode)
+  {
+    while ( xMoreRbspData() )
+    {
+      READ_FLAG( uiCode, "aps_extension_data_flag");
+    }
+  }
+
+}
+#endif
+
+/** copy SAO parameter
+* \param dst  
+* \param src 
+*/
+inline Void copySaoOneLcuParam(SaoLcuParam* dst,  SaoLcuParam* src)
+{
+  Int i;
+  dst->partIdx = src->partIdx;
+  dst->typeIdx = src->typeIdx;
+  if (dst->typeIdx != -1)
+  {
+#if SAO_TYPE_CODING
+    dst->subTypeIdx = src->subTypeIdx ;
+#else
+    if (dst->typeIdx == SAO_BO)
+    {
+      dst->bandPosition = src->bandPosition ;
+    }
+    else
+    {
+      dst->bandPosition = 0;
+    }
+#endif
+    dst->length  = src->length;
+    for (i=0;i<dst->length;i++)
+    {
+      dst->offset[i] = src->offset[i];
+    }
+  }
+  else
+  {
+    dst->length  = 0;
+    for (i=0;i<SAO_BO_LEN;i++)
+    {
+      dst->offset[i] = 0;
+    }
+  }
+}
+
+#if !REMOVE_ALF
+Void TDecCavlc::xParseAlfParam(ALFParam* pAlfParam)
+{
+  UInt uiSymbol;
+  char syntaxString[50];
+  sprintf(syntaxString, "alf_aps_filter_flag[%d]", pAlfParam->componentID);
+  READ_FLAG(uiSymbol, syntaxString);
+  pAlfParam->alf_flag = uiSymbol;
+  if(pAlfParam->alf_flag ==0)
+  {
+    return;
+  }
+  Int iSymbol;
+  pAlfParam->num_coeff = (Int)ALF_MAX_NUM_COEF;
+  switch(pAlfParam->componentID)
+  {
+  case ALF_Cb:
+  case ALF_Cr:
+    {
+      pAlfParam->filter_shape = ALF_CROSS9x7_SQUARE3x3;
+      pAlfParam->filters_per_group = 1;
+      for(Int pos=0; pos< pAlfParam->num_coeff; pos++)
+      {
+        READ_SVLC(iSymbol, "alf_filt_coeff");
+        pAlfParam->coeffmulti[0][pos] = iSymbol;
+      }
+    }
+    break;
+  case ALF_Y:
+    {
+      pAlfParam->filters_per_group = 0;
+      memset (pAlfParam->filterPattern, 0 , sizeof(Int)*NO_VAR_BINS);
+      pAlfParam->filter_shape = 0;
+      // filters_per_fr
+      READ_UVLC (uiSymbol, "alf_no_filters_minus1");
+      pAlfParam->filters_per_group = uiSymbol + 1;
+
+      if(uiSymbol == 1) // filters_per_group == 2
+      {
+        READ_UVLC (uiSymbol, "alf_start_second_filter");
+        pAlfParam->startSecondFilter = uiSymbol;
+        pAlfParam->filterPattern [uiSymbol] = 1;
+      }
+      else if (uiSymbol > 1) // filters_per_group > 2
+      {
+        pAlfParam->filters_per_group = 1;
+        Int numMergeFlags = 16;
+        for (Int i=1; i<numMergeFlags; i++) 
+        {
+          READ_FLAG (uiSymbol,  "alf_filter_pattern");
+          pAlfParam->filterPattern[i] = uiSymbol;
+          pAlfParam->filters_per_group += uiSymbol;
+        }
+      }
+      for(Int idx = 0; idx < pAlfParam->filters_per_group; ++idx)
+      {
+        for(Int i = 0; i < pAlfParam->num_coeff; i++)
+        {
+          pAlfParam->coeffmulti[idx][i] = xGolombDecode(kTableTabShapes[ALF_CROSS9x7_SQUARE3x3][i]);
+        }
+      }
+    }
+    break;
+  default:
+    {
+      printf("Not a legal component ID for ALF\n");
+      assert(0);
+      exit(-1);
+    }
+  }
+}
+
+Int TDecCavlc::xGolombDecode(Int k)
+{
+  Int coeff;
+  UInt symbol;
+  xReadEpExGolomb( symbol, k );
+  coeff = symbol;
+  if(symbol != 0)
+  {
+    xReadFlag(symbol);
+    if(symbol == 0)
+    {
+      coeff = -coeff;
+    }
+  }
+#if ENC_DEC_TRACE
+  fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+  fprintf( g_hTrace, "%-40s se(v) : %d\n", "alf_filt_coeff", coeff ); 
+#endif
+  return coeff;
+}
+#endif
+
+Void TDecCavlc::parsePPS(TComPPS* pcPPS)
+{
+#if ENC_DEC_TRACE  
+  xTracePPSHeader (pcPPS);
+#endif
+  UInt  uiCode;
+
+  Int   iCode;
+
+  READ_UVLC( uiCode, "pic_parameter_set_id");                      pcPPS->setPPSId (uiCode);
+  READ_UVLC( uiCode, "seq_parameter_set_id");                      pcPPS->setSPSId (uiCode);
+
+  READ_FLAG ( uiCode, "sign_data_hiding_flag" ); pcPPS->setSignHideFlag( uiCode );
+
+  READ_FLAG( uiCode,   "cabac_init_present_flag" );            pcPPS->setCabacInitPresentFlag( uiCode ? true : false );
+
+  READ_UVLC(uiCode, "num_ref_idx_l0_default_active_minus1");       pcPPS->setNumRefIdxL0DefaultActive(uiCode+1);
+  READ_UVLC(uiCode, "num_ref_idx_l1_default_active_minus1");       pcPPS->setNumRefIdxL1DefaultActive(uiCode+1);
+
+  READ_SVLC(iCode, "pic_init_qp_minus26" );                        pcPPS->setPicInitQPMinus26(iCode);
+  READ_FLAG( uiCode, "constrained_intra_pred_flag" );              pcPPS->setConstrainedIntraPred( uiCode ? true : false );
+#if PPS_TS_FLAG  
+  READ_FLAG( uiCode, "transform_skip_enabled_flag" );               
+  pcPPS->setUseTransformSkip ( uiCode ? true : false ); 
+#endif
+
+#if !REMOVE_FGS
+  READ_CODE( 2, uiCode, "slice_granularity" );                     pcPPS->setSliceGranularity(uiCode);
+#endif
+  
+  // alf_param() ?
+#if CU_DQP_ENABLE_FLAG
+  READ_FLAG( uiCode, "cu_qp_delta_enabled_flag" );            pcPPS->setUseDQP( uiCode ? true : false );
+  if( pcPPS->getUseDQP() )
+  {
+    READ_UVLC( uiCode, "diff_cu_qp_delta_depth" );
+#if REMOVE_FGS
+    pcPPS->setMaxCuDQPDepth( uiCode );
+#else
+    pcPPS->setMaxCuDQPDepth( uiCode + pcPPS->getSliceGranularity() );
+#endif
+  }
+  else
+  {
+    pcPPS->setMaxCuDQPDepth( 0 );
+  }
+#else
+  READ_UVLC( uiCode, "diff_cu_qp_delta_depth");
+  if(uiCode == 0)
+  {
+    pcPPS->setUseDQP (false);
+    pcPPS->setMaxCuDQPDepth( 0 );
+  }
+  else
+  {
+    pcPPS->setUseDQP (true);
+#if REMOVE_FGS
+    pcPPS->setMaxCuDQPDepth(uiCode - 1);
+#else
+    pcPPS->setMaxCuDQPDepth(uiCode + pcPPS->getSliceGranularity() - 1);
+#endif
+  }
+#endif
+  READ_SVLC( iCode, "cb_qp_offset");
+  pcPPS->setChromaCbQpOffset(iCode);
+#if CHROMA_QP_EXTENSION
+  assert( pcPPS->getChromaCbQpOffset() >= -12 );
+  assert( pcPPS->getChromaCbQpOffset() <=  12 );
+#endif
+
+  READ_SVLC( iCode, "cr_qp_offset");
+  pcPPS->setChromaCrQpOffset(iCode);
+#if CHROMA_QP_EXTENSION
+  assert( pcPPS->getChromaCrQpOffset() >= -12 );
+  assert( pcPPS->getChromaCrQpOffset() <=  12 );
+#endif
+
+#if CHROMA_QP_EXTENSION
+  READ_FLAG( uiCode, "slicelevel_chroma_qp_flag" );
+  pcPPS->setSliceChromaQpFlag( uiCode ? true : false );
+#endif
+
+  READ_FLAG( uiCode, "weighted_pred_flag" );          // Use of Weighting Prediction (P_SLICE)
+  pcPPS->setUseWP( uiCode==1 );
+  READ_FLAG( uiCode, "weighted_bipred_flag" );         // Use of Bi-Directional Weighting Prediction (B_SLICE)
+  pcPPS->setWPBiPred( uiCode==1 );
+  printf("TDecCavlc::parsePPS():\tm_bUseWeightPred=%d\tm_uiBiPredIdc=%d\n", pcPPS->getUseWP(), pcPPS->getWPBiPred());
+
+  READ_FLAG( uiCode, "output_flag_present_flag" );
+  pcPPS->setOutputFlagPresentFlag( uiCode==1 );
+
+#if !TILES_WPP_ENTROPYSLICES_FLAGS
+#if DEPENDENT_SLICES
+  READ_FLAG( uiCode, "dependent_slices_enabled_flag" );
+  pcPPS->setDependentSliceEnabledFlag( uiCode==1 );
+#endif
+#endif
+
+  READ_FLAG( uiCode, "transquant_bypass_enable_flag");
+  pcPPS->setTransquantBypassEnableFlag(uiCode ? true : false);
+
+#if TILES_WPP_ENTROPYSLICES_FLAGS
+#if DEPENDENT_SLICES
+  READ_FLAG( uiCode, "dependent_slices_enabled_flag"    );    pcPPS->setDependentSliceEnabledFlag   ( uiCode == 1 );
+#endif
+  READ_FLAG( uiCode, "tiles_enabled_flag"               );    pcPPS->setTilesEnabledFlag            ( uiCode == 1 );
+  READ_FLAG( uiCode, "entropy_coding_sync_enabled_flag" );    pcPPS->setEntropyCodingSyncEnabledFlag( uiCode == 1 );   
+  READ_FLAG( uiCode, "entropy_slice_enabled_flag"       );    pcPPS->setEntropySliceEnabledFlag     ( uiCode == 1 );   
+
+  if( pcPPS->getTilesEnabledFlag() )
+#else
+  READ_CODE(2, uiCode, "tiles_or_entropy_coding_sync_idc");         pcPPS->setTilesOrEntropyCodingSyncIdc(uiCode);
+  if(pcPPS->getTilesOrEntropyCodingSyncIdc() == 1)
+#endif
+  {
+    READ_UVLC ( uiCode, "num_tile_columns_minus1" );                pcPPS->setNumColumnsMinus1( uiCode );  
+    READ_UVLC ( uiCode, "num_tile_rows_minus1" );                   pcPPS->setNumRowsMinus1( uiCode );  
+    READ_FLAG ( uiCode, "uniform_spacing_flag" );                   pcPPS->setUniformSpacingFlag( uiCode );
+
+    if( !pcPPS->getUniformSpacingFlag())
+    {
+      UInt* columnWidth = (UInt*)malloc(pcPPS->getNumColumnsMinus1()*sizeof(UInt));
+      for(UInt i=0; i<pcPPS->getNumColumnsMinus1(); i++)
+      { 
+        READ_UVLC( uiCode, "column_width_minus1" );  
+        columnWidth[i] = uiCode+1;
+      }
+      pcPPS->setColumnWidth(columnWidth);
+      free(columnWidth);
+
+      UInt* rowHeight = (UInt*)malloc(pcPPS->getNumRowsMinus1()*sizeof(UInt));
+      for(UInt i=0; i<pcPPS->getNumRowsMinus1(); i++)
+      {
+        READ_UVLC( uiCode, "row_height_minus1" );
+        rowHeight[i] = uiCode + 1;
+      }
+      pcPPS->setRowHeight(rowHeight);
+      free(rowHeight);  
+    }
+
+    if(pcPPS->getNumColumnsMinus1() !=0 || pcPPS->getNumRowsMinus1() !=0)
+    {
+      READ_FLAG ( uiCode, "loop_filter_across_tiles_enabled_flag" );   pcPPS->setLoopFilterAcrossTilesEnabledFlag( uiCode ? true : false );
+    }
+  }
+#if !TILES_WPP_ENTROPYSLICES_FLAGS
+#if DEPENDENT_SLICES
+  else if( pcPPS->getTilesOrEntropyCodingSyncIdc()==3 )
+  {
+    READ_FLAG ( uiCode, "cabac_independent_flag" );
+    pcPPS->setCabacIndependentFlag( (uiCode == 1)? true : false );
+  }
+#endif
+#endif
+#if MOVE_LOOP_FILTER_SLICES_FLAG
+  READ_FLAG( uiCode, "loop_filter_across_slices_enabled_flag" );       pcPPS->setLoopFilterAcrossSlicesEnabledFlag( uiCode ? true : false );
+#endif
+  READ_FLAG( uiCode, "deblocking_filter_control_present_flag" );       pcPPS->setDeblockingFilterControlPresentFlag( uiCode ? true : false );
+  if(pcPPS->getDeblockingFilterControlPresentFlag())
+  {
+    READ_FLAG( uiCode, "deblocking_filter_override_enabled_flag" );    pcPPS->setDeblockingFilterOverrideEnabledFlag( uiCode ? true : false );
+    READ_FLAG( uiCode, "pic_disable_deblocking_filter_flag" );         pcPPS->setPicDisableDeblockingFilterFlag(uiCode ? true : false );
+    if(!pcPPS->getPicDisableDeblockingFilterFlag())
+    {
+      READ_SVLC ( iCode, "pps_beta_offset_div2" );                     pcPPS->setDeblockingFilterBetaOffsetDiv2( iCode );
+      READ_SVLC ( iCode, "pps_tc_offset_div2" );                       pcPPS->setDeblockingFilterTcOffsetDiv2( iCode );
+    }
+  }
+  READ_FLAG( uiCode, "pps_scaling_list_data_present_flag" );           pcPPS->setScalingListPresentFlag( uiCode ? true : false );
+  if(pcPPS->getScalingListPresentFlag ())
+  {
+    parseScalingList( pcPPS->getScalingList() );
+  }
+  READ_UVLC( uiCode, "log2_parallel_merge_level_minus2");
+  pcPPS->setLog2ParallelMergeLevelMinus2 (uiCode);
+
+#if SLICE_HEADER_EXTENSION
+  READ_FLAG( uiCode, "slice_header_extension_present_flag");
+  pcPPS->setSliceHeaderExtensionPresentFlag(uiCode);
+#endif
+
+  READ_FLAG( uiCode, "pps_extension_flag");
+  if (uiCode)
+  {
+    while ( xMoreRbspData() )
+    {
+      READ_FLAG( uiCode, "pps_extension_data_flag");
+    }
+  }
+}
+
+#if SUPPORT_FOR_VUI
+#if !BUFFERING_PERIOD_AND_TIMING_SEI
+Void  TDecCavlc::parseVUI(TComVUI* pcVUI)
+#else
+Void  TDecCavlc::parseVUI(TComVUI* pcVUI, TComSPS *pcSPS)
+#endif
+{
+#if ENC_DEC_TRACE
+  fprintf( g_hTrace, "----------- vui_parameters -----------\n");
+#endif
+  UInt  uiCode;
+
+  READ_FLAG(     uiCode, "aspect_ratio_info_present_flag");           pcVUI->setAspectRatioInfoPresentFlag(uiCode);
+  if (pcVUI->getAspectRatioInfoPresentFlag())
+  {
+    READ_CODE(8, uiCode, "aspect_ratio_idc");                         pcVUI->setAspectRatioIdc(uiCode);
+    if (pcVUI->getAspectRatioIdc() == 255)
+    {
+      READ_CODE(16, uiCode, "sar_width");                             pcVUI->setSarWidth(uiCode);
+      READ_CODE(16, uiCode, "sar_height");                            pcVUI->setSarWidth(uiCode);
+    }
+  }
+
+  READ_FLAG(     uiCode, "overscan_info_present_flag");               pcVUI->setOverscanInfoPresentFlag(uiCode);
+  if (pcVUI->getOverscanInfoPresentFlag())
+  {
+    READ_FLAG(   uiCode, "overscan_appropriate_flag");                pcVUI->setOverscanAppropriateFlag(uiCode);
+  }
+
+  READ_FLAG(     uiCode, "video_signal_type_present_flag");           pcVUI->setVideoSignalTypePresentFlag(uiCode);
+  if (pcVUI->getVideoSignalTypePresentFlag())
+  {
+    READ_CODE(3, uiCode, "video_format");                             pcVUI->setVideoFormat(uiCode);
+    READ_FLAG(   uiCode, "video_full_range_flag");                    pcVUI->setVideoFullRangeFlag(uiCode);
+    READ_FLAG(   uiCode, "colour_description_present_flag");          pcVUI->setColourDescriptionPresentFlag(uiCode);
+    if (pcVUI->getColourDescriptionPresentFlag())
+    {
+      READ_CODE(8, uiCode, "colour_primaries");                       pcVUI->setColourPrimaries(uiCode);
+      READ_CODE(8, uiCode, "transfer_characteristics");               pcVUI->setTransferCharacteristics(uiCode);
+      READ_CODE(8, uiCode, "matrix_coefficients");                    pcVUI->setMatrixCoefficients(uiCode);
+    }
+  }
+
+  READ_FLAG(     uiCode, "chroma_loc_info_present_flag");             pcVUI->setChromaLocInfoPresentFlag(uiCode);
+  if (pcVUI->getChromaLocInfoPresentFlag())
+  {
+    READ_UVLC(   uiCode, "chroma_sample_loc_type_top_field" );        pcVUI->setChromaSampleLocTypeTopField(uiCode);
+    READ_UVLC(   uiCode, "chroma_sample_loc_type_bottom_field" );     pcVUI->setChromaSampleLocTypeBottomField(uiCode);
+  }
+
+  READ_FLAG(     uiCode, "neutral_chroma_indication_flag");           pcVUI->setNeutralChromaIndicationFlag(uiCode);
+
+  READ_FLAG(     uiCode, "field_seq_flag");                           pcVUI->setFieldSeqFlag(uiCode);
+  assert(pcVUI->getFieldSeqFlag() == false);        // not supported yet
+
+  READ_FLAG(     uiCode, "hrd_parameters_present_flag");              pcVUI->setHrdParametersPresentFlag(uiCode);
+#if !BUFFERING_PERIOD_AND_TIMING_SEI
+  assert(pcVUI->getHrdParametersPresentFlag() == false);  // not supported yet
+#else
+  if( pcVUI->getHrdParametersPresentFlag() )
+  {
+    READ_FLAG( uiCode, "timing_info_present_flag" );                  pcVUI->setTimingInfoPresentFlag( uiCode );
+    if( pcVUI->getTimingInfoPresentFlag() )
+    {
+      READ_CODE( 32, uiCode, "num_units_in_tick" );                   pcVUI->setNumUnitsInTick( uiCode );
+      READ_CODE( 32, uiCode, "time_scale" );                          pcVUI->setTimeScale( uiCode );
+    }
+    READ_FLAG( uiCode, "nal_hrd_parameters_present_flag" );           pcVUI->setNalHrdParametersPresentFlag( uiCode );
+    READ_FLAG( uiCode, "vcl_hrd_parameters_present_flag" );           pcVUI->setVclHrdParametersPresentFlag( uiCode );
+    if( pcVUI->getNalHrdParametersPresentFlag() || pcVUI->getVclHrdParametersPresentFlag() )
+    {
+      READ_FLAG( uiCode, "sub_pic_Cpb_params_present_flag" );         pcVUI->setSubPicCpbParamsPresentFlag( uiCode );
+      if( pcVUI->getSubPicCpbParamsPresentFlag() )
+      {
+        READ_CODE( 8, uiCode, "tick_divisor_minus2" );                pcVUI->setTickDivisorMinus2( uiCode );
+        READ_CODE( 5, uiCode, "du_cpb_removal_delay_length_minus1" ); pcVUI->setDuCpbRemovalDelayLengthMinus1( uiCode );
+      }
+      READ_CODE( 4, uiCode, "bit_rate_scale" );                       pcVUI->setBitRateScale( uiCode );
+      READ_CODE( 4, uiCode, "cpb_size_scale" );                       pcVUI->setCpbSizeScale( uiCode );
+      READ_CODE( 5, uiCode, "initial_cpb_removal_delay_length_minus1" ); pcVUI->setInitialCpbRemovalDelayLengthMinus1( uiCode );
+      READ_CODE( 5, uiCode, "cpb_removal_delay_length_minus1" );      pcVUI->setCpbRemovalDelayLengthMinus1( uiCode );
+      READ_CODE( 5, uiCode, "dpb_output_delay_length_minus1" );       pcVUI->setDpbOutputDelayLengthMinus1( uiCode );
+    }
+
+    Int i, j, nalOrVcl;
+    for( i = 0; i < pcSPS->getMaxTLayers(); i ++ )
+    {
+      READ_FLAG( uiCode, "fixed_pic_rate_flag" );                     pcVUI->setFixedPicRateFlag( i, uiCode );
+      if( pcVUI->getFixedPicRateFlag( i ) )
+      {
+        READ_UVLC( uiCode, "pic_duration_in_tc_minus1" );             pcVUI->setPicDurationInTcMinus1( i, uiCode );
+      }
+      READ_FLAG( uiCode, "low_delay_hrd_flag" );                      pcVUI->setLowDelayHrdFlag( i, uiCode );
+      READ_UVLC( uiCode, "cpb_cnt_minus1" );                          pcVUI->setCpbCntMinus1( i, uiCode );
+      for( nalOrVcl = 0; nalOrVcl < 2; nalOrVcl ++ )
+      {
+        if( ( ( nalOrVcl == 0 ) && ( pcVUI->getNalHrdParametersPresentFlag() ) ) ||
+            ( ( nalOrVcl == 1 ) && ( pcVUI->getVclHrdParametersPresentFlag() ) ) )
+        {
+          for( j = 0; j < ( pcVUI->getCpbCntMinus1( i ) + 1 ); j ++ )
+          {
+            READ_UVLC( uiCode, "bit_size_value_minus1" );             pcVUI->setBitRateValueMinus1( i, j, nalOrVcl, uiCode );
+            READ_UVLC( uiCode, "cpb_size_value_minus1" );             pcVUI->setCpbSizeValueMinus1( i, j, nalOrVcl, uiCode );
+            READ_FLAG( uiCode, "cbr_flag" );                          pcVUI->setCbrFlag( i, j, nalOrVcl, uiCode );
+          }
+        }
+      }
+    }
+  }
+#endif
+  READ_FLAG(     uiCode, "bitstream_restriction_flag");               pcVUI->setBitstreamRestrictionFlag(uiCode);
+  if (pcVUI->getBitstreamRestrictionFlag())
+  {
+    READ_FLAG(   uiCode, "tiles_fixed_structure_flag");               pcVUI->setTilesFixedStructureFlag(uiCode);
+    READ_FLAG(   uiCode, "motion_vectors_over_pic_boundaries_flag");  pcVUI->setMotionVectorsOverPicBoundariesFlag(uiCode);
+    READ_UVLC(   uiCode, "max_bytes_per_pic_denom" );                 pcVUI->setMaxBytesPerPicDenom(uiCode);
+    READ_UVLC(   uiCode, "max_bits_per_mincu_denom" );                pcVUI->setMaxBitsPerMinCuDenom(uiCode);
+    READ_UVLC(   uiCode, "log2_max_mv_length_horizontal" );           pcVUI->setLog2MaxMvLengthHorizontal(uiCode);
+    READ_UVLC(   uiCode, "log2_max_mv_length_vertical" );             pcVUI->setLog2MaxMvLengthVertical(uiCode);
+  }
+}
+#endif
+
+Void TDecCavlc::parseSPS(TComSPS* pcSPS)
+{
+#if ENC_DEC_TRACE  
+  xTraceSPSHeader (pcSPS);
+#endif
+
+  UInt  uiCode;
+#if SPS_SYNTAX_CHANGES
+  READ_CODE( 4,  uiCode, "video_parameter_set_id");              pcSPS->setVPSId        ( uiCode );
+  READ_CODE( 3,  uiCode, "sps_max_sub_layers_minus1" );          pcSPS->setMaxTLayers   ( uiCode+1 );
+  READ_FLAG(     uiCode, "sps_reserved_zero_bit");               assert(uiCode == 0);
+  parsePTL(pcSPS->getPTL(), 1, pcSPS->getMaxTLayers() - 1);
+  READ_UVLC(     uiCode, "seq_parameter_set_id" );               pcSPS->setSPSId( uiCode );
+  READ_UVLC(     uiCode, "chroma_format_idc" );                  pcSPS->setChromaFormatIdc( uiCode );
+  // in the first version we only support chroma_format_idc equal to 1 (4:2:0), so separate_colour_plane_flag cannot appear in the bitstream
+  assert (uiCode == 1);
+  if( uiCode == 3 )
+  {
+    READ_FLAG(     uiCode, "separate_colour_plane_flag");        assert(uiCode == 0);
+  }
+
+#else
+  READ_CODE( 3,  uiCode, "profile_space" );                      pcSPS->setProfileSpace( uiCode );
+  READ_CODE( 5,  uiCode, "profile_idc" );                        pcSPS->setProfileIdc( uiCode );
+  READ_CODE(16,  uiCode, "reserved_indicator_flags" );           pcSPS->setRsvdIndFlags( uiCode );
+  READ_CODE( 8,  uiCode, "level_idc" );                          pcSPS->setLevelIdc( uiCode );
+  READ_CODE(32,  uiCode, "profile_compatibility");               pcSPS->setProfileCompat( uiCode );
+  READ_UVLC(     uiCode, "seq_parameter_set_id" );               pcSPS->setSPSId( uiCode );
+  READ_UVLC(     uiCode, "video_parameter_set_id" );             pcSPS->setVPSId( uiCode );
+  READ_UVLC(     uiCode, "chroma_format_idc" );                  pcSPS->setChromaFormatIdc( uiCode );
+  READ_CODE( 3,  uiCode, "max_temporal_layers_minus1" );         pcSPS->setMaxTLayers( uiCode+1 );
+#endif
+  READ_UVLC (    uiCode, "pic_width_in_luma_samples" );          pcSPS->setPicWidthInLumaSamples ( uiCode    );
+  READ_UVLC (    uiCode, "pic_height_in_luma_samples" );         pcSPS->setPicHeightInLumaSamples( uiCode    );
+  READ_FLAG(     uiCode, "pic_cropping_flag");                   pcSPS->setPicCroppingFlag ( uiCode ? true : false );
+  if (uiCode != 0)
+  {
+    READ_UVLC(   uiCode, "pic_crop_left_offset" );               pcSPS->setPicCropLeftOffset  ( uiCode * TComSPS::getCropUnitX( pcSPS->getChromaFormatIdc() ) );
+    READ_UVLC(   uiCode, "pic_crop_right_offset" );              pcSPS->setPicCropRightOffset ( uiCode * TComSPS::getCropUnitX( pcSPS->getChromaFormatIdc() ) );
+    READ_UVLC(   uiCode, "pic_crop_top_offset" );                pcSPS->setPicCropTopOffset   ( uiCode * TComSPS::getCropUnitY( pcSPS->getChromaFormatIdc() ) );
+    READ_UVLC(   uiCode, "pic_crop_bottom_offset" );             pcSPS->setPicCropBottomOffset( uiCode * TComSPS::getCropUnitY( pcSPS->getChromaFormatIdc() ) );
+  }
+
+#if FULL_NBIT
+  READ_UVLC(     uiCode, "bit_depth_luma_minus8" );
+  g_uiBitDepth = 8 + uiCode;
+  g_uiBitIncrement = 0;
+  pcSPS->setBitDepth(g_uiBitDepth);
+  pcSPS->setBitIncrement(g_uiBitIncrement);
+  UInt m_uiSaoBitIncrease = g_uiBitDepth + (g_uiBitDepth-8) - min((Int)(g_uiBitDepth + (g_uiBitDepth-8)), 10);
+#else
+  READ_UVLC(     uiCode, "bit_depth_luma_minus8" );
+  g_uiBitDepth = 8;
+  g_uiBitIncrement = uiCode;
+  pcSPS->setBitDepth(g_uiBitDepth);
+  pcSPS->setBitIncrement(g_uiBitIncrement);
+#endif
+  pcSPS->setQpBDOffsetY( (Int) (6*uiCode) );
+
+  g_uiBASE_MAX  = ((1<<(g_uiBitDepth))-1);
+
+#if IBDI_NOCLIP_RANGE
+  g_uiIBDI_MAX  = g_uiBASE_MAX << g_uiBitIncrement;
+#else
+  g_uiIBDI_MAX  = ((1<<(g_uiBitDepth+g_uiBitIncrement))-1);
+#endif
+  READ_UVLC( uiCode,    "bit_depth_chroma_minus8" );
+  pcSPS->setQpBDOffsetC( (Int) (6*uiCode) );
+
+  READ_FLAG( uiCode, "pcm_enabled_flag" ); pcSPS->setUsePCM( uiCode ? true : false );
+
+  if( pcSPS->getUsePCM() )
+  {
+    READ_CODE( 4, uiCode, "pcm_bit_depth_luma_minus1" );           pcSPS->setPCMBitDepthLuma   ( 1 + uiCode );
+    READ_CODE( 4, uiCode, "pcm_bit_depth_chroma_minus1" );         pcSPS->setPCMBitDepthChroma ( 1 + uiCode );
+  }
+
+  READ_UVLC( uiCode,    "log2_max_pic_order_cnt_lsb_minus4" );   pcSPS->setBitsForPOC( 4 + uiCode );
+  for(UInt i=0; i <= pcSPS->getMaxTLayers()-1; i++)
+  {
+    READ_UVLC ( uiCode, "max_dec_pic_buffering");
+    pcSPS->setMaxDecPicBuffering( uiCode, i);
+    READ_UVLC ( uiCode, "num_reorder_pics" );
+    pcSPS->setNumReorderPics(uiCode, i);
+    READ_UVLC ( uiCode, "max_latency_increase");
+    pcSPS->setMaxLatencyIncrease( uiCode, i );
+  }
+
+  READ_FLAG( uiCode, "restricted_ref_pic_lists_flag" );
+  pcSPS->setRestrictedRefPicListsFlag( uiCode );
+  if( pcSPS->getRestrictedRefPicListsFlag() )
+  {
+    READ_FLAG( uiCode, "lists_modification_present_flag" );
+    pcSPS->setListsModificationPresentFlag(uiCode);
+  }
+  else 
+  {
+    pcSPS->setListsModificationPresentFlag(true);
+  }
+  READ_UVLC( uiCode, "log2_min_coding_block_size_minus3" );
+  UInt log2MinCUSize = uiCode + 3;
+  READ_UVLC( uiCode, "log2_diff_max_min_coding_block_size" );
+  UInt uiMaxCUDepthCorrect = uiCode;
+  pcSPS->setMaxCUWidth  ( 1<<(log2MinCUSize + uiMaxCUDepthCorrect) ); g_uiMaxCUWidth  = 1<<(log2MinCUSize + uiMaxCUDepthCorrect);
+  pcSPS->setMaxCUHeight ( 1<<(log2MinCUSize + uiMaxCUDepthCorrect) ); g_uiMaxCUHeight = 1<<(log2MinCUSize + uiMaxCUDepthCorrect);
+  READ_UVLC( uiCode, "log2_min_transform_block_size_minus2" );   pcSPS->setQuadtreeTULog2MinSize( uiCode + 2 );
+
+  READ_UVLC( uiCode, "log2_diff_max_min_transform_block_size" ); pcSPS->setQuadtreeTULog2MaxSize( uiCode + pcSPS->getQuadtreeTULog2MinSize() );
+  pcSPS->setMaxTrSize( 1<<(uiCode + pcSPS->getQuadtreeTULog2MinSize()) );
+  if( pcSPS->getUsePCM() )
+  {
+    READ_UVLC( uiCode, "log2_min_pcm_coding_block_size_minus3" );  pcSPS->setPCMLog2MinSize (uiCode+3); 
+    READ_UVLC( uiCode, "log2_diff_max_min_pcm_coding_block_size" ); pcSPS->setPCMLog2MaxSize ( uiCode+pcSPS->getPCMLog2MinSize() );
+  }
+
+  READ_UVLC( uiCode, "max_transform_hierarchy_depth_inter" );    pcSPS->setQuadtreeTUMaxDepthInter( uiCode+1 );
+  READ_UVLC( uiCode, "max_transform_hierarchy_depth_intra" );    pcSPS->setQuadtreeTUMaxDepthIntra( uiCode+1 );
+  g_uiAddCUDepth = 0;
+  while( ( pcSPS->getMaxCUWidth() >> uiMaxCUDepthCorrect ) > ( 1 << ( pcSPS->getQuadtreeTULog2MinSize() + g_uiAddCUDepth )  ) )
+  {
+    g_uiAddCUDepth++;
+  }
+  pcSPS->setMaxCUDepth( uiMaxCUDepthCorrect+g_uiAddCUDepth  ); 
+  g_uiMaxCUDepth  = uiMaxCUDepthCorrect+g_uiAddCUDepth;
+  // BB: these parameters may be removed completly and replaced by the fixed values
+  pcSPS->setMinTrDepth( 0 );
+  pcSPS->setMaxTrDepth( 1 );
+  READ_FLAG( uiCode, "scaling_list_enabled_flag" );                 pcSPS->setScalingListFlag ( uiCode );
+  if(pcSPS->getScalingListFlag())
+  {
+    READ_FLAG( uiCode, "sps_scaling_list_data_present_flag" );                 pcSPS->setScalingListPresentFlag ( uiCode );
+    if(pcSPS->getScalingListPresentFlag ())
+    {
+      parseScalingList( pcSPS->getScalingList() );
+    }
+  }
+#if !REMOVE_LMCHROMA
+  READ_FLAG( uiCode, "chroma_pred_from_luma_enabled_flag" );        pcSPS->setUseLMChroma ( uiCode ? true : false );
+#endif
+#if !PPS_TS_FLAG
+  READ_FLAG( uiCode, "transform_skip_enabled_flag" );               pcSPS->setUseTransformSkip ( uiCode ? true : false );
+#endif
+#if !MOVE_LOOP_FILTER_SLICES_FLAG
+  READ_FLAG( uiCode, "loop_filter_across_slice_flag" );             pcSPS->setLFCrossSliceBoundaryFlag( uiCode ? true : false);
+#endif
+  READ_FLAG( uiCode, "asymmetric_motion_partitions_enabled_flag" ); pcSPS->setUseAMP( uiCode );
+#if !REMOVE_NSQT
+  READ_FLAG( uiCode, "non_square_quadtree_enabled_flag" );          pcSPS->setUseNSQT( uiCode );
+#endif
+  READ_FLAG( uiCode, "sample_adaptive_offset_enabled_flag" );       pcSPS->setUseSAO ( uiCode ? true : false );
+#if !REMOVE_ALF
+  READ_FLAG( uiCode, "adaptive_loop_filter_enabled_flag" );         pcSPS->setUseALF ( uiCode ? true : false );
+#endif
+  if( pcSPS->getUsePCM() )
+  {
+    READ_FLAG( uiCode, "pcm_loop_filter_disable_flag" );           pcSPS->setPCMFilterDisableFlag ( uiCode ? true : false );
+  }
+
+  READ_FLAG( uiCode, "temporal_id_nesting_flag" );               pcSPS->setTemporalIdNestingFlag ( uiCode > 0 ? true : false );
+
+  READ_UVLC( uiCode, "num_short_term_ref_pic_sets" );
+  pcSPS->createRPSList(uiCode);
+
+  TComRPSList* rpsList = pcSPS->getRPSList();
+  TComReferencePictureSet* rps;
+
+  for(UInt i=0; i< rpsList->getNumberOfReferencePictureSets(); i++)
+  {
+    rps = rpsList->getReferencePictureSet(i);
+    parseShortTermRefPicSet(pcSPS,rps,i);
+  }
+  READ_FLAG( uiCode, "long_term_ref_pics_present_flag" );          pcSPS->setLongTermRefsPresent(uiCode);
+#if LTRP_IN_SPS
+  if (pcSPS->getLongTermRefsPresent()) 
+  {
+    READ_UVLC( uiCode, "num_long_term_ref_pic_sps" );
+    pcSPS->setNumLongTermRefPicSPS(uiCode);
+    for (UInt k = 0; k < pcSPS->getNumLongTermRefPicSPS(); k++)
+    {
+      READ_CODE( pcSPS->getBitsForPOC(), uiCode, "lt_ref_pic_poc_lsb_sps" );
+      pcSPS->setLtRefPicPocLsbSps(uiCode, k);
+      READ_FLAG( uiCode,  "used_by_curr_pic_lt_sps_flag[i]");
+      pcSPS->setUsedByCurrPicLtSPSFlag(k, uiCode?1:0);
+    }
+  }
+#endif
+  READ_FLAG( uiCode, "sps_temporal_mvp_enable_flag" );            pcSPS->setTMVPFlagsPresent(uiCode);
+#if SUPPORT_FOR_VUI
+  READ_FLAG( uiCode, "vui_parameters_present_flag" );             pcSPS->setVuiParametersPresentFlag(uiCode);
+
+  if (pcSPS->getVuiParametersPresentFlag())
+  {
+#if !BUFFERING_PERIOD_AND_TIMING_SEI
+    parseVUI(pcSPS->getVuiParameters());
+#else
+    parseVUI(pcSPS->getVuiParameters(), pcSPS);
+#endif
+  }
+#endif
+#if !SPS_AMVP_CLEANUP
+  // AMVP mode for each depth (AM_NONE or AM_EXPL)
+  for (Int i = 0; i < pcSPS->getMaxCUDepth(); i++)
+  {
+    xReadFlag( uiCode );
+    pcSPS->setAMVPMode( i, (AMVP_MODE)uiCode );
+  }
+#endif
+  READ_FLAG( uiCode, "sps_extension_flag");
+  if (uiCode)
+  {
+    while ( xMoreRbspData() )
+    {
+      READ_FLAG( uiCode, "sps_extension_data_flag");
+    }
+  }
+}
+
+Void TDecCavlc::parseVPS(TComVPS* pcVPS)
+{
+  UInt  uiCode;
+  
+#if VPS_SYNTAX_CHANGES
+  READ_CODE( 4,  uiCode,  "video_parameter_set_id" );             pcVPS->setVPSId( uiCode );
+  READ_FLAG(     uiCode,  "vps_temporal_id_nesting_flag" );       pcVPS->setTemporalNestingFlag( uiCode ? true:false );
+  READ_CODE( 2,  uiCode,  "vps_reserved_zero_2bits" );            assert(uiCode == 0);
+  READ_CODE( 6,  uiCode,  "vps_reserved_zero_6bits" );            assert(uiCode == 0);
+  READ_CODE( 3,  uiCode,  "vps_max_sub_layers_minus1" );          pcVPS->setMaxTLayers( uiCode + 1 );
+  parsePTL ( pcVPS->getPTL(), true, pcVPS->getMaxTLayers()-1);
+  READ_CODE( 12, uiCode,  "vps_reserved_zero_12bits" );           assert(uiCode == 0);
+#else
+  READ_CODE( 3, uiCode, "vps_max_temporal_layers_minus1" );   pcVPS->setMaxTLayers( uiCode + 1 );
+  READ_CODE( 5, uiCode, "vps_max_layers_minus1" );            pcVPS->setMaxLayers( uiCode + 1 );
+  READ_UVLC( uiCode,  "video_parameter_set_id" );             pcVPS->setVPSId( uiCode );
+  READ_FLAG( uiCode,  "vps_temporal_id_nesting_flag" );       pcVPS->setTemporalNestingFlag( uiCode ? true:false );
+#endif
+  for(UInt i = 0; i <= pcVPS->getMaxTLayers()-1; i++)
+  {
+    READ_UVLC( uiCode,  "vps_max_dec_pic_buffering[i]" );     pcVPS->setMaxDecPicBuffering( uiCode, i );
+    READ_UVLC( uiCode,  "vps_num_reorder_pics[i]" );          pcVPS->setNumReorderPics( uiCode, i );
+    READ_UVLC( uiCode,  "vps_max_latency_increase[i]" );      pcVPS->setMaxLatencyIncrease( uiCode, i );
+  }
+#if VPS_SYNTAX_CHANGES
+  READ_UVLC( uiCode,    "vps_num_hrd_parameters" );           assert(uiCode == 0);
+  // hrd_parameters
+#endif  
+  READ_FLAG( uiCode,  "vps_extension_flag" );          assert(!uiCode);
+  //future extensions go here..
+  
+  return;
+}
+
+Void TDecCavlc::parseSliceHeader (TComSlice*& rpcSlice, ParameterSetManagerDecoder *parameterSetManager)
+{
+  UInt  uiCode;
+  Int   iCode;
+
+#if ENC_DEC_TRACE
+  xTraceSliceHeader(rpcSlice);
+#endif
+  TComPPS* pps = NULL;
+  TComSPS* sps = NULL;
+
+  UInt firstSliceInPic;
+  READ_FLAG( firstSliceInPic, "first_slice_in_pic_flag" );
+#if SPLICING_FRIENDLY_PARAMS
+  if( rpcSlice->getRapPicFlag())
+  { 
+    READ_FLAG( uiCode, "no_output_of_prior_pics_flag" );  //ignored
+  }
+#endif
+  READ_UVLC (    uiCode, "pic_parameter_set_id" );  rpcSlice->setPPSId(uiCode);
+  pps = parameterSetManager->getPrefetchedPPS(uiCode);
+  //!KS: need to add error handling code here, if PPS is not available
+  assert(pps!=0);
+  sps = parameterSetManager->getPrefetchedSPS(pps->getSPSId());
+  //!KS: need to add error handling code here, if SPS is not available
+  assert(sps!=0);
+  rpcSlice->setSPS(sps);
+  rpcSlice->setPPS(pps);
+
+  Int numCUs = ((sps->getPicWidthInLumaSamples()+sps->getMaxCUWidth()-1)/sps->getMaxCUWidth())*((sps->getPicHeightInLumaSamples()+sps->getMaxCUHeight()-1)/sps->getMaxCUHeight());
+  Int maxParts = (1<<(sps->getMaxCUDepth()<<1));
+#if REMOVE_FGS
+  Int numParts = 0;
+#else
+  Int numParts = (1<<(pps->getSliceGranularity()<<1));
+#endif
+  UInt lCUAddress = 0;
+  Int reqBitsOuter = 0;
+  while(numCUs>(1<<reqBitsOuter))
+  {
+    reqBitsOuter++;
+  }
+  Int reqBitsInner = 0;
+  while((numParts)>(1<<reqBitsInner)) 
+  {
+    reqBitsInner++;
+  }
+
+  UInt innerAddress = 0;
+  Int  sliceAddress = 0;
+  if(!firstSliceInPic)
+  {
+    UInt address;
+    READ_CODE( reqBitsOuter+reqBitsInner, address, "slice_address" );
+    lCUAddress = address >> reqBitsInner;
+    innerAddress = address - (lCUAddress<<reqBitsInner);
+  }
+  //set uiCode to equal slice start address (or dependent slice start address)
+#if REMOVE_FGS
+  sliceAddress=(maxParts*lCUAddress)+(innerAddress);
+#else
+  sliceAddress=(maxParts*lCUAddress)+(innerAddress*(maxParts>>(pps->getSliceGranularity()<<1)));
+#endif
+  rpcSlice->setDependentSliceCurStartCUAddr( sliceAddress );
+  rpcSlice->setDependentSliceCurEndCUAddr(numCUs*maxParts);
+
+#if SLICEHEADER_SYNTAX_FIX
+  if( pps->getDependentSliceEnabledFlag() && (sliceAddress !=0 ))
+  {
+    READ_FLAG( uiCode, "dependent_slice_flag" );       rpcSlice->setDependentSliceFlag(uiCode ? true : false);
+  }
+  else
+  {
+    rpcSlice->setDependentSliceFlag(false);
+  }
+
+  if (rpcSlice->getDependentSliceFlag())
+  {
+    rpcSlice->setNextSlice          ( false );
+    rpcSlice->setNextDependentSlice ( true  );
+  }
+  else
+  {
+    rpcSlice->setNextSlice          ( true  );
+    rpcSlice->setNextDependentSlice ( false );
+
+    rpcSlice->setSliceCurStartCUAddr(sliceAddress);
+    rpcSlice->setSliceCurEndCUAddr(numCUs*maxParts);
+  }
+  
+  if(!rpcSlice->getDependentSliceFlag())
+  {
+#endif
+    READ_UVLC (    uiCode, "slice_type" );            rpcSlice->setSliceType((SliceType)uiCode);
+#if !SLICEHEADER_SYNTAX_FIX
+    // lightweight_slice_flag
+    READ_FLAG( uiCode, "dependent_slice_flag" );
+    Bool bDependentSlice = uiCode ? true : false;
+#if DEPENDENT_SLICES
+    if( rpcSlice->getPPS()->getDependentSliceEnabledFlag())
+    {
+      if(bDependentSlice)
+      {
+        rpcSlice->setNextSlice        ( false );
+        rpcSlice->setNextDependentSlice( true  );
+#if BYTE_ALIGNMENT
+        m_pcBitstream->readByteAlignment();
+#else
+        m_pcBitstream->readOutTrailingBits();
+#endif
+        return;
+      }
+    }
+#endif
+  if (bDependentSlice)
+  {
+    rpcSlice->setNextSlice        ( false );
+    rpcSlice->setNextDependentSlice ( true  );
+  }
+  else
+  {
+    rpcSlice->setNextSlice        ( true  );
+    rpcSlice->setNextDependentSlice ( false );
+
+    rpcSlice->setSliceCurStartCUAddr(sliceAddress);
+    rpcSlice->setSliceCurEndCUAddr(numCUs*maxParts);
+  }
+
+  if (!bDependentSlice)
+  {
+#endif // !SLICEHEADER_SYNTAX_FIX
+    if( pps->getOutputFlagPresentFlag() )
+    {
+      READ_FLAG( uiCode, "pic_output_flag" );    rpcSlice->setPicOutputFlag( uiCode ? true : false );
+    }
+    else
+    {
+      rpcSlice->setPicOutputFlag( true );
+    }
+    // in the first version chroma_format_idc is equal to one, thus colour_plane_id will not be present
+    assert (sps->getChromaFormatIdc() == 1 );
+    // if( separate_colour_plane_flag  ==  1 )
+    //   colour_plane_id                                      u(2)
+
+#if !SPLICING_FRIENDLY_PARAMS
+    if(   rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR
+#if SUPPORT_FOR_RAP_N_LP
+      || rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP
+      || rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP
+#endif
+      || rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLANT
+      || rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA
+#if !NAL_UNIT_TYPES_J1003_D7
+      || rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRANT
+#endif
+      || rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA )
+    { 
+      READ_UVLC( uiCode, "rap_pic_id" );  //ignored
+      READ_FLAG( uiCode, "no_output_of_prior_pics_flag" );  //ignored
+    }
+#endif
+#if SUPPORT_FOR_RAP_N_LP
+    if( rpcSlice->getIdrPicFlag() )
+#else
+    if( rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR )
+#endif
+    {
+      rpcSlice->setPOC(0);
+      TComReferencePictureSet* rps = rpcSlice->getLocalRPS();
+      rps->setNumberOfNegativePictures(0);
+      rps->setNumberOfPositivePictures(0);
+      rps->setNumberOfLongtermPictures(0);
+      rps->setNumberOfPictures(0);
+      rpcSlice->setRPS(rps);
+    }
+    else
+    {
+      READ_CODE(sps->getBitsForPOC(), uiCode, "pic_order_cnt_lsb");  
+      Int iPOClsb = uiCode;
+      Int iPrevPOC = rpcSlice->getPrevPOC();
+      Int iMaxPOClsb = 1<< sps->getBitsForPOC();
+      Int iPrevPOClsb = iPrevPOC%iMaxPOClsb;
+      Int iPrevPOCmsb = iPrevPOC-iPrevPOClsb;
+      Int iPOCmsb;
+      if( ( iPOClsb  <  iPrevPOClsb ) && ( ( iPrevPOClsb - iPOClsb )  >=  ( iMaxPOClsb / 2 ) ) )
+      {
+        iPOCmsb = iPrevPOCmsb + iMaxPOClsb;
+      }
+      else if( (iPOClsb  >  iPrevPOClsb )  && ( (iPOClsb - iPrevPOClsb )  >  ( iMaxPOClsb / 2 ) ) ) 
+      {
+        iPOCmsb = iPrevPOCmsb - iMaxPOClsb;
+      }
+      else
+      {
+        iPOCmsb = iPrevPOCmsb;
+      }
+#if SUPPORT_FOR_RAP_N_LP
+      if ( rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA
+        || rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLANT
+        || rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP )
+#else
+      if(   rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA
+        || rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLANT )
+#endif
+      {
+        // For BLA picture types, POCmsb is set to 0.
+        iPOCmsb = 0;
+      }
+      rpcSlice->setPOC              (iPOCmsb+iPOClsb);
+
+      TComReferencePictureSet* rps;
+      READ_FLAG( uiCode, "short_term_ref_pic_set_sps_flag" );
+      if(uiCode == 0) // use short-term reference picture set explicitly signalled in slice header
+      {
+        rps = rpcSlice->getLocalRPS();
+        parseShortTermRefPicSet(sps,rps, sps->getRPSList()->getNumberOfReferencePictureSets());
+        rpcSlice->setRPS(rps);
+      }
+      else // use reference to short-term reference picture set in PPS
+      {
+        READ_UVLC( uiCode, "short_term_ref_pic_set_idx"); rpcSlice->setRPS(sps->getRPSList()->getReferencePictureSet(uiCode));
+        rps = rpcSlice->getRPS();
+      }
+      if(sps->getLongTermRefsPresent())
+      {
+        Int offset = rps->getNumberOfNegativePictures()+rps->getNumberOfPositivePictures();
+#if LTRP_IN_SPS
+        UInt numOfLtrp = 0;
+        UInt numLtrpInSPS = 0;
+        if (rpcSlice->getSPS()->getNumLongTermRefPicSPS() > 0)
+        {
+          READ_UVLC( uiCode, "num_long_term_sps");
+          numLtrpInSPS = uiCode;
+          numOfLtrp += numLtrpInSPS;
+          rps->setNumberOfLongtermPictures(numOfLtrp);
+        }
+        Int bitsForLtrpInSPS = 1;
+        while (rpcSlice->getSPS()->getNumLongTermRefPicSPS() > (1 << bitsForLtrpInSPS))
+          bitsForLtrpInSPS++;
+        READ_UVLC( uiCode, "num_long_term_pics");             rps->setNumberOfLongtermPictures(uiCode);
+        numOfLtrp += uiCode;
+        rps->setNumberOfLongtermPictures(numOfLtrp);
+#else
+        READ_UVLC( uiCode, "num_long_term_pics");             rps->setNumberOfLongtermPictures(uiCode);
+#endif
+        Int maxPicOrderCntLSB = 1 << rpcSlice->getSPS()->getBitsForPOC();
+        Int prevLSB = 0, prevDeltaMSB = 0, deltaPocMSBCycleLT = 0;;
+#if LTRP_IN_SPS
+        for(Int j=offset+rps->getNumberOfLongtermPictures()-1, k = 0; k < numOfLtrp; j--, k++)
+#else
+        for(Int j=offset+rps->getNumberOfLongtermPictures()-1 ; j > offset-1; j--)
+#endif
+        {
+#if LTRP_IN_SPS
+          if (k < numLtrpInSPS)
+          {
+            READ_CODE(bitsForLtrpInSPS, uiCode, "lt_idx_sps[i]");
+            Int usedByCurrFromSPS=rpcSlice->getSPS()->getUsedByCurrPicLtSPSFlag(uiCode);
+
+            uiCode = rpcSlice->getSPS()->getLtRefPicPocLsbSps(uiCode);
+            rps->setUsed(j,usedByCurrFromSPS);
+          }
+          else
+          {
+            READ_CODE(rpcSlice->getSPS()->getBitsForPOC(), uiCode, "poc_lsb_lt"); 
+            READ_FLAG( uiCode, "used_by_curr_pic_lt_flag");     rps->setUsed(j,uiCode);
+          }
+#else
+          READ_CODE(rpcSlice->getSPS()->getBitsForPOC(), uiCode, "poc_lsb_lt"); 
+#endif
+          Int poc_lsb_lt = uiCode;
+          READ_FLAG(uiCode,"delta_poc_msb_present_flag");
+          Bool mSBPresentFlag = uiCode ? true : false;
+          if(mSBPresentFlag)                  
+          {
+            READ_UVLC( uiCode, "delta_poc_msb_cycle_lt[i]" );
+            Bool deltaFlag = false;
+#if LTRP_IN_SPS
+            //            First LTRP                               || First LTRP from SH           || curr LSB    != prev LSB
+            if( (j == offset+rps->getNumberOfLongtermPictures()-1) || (j == offset+(numOfLtrp-numLtrpInSPS)-1) || (poc_lsb_lt != prevLSB) )
+#else
+            //            First LTRP                               || curr LSB    != prev LSB
+            if( (j == offset+rps->getNumberOfLongtermPictures()-1) || (poc_lsb_lt != prevLSB) )
+#endif
+            {
+              deltaFlag = true;
+            }
+            if(deltaFlag)
+            {
+              deltaPocMSBCycleLT = uiCode;
+            }
+            else
+            {
+              deltaPocMSBCycleLT = uiCode + prevDeltaMSB;              
+            }
+
+            Int pocLTCurr = rpcSlice->getPOC() - deltaPocMSBCycleLT * maxPicOrderCntLSB 
+                                        - iPOClsb + poc_lsb_lt;                                      
+            rps->setPOC     (j, pocLTCurr); 
+            rps->setDeltaPOC(j, - rpcSlice->getPOC() + pocLTCurr);
+            rps->setCheckLTMSBPresent(j,true);  
+          }
+          else
+          {
+            rps->setPOC     (j, poc_lsb_lt);
+            rps->setDeltaPOC(j, - rpcSlice->getPOC() + poc_lsb_lt);
+            rps->setCheckLTMSBPresent(j,false);  
+          }
+#if !LTRP_IN_SPS
+        READ_FLAG( uiCode, "used_by_curr_pic_lt_flag");     rps->setUsed(j,uiCode);
+#endif
+          prevLSB = poc_lsb_lt;
+          prevDeltaMSB = deltaPocMSBCycleLT;
+        }
+        offset += rps->getNumberOfLongtermPictures();
+        rps->setNumberOfPictures(offset);        
+      }  
+#if SUPPORT_FOR_RAP_N_LP
+      if ( rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA
+        || rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLANT
+        || rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP )
+#else
+      if(   rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA
+        || rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLANT )
+#endif
+      {
+        // In the case of BLA picture types, rps data is read from slice header but ignored
+        rps = rpcSlice->getLocalRPS();
+        rps->setNumberOfNegativePictures(0);
+        rps->setNumberOfPositivePictures(0);
+        rps->setNumberOfLongtermPictures(0);
+        rps->setNumberOfPictures(0);
+        rpcSlice->setRPS(rps);
+      }
+    }
+#if REMOVE_ALF
+    if(sps->getUseSAO())
+#else
+    if(sps->getUseSAO() || sps->getUseALF())
+#endif
+    {
+      if (sps->getUseSAO())
+      {
+        READ_FLAG(uiCode, "slice_sao_luma_flag");  rpcSlice->setSaoEnabledFlag((Bool)uiCode);
+#if !SAO_LUM_CHROMA_ONOFF_FLAGS
+        if (rpcSlice->getSaoEnabledFlag() )
+#endif
+        {
+#if SAO_TYPE_SHARING 
+          READ_FLAG(uiCode, "slice_sao_chroma_flag");  rpcSlice->setSaoEnabledFlagChroma((Bool)uiCode);
+#else
+          READ_FLAG(uiCode, "sao_cb_enable_flag");  rpcSlice->setSaoEnabledFlagCb((Bool)uiCode);
+          READ_FLAG(uiCode, "sao_cr_enable_flag");  rpcSlice->setSaoEnabledFlagCr((Bool)uiCode);
+#endif
+        }
+#if !SAO_LUM_CHROMA_ONOFF_FLAGS
+        else
+        {
+#if SAO_TYPE_SHARING
+          rpcSlice->setSaoEnabledFlagChroma(0);
+#else
+          rpcSlice->setSaoEnabledFlagCb(0);
+          rpcSlice->setSaoEnabledFlagCr(0);
+#endif
+        }
+#endif
+      }
+#if !REMOVE_APS
+      READ_UVLC (    uiCode, "aps_id" );  rpcSlice->setAPSId(uiCode);
+#endif
+    }
+    if (!rpcSlice->isIntra())
+    {
+      if (rpcSlice->getSPS()->getTMVPFlagsPresent())
+      {
+        READ_FLAG( uiCode, "enable_temporal_mvp_flag" );
+        rpcSlice->setEnableTMVPFlag(uiCode); 
+      }
+      else
+      {
+        rpcSlice->setEnableTMVPFlag(false);
+      }
+      READ_FLAG( uiCode, "num_ref_idx_active_override_flag");
+      if (uiCode)
+      {
+        READ_UVLC (uiCode, "num_ref_idx_l0_active_minus1" );  rpcSlice->setNumRefIdx( REF_PIC_LIST_0, uiCode + 1 );
+        if (rpcSlice->isInterB())
+        {
+          READ_UVLC (uiCode, "num_ref_idx_l1_active_minus1" );  rpcSlice->setNumRefIdx( REF_PIC_LIST_1, uiCode + 1 );
+        }
+        else
+        {
+          rpcSlice->setNumRefIdx(REF_PIC_LIST_1, 0);
+        }
+      }
+      else
+      {
+        rpcSlice->setNumRefIdx(REF_PIC_LIST_0, rpcSlice->getPPS()->getNumRefIdxL0DefaultActive());
+        if (rpcSlice->isInterB())
+        {
+          rpcSlice->setNumRefIdx(REF_PIC_LIST_1, rpcSlice->getPPS()->getNumRefIdxL1DefaultActive());
+        }
+        else
+        {
+          rpcSlice->setNumRefIdx(REF_PIC_LIST_1,0);
+        }
+      }
+    }
+    // }
+    TComRefPicListModification* refPicListModification = rpcSlice->getRefPicListModification();
+    if(!rpcSlice->isIntra())
+    {
+      if( !rpcSlice->getSPS()->getListsModificationPresentFlag() )
+      {
+        refPicListModification->setRefPicListModificationFlagL0( 0 );
+      }
+      else
+      {
+        READ_FLAG( uiCode, "ref_pic_list_modification_flag_l0" ); refPicListModification->setRefPicListModificationFlagL0( uiCode ? 1 : 0 );
+      }
+
+      if(refPicListModification->getRefPicListModificationFlagL0())
+      {
+        uiCode = 0;
+        Int i = 0;
+        Int numRpsCurrTempList0 = rpcSlice->getNumRpsCurrTempList();
+        if ( numRpsCurrTempList0 > 1 )
+        {
+          Int length = 1;
+          numRpsCurrTempList0 --;
+          while ( numRpsCurrTempList0 >>= 1) 
+          {
+            length ++;
+          }
+          for (i = 0; i < rpcSlice->getNumRefIdx(REF_PIC_LIST_0); i ++)
+          {
+            READ_CODE( length, uiCode, "list_entry_l0" );
+            refPicListModification->setRefPicSetIdxL0(i, uiCode );
+          }
+        }
+        else
+        {
+          for (i = 0; i < rpcSlice->getNumRefIdx(REF_PIC_LIST_0); i ++)
+          {
+            refPicListModification->setRefPicSetIdxL0(i, 0 );
+          }
+        }
+      }
+    }
+    else
+    {
+      refPicListModification->setRefPicListModificationFlagL0(0);
+    }
+    if(rpcSlice->isInterB())
+    {
+      if( !rpcSlice->getSPS()->getListsModificationPresentFlag() )
+      {
+        refPicListModification->setRefPicListModificationFlagL1( 0 );
+      }
+      else
+      {
+        READ_FLAG( uiCode, "ref_pic_list_modification_flag_l1" ); refPicListModification->setRefPicListModificationFlagL1( uiCode ? 1 : 0 );
+      }
+      if(refPicListModification->getRefPicListModificationFlagL1())
+      {
+        uiCode = 0;
+        Int i = 0;
+        Int numRpsCurrTempList1 = rpcSlice->getNumRpsCurrTempList();
+        if ( numRpsCurrTempList1 > 1 )
+        {
+          Int length = 1;
+          numRpsCurrTempList1 --;
+          while ( numRpsCurrTempList1 >>= 1) 
+          {
+            length ++;
+          }
+          for (i = 0; i < rpcSlice->getNumRefIdx(REF_PIC_LIST_1); i ++)
+          {
+            READ_CODE( length, uiCode, "list_entry_l1" );
+            refPicListModification->setRefPicSetIdxL1(i, uiCode );
+          }
+        }
+        else
+        {
+          for (i = 0; i < rpcSlice->getNumRefIdx(REF_PIC_LIST_1); i ++)
+          {
+            refPicListModification->setRefPicSetIdxL1(i, 0 );
+          }
+        }
+      }
+    }  
+    else
+    {
+      refPicListModification->setRefPicListModificationFlagL1(0);
+    }
+#if !SLICEHEADER_SYNTAX_FIX
+  }
+  else
+  {
+    // initialize from previous slice
+    pps = rpcSlice->getPPS();
+    sps = rpcSlice->getSPS();
+  }
+#endif
+    if (rpcSlice->isInterB())
+    {
+      READ_FLAG( uiCode, "mvd_l1_zero_flag" );       rpcSlice->setMvdL1ZeroFlag( (uiCode ? true : false) );
+    }
+
+    rpcSlice->setCabacInitFlag( false ); // default
+    if(pps->getCabacInitPresentFlag() && !rpcSlice->isIntra())
+    {
+      READ_FLAG(uiCode, "cabac_init_flag");
+      rpcSlice->setCabacInitFlag( uiCode ? true : false );
+    }
+
+#if !SLICEHEADER_SYNTAX_FIX
+  if(!bDependentSlice)
+  {
+#else
+    if ( rpcSlice->getEnableTMVPFlag() )
+    {
+      if ( rpcSlice->getSliceType() == B_SLICE )
+      {
+        READ_FLAG( uiCode, "collocated_from_l0_flag" );
+        rpcSlice->setColFromL0Flag(uiCode);
+      }
+      else
+      {
+        rpcSlice->setColFromL0Flag( 1 );
+      }
+
+      if ( rpcSlice->getSliceType() != I_SLICE &&
+        ((rpcSlice->getColFromL0Flag()==1 && rpcSlice->getNumRefIdx(REF_PIC_LIST_0)>1)||
+        (rpcSlice->getColFromL0Flag() ==0 && rpcSlice->getNumRefIdx(REF_PIC_LIST_1)>1)))
+      {
+        READ_UVLC( uiCode, "collocated_ref_idx" );
+        rpcSlice->setColRefIdx(uiCode);
+      }
+      else
+      {
+        rpcSlice->setColRefIdx(0);
+      }
+    }
+    if ( (pps->getUseWP() && rpcSlice->getSliceType()==P_SLICE) || (pps->getWPBiPred() && rpcSlice->getSliceType()==B_SLICE) )
+    {
+      xParsePredWeightTable(rpcSlice);
+      rpcSlice->initWpScaling();
+    }
+    READ_UVLC( uiCode, "five_minus_max_num_merge_cand");
+    rpcSlice->setMaxNumMergeCand(MRG_MAX_NUM_CANDS - uiCode);
+
+#endif
+    READ_SVLC( iCode, "slice_qp_delta" ); 
+    rpcSlice->setSliceQp (26 + pps->getPicInitQPMinus26() + iCode);
+
+    assert( rpcSlice->getSliceQp() >= -sps->getQpBDOffsetY() );
+    assert( rpcSlice->getSliceQp() <=  51 );
+
+#if CHROMA_QP_EXTENSION
+    if (rpcSlice->getPPS()->getSliceChromaQpFlag())
+    {
+      READ_SVLC( iCode, "slice_qp_delta_cb" );
+      rpcSlice->setSliceQpDeltaCb( iCode );
+      assert( rpcSlice->getSliceQpDeltaCb() >= -12 );
+      assert( rpcSlice->getSliceQpDeltaCb() <=  12 );
+      assert( (rpcSlice->getPPS()->getChromaCbQpOffset() + rpcSlice->getSliceQpDeltaCb()) >= -12 );
+      assert( (rpcSlice->getPPS()->getChromaCbQpOffset() + rpcSlice->getSliceQpDeltaCb()) <=  12 );
+
+      READ_SVLC( iCode, "slice_qp_delta_cr" );
+      rpcSlice->setSliceQpDeltaCr( iCode );
+      assert( rpcSlice->getSliceQpDeltaCr() >= -12 );
+      assert( rpcSlice->getSliceQpDeltaCr() <=  12 );
+      assert( (rpcSlice->getPPS()->getChromaCrQpOffset() + rpcSlice->getSliceQpDeltaCr()) >= -12 );
+      assert( (rpcSlice->getPPS()->getChromaCrQpOffset() + rpcSlice->getSliceQpDeltaCr()) <=  12 );
+    }
+#endif
+
+    if (rpcSlice->getPPS()->getDeblockingFilterControlPresentFlag())
+    {
+      if(rpcSlice->getPPS()->getDeblockingFilterOverrideEnabledFlag())
+      {
+        READ_FLAG ( uiCode, "deblocking_filter_override_flag" );        rpcSlice->setDeblockingFilterOverrideFlag(uiCode ? true : false);
+      }
+      else
+      {  
+        rpcSlice->setDeblockingFilterOverrideFlag(0);
+      }
+      if(rpcSlice->getDeblockingFilterOverrideFlag())
+      {
+        READ_FLAG ( uiCode, "slice_disable_deblocking_filter_flag" );   rpcSlice->setDeblockingFilterDisable(uiCode ? 1 : 0);
+        if(!rpcSlice->getDeblockingFilterDisable())
+        {
+          READ_SVLC( iCode, "beta_offset_div2" );                       rpcSlice->setDeblockingFilterBetaOffsetDiv2(iCode);
+          READ_SVLC( iCode, "tc_offset_div2" );                         rpcSlice->setDeblockingFilterTcOffsetDiv2(iCode);
+        }
+      }
+      else
+      {
+        rpcSlice->setDeblockingFilterDisable   ( rpcSlice->getPPS()->getPicDisableDeblockingFilterFlag() );
+        rpcSlice->setDeblockingFilterBetaOffsetDiv2( rpcSlice->getPPS()->getDeblockingFilterBetaOffsetDiv2() );
+        rpcSlice->setDeblockingFilterTcOffsetDiv2  ( rpcSlice->getPPS()->getDeblockingFilterTcOffsetDiv2() );
+      }
+    }
+#if !SLICEHEADER_SYNTAX_FIX
+    if ( rpcSlice->getEnableTMVPFlag() )
+    {
+      if ( rpcSlice->getSliceType() == B_SLICE )
+      {
+        READ_FLAG( uiCode, "collocated_from_l0_flag" );
+        rpcSlice->setColFromL0Flag(uiCode);
+      }
+
+      if ( rpcSlice->getSliceType() != I_SLICE &&
+        ((rpcSlice->getColFromL0Flag()==1 && rpcSlice->getNumRefIdx(REF_PIC_LIST_0)>1)||
+        (rpcSlice->getColFromL0Flag() ==0 && rpcSlice->getNumRefIdx(REF_PIC_LIST_1)>1)))
+      {
+        READ_UVLC( uiCode, "collocated_ref_idx" );
+        rpcSlice->setColRefIdx(uiCode);
+      }
+      else
+      {
+        rpcSlice->setColRefIdx(0);
+      }
+    }
+    if ( (pps->getUseWP() && rpcSlice->getSliceType()==P_SLICE) || (pps->getWPBiPred() && rpcSlice->getSliceType()==B_SLICE) )
+    {
+      xParsePredWeightTable(rpcSlice);
+      rpcSlice->initWpScaling();
+    }
+  }
+
+    READ_UVLC( uiCode, "five_minus_max_num_merge_cand");
+    rpcSlice->setMaxNumMergeCand(MRG_MAX_NUM_CANDS - uiCode);
+
+  if (!bDependentSlice)
+  {
+#endif
+#if !REMOVE_ALF
+    if(sps->getUseALF())
+    {
+      char syntaxString[50];
+      for(Int compIdx=0; compIdx< 3; compIdx++)
+      {
+        sprintf(syntaxString, "alf_slice_filter_flag[%d]", compIdx);
+        READ_FLAG(uiCode, syntaxString);
+        rpcSlice->setAlfEnabledFlag( (uiCode ==1), compIdx);
+      }
+    }
+    Bool isAlfEnabled = (!rpcSlice->getSPS()->getUseALF())?(false):(rpcSlice->getAlfEnabledFlag(0)||rpcSlice->getAlfEnabledFlag(1)||rpcSlice->getAlfEnabledFlag(2));
+#endif
+#if !SAO_LUM_CHROMA_ONOFF_FLAGS
+    Bool isSAOEnabled = (!rpcSlice->getSPS()->getUseSAO())?(false):(rpcSlice->getSaoEnabledFlag());
+#else
+    Bool isSAOEnabled = (!rpcSlice->getSPS()->getUseSAO())?(false):(rpcSlice->getSaoEnabledFlag()||rpcSlice->getSaoEnabledFlagChroma());
+#endif
+    Bool isDBFEnabled = (!rpcSlice->getDeblockingFilterDisable());
+
+#if REMOVE_ALF
+#if MOVE_LOOP_FILTER_SLICES_FLAG
+    if(rpcSlice->getPPS()->getLoopFilterAcrossSlicesEnabledFlag() && ( isSAOEnabled || isDBFEnabled ))
+#else
+    if(rpcSlice->getSPS()->getLFCrossSliceBoundaryFlag() && ( isSAOEnabled || isDBFEnabled ))
+#endif
+#else
+    if(rpcSlice->getSPS()->getLFCrossSliceBoundaryFlag() && ( isAlfEnabled || isSAOEnabled || isDBFEnabled ))
+#endif
+    {
+      READ_FLAG( uiCode, "slice_loop_filter_across_slices_enabled_flag");
+    }
+    else
+    {
+#if MOVE_LOOP_FILTER_SLICES_FLAG
+      uiCode = rpcSlice->getPPS()->getLoopFilterAcrossSlicesEnabledFlag()?1:0;
+#else
+      uiCode = rpcSlice->getSPS()->getLFCrossSliceBoundaryFlag()?1:0;
+#endif
+    }
+    rpcSlice->setLFCrossSliceBoundaryFlag( (uiCode==1)?true:false);
+
+#if !SLICEHEADER_SYNTAX_FIX
+  }
+#else
+  }
+    if( pps->getTilesEnabledFlag() || pps->getEntropyCodingSyncEnabledFlag() )
+#endif
+    {
+#if !SLICEHEADER_SYNTAX_FIX
+      Int tilesOrEntropyCodingSyncIdc = pps->getTilesOrEntropyCodingSyncIdc();
+#endif
+      UInt *entryPointOffset          = NULL;
+      UInt numEntryPointOffsets, offsetLenMinus1;
+
+#if !SLICEHEADER_SYNTAX_FIX
+      rpcSlice->setNumEntryPointOffsets ( 0 ); // default
+
+      if (tilesOrEntropyCodingSyncIdc>0)
+      {
+#endif
+      READ_UVLC(numEntryPointOffsets, "num_entry_point_offsets"); rpcSlice->setNumEntryPointOffsets ( numEntryPointOffsets );
+      if (numEntryPointOffsets>0)
+      {
+        READ_UVLC(offsetLenMinus1, "offset_len_minus1");
+      }
+      entryPointOffset = new UInt[numEntryPointOffsets];
+      for (UInt idx=0; idx<numEntryPointOffsets; idx++)
+      {
+        READ_CODE(offsetLenMinus1+1, uiCode, "entry_point_offset");
+        entryPointOffset[ idx ] = uiCode;
+      }
+#if !SLICEHEADER_SYNTAX_FIX
+      }
+#endif
+
+#if !SLICEHEADER_SYNTAX_FIX
+      if ( tilesOrEntropyCodingSyncIdc == 1 ) // tiles
+#else
+      if ( pps->getTilesEnabledFlag() )
+#endif
+      {
+        rpcSlice->setTileLocationCount( numEntryPointOffsets );
+
+        UInt prevPos = 0;
+        for (Int idx=0; idx<rpcSlice->getTileLocationCount(); idx++)
+        {
+          rpcSlice->setTileLocation( idx, prevPos + entryPointOffset [ idx ] );
+          prevPos += entryPointOffset[ idx ];
+        }
+      }
+#if !SLICEHEADER_SYNTAX_FIX
+      else if ( tilesOrEntropyCodingSyncIdc == 2 ) // wavefront
+#else
+      else if ( pps->getEntropyCodingSyncEnabledFlag() )
+#endif
+      {
+      Int numSubstreams = rpcSlice->getNumEntryPointOffsets()+1;
+        rpcSlice->allocSubstreamSizes(numSubstreams);
+        UInt *pSubstreamSizes       = rpcSlice->getSubstreamSizes();
+        for (Int idx=0; idx<numSubstreams-1; idx++)
+        {
+          if ( idx < numEntryPointOffsets )
+          {
+            pSubstreamSizes[ idx ] = ( entryPointOffset[ idx ] << 3 ) ;
+          }
+          else
+          {
+            pSubstreamSizes[ idx ] = 0;
+          }
+        }
+      }
+
+      if (entryPointOffset)
+      {
+        delete [] entryPointOffset;
+      }
+    }
+#if SLICEHEADER_SYNTAX_FIX
+    else
+    {
+      rpcSlice->setNumEntryPointOffsets ( 0 );
+    }
+#endif
+
+#if SLICE_HEADER_EXTENSION
+  if(pps->getSliceHeaderExtensionPresentFlag())
+  {
+    READ_UVLC(uiCode,"slice_header_extension_length");
+    for(Int i=0; i<uiCode; i++)
+    {
+      UInt ignore;
+      READ_CODE(8,ignore,"slice_header_extension_data_byte");
+    }
+  }
+#endif
+#if BYTE_ALIGNMENT
+  m_pcBitstream->readByteAlignment();
+#else
+  if (!bDependentSlice)
+  {
+    // Reading location information
+    // read out trailing bits
+    m_pcBitstream->readOutTrailingBits();
+  }
+#endif
+  return;
+}
+  
+#if PROFILE_TIER_LEVEL_SYNTAX
+Void TDecCavlc::parsePTL( TComPTL *rpcPTL, Bool profilePresentFlag, Int maxNumSubLayersMinus1 )
+{
+  UInt uiCode;
+  if(profilePresentFlag)
+  {
+    parseProfileTier(rpcPTL->getGeneralPTL());
+  }
+  READ_CODE( 8, uiCode, "general_level_idc" );    rpcPTL->getGeneralPTL()->setLevelIdc(uiCode);
+
+  for(Int i = 0; i < maxNumSubLayersMinus1; i++)
+  {
+    READ_FLAG( uiCode, "sub_layer_profile_present_flag[i]" ); rpcPTL->setSubLayerProfilePresentFlag(i, uiCode);
+    READ_FLAG( uiCode, "sub_layer_level_present_flag[i]"   ); rpcPTL->setSubLayerLevelPresentFlag  (i, uiCode);
+    if( profilePresentFlag && rpcPTL->getSubLayerProfilePresentFlag(i) )
+    {
+      parseProfileTier(rpcPTL->getSubLayerPTL(i));
+    }
+    if(rpcPTL->getSubLayerLevelPresentFlag(i))
+    {
+      READ_CODE( 8, uiCode, "sub_layer_level_idc[i]" );   rpcPTL->getSubLayerPTL(i)->setLevelIdc(uiCode);
+    }
+  }
+}
+Void TDecCavlc::parseProfileTier(ProfileTierLevel *ptl)
+{
+  UInt uiCode;
+  READ_CODE(2 , uiCode, "XXX_profile_space[]");   ptl->setProfileSpace(uiCode);
+  READ_FLAG(    uiCode, "XXX_tier_flag[]"    );   ptl->setTierFlag    (uiCode ? 1 : 0);
+  READ_CODE(5 , uiCode, "XXX_profile_idc[]"  );   ptl->setProfileIdc  (uiCode);
+  for(Int j = 0; j < 32; j++)
+  {
+    READ_FLAG(  uiCode, "XXX_profile_compatibility_flag[][j]");   ptl->setProfileCompatibilityFlag(j, uiCode ? 1 : 0);
+  }
+  READ_CODE(16, uiCode, "XXX_reserved_zero_16bits[]");  assert( uiCode == 0 );  
+}
+#endif
+Void TDecCavlc::parseTerminatingBit( UInt& ruiBit )
+{
+  ruiBit = false;
+  Int iBitsLeft = m_pcBitstream->getNumBitsLeft();
+  if(iBitsLeft <= 8)
+  {
+    UInt uiPeekValue = m_pcBitstream->peekBits(iBitsLeft);
+    if (uiPeekValue == (1<<(iBitsLeft-1)))
+    {
+      ruiBit = true;
+    }
+  }
+}
+
+Void TDecCavlc::parseSkipFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert(0);
+}
+
+#if INTRA_BL
+Void TDecCavlc::parseIntraBLFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+  assert(0);
+}
+#endif
+
+Void TDecCavlc::parseMVPIdx( Int& riMVPIdx )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseSplitFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parsePartSize( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parsePredMode( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert(0);
+}
+
+/** Parse I_PCM information. 
+* \param pcCU pointer to CU
+* \param uiAbsPartIdx CU index
+* \param uiDepth CU depth
+* \returns Void
+*
+* If I_PCM flag indicates that the CU is I_PCM, parse its PCM alignment bits and codes.  
+*/
+Void TDecCavlc::parseIPCMInfo( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseIntraDirLumaAng  ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{ 
+  assert(0);
+}
+
+Void TDecCavlc::parseIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseInterDir( TComDataCU* pcCU, UInt& ruiInterDir, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseRefFrmIdx( TComDataCU* pcCU, Int& riRefFrmIdx, UInt uiAbsPartIdx, UInt uiDepth, RefPicList eRefList )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseMvd( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth, RefPicList eRefList )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseDeltaQP( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  Int qp;
+  Int  iDQp;
+
+  xReadSvlc( iDQp );
+
+  Int qpBdOffsetY = pcCU->getSlice()->getSPS()->getQpBDOffsetY();
+  qp = (((Int) pcCU->getRefQP( uiAbsPartIdx ) + iDQp + 52 + 2*qpBdOffsetY )%(52+ qpBdOffsetY)) -  qpBdOffsetY;
+
+  UInt uiAbsQpCUPartIdx = (uiAbsPartIdx>>((g_uiMaxCUDepth - pcCU->getSlice()->getPPS()->getMaxCuDQPDepth())<<1))<<((g_uiMaxCUDepth - pcCU->getSlice()->getPPS()->getMaxCuDQPDepth())<<1) ;
+  UInt uiQpCUDepth =   min(uiDepth,pcCU->getSlice()->getPPS()->getMaxCuDQPDepth()) ;
+
+  pcCU->setQPSubParts( qp, uiAbsQpCUPartIdx, uiQpCUDepth );
+}
+
+Void TDecCavlc::parseCoeffNxN( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseTransformSubdivFlag( UInt& ruiSubdivFlag, UInt uiLog2TransformBlockSize )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseQtCbf( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth, UInt uiDepth )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseQtRootCbf( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt& uiQtRootCbf )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseTransformSkipFlags (TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, UInt uiDepth, TextType eTType)
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseMergeFlag ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPUIdx )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseMergeIndex ( TComDataCU* pcCU, UInt& ruiMergeIndex, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert(0);
+}
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+
+/** Parse PCM alignment zero bits.
+* \returns Void
+*/
+Void TDecCavlc::xReadPCMAlignZero( )
+{
+  UInt uiNumberOfBits = m_pcBitstream->getNumBitsUntilByteAligned();
+
+  if(uiNumberOfBits)
+  {
+    UInt uiBits;
+    UInt uiSymbol;
+
+    for(uiBits = 0; uiBits < uiNumberOfBits; uiBits++)
+    {
+      xReadFlag( uiSymbol );
+
+      if(uiSymbol)
+      {
+        printf("\nWarning! pcm_align_zero include a non-zero value.\n");
+      }
+    }
+  }
+}
+
+Void TDecCavlc::xReadUnaryMaxSymbol( UInt& ruiSymbol, UInt uiMaxSymbol )
+{
+  if (uiMaxSymbol == 0)
+  {
+    ruiSymbol = 0;
+    return;
+  }
+
+  xReadFlag( ruiSymbol );
+
+  if (ruiSymbol == 0 || uiMaxSymbol == 1)
+  {
+    return;
+  }
+
+  UInt uiSymbol = 0;
+  UInt uiCont;
+
+  do
+  {
+    xReadFlag( uiCont );
+    uiSymbol++;
+  }
+  while( uiCont && (uiSymbol < uiMaxSymbol-1) );
+
+  if( uiCont && (uiSymbol == uiMaxSymbol-1) )
+  {
+    uiSymbol++;
+  }
+
+  ruiSymbol = uiSymbol;
+}
+
+Void TDecCavlc::xReadExGolombLevel( UInt& ruiSymbol )
+{
+  UInt uiSymbol ;
+  UInt uiCount = 0;
+  do
+  {
+    xReadFlag( uiSymbol );
+    uiCount++;
+  }
+  while( uiSymbol && (uiCount != 13));
+
+  ruiSymbol = uiCount-1;
+
+  if( uiSymbol )
+  {
+    xReadEpExGolomb( uiSymbol, 0 );
+    ruiSymbol += uiSymbol+1;
+  }
+
+  return;
+}
+
+Void TDecCavlc::xReadEpExGolomb( UInt& ruiSymbol, UInt uiCount )
+{
+  UInt uiSymbol = 0;
+  UInt uiBit = 1;
+
+
+  while( uiBit )
+  {
+    xReadFlag( uiBit );
+    uiSymbol += uiBit << uiCount++;
+  }
+
+  uiCount--;
+  while( uiCount-- )
+  {
+    xReadFlag( uiBit );
+    uiSymbol += uiBit << uiCount;
+  }
+
+  ruiSymbol = uiSymbol;
+
+  return;
+}
+
+UInt TDecCavlc::xGetBit()
+{
+  UInt ruiCode;
+  m_pcBitstream->read( 1, ruiCode );
+  return ruiCode;
+}
+
+
+/** parse explicit wp tables
+* \param TComSlice* pcSlice
+* \returns Void
+*/
+Void TDecCavlc::xParsePredWeightTable( TComSlice* pcSlice )
+{
+  wpScalingParam  *wp;
+  Bool            bChroma     = true; // color always present in HEVC ?
+  TComPPS*        pps         = pcSlice->getPPS();
+  SliceType       eSliceType  = pcSlice->getSliceType();
+  Int             iNbRef       = (eSliceType == B_SLICE ) ? (2) : (1);
+  UInt            uiLog2WeightDenomLuma, uiLog2WeightDenomChroma;
+  UInt            uiMode      = 0;
+#if NUM_WP_LIMIT
+  UInt            uiTotalSignalledWeightFlags = 0;
+#endif
+  if ( (eSliceType==P_SLICE && pps->getUseWP()) || (eSliceType==B_SLICE && pps->getWPBiPred()) )
+  {
+    uiMode = 1; // explicit
+  }
+  if ( uiMode == 1 )  // explicit
+  {
+    printf("\nTDecCavlc::xParsePredWeightTable(poc=%d) explicit...\n", pcSlice->getPOC());
+    Int iDeltaDenom;
+    // decode delta_luma_log2_weight_denom :
+    READ_UVLC( uiLog2WeightDenomLuma, "luma_log2_weight_denom" );     // ue(v): luma_log2_weight_denom
+    if( bChroma ) 
+    {
+      READ_SVLC( iDeltaDenom, "delta_chroma_log2_weight_denom" );     // se(v): delta_chroma_log2_weight_denom
+      assert((iDeltaDenom + (Int)uiLog2WeightDenomLuma)>=0);
+      uiLog2WeightDenomChroma = (UInt)(iDeltaDenom + uiLog2WeightDenomLuma);
+    }
+
+    for ( Int iNumRef=0 ; iNumRef<iNbRef ; iNumRef++ ) 
+    {
+      RefPicList  eRefPicList = ( iNumRef ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
+      for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) 
+      {
+        pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
+
+        wp[0].uiLog2WeightDenom = uiLog2WeightDenomLuma;
+        wp[1].uiLog2WeightDenom = uiLog2WeightDenomChroma;
+        wp[2].uiLog2WeightDenom = uiLog2WeightDenomChroma;
+
+        UInt  uiCode;
+        READ_FLAG( uiCode, "luma_weight_lX_flag" );           // u(1): luma_weight_l0_flag
+        wp[0].bPresentFlag = ( uiCode == 1 );
+#if NUM_WP_LIMIT
+        uiTotalSignalledWeightFlags += wp[0].bPresentFlag;
+      }
+      if ( bChroma ) 
+      {
+        UInt  uiCode;
+        for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) 
+        {
+          pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
+          READ_FLAG( uiCode, "chroma_weight_lX_flag" );      // u(1): chroma_weight_l0_flag
+          wp[1].bPresentFlag = ( uiCode == 1 );
+          wp[2].bPresentFlag = ( uiCode == 1 );
+          uiTotalSignalledWeightFlags += 2*wp[1].bPresentFlag;
+        }
+      }
+      for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) 
+      {
+        pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
+#endif
+        if ( wp[0].bPresentFlag ) 
+        {
+          Int iDeltaWeight;
+          READ_SVLC( iDeltaWeight, "delta_luma_weight_lX" );  // se(v): delta_luma_weight_l0[i]
+          wp[0].iWeight = (iDeltaWeight + (1<<wp[0].uiLog2WeightDenom));
+          READ_SVLC( wp[0].iOffset, "luma_offset_lX" );       // se(v): luma_offset_l0[i]
+        }
+        else 
+        {
+          wp[0].iWeight = (1 << wp[0].uiLog2WeightDenom);
+          wp[0].iOffset = 0;
+        }
+        if ( bChroma ) 
+        {
+#if !NUM_WP_LIMIT
+          READ_FLAG( uiCode, "chroma_weight_lX_flag" );      // u(1): chroma_weight_l0_flag
+          wp[1].bPresentFlag = ( uiCode == 1 );
+          wp[2].bPresentFlag = ( uiCode == 1 );
+#endif
+          if ( wp[1].bPresentFlag ) 
+          {
+            for ( Int j=1 ; j<3 ; j++ ) 
+            {
+              Int iDeltaWeight;
+              READ_SVLC( iDeltaWeight, "delta_chroma_weight_lX" );  // se(v): chroma_weight_l0[i][j]
+              wp[j].iWeight = (iDeltaWeight + (1<<wp[1].uiLog2WeightDenom));
+
+              Int iDeltaChroma;
+              READ_SVLC( iDeltaChroma, "delta_chroma_offset_lX" );  // se(v): delta_chroma_offset_l0[i][j]
+              Int shift = ((1<<(g_uiBitDepth+g_uiBitIncrement-1)));
+              Int pred = ( shift - ( ( shift*wp[j].iWeight)>>(wp[j].uiLog2WeightDenom) ) );
+#if WP_PARAM_RANGE_LIMIT
+              wp[j].iOffset = Clip3(-128, 127, (iDeltaChroma + pred) );
+#else
+              wp[j].iOffset = iDeltaChroma + pred;
+#endif
+            }
+          }
+          else 
+          {
+            for ( Int j=1 ; j<3 ; j++ ) 
+            {
+              wp[j].iWeight = (1 << wp[j].uiLog2WeightDenom);
+              wp[j].iOffset = 0;
+            }
+          }
+        }
+      }
+
+      for ( Int iRefIdx=pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx<MAX_NUM_REF ; iRefIdx++ ) 
+      {
+        pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
+
+        wp[0].bPresentFlag = false;
+        wp[1].bPresentFlag = false;
+        wp[2].bPresentFlag = false;
+      }
+    }
+#if NUM_WP_LIMIT
+    assert(uiTotalSignalledWeightFlags<=24);
+#endif
+  }
+  else
+  {
+    printf("\n wrong weight pred table syntax \n ");
+    assert(0);
+  }
+}
+
+/** decode quantization matrix
+* \param scalingList quantization matrix information
+*/
+Void TDecCavlc::parseScalingList(TComScalingList* scalingList)
+{
+  UInt  code, sizeId, listId;
+  Bool scalingListPredModeFlag;
+  //for each size
+  for(sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
+  {
+    for(listId = 0; listId <  g_scalingListNum[sizeId]; listId++)
+    {
+      READ_FLAG( code, "scaling_list_pred_mode_flag");
+      scalingListPredModeFlag = (code) ? true : false;
+      if(!scalingListPredModeFlag) //Copy Mode
+      {
+        READ_UVLC( code, "scaling_list_pred_matrix_id_delta");
+        scalingList->setRefMatrixId (sizeId,listId,(UInt)((Int)(listId)-(code)));
+        if( sizeId > SCALING_LIST_8x8 )
+        {
+          scalingList->setScalingListDC(sizeId,listId,((listId == scalingList->getRefMatrixId (sizeId,listId))? 16 :scalingList->getScalingListDC(sizeId, scalingList->getRefMatrixId (sizeId,listId))));
+        }
+        scalingList->processRefMatrix( sizeId, listId, scalingList->getRefMatrixId (sizeId,listId));
+
+      }
+      else //DPCM Mode
+      {
+        xDecodeScalingList(scalingList, sizeId, listId);
+      }
+    }
+  }
+
+  return;
+}
+/** decode DPCM
+* \param scalingList  quantization matrix information
+* \param sizeId size index
+* \param listId list index
+*/
+Void TDecCavlc::xDecodeScalingList(TComScalingList *scalingList, UInt sizeId, UInt listId)
+{
+  Int i,coefNum = min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]);
+  Int data;
+  Int scalingListDcCoefMinus8 = 0;
+  Int nextCoef = SCALING_LIST_START_VALUE;
+#if REMOVE_ZIGZAG_SCAN
+  UInt* scan  = (sizeId == 0) ? g_auiSigLastScan [ SCAN_DIAG ] [ 1 ] :  g_sigLastScanCG32x32;
+#else
+  UInt* scan  = g_auiFrameScanXY [ (sizeId == 0)? 1 : 2 ];
+#endif
+  Int *dst = scalingList->getScalingListAddress(sizeId, listId);
+
+  if( sizeId > SCALING_LIST_8x8 )
+  {
+    READ_SVLC( scalingListDcCoefMinus8, "scaling_list_dc_coef_minus8");
+    scalingList->setScalingListDC(sizeId,listId,scalingListDcCoefMinus8 + 8);
+    nextCoef = scalingList->getScalingListDC(sizeId,listId);
+  }
+
+  for(i = 0; i < coefNum; i++)
+  {
+    READ_SVLC( data, "scaling_list_delta_coef");
+    nextCoef = (nextCoef + data + 256 ) % 256;
+    dst[scan[i]] = nextCoef;
+  }
+}
+
+Bool TDecCavlc::xMoreRbspData()
+{ 
+  Int bitsLeft = m_pcBitstream->getNumBitsLeft();
+
+  // if there are more than 8 bits, it cannot be rbsp_trailing_bits
+  if (bitsLeft > 8)
+  {
+    return true;
+  }
+
+  UChar lastByte = m_pcBitstream->peekBits(bitsLeft);
+  Int cnt = bitsLeft;
+
+  // remove trailing bits equal to zero
+  while ((cnt>0) && ((lastByte & 1) == 0))
+  {
+    lastByte >>= 1;
+    cnt--;
+  }
+  // remove bit equal to one
+  cnt--;
+
+  // we should not have a negative number of bits
+  assert (cnt>=0);
+
+  // we have more data, if cnt is not zero
+  return (cnt>0);
+}
+
+//! \}
+
Index: /trunk/source/Lib/TLibDecoder/TDecCAVLC.h
===================================================================
--- /trunk/source/Lib/TLibDecoder/TDecCAVLC.h	(revision 2)
+++ /trunk/source/Lib/TLibDecoder/TDecCAVLC.h	(revision 2)
@@ -0,0 +1,159 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TDecCAVLC.h
+    \brief    CAVLC decoder class (header)
+*/
+
+#ifndef __TDECCAVLC__
+#define __TDECCAVLC__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TDecEntropy.h"
+#include "SyntaxElementParser.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+class SEImessages;
+
+/// CAVLC decoder class
+class TDecCavlc : public SyntaxElementParser, public TDecEntropyIf
+{
+public:
+  TDecCavlc();
+  virtual ~TDecCavlc();
+  
+protected:
+  Void  xReadEpExGolomb       ( UInt& ruiSymbol, UInt uiCount );
+  Void  xReadExGolombLevel    ( UInt& ruiSymbol );
+  Void  xReadUnaryMaxSymbol   ( UInt& ruiSymbol, UInt uiMaxSymbol );
+  
+  Void  xReadPCMAlignZero     ();
+
+  UInt  xGetBit             ();
+  
+  void  parseShortTermRefPicSet            (TComSPS* pcSPS, TComReferencePictureSet* pcRPS, Int idx);
+private:
+#if !REMOVE_FGS
+  Int           m_iSliceGranularity; //!< slice granularity
+#endif
+  
+public:
+
+  /// rest entropy coder by intial QP and IDC in CABAC
+  Void  resetEntropy        ( TComSlice* pcSlice  )     { assert(0); };
+  Void  setBitstream        ( TComInputBitstream* p )   { m_pcBitstream = p; }
+#if !REMOVE_FGS
+  /// set slice granularity
+  Void setSliceGranularity(Int iSliceGranularity)  {m_iSliceGranularity = iSliceGranularity;}
+
+  /// get slice granularity
+  Int  getSliceGranularity()                       {return m_iSliceGranularity;             }
+#endif
+  Void  parseTransformSubdivFlag( UInt& ruiSubdivFlag, UInt uiLog2TransformBlockSize );
+  Void  parseQtCbf          ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth, UInt uiDepth );
+  Void  parseQtRootCbf      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt& uiQtRootCbf );
+  Void  parseVPS            ( TComVPS* pcVPS );
+  Void  parseSPS            ( TComSPS* pcSPS );
+  Void  parsePPS            ( TComPPS* pcPPS);
+#if SUPPORT_FOR_VUI
+#if !BUFFERING_PERIOD_AND_TIMING_SEI
+  Void  parseVUI            ( TComVUI* pcVUI );
+#else
+  Void  parseVUI            ( TComVUI* pcVUI, TComSPS* pcSPS );
+#endif
+#endif
+  Void  parseSEI(SEImessages&);
+#if !REMOVE_APS
+  Void  parseAPS            ( TComAPS* pAPS );
+#endif
+#if PROFILE_TIER_LEVEL_SYNTAX
+  Void  parsePTL            ( TComPTL *rpcPTL, Bool profilePresentFlag, Int maxNumSubLayersMinus1 );
+  Void  parseProfileTier    (ProfileTierLevel *ptl);
+#endif
+  Void  parseSliceHeader    ( TComSlice*& rpcSlice, ParameterSetManagerDecoder *parameterSetManager);
+  Void  parseTerminatingBit ( UInt& ruiBit );
+  
+  Void  parseMVPIdx         ( Int& riMVPIdx );
+  
+  Void  parseSkipFlag       ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void  parseCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void parseMergeFlag       ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPUIdx );
+  Void parseMergeIndex      ( TComDataCU* pcCU, UInt& ruiMergeIndex, UInt uiAbsPartIdx, UInt uiDepth );
+  Void parseSplitFlag       ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void parsePartSize        ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void parsePredMode        ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  
+  Void parseIntraDirLumaAng ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  
+  Void parseIntraDirChroma  ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  
+  Void parseInterDir        ( TComDataCU* pcCU, UInt& ruiInterDir, UInt uiAbsPartIdx, UInt uiDepth );
+  Void parseRefFrmIdx       ( TComDataCU* pcCU, Int& riRefFrmIdx,  UInt uiAbsPartIdx, UInt uiDepth, RefPicList eRefList );
+  Void parseMvd             ( TComDataCU* pcCU, UInt uiAbsPartAddr,UInt uiPartIdx,    UInt uiDepth, RefPicList eRefList );
+  
+  Void parseDeltaQP         ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void parseCoeffNxN        ( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType );
+  Void parseTransformSkipFlags ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, UInt uiDepth, TextType eTType);
+
+  Void parseIPCMInfo        ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth);
+
+#if INTRA_BL
+  Void parseIntraBLFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
+#endif
+  Void updateContextTables  ( SliceType eSliceType, Int iQp ) { return; }
+  Void decodeFlush() {};
+
+  Void xParsePredWeightTable ( TComSlice* pcSlice );
+  Void  parseScalingList               ( TComScalingList* scalingList );
+  Void xDecodeScalingList    ( TComScalingList *scalingList, UInt sizeId, UInt listId);
+protected:
+#if !REMOVE_ALF
+  Void  xParseAlfParam       ( ALFParam* pAlfParam );
+  Int   xGolombDecode        ( Int k );
+#endif
+  Bool  xMoreRbspData();
+};
+
+//! \}
+
+#endif // !defined(AFX_TDECCAVLC_H__9732DD64_59B0_4A41_B29E_1A5B18821EAD__INCLUDED_)
+
Index: /trunk/source/Lib/TLibDecoder/TDecCu.cpp
===================================================================
--- /trunk/source/Lib/TLibDecoder/TDecCu.cpp	(revision 2)
+++ /trunk/source/Lib/TLibDecoder/TDecCu.cpp	(revision 2)
@@ -0,0 +1,1004 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TDecCu.cpp
+    \brief    CU decoder class
+*/
+
+#include "TDecCu.h"
+#if SVC_EXTENSION
+#include "TDecTop.h"
+#endif
+
+
+//! \ingroup TLibDecoder
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TDecCu::TDecCu()
+{
+  m_ppcYuvResi = NULL;
+  m_ppcYuvReco = NULL;
+  m_ppcCU      = NULL;
+}
+
+TDecCu::~TDecCu()
+{
+}
+
+#if SVC_EXTENSION
+Void TDecCu::init(TDecTop** ppcDecTop, TDecEntropy* pcEntropyDecoder, TComTrQuant* pcTrQuant, TComPrediction* pcPrediction, UInt layerId)
+#else
+Void TDecCu::init( TDecEntropy* pcEntropyDecoder, TComTrQuant* pcTrQuant, TComPrediction* pcPrediction)
+#endif 
+{
+  m_pcEntropyDecoder  = pcEntropyDecoder;
+  m_pcTrQuant         = pcTrQuant;
+  m_pcPrediction      = pcPrediction;
+#if SVC_EXTENSION   
+  m_ppcTDecTop = ppcDecTop;
+  m_layerId = layerId; 
+
+  for ( UInt ui = 0; ui < m_uiMaxDepth-1; ui++ )
+  {
+    m_ppcCU     [ui]->setLayerId(layerId);
+  }
+#endif
+}
+
+/**
+ \param    uiMaxDepth    total number of allowable depth
+ \param    uiMaxWidth    largest CU width
+ \param    uiMaxHeight   largest CU height
+ */
+Void TDecCu::create( UInt uiMaxDepth, UInt uiMaxWidth, UInt uiMaxHeight )
+{
+  m_uiMaxDepth = uiMaxDepth+1;
+  
+  m_ppcYuvResi = new TComYuv*[m_uiMaxDepth-1];
+  m_ppcYuvReco = new TComYuv*[m_uiMaxDepth-1];
+  m_ppcCU      = new TComDataCU*[m_uiMaxDepth-1];
+  
+  UInt uiNumPartitions;
+  for ( UInt ui = 0; ui < m_uiMaxDepth-1; ui++ )
+  {
+    uiNumPartitions = 1<<( ( m_uiMaxDepth - ui - 1 )<<1 );
+    UInt uiWidth  = uiMaxWidth  >> ui;
+    UInt uiHeight = uiMaxHeight >> ui;
+    
+    m_ppcYuvResi[ui] = new TComYuv;    m_ppcYuvResi[ui]->create( uiWidth, uiHeight );
+    m_ppcYuvReco[ui] = new TComYuv;    m_ppcYuvReco[ui]->create( uiWidth, uiHeight );
+    m_ppcCU     [ui] = new TComDataCU; m_ppcCU     [ui]->create( uiNumPartitions, uiWidth, uiHeight, true, uiMaxWidth >> (m_uiMaxDepth - 1) );
+  }
+  
+  m_bDecodeDQP = false;
+
+  // initialize partition order.
+  UInt* piTmp = &g_auiZscanToRaster[0];
+  initZscanToRaster(m_uiMaxDepth, 1, 0, piTmp);
+  initRasterToZscan( uiMaxWidth, uiMaxHeight, m_uiMaxDepth );
+  
+  // initialize conversion matrix from partition index to pel
+  initRasterToPelXY( uiMaxWidth, uiMaxHeight, m_uiMaxDepth );
+  initMotionReferIdx ( uiMaxWidth, uiMaxHeight, m_uiMaxDepth );
+}
+
+Void TDecCu::destroy()
+{
+  for ( UInt ui = 0; ui < m_uiMaxDepth-1; ui++ )
+  {
+    m_ppcYuvResi[ui]->destroy(); delete m_ppcYuvResi[ui]; m_ppcYuvResi[ui] = NULL;
+    m_ppcYuvReco[ui]->destroy(); delete m_ppcYuvReco[ui]; m_ppcYuvReco[ui] = NULL;
+    m_ppcCU     [ui]->destroy(); delete m_ppcCU     [ui]; m_ppcCU     [ui] = NULL;
+  }
+  
+  delete [] m_ppcYuvResi; m_ppcYuvResi = NULL;
+  delete [] m_ppcYuvReco; m_ppcYuvReco = NULL;
+  delete [] m_ppcCU     ; m_ppcCU      = NULL;
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/** \param    pcCU        pointer of CU data
+ \param    ruiIsLast   last data?
+ */
+Void TDecCu::decodeCU( TComDataCU* pcCU, UInt& ruiIsLast )
+{
+  if ( pcCU->getSlice()->getPPS()->getUseDQP() )
+  {
+    setdQPFlag(true);
+  }
+
+  pcCU->setNumSucIPCM(0);
+
+  // start from the top level CU
+#if SVC_EXTENSION
+  pcCU->setLayerId(m_layerId);
+#endif
+  xDecodeCU( pcCU, 0, 0, ruiIsLast);
+}
+
+/** \param    pcCU        pointer of CU data
+ */
+Void TDecCu::decompressCU( TComDataCU* pcCU )
+{
+  xDecompressCU( pcCU, pcCU, 0,  0 );
+}
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+/**decode end-of-slice flag
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \param uiDepth 
+ * \returns Bool
+ */
+Bool TDecCu::xDecodeSliceEnd( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth)
+{
+  UInt uiIsLast;
+  TComPic* pcPic = pcCU->getPic();
+  TComSlice * pcSlice = pcPic->getSlice(pcPic->getCurrSliceIdx());
+  UInt uiCurNumParts    = pcPic->getNumPartInCU() >> (uiDepth<<1);
+  UInt uiWidth = pcSlice->getSPS()->getPicWidthInLumaSamples();
+  UInt uiHeight = pcSlice->getSPS()->getPicHeightInLumaSamples();
+#if REMOVE_FGS
+  UInt uiGranularityWidth = g_uiMaxCUWidth;
+#else
+  UInt uiGranularityWidth = g_uiMaxCUWidth>>(pcSlice->getPPS()->getSliceGranularity());
+#endif
+  UInt uiPosX = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
+  UInt uiPosY = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
+
+  if(((uiPosX+pcCU->getWidth(uiAbsPartIdx))%uiGranularityWidth==0||(uiPosX+pcCU->getWidth(uiAbsPartIdx)==uiWidth))
+    &&((uiPosY+pcCU->getHeight(uiAbsPartIdx))%uiGranularityWidth==0||(uiPosY+pcCU->getHeight(uiAbsPartIdx)==uiHeight)))
+  {
+    m_pcEntropyDecoder->decodeTerminatingBit( uiIsLast );
+  }
+  else
+  {
+    uiIsLast=0;
+  }
+  
+  if(uiIsLast) 
+  {
+    if(pcSlice->isNextDependentSlice()&&!pcSlice->isNextSlice()) 
+    {
+      pcSlice->setDependentSliceCurEndCUAddr(pcCU->getSCUAddr()+uiAbsPartIdx+uiCurNumParts);
+    }
+    else 
+    {
+      pcSlice->setSliceCurEndCUAddr(pcCU->getSCUAddr()+uiAbsPartIdx+uiCurNumParts);
+      pcSlice->setDependentSliceCurEndCUAddr(pcCU->getSCUAddr()+uiAbsPartIdx+uiCurNumParts);
+    }
+  }
+
+  return uiIsLast>0;
+}
+
+/** decode CU block recursively
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \param uiDepth 
+ * \returns Void
+ */
+
+Void TDecCu::xDecodeCU( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt& ruiIsLast)
+{
+  TComPic* pcPic = pcCU->getPic();
+  UInt uiCurNumParts    = pcPic->getNumPartInCU() >> (uiDepth<<1);
+  UInt uiQNumParts      = uiCurNumParts>>2;
+  
+  Bool bBoundary = false;
+  UInt uiLPelX   = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
+  UInt uiRPelX   = uiLPelX + (g_uiMaxCUWidth>>uiDepth)  - 1;
+  UInt uiTPelY   = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
+  UInt uiBPelY   = uiTPelY + (g_uiMaxCUHeight>>uiDepth) - 1;
+  
+  TComSlice * pcSlice = pcCU->getPic()->getSlice(pcCU->getPic()->getCurrSliceIdx());
+  Bool bStartInCU = pcCU->getSCUAddr()+uiAbsPartIdx+uiCurNumParts>pcSlice->getDependentSliceCurStartCUAddr()&&pcCU->getSCUAddr()+uiAbsPartIdx<pcSlice->getDependentSliceCurStartCUAddr();
+  if((!bStartInCU) && ( uiRPelX < pcSlice->getSPS()->getPicWidthInLumaSamples() ) && ( uiBPelY < pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+  {
+    if(pcCU->getNumSucIPCM() == 0)
+    {
+      m_pcEntropyDecoder->decodeSplitFlag( pcCU, uiAbsPartIdx, uiDepth );
+    }
+    else
+    {
+      pcCU->setDepthSubParts( uiDepth, uiAbsPartIdx );
+    }
+  }
+  else
+  {
+    bBoundary = true;
+  }
+  
+  if( ( ( uiDepth < pcCU->getDepth( uiAbsPartIdx ) ) && ( uiDepth < g_uiMaxCUDepth - g_uiAddCUDepth ) ) || bBoundary )
+  {
+    UInt uiIdx = uiAbsPartIdx;
+    if( (g_uiMaxCUWidth>>uiDepth) == pcCU->getSlice()->getPPS()->getMinCuDQPSize() && pcCU->getSlice()->getPPS()->getUseDQP())
+    {
+      setdQPFlag(true);
+      pcCU->setQPSubParts( pcCU->getRefQP(uiAbsPartIdx), uiAbsPartIdx, uiDepth ); // set QP to default QP
+    }
+
+    for ( UInt uiPartUnitIdx = 0; uiPartUnitIdx < 4; uiPartUnitIdx++ )
+    {
+      uiLPelX   = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiIdx] ];
+      uiTPelY   = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiIdx] ];
+      
+      Bool bSubInSlice = pcCU->getSCUAddr()+uiIdx+uiQNumParts>pcSlice->getDependentSliceCurStartCUAddr();
+      if ( bSubInSlice )
+      {
+        if ( ( uiLPelX < pcCU->getSlice()->getSPS()->getPicWidthInLumaSamples() ) && ( uiTPelY < pcCU->getSlice()->getSPS()->getPicHeightInLumaSamples() ) )
+        {
+          xDecodeCU( pcCU, uiIdx, uiDepth+1, ruiIsLast );
+        }
+        else
+        {
+          pcCU->setOutsideCUPart( uiIdx, uiDepth+1 );
+        }
+      }
+      if(ruiIsLast)
+      {
+        break;
+      }
+      
+      uiIdx += uiQNumParts;
+    }
+    if( (g_uiMaxCUWidth>>uiDepth) == pcCU->getSlice()->getPPS()->getMinCuDQPSize() && pcCU->getSlice()->getPPS()->getUseDQP())
+    {
+      if ( getdQPFlag() )
+      {
+        UInt uiQPSrcPartIdx;
+        if ( pcPic->getCU( pcCU->getAddr() )->getDependentSliceStartCU(uiAbsPartIdx) != pcSlice->getDependentSliceCurStartCUAddr() )
+        {
+          uiQPSrcPartIdx = pcSlice->getDependentSliceCurStartCUAddr() % pcPic->getNumPartInCU();
+        }
+        else
+        {
+          uiQPSrcPartIdx = uiAbsPartIdx;
+        }
+        pcCU->setQPSubParts( pcCU->getRefQP( uiQPSrcPartIdx ), uiAbsPartIdx, uiDepth ); // set QP to default QP
+      }
+    }
+    return;
+  }
+  
+  if( (g_uiMaxCUWidth>>uiDepth) >= pcCU->getSlice()->getPPS()->getMinCuDQPSize() && pcCU->getSlice()->getPPS()->getUseDQP())
+  {
+    setdQPFlag(true);
+    pcCU->setQPSubParts( pcCU->getRefQP(uiAbsPartIdx), uiAbsPartIdx, uiDepth ); // set QP to default QP
+  }
+
+  if (pcCU->getSlice()->getPPS()->getTransquantBypassEnableFlag() && pcCU->getNumSucIPCM() == 0 )
+  {
+    m_pcEntropyDecoder->decodeCUTransquantBypassFlag( pcCU, uiAbsPartIdx, uiDepth );
+  }
+  
+  // decode CU mode and the partition size
+  if( !pcCU->getSlice()->isIntra() && pcCU->getNumSucIPCM() == 0 )
+  {
+    m_pcEntropyDecoder->decodeSkipFlag( pcCU, uiAbsPartIdx, uiDepth );
+  }
+ 
+  if( pcCU->isSkipped(uiAbsPartIdx) )
+  {
+    m_ppcCU[uiDepth]->copyInterPredInfoFrom( pcCU, uiAbsPartIdx, REF_PIC_LIST_0 );
+    m_ppcCU[uiDepth]->copyInterPredInfoFrom( pcCU, uiAbsPartIdx, REF_PIC_LIST_1 );
+    TComMvField cMvFieldNeighbours[MRG_MAX_NUM_CANDS << 1]; // double length for mv of both lists
+    UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS];
+    Int numValidMergeCand = 0;
+    for( UInt ui = 0; ui < m_ppcCU[uiDepth]->getSlice()->getMaxNumMergeCand(); ++ui )
+    {
+      uhInterDirNeighbours[ui] = 0;
+    }
+    m_pcEntropyDecoder->decodeMergeIndex( pcCU, 0, uiAbsPartIdx, SIZE_2Nx2N, uhInterDirNeighbours, cMvFieldNeighbours, uiDepth );
+    UInt uiMergeIndex = pcCU->getMergeIndex(uiAbsPartIdx);
+    m_ppcCU[uiDepth]->getInterMergeCandidates( 0, 0, uiDepth, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand, uiMergeIndex );
+    pcCU->setInterDirSubParts( uhInterDirNeighbours[uiMergeIndex], uiAbsPartIdx, 0, uiDepth );
+
+    TComMv cTmpMv( 0, 0 );
+    for ( UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )
+    {        
+      if ( pcCU->getSlice()->getNumRefIdx( RefPicList( uiRefListIdx ) ) > 0 )
+      {
+        pcCU->setMVPIdxSubParts( 0, RefPicList( uiRefListIdx ), uiAbsPartIdx, 0, uiDepth);
+        pcCU->setMVPNumSubParts( 0, RefPicList( uiRefListIdx ), uiAbsPartIdx, 0, uiDepth);
+        pcCU->getCUMvField( RefPicList( uiRefListIdx ) )->setAllMvd( cTmpMv, SIZE_2Nx2N, uiAbsPartIdx, uiDepth );
+        pcCU->getCUMvField( RefPicList( uiRefListIdx ) )->setAllMvField( cMvFieldNeighbours[ 2*uiMergeIndex + uiRefListIdx ], SIZE_2Nx2N, uiAbsPartIdx, uiDepth );
+      }
+    }
+    xFinishDecodeCU( pcCU, uiAbsPartIdx, uiDepth, ruiIsLast );
+    return;
+  }
+#if INTRA_BL
+  m_pcEntropyDecoder->decodeIntraBLFlag( pcCU, uiAbsPartIdx, 0, uiDepth );
+  if ( pcCU->isIntraBL( uiAbsPartIdx ) )
+  {
+    pcCU->setSizeSubParts( g_uiMaxCUWidth>>uiDepth, g_uiMaxCUHeight>>uiDepth, uiAbsPartIdx, uiDepth ); 
+  }
+  else
+  {
+#endif
+
+  if( pcCU->getNumSucIPCM() == 0 ) 
+  {
+    m_pcEntropyDecoder->decodePredMode( pcCU, uiAbsPartIdx, uiDepth );
+    m_pcEntropyDecoder->decodePartSize( pcCU, uiAbsPartIdx, uiDepth );
+  }
+  else
+  {
+    pcCU->setPredModeSubParts( MODE_INTRA, uiAbsPartIdx, uiDepth );
+    pcCU->setPartSizeSubParts( SIZE_2Nx2N, uiAbsPartIdx, uiDepth );
+    pcCU->setSizeSubParts( g_uiMaxCUWidth>>uiDepth, g_uiMaxCUHeight>>uiDepth, uiAbsPartIdx, uiDepth ); 
+    pcCU->setTrIdxSubParts( 0, uiAbsPartIdx, uiDepth );
+  }
+
+  if (pcCU->isIntra( uiAbsPartIdx ) && pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_2Nx2N )
+  {
+    m_pcEntropyDecoder->decodeIPCMInfo( pcCU, uiAbsPartIdx, uiDepth );
+
+    if(pcCU->getIPCMFlag(uiAbsPartIdx))
+    {
+      xFinishDecodeCU( pcCU, uiAbsPartIdx, uiDepth, ruiIsLast );
+      return;
+    }
+  }  
+#if INTRA_BL
+  // prediction mode ( Intra : direction mode, Inter : Mv, reference idx )
+  m_pcEntropyDecoder->decodePredInfo( pcCU, uiAbsPartIdx, uiDepth, m_ppcCU[uiDepth]);
+  }
+#endif
+
+  UInt uiCurrWidth      = pcCU->getWidth ( uiAbsPartIdx );
+  UInt uiCurrHeight     = pcCU->getHeight( uiAbsPartIdx );
+  
+#if !INTRA_BL
+  // prediction mode ( Intra : direction mode, Inter : Mv, reference idx )
+  m_pcEntropyDecoder->decodePredInfo( pcCU, uiAbsPartIdx, uiDepth, m_ppcCU[uiDepth]);
+#endif
+  
+  // Coefficient decoding
+  Bool bCodeDQP = getdQPFlag();
+  m_pcEntropyDecoder->decodeCoeff( pcCU, uiAbsPartIdx, uiDepth, uiCurrWidth, uiCurrHeight, bCodeDQP );
+  setdQPFlag( bCodeDQP );
+  xFinishDecodeCU( pcCU, uiAbsPartIdx, uiDepth, ruiIsLast );
+}
+
+Void TDecCu::xFinishDecodeCU( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt& ruiIsLast)
+{
+  if(  pcCU->getSlice()->getPPS()->getUseDQP())
+  {
+    pcCU->setQPSubParts( getdQPFlag()?pcCU->getRefQP(uiAbsPartIdx):pcCU->getCodedQP(), uiAbsPartIdx, uiDepth ); // set QP
+  }
+  if( pcCU->getNumSucIPCM() > 0 )
+  {
+    ruiIsLast = 0;
+    return;
+  }
+
+  ruiIsLast = xDecodeSliceEnd( pcCU, uiAbsPartIdx, uiDepth);
+}
+
+Void TDecCu::xDecompressCU( TComDataCU* pcCU, TComDataCU* pcCUCur, UInt uiAbsPartIdx,  UInt uiDepth )
+{
+  TComPic* pcPic = pcCU->getPic();
+  
+  Bool bBoundary = false;
+  UInt uiLPelX   = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
+  UInt uiRPelX   = uiLPelX + (g_uiMaxCUWidth>>uiDepth)  - 1;
+  UInt uiTPelY   = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
+  UInt uiBPelY   = uiTPelY + (g_uiMaxCUHeight>>uiDepth) - 1;
+  
+  UInt uiCurNumParts    = pcPic->getNumPartInCU() >> (uiDepth<<1);
+  TComSlice * pcSlice = pcCU->getPic()->getSlice(pcCU->getPic()->getCurrSliceIdx());
+  Bool bStartInCU = pcCU->getSCUAddr()+uiAbsPartIdx+uiCurNumParts>pcSlice->getDependentSliceCurStartCUAddr()&&pcCU->getSCUAddr()+uiAbsPartIdx<pcSlice->getDependentSliceCurStartCUAddr();
+  if(bStartInCU||( uiRPelX >= pcSlice->getSPS()->getPicWidthInLumaSamples() ) || ( uiBPelY >= pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+  {
+    bBoundary = true;
+  }
+  
+  if( ( ( uiDepth < pcCU->getDepth( uiAbsPartIdx ) ) && ( uiDepth < g_uiMaxCUDepth - g_uiAddCUDepth ) ) || bBoundary )
+  {
+    UInt uiNextDepth = uiDepth + 1;
+    UInt uiQNumParts = pcCU->getTotalNumPart() >> (uiNextDepth<<1);
+    UInt uiIdx = uiAbsPartIdx;
+    for ( UInt uiPartIdx = 0; uiPartIdx < 4; uiPartIdx++ )
+    {
+      uiLPelX = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiIdx] ];
+      uiTPelY = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiIdx] ];
+      
+      Bool binSlice = (pcCU->getSCUAddr()+uiIdx+uiQNumParts>pcSlice->getDependentSliceCurStartCUAddr())&&(pcCU->getSCUAddr()+uiIdx<pcSlice->getDependentSliceCurEndCUAddr());
+      if(binSlice&&( uiLPelX < pcSlice->getSPS()->getPicWidthInLumaSamples() ) && ( uiTPelY < pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+      {
+        xDecompressCU(pcCU, m_ppcCU[uiNextDepth], uiIdx, uiNextDepth );
+      }
+      
+      uiIdx += uiQNumParts;
+    }
+    return;
+  }
+  
+  // Residual reconstruction
+  m_ppcYuvResi[uiDepth]->clear();
+  
+  m_ppcCU[uiDepth]->copySubCU( pcCU, uiAbsPartIdx, uiDepth );
+  
+  switch( m_ppcCU[uiDepth]->getPredictionMode(0) )
+  {
+    case MODE_INTER:
+      xReconInter( m_ppcCU[uiDepth], uiAbsPartIdx, uiDepth );
+      break;
+    case MODE_INTRA:
+      xReconIntraQT( m_ppcCU[uiDepth], uiAbsPartIdx, uiDepth );
+      break;
+#if INTRA_BL
+    case MODE_INTRA_BL:
+      xReconIntraQT( m_ppcCU[uiDepth], uiAbsPartIdx, uiDepth );
+      break;
+#endif
+    default:
+      assert(0);
+      break;
+  }
+  if ( m_ppcCU[uiDepth]->isLosslessCoded(0) && (m_ppcCU[uiDepth]->getIPCMFlag(0) == false))
+  {
+    xFillPCMBuffer(m_ppcCU[uiDepth], uiAbsPartIdx, uiDepth);    
+  }
+  
+  xCopyToPic( m_ppcCU[uiDepth], pcPic, uiAbsPartIdx, uiDepth );
+}
+
+Void TDecCu::xReconInter( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  
+  // inter prediction
+  m_pcPrediction->motionCompensation( pcCU, m_ppcYuvReco[uiDepth] );
+  
+  // inter recon
+  xDecodeInterTexture( pcCU, 0, uiDepth );
+  
+  // clip for only non-zero cbp case
+  if  ( ( pcCU->getCbf( 0, TEXT_LUMA ) ) || ( pcCU->getCbf( 0, TEXT_CHROMA_U ) ) || ( pcCU->getCbf(0, TEXT_CHROMA_V ) ) )
+  {
+    m_ppcYuvReco[uiDepth]->addClip( m_ppcYuvReco[uiDepth], m_ppcYuvResi[uiDepth], 0, pcCU->getWidth( 0 ) );
+  }
+  else
+  {
+    m_ppcYuvReco[uiDepth]->copyPartToPartYuv( m_ppcYuvReco[uiDepth],0, pcCU->getWidth( 0 ),pcCU->getHeight( 0 ));
+  }
+}
+
+Void
+TDecCu::xIntraRecLumaBlk( TComDataCU* pcCU,
+                         UInt        uiTrDepth,
+                         UInt        uiAbsPartIdx,
+                         TComYuv*    pcRecoYuv,
+                         TComYuv*    pcPredYuv, 
+                         TComYuv*    pcResiYuv )
+{
+  UInt    uiWidth           = pcCU     ->getWidth   ( 0 ) >> uiTrDepth;
+  UInt    uiHeight          = pcCU     ->getHeight  ( 0 ) >> uiTrDepth;
+  UInt    uiStride          = pcRecoYuv->getStride  ();
+  Pel*    piReco            = pcRecoYuv->getLumaAddr( uiAbsPartIdx );
+  Pel*    piPred            = pcPredYuv->getLumaAddr( uiAbsPartIdx );
+  Pel*    piResi            = pcResiYuv->getLumaAddr( uiAbsPartIdx );
+  
+  UInt    uiNumCoeffInc     = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 );
+  TCoeff* pcCoeff           = pcCU->getCoeffY() + ( uiNumCoeffInc * uiAbsPartIdx );
+  
+  UInt    uiLumaPredMode    = pcCU->getLumaIntraDir     ( uiAbsPartIdx );
+  
+  UInt    uiZOrder          = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
+  Pel*    piRecIPred        = pcCU->getPic()->getPicYuvRec()->getLumaAddr( pcCU->getAddr(), uiZOrder );
+  UInt    uiRecIPredStride  = pcCU->getPic()->getPicYuvRec()->getStride  ();
+  Bool    useTransformSkip  = pcCU->getTransformSkip(uiAbsPartIdx, TEXT_LUMA);
+  //===== init availability pattern =====
+  Bool  bAboveAvail = false;
+  Bool  bLeftAvail  = false;
+  pcCU->getPattern()->initPattern   ( pcCU, uiTrDepth, uiAbsPartIdx );
+  pcCU->getPattern()->initAdiPattern( pcCU, uiAbsPartIdx, uiTrDepth, 
+                                     m_pcPrediction->getPredicBuf       (),
+                                     m_pcPrediction->getPredicBufWidth  (),
+                                     m_pcPrediction->getPredicBufHeight (),
+                                     bAboveAvail, bLeftAvail );
+  
+  //===== get prediction signal =====
+#if INTRA_BL
+  if(pcCU->isIntraBL ( uiAbsPartIdx ) )
+  {
+    pcCU->getBaseLumaBlk( uiWidth, uiHeight, uiAbsPartIdx, piPred, uiStride );
+  }
+  else
+#endif
+  m_pcPrediction->predIntraLumaAng( pcCU->getPattern(), uiLumaPredMode, piPred, uiStride, uiWidth, uiHeight, pcCU, bAboveAvail, bLeftAvail );
+  
+  //===== inverse transform =====
+  m_pcTrQuant->setQPforQuant  ( pcCU->getQP(0), TEXT_LUMA, pcCU->getSlice()->getSPS()->getQpBDOffsetY(), 0 );
+
+  Int scalingListType = (pcCU->isIntra(uiAbsPartIdx) ? 0 : 3) + g_eTTable[(Int)TEXT_LUMA];
+  assert(scalingListType < 6);
+  m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_LUMA, pcCU->getLumaIntraDir( uiAbsPartIdx ), piResi, uiStride, pcCoeff, uiWidth, uiHeight, scalingListType, useTransformSkip );
+
+  
+  //===== reconstruction =====
+  Pel* pPred      = piPred;
+  Pel* pResi      = piResi;
+  Pel* pReco      = piReco;
+  Pel* pRecIPred  = piRecIPred;
+  for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+  {
+    for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+    {
+      pReco    [ uiX ] = Clip( pPred[ uiX ] + pResi[ uiX ] );
+      pRecIPred[ uiX ] = pReco[ uiX ];
+    }
+    pPred     += uiStride;
+    pResi     += uiStride;
+    pReco     += uiStride;
+    pRecIPred += uiRecIPredStride;
+  }
+}
+
+
+Void
+TDecCu::xIntraRecChromaBlk( TComDataCU* pcCU,
+                           UInt        uiTrDepth,
+                           UInt        uiAbsPartIdx,
+                           TComYuv*    pcRecoYuv,
+                           TComYuv*    pcPredYuv, 
+                           TComYuv*    pcResiYuv,
+                           UInt        uiChromaId )
+{
+  UInt uiFullDepth  = pcCU->getDepth( 0 ) + uiTrDepth;
+  UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiFullDepth ] + 2;
+
+  if( uiLog2TrSize == 2 )
+  {
+    assert( uiTrDepth > 0 );
+    uiTrDepth--;
+    UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrDepth ) << 1 );
+    Bool bFirstQ = ( ( uiAbsPartIdx % uiQPDiv ) == 0 );
+    if( !bFirstQ )
+    {
+      return;
+    }
+  }
+  
+  TextType  eText             = ( uiChromaId > 0 ? TEXT_CHROMA_V : TEXT_CHROMA_U );
+  UInt      uiWidth           = pcCU     ->getWidth   ( 0 ) >> ( uiTrDepth + 1 );
+  UInt      uiHeight          = pcCU     ->getHeight  ( 0 ) >> ( uiTrDepth + 1 );
+  UInt      uiStride          = pcRecoYuv->getCStride ();
+  Pel*      piReco            = ( uiChromaId > 0 ? pcRecoYuv->getCrAddr( uiAbsPartIdx ) : pcRecoYuv->getCbAddr( uiAbsPartIdx ) );
+  Pel*      piPred            = ( uiChromaId > 0 ? pcPredYuv->getCrAddr( uiAbsPartIdx ) : pcPredYuv->getCbAddr( uiAbsPartIdx ) );
+  Pel*      piResi            = ( uiChromaId > 0 ? pcResiYuv->getCrAddr( uiAbsPartIdx ) : pcResiYuv->getCbAddr( uiAbsPartIdx ) );
+  
+  UInt      uiNumCoeffInc     = ( ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 ) ) >> 2;
+  TCoeff*   pcCoeff           = ( uiChromaId > 0 ? pcCU->getCoeffCr() : pcCU->getCoeffCb() ) + ( uiNumCoeffInc * uiAbsPartIdx );
+  
+  UInt      uiChromaPredMode  = pcCU->getChromaIntraDir( 0 );
+  
+  UInt      uiZOrder          = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
+  Pel*      piRecIPred        = ( uiChromaId > 0 ? pcCU->getPic()->getPicYuvRec()->getCrAddr( pcCU->getAddr(), uiZOrder ) : pcCU->getPic()->getPicYuvRec()->getCbAddr( pcCU->getAddr(), uiZOrder ) );
+  UInt      uiRecIPredStride  = pcCU->getPic()->getPicYuvRec()->getCStride();
+  Bool      useTransformSkipChroma = pcCU->getTransformSkip(uiAbsPartIdx,eText);
+  //===== init availability pattern =====
+  Bool  bAboveAvail = false;
+  Bool  bLeftAvail  = false;
+  pcCU->getPattern()->initPattern         ( pcCU, uiTrDepth, uiAbsPartIdx );
+
+#if !REMOVE_LMCHROMA
+  if( uiChromaPredMode == LM_CHROMA_IDX && uiChromaId == 0 )
+  {
+    pcCU->getPattern()->initAdiPattern( pcCU, uiAbsPartIdx, uiTrDepth, 
+                                     m_pcPrediction->getPredicBuf       (),
+                                     m_pcPrediction->getPredicBufWidth  (),
+                                     m_pcPrediction->getPredicBufHeight (),
+                                     bAboveAvail, bLeftAvail, 
+                                     true );
+
+    m_pcPrediction->getLumaRecPixels( pcCU->getPattern(), uiWidth, uiHeight );
+  }
+#endif
+  
+  pcCU->getPattern()->initAdiPatternChroma( pcCU, uiAbsPartIdx, uiTrDepth,
+                                           m_pcPrediction->getPredicBuf       (),
+                                           m_pcPrediction->getPredicBufWidth  (),
+                                           m_pcPrediction->getPredicBufHeight (),
+                                           bAboveAvail, bLeftAvail );
+  Int* pPatChroma   = ( uiChromaId > 0 ? pcCU->getPattern()->getAdiCrBuf( uiWidth, uiHeight, m_pcPrediction->getPredicBuf() ) : pcCU->getPattern()->getAdiCbBuf( uiWidth, uiHeight, m_pcPrediction->getPredicBuf() ) );
+  
+  //===== get prediction signal =====
+#if INTRA_BL
+  if(pcCU->isIntraBL ( uiAbsPartIdx ) )
+  {
+    pcCU->getBaseChromaBlk( uiWidth, uiHeight, uiAbsPartIdx, piPred, uiStride, uiChromaId );
+  }
+  else
+#endif
+#if !REMOVE_LMCHROMA
+  if( uiChromaPredMode == LM_CHROMA_IDX )
+  {
+    m_pcPrediction->predLMIntraChroma( pcCU->getPattern(), pPatChroma, piPred, uiStride, uiWidth, uiHeight, uiChromaId );
+  }
+  else
+#endif
+  {
+    if( uiChromaPredMode == DM_CHROMA_IDX )
+    {
+      uiChromaPredMode = pcCU->getLumaIntraDir( 0 );
+    }
+    m_pcPrediction->predIntraChromaAng( pcCU->getPattern(), pPatChroma, uiChromaPredMode, piPred, uiStride, uiWidth, uiHeight, pcCU, bAboveAvail, bLeftAvail );  
+  }
+
+  //===== inverse transform =====
+#if CHROMA_QP_EXTENSION
+  Int curChromaQpOffset;
+  if(eText == TEXT_CHROMA_U)
+  {
+    curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCbQpOffset() + pcCU->getSlice()->getSliceQpDeltaCb();
+  }
+  else
+  {
+    curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCrQpOffset() + pcCU->getSlice()->getSliceQpDeltaCr();
+  }
+  m_pcTrQuant->setQPforQuant  ( pcCU->getQP(0), eText, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
+#else
+  if(eText == TEXT_CHROMA_U)
+  {
+    m_pcTrQuant->setQPforQuant  ( pcCU->getQP(0), eText, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), pcCU->getSlice()->getPPS()->getChromaCbQpOffset() );
+  }
+  else
+  {
+    m_pcTrQuant->setQPforQuant  ( pcCU->getQP(0), eText, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), pcCU->getSlice()->getPPS()->getChromaCrQpOffset() );
+  }
+#endif
+
+  Int scalingListType = (pcCU->isIntra(uiAbsPartIdx) ? 0 : 3) + g_eTTable[(Int)eText];
+  assert(scalingListType < 6);
+  m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), eText, REG_DCT, piResi, uiStride, pcCoeff, uiWidth, uiHeight, scalingListType, useTransformSkipChroma );
+
+  //===== reconstruction =====
+  Pel* pPred      = piPred;
+  Pel* pResi      = piResi;
+  Pel* pReco      = piReco;
+  Pel* pRecIPred  = piRecIPred;
+  for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+  {
+    for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+    {
+      pReco    [ uiX ] = Clip( pPred[ uiX ] + pResi[ uiX ] );
+      pRecIPred[ uiX ] = pReco[ uiX ];
+    }
+    pPred     += uiStride;
+    pResi     += uiStride;
+    pReco     += uiStride;
+    pRecIPred += uiRecIPredStride;
+  }
+}
+
+
+Void
+TDecCu::xReconIntraQT( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt  uiInitTrDepth = ( pcCU->getPartitionSize(0) == SIZE_2Nx2N ? 0 : 1 );
+  UInt  uiNumPart     = pcCU->getNumPartInter();
+  UInt  uiNumQParts   = pcCU->getTotalNumPart() >> 2;
+  
+  if (pcCU->getIPCMFlag(0))
+  {
+    xReconPCM( pcCU, uiAbsPartIdx, uiDepth );
+    return;
+  }
+
+  for( UInt uiPU = 0; uiPU < uiNumPart; uiPU++ )
+  {
+    xIntraLumaRecQT( pcCU, uiInitTrDepth, uiPU * uiNumQParts, m_ppcYuvReco[uiDepth], m_ppcYuvReco[uiDepth], m_ppcYuvResi[uiDepth] );
+  }  
+
+  for( UInt uiPU = 0; uiPU < uiNumPart; uiPU++ )
+  {
+    xIntraChromaRecQT( pcCU, uiInitTrDepth, uiPU * uiNumQParts, m_ppcYuvReco[uiDepth], m_ppcYuvReco[uiDepth], m_ppcYuvResi[uiDepth] );
+  }
+
+}
+
+
+/** Function for deriving recontructed PU/CU Luma sample with QTree structure
+ * \param pcCU pointer of current CU
+ * \param uiTrDepth current tranform split depth
+ * \param uiAbsPartIdx  part index
+ * \param pcRecoYuv pointer to reconstructed sample arrays
+ * \param pcPredYuv pointer to prediction sample arrays
+ * \param pcResiYuv pointer to residue sample arrays
+ * 
+ \ This function dervies recontructed PU/CU Luma sample with recursive QTree structure
+ */
+Void
+TDecCu::xIntraLumaRecQT( TComDataCU* pcCU,
+                     UInt        uiTrDepth,
+                     UInt        uiAbsPartIdx,
+                     TComYuv*    pcRecoYuv,
+                     TComYuv*    pcPredYuv, 
+                     TComYuv*    pcResiYuv )
+{
+  UInt uiFullDepth  = pcCU->getDepth(0) + uiTrDepth;
+  UInt uiTrMode     = pcCU->getTransformIdx( uiAbsPartIdx );
+  if( uiTrMode == uiTrDepth )
+  {
+    xIntraRecLumaBlk  ( pcCU, uiTrDepth, uiAbsPartIdx, pcRecoYuv, pcPredYuv, pcResiYuv );
+  }
+  else
+  {
+    UInt uiNumQPart  = pcCU->getPic()->getNumPartInCU() >> ( ( uiFullDepth + 1 ) << 1 );
+    for( UInt uiPart = 0; uiPart < 4; uiPart++ )
+    {
+      xIntraLumaRecQT( pcCU, uiTrDepth + 1, uiAbsPartIdx + uiPart * uiNumQPart, pcRecoYuv, pcPredYuv, pcResiYuv );
+    }
+  }
+}
+
+/** Function for deriving recontructed PU/CU chroma samples with QTree structure
+ * \param pcCU pointer of current CU
+ * \param uiTrDepth current tranform split depth
+ * \param uiAbsPartIdx  part index
+ * \param pcRecoYuv pointer to reconstructed sample arrays
+ * \param pcPredYuv pointer to prediction sample arrays
+ * \param pcResiYuv pointer to residue sample arrays
+ * 
+ \ This function dervies recontructed PU/CU chroma samples with QTree recursive structure
+ */
+Void
+TDecCu::xIntraChromaRecQT( TComDataCU* pcCU,
+                     UInt        uiTrDepth,
+                     UInt        uiAbsPartIdx,
+                     TComYuv*    pcRecoYuv,
+                     TComYuv*    pcPredYuv, 
+                     TComYuv*    pcResiYuv )
+{
+  UInt uiFullDepth  = pcCU->getDepth(0) + uiTrDepth;
+  UInt uiTrMode     = pcCU->getTransformIdx( uiAbsPartIdx );
+  if( uiTrMode == uiTrDepth )
+  {
+    xIntraRecChromaBlk( pcCU, uiTrDepth, uiAbsPartIdx, pcRecoYuv, pcPredYuv, pcResiYuv, 0 );
+    xIntraRecChromaBlk( pcCU, uiTrDepth, uiAbsPartIdx, pcRecoYuv, pcPredYuv, pcResiYuv, 1 );
+  }
+  else
+  {
+    UInt uiNumQPart  = pcCU->getPic()->getNumPartInCU() >> ( ( uiFullDepth + 1 ) << 1 );
+    for( UInt uiPart = 0; uiPart < 4; uiPart++ )
+    {
+      xIntraChromaRecQT( pcCU, uiTrDepth + 1, uiAbsPartIdx + uiPart * uiNumQPart, pcRecoYuv, pcPredYuv, pcResiYuv );
+    }
+  }
+}
+
+Void TDecCu::xCopyToPic( TComDataCU* pcCU, TComPic* pcPic, UInt uiZorderIdx, UInt uiDepth )
+{
+  UInt uiCUAddr = pcCU->getAddr();
+  
+  m_ppcYuvReco[uiDepth]->copyToPicYuv  ( pcPic->getPicYuvRec (), uiCUAddr, uiZorderIdx );
+  
+  return;
+}
+
+Void TDecCu::xDecodeInterTexture ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt    uiWidth    = pcCU->getWidth ( uiAbsPartIdx );
+  UInt    uiHeight   = pcCU->getHeight( uiAbsPartIdx );
+  TCoeff* piCoeff;
+  
+  Pel*    pResi;
+  UInt    uiLumaTrMode, uiChromaTrMode;
+  
+  pcCU->convertTransIdx( uiAbsPartIdx, pcCU->getTransformIdx( uiAbsPartIdx ), uiLumaTrMode, uiChromaTrMode );
+  
+  // Y
+  piCoeff = pcCU->getCoeffY();
+  pResi = m_ppcYuvResi[uiDepth]->getLumaAddr();
+
+  m_pcTrQuant->setQPforQuant( pcCU->getQP( uiAbsPartIdx ), TEXT_LUMA, pcCU->getSlice()->getSPS()->getQpBDOffsetY(), 0 );
+
+  m_pcTrQuant->invRecurTransformNxN ( pcCU, 0, TEXT_LUMA, pResi, 0, m_ppcYuvResi[uiDepth]->getStride(), uiWidth, uiHeight, uiLumaTrMode, 0, piCoeff );
+  
+  // Cb and Cr
+#if CHROMA_QP_EXTENSION
+  Int curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCbQpOffset() + pcCU->getSlice()->getSliceQpDeltaCb();
+  m_pcTrQuant->setQPforQuant( pcCU->getQP( uiAbsPartIdx ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
+#else
+  m_pcTrQuant->setQPforQuant( pcCU->getQP( uiAbsPartIdx ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), pcCU->getSlice()->getPPS()->getChromaCbQpOffset() );
+#endif
+
+  uiWidth  >>= 1;
+  uiHeight >>= 1;
+  piCoeff = pcCU->getCoeffCb(); pResi = m_ppcYuvResi[uiDepth]->getCbAddr();
+  m_pcTrQuant->invRecurTransformNxN ( pcCU, 0, TEXT_CHROMA_U, pResi, 0, m_ppcYuvResi[uiDepth]->getCStride(), uiWidth, uiHeight, uiChromaTrMode, 0, piCoeff );
+
+#if CHROMA_QP_EXTENSION
+  curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCrQpOffset() + pcCU->getSlice()->getSliceQpDeltaCr();
+  m_pcTrQuant->setQPforQuant( pcCU->getQP( uiAbsPartIdx ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
+#else
+  m_pcTrQuant->setQPforQuant( pcCU->getQP( uiAbsPartIdx ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), pcCU->getSlice()->getPPS()->getChromaCrQpOffset() );
+#endif
+
+  piCoeff = pcCU->getCoeffCr(); pResi = m_ppcYuvResi[uiDepth]->getCrAddr();
+  m_pcTrQuant->invRecurTransformNxN ( pcCU, 0, TEXT_CHROMA_V, pResi, 0, m_ppcYuvResi[uiDepth]->getCStride(), uiWidth, uiHeight, uiChromaTrMode, 0, piCoeff );
+}
+
+/** Function for deriving reconstructed luma/chroma samples of a PCM mode CU.
+ * \param pcCU pointer to current CU
+ * \param uiPartIdx part index
+ * \param piPCM pointer to PCM code arrays
+ * \param piReco pointer to reconstructed sample arrays
+ * \param uiStride stride of reconstructed sample arrays
+ * \param uiWidth CU width
+ * \param uiHeight CU height
+ * \param ttText texture component type
+ * \returns Void
+ */
+Void TDecCu::xDecodePCMTexture( TComDataCU* pcCU, UInt uiPartIdx, Pel *piPCM, Pel* piReco, UInt uiStride, UInt uiWidth, UInt uiHeight, TextType ttText)
+{
+  UInt uiX, uiY;
+  Pel* piPicReco;
+  UInt uiPicStride;
+  UInt uiPcmLeftShiftBit; 
+
+  if( ttText == TEXT_LUMA )
+  {
+    uiPicStride   = pcCU->getPic()->getPicYuvRec()->getStride();
+    piPicReco = pcCU->getPic()->getPicYuvRec()->getLumaAddr(pcCU->getAddr(), pcCU->getZorderIdxInCU()+uiPartIdx);
+    uiPcmLeftShiftBit = g_uiBitDepth + g_uiBitIncrement - pcCU->getSlice()->getSPS()->getPCMBitDepthLuma();
+  }
+  else
+  {
+    uiPicStride = pcCU->getPic()->getPicYuvRec()->getCStride();
+
+    if( ttText == TEXT_CHROMA_U )
+    {
+      piPicReco = pcCU->getPic()->getPicYuvRec()->getCbAddr(pcCU->getAddr(), pcCU->getZorderIdxInCU()+uiPartIdx);
+    }
+    else
+    {
+      piPicReco = pcCU->getPic()->getPicYuvRec()->getCrAddr(pcCU->getAddr(), pcCU->getZorderIdxInCU()+uiPartIdx);
+    }
+    uiPcmLeftShiftBit = g_uiBitDepth + g_uiBitIncrement - pcCU->getSlice()->getSPS()->getPCMBitDepthChroma();
+  }
+
+  for( uiY = 0; uiY < uiHeight; uiY++ )
+  {
+    for( uiX = 0; uiX < uiWidth; uiX++ )
+    {
+      piReco[uiX] = (piPCM[uiX] << uiPcmLeftShiftBit);
+      piPicReco[uiX] = piReco[uiX];
+    }
+    piPCM += uiWidth;
+    piReco += uiStride;
+    piPicReco += uiPicStride;
+  }
+}
+
+/** Function for reconstructing a PCM mode CU.
+ * \param pcCU pointer to current CU
+ * \param uiAbsPartIdx CU index
+ * \param uiDepth CU Depth
+ * \returns Void
+ */
+Void TDecCu::xReconPCM( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  // Luma
+  UInt uiWidth  = (g_uiMaxCUWidth >> uiDepth);
+  UInt uiHeight = (g_uiMaxCUHeight >> uiDepth);
+
+  Pel* piPcmY = pcCU->getPCMSampleY();
+  Pel* piRecoY = m_ppcYuvReco[uiDepth]->getLumaAddr(0, uiWidth);
+
+  UInt uiStride = m_ppcYuvResi[uiDepth]->getStride();
+
+  xDecodePCMTexture( pcCU, 0, piPcmY, piRecoY, uiStride, uiWidth, uiHeight, TEXT_LUMA);
+
+  // Cb and Cr
+  UInt uiCWidth  = (uiWidth>>1);
+  UInt uiCHeight = (uiHeight>>1);
+
+  Pel* piPcmCb = pcCU->getPCMSampleCb();
+  Pel* piPcmCr = pcCU->getPCMSampleCr();
+  Pel* pRecoCb = m_ppcYuvReco[uiDepth]->getCbAddr();
+  Pel* pRecoCr = m_ppcYuvReco[uiDepth]->getCrAddr();
+
+  UInt uiCStride = m_ppcYuvReco[uiDepth]->getCStride();
+
+  xDecodePCMTexture( pcCU, 0, piPcmCb, pRecoCb, uiCStride, uiCWidth, uiCHeight, TEXT_CHROMA_U);
+  xDecodePCMTexture( pcCU, 0, piPcmCr, pRecoCr, uiCStride, uiCWidth, uiCHeight, TEXT_CHROMA_V);
+}
+
+/** Function for filling the PCM buffer of a CU using its reconstructed sample array 
+ * \param pcCU pointer to current CU
+ * \param uiAbsPartIdx CU index
+ * \param uiDepth CU Depth
+ * \returns Void
+ */
+Void TDecCu::xFillPCMBuffer(TComDataCU* pCU, UInt absPartIdx, UInt depth)
+{
+  // Luma
+  UInt width  = (g_uiMaxCUWidth >> depth);
+  UInt height = (g_uiMaxCUHeight >> depth);
+
+  Pel* pPcmY = pCU->getPCMSampleY();
+  Pel* pRecoY = m_ppcYuvReco[depth]->getLumaAddr(0, width);
+
+  UInt stride = m_ppcYuvReco[depth]->getStride();
+
+  for(Int y = 0; y < height; y++ )
+  {
+    for(Int x = 0; x < width; x++ )
+    {
+      pPcmY[x] = pRecoY[x];
+    }
+    pPcmY += width;
+    pRecoY += stride;
+  }
+
+  // Cb and Cr
+  UInt widthC  = (width>>1);
+  UInt heightC = (height>>1);
+
+  Pel* pPcmCb = pCU->getPCMSampleCb();
+  Pel* pPcmCr = pCU->getPCMSampleCr();
+  Pel* pRecoCb = m_ppcYuvReco[depth]->getCbAddr();
+  Pel* pRecoCr = m_ppcYuvReco[depth]->getCrAddr();
+
+  UInt strideC = m_ppcYuvReco[depth]->getCStride();
+
+  for(Int y = 0; y < heightC; y++ )
+  {
+    for(Int x = 0; x < widthC; x++ )
+    {
+      pPcmCb[x] = pRecoCb[x];
+      pPcmCr[x] = pRecoCr[x];
+    }
+    pPcmCr += widthC;
+    pPcmCb += widthC;
+    pRecoCb += strideC;
+    pRecoCr += strideC;
+  }
+
+}
+
+//! \}
Index: /trunk/source/Lib/TLibDecoder/TDecCu.h
===================================================================
--- /trunk/source/Lib/TLibDecoder/TDecCu.h	(revision 2)
+++ /trunk/source/Lib/TLibDecoder/TDecCu.h	(revision 2)
@@ -0,0 +1,143 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TDecCu.h
+    \brief    CU decoder class (header)
+*/
+
+#ifndef __TDECCU__
+#define __TDECCU__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TLibCommon/TComTrQuant.h"
+#include "TLibCommon/TComPrediction.h"
+#include "TDecEntropy.h"
+
+//! \ingroup TLibDecoder
+//! \{
+#if SVC_EXTENSION
+class TDecTop;
+#endif
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// CU decoder class
+class TDecCu
+{
+private:
+  UInt                m_uiMaxDepth;       ///< max. number of depth
+  TComYuv**           m_ppcYuvResi;       ///< array of residual buffer
+  TComYuv**           m_ppcYuvReco;       ///< array of prediction & reconstruction buffer
+  TComDataCU**        m_ppcCU;            ///< CU data array
+  
+  // access channel
+  TComTrQuant*        m_pcTrQuant;
+  TComPrediction*     m_pcPrediction;
+  TDecEntropy*        m_pcEntropyDecoder;
+
+  Bool                m_bDecodeDQP;
+#if SVC_EXTENSION
+  TDecTop**           m_ppcTDecTop;
+  UInt                m_layerId;   
+#endif
+  
+#if INTRA_BL
+  TComPicYuv*         m_pcPicYuvRecBase;       ///< reconstructed base layer
+#endif 
+  
+public:
+  TDecCu();
+  virtual ~TDecCu();
+  
+  /// initialize access channels
+#if SVC_EXTENSION
+  Void  init                    ( TDecTop** ppcDecTop, TDecEntropy* pcEntropyDecoder, TComTrQuant* pcTrQuant, TComPrediction* pcPrediction, UInt layerId );
+#else
+  Void  init                    ( TDecEntropy* pcEntropyDecoder, TComTrQuant* pcTrQuant, TComPrediction* pcPrediction );
+#endif 
+
+  /// create internal buffers
+  Void  create                  ( UInt uiMaxDepth, UInt uiMaxWidth, UInt uiMaxHeight );
+  
+  /// destroy internal buffers
+  Void  destroy                 ();
+  
+  /// decode CU information
+  Void  decodeCU                ( TComDataCU* pcCU, UInt& ruiIsLast );
+  
+  /// reconstruct CU information
+  Void  decompressCU            ( TComDataCU* pcCU );
+  
+#if SVC_EXTENSION
+  TDecTop*   getLayerDec        ( UInt LayerId )  { return m_ppcTDecTop[LayerId]; }
+#endif
+#if INTRA_BL
+  Void  setBaseRecPic           ( TComPicYuv* p ) { m_pcPicYuvRecBase = p; }
+#endif 
+protected:
+  
+  Void xDecodeCU                ( TComDataCU* pcCU,                       UInt uiAbsPartIdx, UInt uiDepth, UInt &ruiIsLast);
+  Void xFinishDecodeCU          ( TComDataCU* pcCU,                       UInt uiAbsPartIdx, UInt uiDepth, UInt &ruiIsLast);
+  Bool xDecodeSliceEnd          ( TComDataCU* pcCU,                       UInt uiAbsPartIdx, UInt uiDepth);
+  Void xDecompressCU            ( TComDataCU* pcCU, TComDataCU* pcCUCur,  UInt uiAbsPartIdx, UInt uiDepth );
+  
+  Void xReconInter              ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  
+  Void  xReconIntraQT           ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void  xIntraRecLumaBlk        ( TComDataCU* pcCU, UInt uiTrDepth, UInt uiAbsPartIdx, TComYuv* pcRecoYuv, TComYuv* pcPredYuv, TComYuv* pcResiYuv );
+  Void  xIntraRecChromaBlk      ( TComDataCU* pcCU, UInt uiTrDepth, UInt uiAbsPartIdx, TComYuv* pcRecoYuv, TComYuv* pcPredYuv, TComYuv* pcResiYuv, UInt uiChromaId );
+  
+  Void  xReconPCM               ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+
+  Void xDecodeInterTexture      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void xDecodePCMTexture        ( TComDataCU* pcCU, UInt uiPartIdx, Pel *piPCM, Pel* piReco, UInt uiStride, UInt uiWidth, UInt uiHeight, TextType ttText);
+  
+  Void xCopyToPic               ( TComDataCU* pcCU, TComPic* pcPic, UInt uiZorderIdx, UInt uiDepth );
+
+  Void  xIntraLumaRecQT         ( TComDataCU* pcCU, UInt uiTrDepth, UInt uiAbsPartIdx, TComYuv* pcRecoYuv, TComYuv* pcPredYuv, TComYuv* pcResiYuv );
+  Void  xIntraChromaRecQT       ( TComDataCU* pcCU, UInt uiTrDepth, UInt uiAbsPartIdx, TComYuv* pcRecoYuv, TComYuv* pcPredYuv, TComYuv* pcResiYuv );
+
+  Bool getdQPFlag               ()                        { return m_bDecodeDQP;        }
+  Void setdQPFlag               ( Bool b )                { m_bDecodeDQP = b;           }
+  Void xFillPCMBuffer           (TComDataCU* pCU, UInt absPartIdx, UInt depth);
+};
+
+//! \}
+
+#endif
+
Index: /trunk/source/Lib/TLibDecoder/TDecEntropy.cpp
===================================================================
--- /trunk/source/Lib/TLibDecoder/TDecEntropy.cpp	(revision 2)
+++ /trunk/source/Lib/TLibDecoder/TDecEntropy.cpp	(revision 2)
@@ -0,0 +1,623 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TDecEntropy.cpp
+    \brief    entropy decoder class
+*/
+
+#include "TDecEntropy.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+Void TDecEntropy::setEntropyDecoder         ( TDecEntropyIf* p )
+{
+  m_pcEntropyDecoderIf = p;
+}
+
+#include "TLibCommon/TComAdaptiveLoopFilter.h"
+#include "TLibCommon/TComSampleAdaptiveOffset.h"
+
+Void TDecEntropy::decodeSkipFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  m_pcEntropyDecoderIf->parseSkipFlag( pcCU, uiAbsPartIdx, uiDepth );
+}
+
+Void TDecEntropy::decodeCUTransquantBypassFlag(TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  m_pcEntropyDecoderIf->parseCUTransquantBypassFlag( pcCU, uiAbsPartIdx, uiDepth );
+}
+
+#if INTRA_BL
+Void TDecEntropy::decodeIntraBLFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+  m_pcEntropyDecoderIf->parseIntraBLFlag( pcCU, uiAbsPartIdx, uiPartIdx, uiDepth );
+}
+#endif
+
+/** decode merge flag
+ * \param pcSubCU
+ * \param uiAbsPartIdx 
+ * \param uiDepth
+ * \param uiPUIdx 
+ * \returns Void
+ */
+Void TDecEntropy::decodeMergeFlag( TComDataCU* pcSubCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPUIdx )
+{ 
+  // at least one merge candidate exists
+  m_pcEntropyDecoderIf->parseMergeFlag( pcSubCU, uiAbsPartIdx, uiDepth, uiPUIdx );
+}
+
+/** decode merge index
+ * \param pcCU
+ * \param uiPartIdx 
+ * \param uiAbsPartIdx 
+ * \param puhInterDirNeighbours pointer to list of inter direction from the casual neighbours
+ * \param pcMvFieldNeighbours pointer to list of motion vector field from the casual neighbours
+ * \param uiDepth
+ * \returns Void
+ */
+Void TDecEntropy::decodeMergeIndex( TComDataCU* pcCU, UInt uiPartIdx, UInt uiAbsPartIdx, PartSize eCUMode, UChar* puhInterDirNeighbours, TComMvField* pcMvFieldNeighbours, UInt uiDepth )
+{
+  UInt uiMergeIndex = 0;
+  m_pcEntropyDecoderIf->parseMergeIndex( pcCU, uiMergeIndex, uiAbsPartIdx, uiDepth );
+  pcCU->setMergeIndexSubParts( uiMergeIndex, uiAbsPartIdx, uiPartIdx, uiDepth );
+}
+
+Void TDecEntropy::decodeSplitFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  m_pcEntropyDecoderIf->parseSplitFlag( pcCU, uiAbsPartIdx, uiDepth );
+}
+
+Void TDecEntropy::decodePredMode( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  m_pcEntropyDecoderIf->parsePredMode( pcCU, uiAbsPartIdx, uiDepth );
+}
+
+Void TDecEntropy::decodePartSize( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  m_pcEntropyDecoderIf->parsePartSize( pcCU, uiAbsPartIdx, uiDepth );
+}
+
+Void TDecEntropy::decodePredInfo    ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, TComDataCU* pcSubCU )
+{
+#if INTRA_BL
+  if( pcCU->isIntraBL( uiAbsPartIdx ) )                                 // Do nothing for Intra BL mode.
+  {
+    return;
+  }
+#endif
+  if( pcCU->isIntra( uiAbsPartIdx ) )                                 // If it is Intra mode, encode intra prediction mode.
+  {
+    decodeIntraDirModeLuma  ( pcCU, uiAbsPartIdx, uiDepth );
+    decodeIntraDirModeChroma( pcCU, uiAbsPartIdx, uiDepth );
+  }
+  else                                                                // if it is Inter mode, encode motion vector and reference index
+  {
+    decodePUWise( pcCU, uiAbsPartIdx, uiDepth, pcSubCU );
+  }
+}
+
+/** Parse I_PCM information. 
+ * \param pcCU  pointer to CUpointer to CU
+ * \param uiAbsPartIdx CU index
+ * \param uiDepth CU depth
+ * \returns Void
+ */
+Void TDecEntropy::decodeIPCMInfo( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  if(!pcCU->getSlice()->getSPS()->getUsePCM()
+    || pcCU->getWidth(uiAbsPartIdx) > (1<<pcCU->getSlice()->getSPS()->getPCMLog2MaxSize())
+    || pcCU->getWidth(uiAbsPartIdx) < (1<<pcCU->getSlice()->getSPS()->getPCMLog2MinSize()) )
+  {
+    return;
+  }
+  
+  m_pcEntropyDecoderIf->parseIPCMInfo( pcCU, uiAbsPartIdx, uiDepth );
+}
+
+Void TDecEntropy::decodeIntraDirModeLuma  ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  m_pcEntropyDecoderIf->parseIntraDirLumaAng( pcCU, uiAbsPartIdx, uiDepth );
+}
+
+Void TDecEntropy::decodeIntraDirModeChroma( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  m_pcEntropyDecoderIf->parseIntraDirChroma( pcCU, uiAbsPartIdx, uiDepth );
+}
+
+/** decode motion information for every PU block.
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \param uiDepth
+ * \param pcSubCU
+ * \returns Void
+ */
+Void TDecEntropy::decodePUWise( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, TComDataCU* pcSubCU )
+{
+  PartSize ePartSize = pcCU->getPartitionSize( uiAbsPartIdx );
+  UInt uiNumPU = ( ePartSize == SIZE_2Nx2N ? 1 : ( ePartSize == SIZE_NxN ? 4 : 2 ) );
+  UInt uiPUOffset = ( g_auiPUOffset[UInt( ePartSize )] << ( ( pcCU->getSlice()->getSPS()->getMaxCUDepth() - uiDepth ) << 1 ) ) >> 4;
+
+  TComMvField cMvFieldNeighbours[MRG_MAX_NUM_CANDS << 1]; // double length for mv of both lists
+  UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS];
+
+  for ( UInt ui = 0; ui < pcCU->getSlice()->getMaxNumMergeCand(); ui++ )
+  {
+    uhInterDirNeighbours[ui] = 0;
+  }
+  Int numValidMergeCand = 0;
+  bool isMerged = false;
+
+  pcSubCU->copyInterPredInfoFrom( pcCU, uiAbsPartIdx, REF_PIC_LIST_0 );
+  pcSubCU->copyInterPredInfoFrom( pcCU, uiAbsPartIdx, REF_PIC_LIST_1 );
+  for ( UInt uiPartIdx = 0, uiSubPartIdx = uiAbsPartIdx; uiPartIdx < uiNumPU; uiPartIdx++, uiSubPartIdx += uiPUOffset )
+  {
+    decodeMergeFlag( pcCU, uiSubPartIdx, uiDepth, uiPartIdx );
+    if ( pcCU->getMergeFlag( uiSubPartIdx ) )
+    {
+      decodeMergeIndex( pcCU, uiPartIdx, uiSubPartIdx, ePartSize, uhInterDirNeighbours, cMvFieldNeighbours, uiDepth );
+      UInt uiMergeIndex = pcCU->getMergeIndex(uiSubPartIdx);
+#if REF_IDX_FRAMEWORK  // HM bug fix
+      if(uiPartIdx)
+      {
+        for(UInt ui=0; ui<uiMergeIndex+1; ui++)
+        {
+          cMvFieldNeighbours[(ui<<1)].setMvField(TComMv(), NOT_VALID);
+          cMvFieldNeighbours[(ui<<1)+1].setMvField(TComMv(), NOT_VALID);
+        }
+      }
+#endif
+      if ( pcCU->getSlice()->getPPS()->getLog2ParallelMergeLevelMinus2() && ePartSize != SIZE_2Nx2N && pcSubCU->getWidth( 0 ) <= 8 ) 
+      {
+        pcSubCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uiDepth );
+        if ( !isMerged )
+        {
+          pcSubCU->getInterMergeCandidates( 0, 0, uiDepth, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand );
+          isMerged = true;
+        }
+        pcSubCU->setPartSizeSubParts( ePartSize, 0, uiDepth );
+      }
+      else
+      {
+        uiMergeIndex = pcCU->getMergeIndex(uiSubPartIdx);
+        pcSubCU->getInterMergeCandidates( uiSubPartIdx-uiAbsPartIdx, uiPartIdx, uiDepth, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand, uiMergeIndex );
+      }
+      pcCU->setInterDirSubParts( uhInterDirNeighbours[uiMergeIndex], uiSubPartIdx, uiPartIdx, uiDepth );
+
+      TComMv cTmpMv( 0, 0 );
+      for ( UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )
+      {        
+        if ( pcCU->getSlice()->getNumRefIdx( RefPicList( uiRefListIdx ) ) > 0 )
+        {
+          pcCU->setMVPIdxSubParts( 0, RefPicList( uiRefListIdx ), uiSubPartIdx, uiPartIdx, uiDepth);
+          pcCU->setMVPNumSubParts( 0, RefPicList( uiRefListIdx ), uiSubPartIdx, uiPartIdx, uiDepth);
+          pcCU->getCUMvField( RefPicList( uiRefListIdx ) )->setAllMvd( cTmpMv, ePartSize, uiSubPartIdx, uiDepth, uiPartIdx );
+          pcCU->getCUMvField( RefPicList( uiRefListIdx ) )->setAllMvField( cMvFieldNeighbours[ 2*uiMergeIndex + uiRefListIdx ], ePartSize, uiSubPartIdx, uiDepth, uiPartIdx );
+        }
+      }
+    }
+    else
+    {
+      decodeInterDirPU( pcCU, uiSubPartIdx, uiDepth, uiPartIdx );
+      for ( UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )
+      {        
+        if ( pcCU->getSlice()->getNumRefIdx( RefPicList( uiRefListIdx ) ) > 0 )
+        {
+          decodeRefFrmIdxPU( pcCU,    uiSubPartIdx,              uiDepth, uiPartIdx, RefPicList( uiRefListIdx ) );
+          decodeMvdPU      ( pcCU,    uiSubPartIdx,              uiDepth, uiPartIdx, RefPicList( uiRefListIdx ) );
+          decodeMVPIdxPU   ( pcSubCU, uiSubPartIdx-uiAbsPartIdx, uiDepth, uiPartIdx, RefPicList( uiRefListIdx ) );
+        }
+      }
+    }
+    if ( (pcCU->getInterDir(uiSubPartIdx) == 3) && pcSubCU->isBipredRestriction(uiPartIdx) )
+    {
+      pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMv( TComMv(0,0), ePartSize, uiSubPartIdx, uiDepth, uiPartIdx);
+      pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllRefIdx( -1, ePartSize, uiSubPartIdx, uiDepth, uiPartIdx);
+      pcCU->setInterDirSubParts( 1, uiSubPartIdx, uiPartIdx, uiDepth);
+    }
+  }
+  return;
+}
+
+/** decode inter direction for a PU block
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \param uiDepth
+ * \param uiPartIdx 
+ * \returns Void
+ */
+Void TDecEntropy::decodeInterDirPU( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPartIdx )
+{
+  UInt uiInterDir;
+
+  if ( pcCU->getSlice()->isInterP() )
+  {
+    uiInterDir = 1;
+  }
+  else
+  {
+    m_pcEntropyDecoderIf->parseInterDir( pcCU, uiInterDir, uiAbsPartIdx, uiDepth );
+  }
+
+  pcCU->setInterDirSubParts( uiInterDir, uiAbsPartIdx, uiPartIdx, uiDepth );
+}
+
+Void TDecEntropy::decodeRefFrmIdxPU( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPartIdx, RefPicList eRefList )
+{
+  Int iRefFrmIdx = 0;
+  Int iParseRefFrmIdx = pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList );
+
+  if ( pcCU->getSlice()->getNumRefIdx( eRefList ) > 1 && iParseRefFrmIdx )
+  {
+    m_pcEntropyDecoderIf->parseRefFrmIdx( pcCU, iRefFrmIdx, uiAbsPartIdx, uiDepth, eRefList );
+  }
+  else if ( !iParseRefFrmIdx )
+  {
+    iRefFrmIdx = NOT_VALID;
+  }
+  else
+  {
+    iRefFrmIdx = 0;
+  }
+
+  PartSize ePartSize = pcCU->getPartitionSize( uiAbsPartIdx );
+  pcCU->getCUMvField( eRefList )->setAllRefIdx( iRefFrmIdx, ePartSize, uiAbsPartIdx, uiDepth, uiPartIdx );
+}
+
+/** decode motion vector difference for a PU block
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \param uiDepth
+ * \param uiPartIdx
+ * \param eRefList 
+ * \returns Void
+ */
+Void TDecEntropy::decodeMvdPU( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPartIdx, RefPicList eRefList )
+{
+  if ( pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList ) )
+  {
+    m_pcEntropyDecoderIf->parseMvd( pcCU, uiAbsPartIdx, uiPartIdx, uiDepth, eRefList );
+  }
+}
+
+Void TDecEntropy::decodeMVPIdxPU( TComDataCU* pcSubCU, UInt uiPartAddr, UInt uiDepth, UInt uiPartIdx, RefPicList eRefList )
+{
+  Int iMVPIdx = -1;
+
+  TComMv cZeroMv( 0, 0 );
+  TComMv cMv     = cZeroMv;
+  Int    iRefIdx = -1;
+
+  TComCUMvField* pcSubCUMvField = pcSubCU->getCUMvField( eRefList );
+  AMVPInfo* pAMVPInfo = pcSubCUMvField->getAMVPInfo();
+
+  iRefIdx = pcSubCUMvField->getRefIdx(uiPartAddr);
+  cMv = cZeroMv;
+
+#if !SPS_AMVP_CLEANUP
+  if ( (pcSubCU->getInterDir(uiPartAddr) & ( 1 << eRefList )) && (pcSubCU->getAMVPMode(uiPartAddr) == AM_EXPL) )
+#else
+  if ( (pcSubCU->getInterDir(uiPartAddr) & ( 1 << eRefList )) )
+#endif
+  {
+    m_pcEntropyDecoderIf->parseMVPIdx( iMVPIdx );
+  }
+  pcSubCU->fillMvpCand(uiPartIdx, uiPartAddr, eRefList, iRefIdx, pAMVPInfo);
+  pcSubCU->setMVPNumSubParts(pAMVPInfo->iN, eRefList, uiPartAddr, uiPartIdx, uiDepth);
+  pcSubCU->setMVPIdxSubParts( iMVPIdx, eRefList, uiPartAddr, uiPartIdx, uiDepth );
+  if ( iRefIdx >= 0 )
+  {
+    m_pcPrediction->getMvPredAMVP( pcSubCU, uiPartIdx, uiPartAddr, eRefList, iRefIdx, cMv);
+    cMv += pcSubCUMvField->getMvd( uiPartAddr );
+  }
+
+  PartSize ePartSize = pcSubCU->getPartitionSize( uiPartAddr );
+  pcSubCU->getCUMvField( eRefList )->setAllMv(cMv, ePartSize, uiPartAddr, 0, uiPartIdx);
+}
+
+Void TDecEntropy::xDecodeTransform( TComDataCU* pcCU, UInt offsetLuma, UInt offsetChroma, UInt uiAbsPartIdx, UInt absTUPartIdx, UInt uiDepth, UInt width, UInt height, UInt uiTrIdx, UInt uiInnerQuadIdx, Bool& bCodeDQP)
+{
+  UInt uiSubdiv;
+  const UInt uiLog2TrafoSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth()]+2 - uiDepth;
+
+  if(uiTrIdx==0)
+  {
+    m_bakAbsPartIdxCU = uiAbsPartIdx;
+  }
+  if( uiLog2TrafoSize == 2 )
+  {
+    UInt partNum = pcCU->getPic()->getNumPartInCU() >> ( ( uiDepth - 1 ) << 1 );
+    if( ( uiAbsPartIdx % partNum ) == 0 )
+    {
+      m_uiBakAbsPartIdx   = uiAbsPartIdx;
+      m_uiBakChromaOffset = offsetChroma;
+    }
+  }
+  if( pcCU->getPredictionMode(uiAbsPartIdx) == MODE_INTRA && pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_NxN && uiDepth == pcCU->getDepth(uiAbsPartIdx) )
+  {
+    uiSubdiv = 1;
+  }
+  else if( (pcCU->getSlice()->getSPS()->getQuadtreeTUMaxDepthInter() == 1) && (pcCU->getPredictionMode(uiAbsPartIdx) == MODE_INTER) && ( pcCU->getPartitionSize(uiAbsPartIdx) != SIZE_2Nx2N ) && (uiDepth == pcCU->getDepth(uiAbsPartIdx)) )
+  {
+    uiSubdiv = (uiLog2TrafoSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx));
+  }
+  else if( uiLog2TrafoSize > pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() )
+  {
+    uiSubdiv = 1;
+  }
+  else if( uiLog2TrafoSize == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+  {
+    uiSubdiv = 0;
+  }
+  else if( uiLog2TrafoSize == pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
+  {
+    uiSubdiv = 0;
+  }
+  else
+  {
+    assert( uiLog2TrafoSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) );
+#if TRANS_SPLIT_FLAG_CTX_REDUCTION
+    m_pcEntropyDecoderIf->parseTransformSubdivFlag( uiSubdiv, 5 - uiLog2TrafoSize );
+#else
+    m_pcEntropyDecoderIf->parseTransformSubdivFlag( uiSubdiv, uiDepth );
+#endif
+  }
+  
+  const UInt uiTrDepth = uiDepth - pcCU->getDepth( uiAbsPartIdx );
+  {
+    const Bool bFirstCbfOfCU = uiTrDepth == 0;
+    if( bFirstCbfOfCU )
+    {
+      pcCU->setCbfSubParts( 0, TEXT_CHROMA_U, uiAbsPartIdx, uiDepth );
+      pcCU->setCbfSubParts( 0, TEXT_CHROMA_V, uiAbsPartIdx, uiDepth );
+    }
+    if( bFirstCbfOfCU || uiLog2TrafoSize > 2 )
+    {
+      if( bFirstCbfOfCU || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth - 1 ) )
+      {
+        m_pcEntropyDecoderIf->parseQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth, uiDepth );
+      }
+      if( bFirstCbfOfCU || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth - 1 ) )
+      {
+        m_pcEntropyDecoderIf->parseQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth, uiDepth );
+      }
+    }
+    else
+    {
+      pcCU->setCbfSubParts( pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth - 1 ) << uiTrDepth, TEXT_CHROMA_U, uiAbsPartIdx, uiDepth );
+      pcCU->setCbfSubParts( pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth - 1 ) << uiTrDepth, TEXT_CHROMA_V, uiAbsPartIdx, uiDepth );
+    }
+  }
+  
+  if( uiSubdiv )
+  {
+    UInt size;
+    width  >>= 1;
+    height >>= 1;
+    size = width*height;
+    uiTrIdx++;
+    ++uiDepth;
+    const UInt uiQPartNum = pcCU->getPic()->getNumPartInCU() >> (uiDepth << 1);
+    const UInt uiStartAbsPartIdx = uiAbsPartIdx;
+    UInt uiLumaTrMode, uiChromaTrMode;
+    pcCU->convertTransIdx( uiStartAbsPartIdx, uiTrDepth+1, uiLumaTrMode, uiChromaTrMode );
+    UInt uiYCbf = 0;
+    UInt uiUCbf = 0;
+    UInt uiVCbf = 0;
+    
+    for( Int i = 0; i < 4; i++ )
+    {
+#if REMOVE_NSQT
+      UInt nsAddr = uiAbsPartIdx;
+#else
+      UInt nsAddr = 0;
+      nsAddr = pcCU->getNSAbsPartIdx( uiLog2TrafoSize-1, uiAbsPartIdx, absTUPartIdx, i, uiTrDepth+1 );
+#endif
+      xDecodeTransform( pcCU, offsetLuma, offsetChroma, uiAbsPartIdx, nsAddr, uiDepth, width, height, uiTrIdx, i, bCodeDQP );
+      uiYCbf |= pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA, uiLumaTrMode );
+      uiUCbf |= pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiChromaTrMode );
+      uiVCbf |= pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiChromaTrMode );
+      uiAbsPartIdx += uiQPartNum;
+      offsetLuma += size;  offsetChroma += (size>>2);
+    }
+    
+    pcCU->convertTransIdx( uiStartAbsPartIdx, uiTrDepth, uiLumaTrMode, uiChromaTrMode );
+    for( UInt ui = 0; ui < 4 * uiQPartNum; ++ui )
+    {
+      pcCU->getCbf( TEXT_LUMA     )[uiStartAbsPartIdx + ui] |= uiYCbf << uiLumaTrMode;
+      pcCU->getCbf( TEXT_CHROMA_U )[uiStartAbsPartIdx + ui] |= uiUCbf << uiChromaTrMode;
+      pcCU->getCbf( TEXT_CHROMA_V )[uiStartAbsPartIdx + ui] |= uiVCbf << uiChromaTrMode;
+    }
+  }
+  else
+  {
+    assert( uiDepth >= pcCU->getDepth( uiAbsPartIdx ) );
+    pcCU->setTrIdxSubParts( uiTrDepth, uiAbsPartIdx, uiDepth );
+    
+    {
+      DTRACE_CABAC_VL( g_nSymbolCounter++ );
+      DTRACE_CABAC_T( "\tTrIdx: abspart=" );
+      DTRACE_CABAC_V( uiAbsPartIdx );
+      DTRACE_CABAC_T( "\tdepth=" );
+      DTRACE_CABAC_V( uiDepth );
+      DTRACE_CABAC_T( "\ttrdepth=" );
+      DTRACE_CABAC_V( uiTrDepth );
+      DTRACE_CABAC_T( "\n" );
+    }
+    
+    UInt uiLumaTrMode, uiChromaTrMode;
+    pcCU->convertTransIdx( uiAbsPartIdx, uiTrDepth, uiLumaTrMode, uiChromaTrMode );
+#if !REMOVE_NSQT
+    if(pcCU->getPredictionMode( uiAbsPartIdx ) == MODE_INTER && pcCU->useNonSquarePU( uiAbsPartIdx ) )
+    {
+      pcCU->setNSQTIdxSubParts( uiLog2TrafoSize, uiAbsPartIdx, absTUPartIdx, uiLumaTrMode );
+    }
+#endif
+    pcCU->setCbfSubParts ( 0, TEXT_LUMA, uiAbsPartIdx, uiDepth );
+#if INTRA_BL
+    if( ( !pcCU->isIntra(uiAbsPartIdx) ) && uiDepth == pcCU->getDepth( uiAbsPartIdx ) && !pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, 0 ) && !pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, 0 ) )
+#else
+    if( pcCU->getPredictionMode(uiAbsPartIdx) != MODE_INTRA && uiDepth == pcCU->getDepth( uiAbsPartIdx ) && !pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, 0 ) && !pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, 0 ) )
+#endif 
+    {
+      pcCU->setCbfSubParts( 1 << uiLumaTrMode, TEXT_LUMA, uiAbsPartIdx, uiDepth );
+    }
+    else
+    {
+      m_pcEntropyDecoderIf->parseQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA, uiLumaTrMode, uiDepth );
+    }
+
+
+    // transform_unit begin
+    UInt cbfY = pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA    , uiTrIdx );
+    UInt cbfU = pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrIdx );
+    UInt cbfV = pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrIdx );
+    if( uiLog2TrafoSize == 2 )
+    {
+      UInt partNum = pcCU->getPic()->getNumPartInCU() >> ( ( uiDepth - 1 ) << 1 );
+      if( ( uiAbsPartIdx % partNum ) == (partNum - 1) )
+      {
+        cbfU = pcCU->getCbf( m_uiBakAbsPartIdx, TEXT_CHROMA_U, uiTrIdx );
+        cbfV = pcCU->getCbf( m_uiBakAbsPartIdx, TEXT_CHROMA_V, uiTrIdx );
+      }
+    }
+    if ( cbfY || cbfU || cbfV )
+    {
+      // dQP: only for LCU
+      if ( pcCU->getSlice()->getPPS()->getUseDQP() )
+      {
+        if ( bCodeDQP )
+        {
+          decodeQP( pcCU, m_bakAbsPartIdxCU);
+          bCodeDQP = false;
+        }
+      }
+    }
+    if( cbfY )
+    {
+      Int trWidth = width;
+      Int trHeight = height;
+#if !REMOVE_NSQT
+      pcCU->getNSQTSize( uiTrIdx, uiAbsPartIdx, trWidth, trHeight );
+#endif
+      m_pcEntropyDecoderIf->parseCoeffNxN( pcCU, (pcCU->getCoeffY()+offsetLuma), uiAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_LUMA );
+    }
+    if( uiLog2TrafoSize > 2 )
+    {
+      Int trWidth = width >> 1;
+      Int trHeight = height >> 1;
+#if !REMOVE_NSQT
+      pcCU->getNSQTSize( uiTrIdx, uiAbsPartIdx, trWidth, trHeight );
+#endif
+      if( cbfU )
+      {
+        m_pcEntropyDecoderIf->parseCoeffNxN( pcCU, (pcCU->getCoeffCb()+offsetChroma), uiAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_CHROMA_U );
+      }
+      if( cbfV )
+      {
+        m_pcEntropyDecoderIf->parseCoeffNxN( pcCU, (pcCU->getCoeffCr()+offsetChroma), uiAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_CHROMA_V );
+      }
+    }
+    else
+    {
+      UInt partNum = pcCU->getPic()->getNumPartInCU() >> ( ( uiDepth - 1 ) << 1 );
+      if( ( uiAbsPartIdx % partNum ) == (partNum - 1) )
+      {
+        Int trWidth = width;
+        Int trHeight = height;
+#if !REMOVE_NSQT
+        pcCU->getNSQTSize( uiTrIdx - 1, uiAbsPartIdx, trWidth, trHeight );
+#endif
+        if( cbfU )
+        {
+          m_pcEntropyDecoderIf->parseCoeffNxN( pcCU, (pcCU->getCoeffCb()+m_uiBakChromaOffset), m_uiBakAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_CHROMA_U );
+        }
+        if( cbfV )
+        {
+          m_pcEntropyDecoderIf->parseCoeffNxN( pcCU, (pcCU->getCoeffCr()+m_uiBakChromaOffset), m_uiBakAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_CHROMA_V );
+        }
+      }
+    }
+    // transform_unit end
+  }
+}
+
+Void TDecEntropy::decodeQP          ( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  if ( pcCU->getSlice()->getPPS()->getUseDQP() )
+  {
+    m_pcEntropyDecoderIf->parseDeltaQP( pcCU, uiAbsPartIdx, pcCU->getDepth( uiAbsPartIdx ) );
+  }
+}
+
+
+/** decode coefficients
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \param uiDepth
+ * \param uiWidth
+ * \param uiHeight 
+ * \returns Void
+ */
+Void TDecEntropy::decodeCoeff( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiWidth, UInt uiHeight, Bool& bCodeDQP )
+{
+  UInt uiMinCoeffSize = pcCU->getPic()->getMinCUWidth()*pcCU->getPic()->getMinCUHeight();
+  UInt uiLumaOffset   = uiMinCoeffSize*uiAbsPartIdx;
+  UInt uiChromaOffset = uiLumaOffset>>2;
+  
+  if( pcCU->isIntra(uiAbsPartIdx) )
+  {
+  }
+  else
+  {
+    UInt uiQtRootCbf = 1;
+    if( !( pcCU->getPartitionSize( uiAbsPartIdx) == SIZE_2Nx2N && pcCU->getMergeFlag( uiAbsPartIdx ) ) )
+    {
+      m_pcEntropyDecoderIf->parseQtRootCbf( pcCU, uiAbsPartIdx, uiDepth, uiQtRootCbf );
+    }
+    if ( !uiQtRootCbf )
+    {
+      pcCU->setCbfSubParts( 0, 0, 0, uiAbsPartIdx, uiDepth );
+      pcCU->setTrIdxSubParts( 0 , uiAbsPartIdx, uiDepth );
+#if !REMOVE_NSQT
+      pcCU->setNSQTIdxSubParts( uiAbsPartIdx, uiDepth );
+#endif
+      return;
+    }
+    
+  }
+  xDecodeTransform( pcCU, uiLumaOffset, uiChromaOffset, uiAbsPartIdx, uiAbsPartIdx, uiDepth, uiWidth, uiHeight, 0, 0, bCodeDQP );
+}
+
+//! \}
Index: /trunk/source/Lib/TLibDecoder/TDecEntropy.h
===================================================================
--- /trunk/source/Lib/TLibDecoder/TDecEntropy.h	(revision 2)
+++ /trunk/source/Lib/TLibDecoder/TDecEntropy.h	(revision 2)
@@ -0,0 +1,201 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TDecEntropy.h
+    \brief    entropy decoder class (header)
+*/
+
+#ifndef __TDECENTROPY__
+#define __TDECENTROPY__
+
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComBitStream.h"
+#include "TLibCommon/TComSlice.h"
+#include "TLibCommon/TComPic.h"
+#include "TLibCommon/TComPrediction.h"
+#include "TLibCommon/TComAdaptiveLoopFilter.h"
+#include "TLibCommon/TComSampleAdaptiveOffset.h"
+
+class TDecSbac;
+class TDecCavlc;
+class SEImessages;
+class ParameterSetManagerDecoder;
+
+//! \ingroup TLibDecoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// entropy decoder pure class
+class TDecEntropyIf
+{
+public:
+  //  Virtual list for SBAC/CAVLC
+  virtual Void  resetEntropy          ( TComSlice* pcSlice )     = 0;
+  virtual Void  setBitstream          ( TComInputBitstream* p )  = 0;
+
+  virtual Void  decodeFlush()                                                                      = 0;
+  virtual Void  parseVPS                  ( TComVPS* pcVPS )                       = 0;
+  virtual Void  parseSPS                  ( TComSPS* pcSPS )                                      = 0;
+  virtual Void  parsePPS                  ( TComPPS* pcPPS )                                      = 0;
+#if !REMOVE_APS
+  virtual Void  parseAPS                  ( TComAPS* pAPS  )                                      = 0;
+#endif
+
+  virtual Void parseSliceHeader          ( TComSlice*& rpcSlice, ParameterSetManagerDecoder *parameterSetManager)       = 0;
+
+  virtual Void  parseTerminatingBit       ( UInt& ruilsLast )                                     = 0;
+  
+  virtual Void parseMVPIdx        ( Int& riMVPIdx ) = 0;
+  
+public:
+  virtual Void parseSkipFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+  virtual Void parseCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+  virtual Void parseSplitFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+  virtual Void parseMergeFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPUIdx ) = 0;
+  virtual Void parseMergeIndex    ( TComDataCU* pcCU, UInt& ruiMergeIndex, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+  virtual Void parsePartSize      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+  virtual Void parsePredMode      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+  
+  virtual Void parseIntraDirLumaAng( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+  
+  virtual Void parseIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+  
+  virtual Void parseInterDir      ( TComDataCU* pcCU, UInt& ruiInterDir, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+  virtual Void parseRefFrmIdx     ( TComDataCU* pcCU, Int& riRefFrmIdx, UInt uiAbsPartIdx, UInt uiDepth, RefPicList eRefList ) = 0;
+  virtual Void parseMvd           ( TComDataCU* pcCU, UInt uiAbsPartAddr, UInt uiPartIdx, UInt uiDepth, RefPicList eRefList ) = 0;
+  
+  virtual Void parseTransformSubdivFlag( UInt& ruiSubdivFlag, UInt uiLog2TransformBlockSize ) = 0;
+  virtual Void parseQtCbf         ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth, UInt uiDepth ) = 0;
+  virtual Void parseQtRootCbf     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt& uiQtRootCbf ) = 0;
+  
+  virtual Void parseDeltaQP       ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+  
+  virtual Void parseIPCMInfo     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth) = 0;
+
+  virtual Void parseCoeffNxN( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType ) = 0;
+  virtual Void parseTransformSkipFlags ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, UInt uiDepth, TextType eTType) = 0;
+
+#if INTRA_BL
+  virtual Void parseIntraBLFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth ) = 0;
+#endif
+#if !REMOVE_FGS
+  /// set slice granularity
+  virtual Void setSliceGranularity(Int iSliceGranularity) = 0;
+
+  /// get slice granularity
+  virtual Int  getSliceGranularity()                      = 0;
+#endif
+  virtual Void updateContextTables( SliceType eSliceType, Int iQp ) = 0;
+  
+  virtual ~TDecEntropyIf() {}
+};
+
+/// entropy decoder class
+class TDecEntropy
+{
+private:
+  TDecEntropyIf*  m_pcEntropyDecoderIf;
+  TComPrediction* m_pcPrediction;
+  UInt    m_uiBakAbsPartIdx;
+  UInt    m_uiBakChromaOffset;
+  UInt    m_bakAbsPartIdxCU;
+  
+public:
+  Void init (TComPrediction* p) {m_pcPrediction = p;}
+  Void decodePUWise       ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, TComDataCU* pcSubCU );
+  Void decodeInterDirPU   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPartIdx );
+  Void decodeRefFrmIdxPU  ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPartIdx, RefPicList eRefList );
+  Void decodeMvdPU        ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPartIdx, RefPicList eRefList );
+  Void decodeMVPIdxPU     ( TComDataCU* pcSubCU, UInt uiPartAddr, UInt uiDepth, UInt uiPartIdx, RefPicList eRefList );
+  
+  Void    setEntropyDecoder           ( TDecEntropyIf* p );
+  Void    setBitstream                ( TComInputBitstream* p ) { m_pcEntropyDecoderIf->setBitstream(p);                    }
+  Void    resetEntropy                ( TComSlice* p)           { m_pcEntropyDecoderIf->resetEntropy(p);                    }
+  Void    decodeVPS                   ( TComVPS* pcVPS ) { m_pcEntropyDecoderIf->parseVPS(pcVPS); }
+  Void    decodeSPS                   ( TComSPS* pcSPS     )    { m_pcEntropyDecoderIf->parseSPS(pcSPS);                    }
+  Void    decodePPS                   ( TComPPS* pcPPS, ParameterSetManagerDecoder *parameterSet    )    { m_pcEntropyDecoderIf->parsePPS(pcPPS);                    }
+#if !REMOVE_APS
+  Void    decodeAPS                   ( TComAPS* pAPS      )    { m_pcEntropyDecoderIf->parseAPS(pAPS);}
+#endif
+  Void    decodeSliceHeader           ( TComSlice*& rpcSlice, ParameterSetManagerDecoder *parameterSetManager)  { m_pcEntropyDecoderIf->parseSliceHeader(rpcSlice, parameterSetManager);         }
+
+  Void    decodeTerminatingBit        ( UInt& ruiIsLast )       { m_pcEntropyDecoderIf->parseTerminatingBit(ruiIsLast);     }
+  
+  TDecEntropyIf* getEntropyDecoder() { return m_pcEntropyDecoderIf; }
+  
+public:
+  Void decodeSplitFlag         ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void decodeSkipFlag          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void decodeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void decodeMergeFlag         ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPUIdx );
+  Void decodeMergeIndex        ( TComDataCU* pcSubCU, UInt uiPartIdx, UInt uiPartAddr, PartSize eCUMode, UChar* puhInterDirNeighbours, TComMvField* pcMvFieldNeighbours, UInt uiDepth );
+  Void decodePredMode          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void decodePartSize          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  
+  Void decodeIPCMInfo          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+
+  Void decodePredInfo          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, TComDataCU* pcSubCU );
+  
+  Void decodeIntraDirModeLuma  ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void decodeIntraDirModeChroma( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  
+  Void decodeQP                ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  
+  Void updateContextTables    ( SliceType eSliceType, Int iQp ) { m_pcEntropyDecoderIf->updateContextTables( eSliceType, iQp ); }
+  
+#if INTRA_BL
+  Void decodeIntraBLFlag       ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
+#endif
+  
+private:
+  Void xDecodeTransform        ( TComDataCU* pcCU, UInt offsetLuma, UInt offsetChroma, UInt uiAbsPartIdx, UInt absTUPartIdx, UInt uiDepth, UInt width, UInt height, UInt uiTrIdx, UInt uiInnerQuadIdx, Bool& bCodeDQP );
+
+public:
+  Void decodeCoeff             ( TComDataCU* pcCU                 , UInt uiAbsPartIdx, UInt uiDepth, UInt uiWidth, UInt uiHeight, Bool& bCodeDQP );
+  
+#if !REMOVE_FGS
+  /// set slice granularity
+  Void setSliceGranularity (Int iSliceGranularity) {m_pcEntropyDecoderIf->setSliceGranularity(iSliceGranularity);}
+#endif
+  
+  Void decodeFlush() { m_pcEntropyDecoderIf->decodeFlush(); }
+
+};// END CLASS DEFINITION TDecEntropy
+
+//! \}
+
+#endif // __TDECENTROPY__
+
Index: /trunk/source/Lib/TLibDecoder/TDecGop.cpp
===================================================================
--- /trunk/source/Lib/TLibDecoder/TDecGop.cpp	(revision 2)
+++ /trunk/source/Lib/TLibDecoder/TDecGop.cpp	(revision 2)
@@ -0,0 +1,417 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TDecGop.cpp
+    \brief    GOP decoder class
+*/
+
+extern bool g_md5_mismatch; ///< top level flag to signal when there is a decode problem
+
+#include "TDecGop.h"
+#include "TDecCAVLC.h"
+#include "TDecSbac.h"
+#include "TDecBinCoder.h"
+#include "TDecBinCoderCABAC.h"
+#include "libmd5/MD5.h"
+#include "TLibCommon/SEI.h"
+#if SVC_EXTENSION
+#include "TDecTop.h"
+#endif
+
+#include <time.h>
+
+//! \ingroup TLibDecoder
+//! \{
+static void calcAndPrintHashStatus(TComPicYuv& pic, const SEImessages* seis);
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+
+TDecGop::TDecGop()
+{
+  m_iGopSize = 0;
+  m_dDecTime = 0;
+  m_pcSbacDecoders = NULL;
+  m_pcBinCABACs = NULL;
+}
+
+TDecGop::~TDecGop()
+{
+  
+}
+
+#if SVC_EXTENSION
+Void TDecGop::create(UInt layerId)
+{
+  m_layerId = layerId;
+}
+#else
+Void TDecGop::create()
+{
+  
+}
+#endif
+
+Void TDecGop::destroy()
+{
+}
+#if SVC_EXTENSION
+Void TDecGop::init(TDecTop**               ppcDecTop,
+                   TDecEntropy*            pcEntropyDecoder,
+#else
+Void TDecGop::init( TDecEntropy*            pcEntropyDecoder, 
+#endif
+                   TDecSbac*               pcSbacDecoder, 
+                   TDecBinCABAC*           pcBinCABAC,
+                   TDecCavlc*              pcCavlcDecoder, 
+                   TDecSlice*              pcSliceDecoder, 
+                   TComLoopFilter*         pcLoopFilter,
+#if !REMOVE_ALF
+                   TComAdaptiveLoopFilter* pcAdaptiveLoopFilter,
+#endif
+                   TComSampleAdaptiveOffset* pcSAO
+                   )
+{
+  m_pcEntropyDecoder      = pcEntropyDecoder;
+  m_pcSbacDecoder         = pcSbacDecoder;
+  m_pcBinCABAC            = pcBinCABAC;
+  m_pcCavlcDecoder        = pcCavlcDecoder;
+  m_pcSliceDecoder        = pcSliceDecoder;
+  m_pcLoopFilter          = pcLoopFilter;
+#if !REMOVE_ALF
+  m_pcAdaptiveLoopFilter  = pcAdaptiveLoopFilter;
+#endif
+  m_pcSAO  = pcSAO;
+#if SVC_EXTENSION   
+  m_ppcTDecTop            = ppcDecTop;
+#endif
+}
+
+
+// ====================================================================================================================
+// Private member functions
+// ====================================================================================================================
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+Void TDecGop::decompressSlice(TComInputBitstream* pcBitstream, TComPic*& rpcPic)
+{
+  TComSlice*  pcSlice = rpcPic->getSlice(rpcPic->getCurrSliceIdx());
+  // Table of extracted substreams.
+  // These must be deallocated AND their internal fifos, too.
+  TComInputBitstream **ppcSubstreams = NULL;
+
+  //-- For time output for each slice
+  long iBeforeTime = clock();
+  
+  UInt uiStartCUAddr   = pcSlice->getDependentSliceCurStartCUAddr();
+
+  UInt uiSliceStartCuAddr = pcSlice->getSliceCurStartCUAddr();
+  if(uiSliceStartCuAddr == uiStartCUAddr)
+  {
+    m_sliceStartCUAddress.push_back(uiSliceStartCuAddr);
+  }
+
+  m_pcSbacDecoder->init( (TDecBinIf*)m_pcBinCABAC );
+  m_pcEntropyDecoder->setEntropyDecoder (m_pcSbacDecoder);
+
+#if TILES_WPP_ENTROPYSLICES_FLAGS
+  UInt uiNumSubstreams = pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag() ? pcSlice->getNumEntryPointOffsets()+1 : pcSlice->getPPS()->getNumSubstreams();
+#else
+  UInt uiNumSubstreams = pcSlice->getPPS()->getTilesOrEntropyCodingSyncIdc() == 2 ? pcSlice->getNumEntryPointOffsets()+1 : pcSlice->getPPS()->getNumSubstreams();
+#endif
+
+  // init each couple {EntropyDecoder, Substream}
+  UInt *puiSubstreamSizes = pcSlice->getSubstreamSizes();
+  ppcSubstreams    = new TComInputBitstream*[uiNumSubstreams];
+  m_pcSbacDecoders = new TDecSbac[uiNumSubstreams];
+  m_pcBinCABACs    = new TDecBinCABAC[uiNumSubstreams];
+  for ( UInt ui = 0 ; ui < uiNumSubstreams ; ui++ )
+  {
+    m_pcSbacDecoders[ui].init(&m_pcBinCABACs[ui]);
+    ppcSubstreams[ui] = pcBitstream->extractSubstream(ui+1 < uiNumSubstreams ? puiSubstreamSizes[ui] : pcBitstream->getNumBitsLeft());
+  }
+
+  for ( UInt ui = 0 ; ui+1 < uiNumSubstreams; ui++ )
+  {
+    m_pcEntropyDecoder->setEntropyDecoder ( &m_pcSbacDecoders[uiNumSubstreams - 1 - ui] );
+    m_pcEntropyDecoder->setBitstream      (  ppcSubstreams   [uiNumSubstreams - 1 - ui] );
+    m_pcEntropyDecoder->resetEntropy      (pcSlice);
+  }
+
+  m_pcEntropyDecoder->setEntropyDecoder ( m_pcSbacDecoder  );
+  m_pcEntropyDecoder->setBitstream      ( ppcSubstreams[0] );
+  m_pcEntropyDecoder->resetEntropy      (pcSlice);
+
+  if(uiSliceStartCuAddr == uiStartCUAddr)
+  {
+    m_LFCrossSliceBoundaryFlag.push_back( pcSlice->getLFCrossSliceBoundaryFlag());
+#if !REMOVE_ALF
+    if(pcSlice->getSPS()->getUseALF())
+    {
+      for(Int compIdx=0; compIdx < 3; compIdx++)
+      {
+        m_sliceAlfEnabled[compIdx].push_back(  pcSlice->getAlfEnabledFlag(compIdx) );
+      }
+    }
+#endif
+  }
+  m_pcSbacDecoders[0].load(m_pcSbacDecoder);
+  m_pcSliceDecoder->decompressSlice( pcBitstream, ppcSubstreams, rpcPic, m_pcSbacDecoder, m_pcSbacDecoders);
+  m_pcEntropyDecoder->setBitstream(  ppcSubstreams[uiNumSubstreams-1] );
+  // deallocate all created substreams, including internal buffers.
+  for (UInt ui = 0; ui < uiNumSubstreams; ui++)
+  {
+    ppcSubstreams[ui]->deleteFifo();
+    delete ppcSubstreams[ui];
+  }
+  delete[] ppcSubstreams;
+  delete[] m_pcSbacDecoders; m_pcSbacDecoders = NULL;
+  delete[] m_pcBinCABACs; m_pcBinCABACs = NULL;
+
+  m_dDecTime += (double)(clock()-iBeforeTime) / CLOCKS_PER_SEC;
+}
+
+Void TDecGop::filterPicture(TComPic*& rpcPic)
+{
+  TComSlice*  pcSlice = rpcPic->getSlice(rpcPic->getCurrSliceIdx());
+
+  //-- For time output for each slice
+  long iBeforeTime = clock();
+
+  // deblocking filter
+  Bool bLFCrossTileBoundary = pcSlice->getPPS()->getLoopFilterAcrossTilesEnabledFlag();
+  m_pcLoopFilter->setCfg(pcSlice->getPPS()->getDeblockingFilterControlPresentFlag(), pcSlice->getDeblockingFilterDisable(), pcSlice->getDeblockingFilterBetaOffsetDiv2(), pcSlice->getDeblockingFilterTcOffsetDiv2(), bLFCrossTileBoundary);
+  m_pcLoopFilter->loopFilterPic( rpcPic );
+
+  pcSlice = rpcPic->getSlice(0);
+#if REMOVE_ALF
+  if(pcSlice->getSPS()->getUseSAO())
+#else
+  if(pcSlice->getSPS()->getUseSAO() || pcSlice->getSPS()->getUseALF())
+#endif
+  {
+#if !REMOVE_FGS
+    Int sliceGranularity = pcSlice->getPPS()->getSliceGranularity();
+#endif
+    m_sliceStartCUAddress.push_back(rpcPic->getNumCUsInFrame()* rpcPic->getNumPartInCU());
+#if REMOVE_FGS
+    rpcPic->createNonDBFilterInfo(m_sliceStartCUAddress, 0, &m_LFCrossSliceBoundaryFlag, rpcPic->getPicSym()->getNumTiles(), bLFCrossTileBoundary);
+#else
+    rpcPic->createNonDBFilterInfo(m_sliceStartCUAddress, sliceGranularity, &m_LFCrossSliceBoundaryFlag, rpcPic->getPicSym()->getNumTiles(), bLFCrossTileBoundary);
+#endif
+  }
+
+  if( pcSlice->getSPS()->getUseSAO() )
+  {
+#if !SAO_LUM_CHROMA_ONOFF_FLAGS
+    if(pcSlice->getSaoEnabledFlag())
+#else
+    if(pcSlice->getSaoEnabledFlag()||pcSlice->getSaoEnabledFlagChroma())
+#endif
+    {
+#if REMOVE_APS
+      SAOParam *saoParam = rpcPic->getPicSym()->getSaoParam();
+#else
+      SAOParam *saoParam = pcSlice->getAPS()->getSaoParam();
+#endif
+      saoParam->bSaoFlag[0] = pcSlice->getSaoEnabledFlag();
+#if SAO_TYPE_SHARING
+      saoParam->bSaoFlag[1] = pcSlice->getSaoEnabledFlagChroma();
+#else
+      saoParam->bSaoFlag[1] = pcSlice->getSaoEnabledFlagCb();
+      saoParam->bSaoFlag[2] = pcSlice->getSaoEnabledFlagCr();
+#endif
+      m_pcSAO->setSaoLcuBasedOptimization(1);
+      m_pcSAO->createPicSaoInfo(rpcPic, (Int) m_sliceStartCUAddress.size() - 1);
+      m_pcSAO->SAOProcess(rpcPic, saoParam);
+#if !REMOVE_ALF
+      m_pcAdaptiveLoopFilter->PCMLFDisableProcess(rpcPic);
+#else
+      m_pcSAO->PCMLFDisableProcess(rpcPic);
+#endif
+      m_pcSAO->destroyPicSaoInfo();
+    }
+  }
+
+#if !REMOVE_ALF
+  // adaptive loop filter
+  if( pcSlice->getSPS()->getUseALF() )
+  {
+    m_pcAdaptiveLoopFilter->createPicAlfInfo(rpcPic, (Int) m_sliceStartCUAddress.size()-1);
+    m_pcAdaptiveLoopFilter->ALFProcess(rpcPic, pcSlice->getAPS()->getAlfParam(), m_sliceAlfEnabled);
+    m_pcAdaptiveLoopFilter->PCMLFDisableProcess(rpcPic);
+    m_pcAdaptiveLoopFilter->destroyPicAlfInfo();
+  }
+#endif
+
+#if REMOVE_ALF
+  if(pcSlice->getSPS()->getUseSAO())
+#else
+  if(pcSlice->getSPS()->getUseSAO() || pcSlice->getSPS()->getUseALF())
+#endif
+  {
+    rpcPic->destroyNonDBFilterInfo();
+  }
+
+  rpcPic->compressMotion(); 
+  Char c = (pcSlice->isIntra() ? 'I' : pcSlice->isInterP() ? 'P' : 'B');
+  if (!pcSlice->isReferenced()) c += 32;
+
+  //-- For time output for each slice
+#if SVC_EXTENSION
+  printf("\nPOC %4d LId: %1d TId: %1d ( %c-SLICE, QP%3d ) ", pcSlice->getPOC(),
+                                                    rpcPic->getLayerId(),
+                                                    pcSlice->getTLayer(),
+                                                    c,
+                                                    pcSlice->getSliceQp() );
+#else
+  printf("\nPOC %4d TId: %1d ( %c-SLICE, QP%3d ) ", pcSlice->getPOC(),
+                                                    pcSlice->getTLayer(),
+                                                    c,
+                                                    pcSlice->getSliceQp() );
+#endif
+  m_dDecTime += (double)(clock()-iBeforeTime) / CLOCKS_PER_SEC;
+  printf ("[DT %6.3f] ", m_dDecTime );
+  m_dDecTime  = 0;
+
+  for (Int iRefList = 0; iRefList < 2; iRefList++)
+  {
+    printf ("[L%d ", iRefList);
+    for (Int iRefIndex = 0; iRefIndex < pcSlice->getNumRefIdx(RefPicList(iRefList)); iRefIndex++)
+    {
+      printf ("%d ", pcSlice->getRefPOC(RefPicList(iRefList), iRefIndex));
+    }
+    printf ("] ");
+  }
+  if (m_decodedPictureHashSEIEnabled)
+  {
+    calcAndPrintHashStatus(*rpcPic->getPicYuvRec(), rpcPic->getSEIs());
+  }
+
+#if FIXED_ROUNDING_FRAME_MEMORY
+  rpcPic->getPicYuvRec()->xFixedRoundingPic();
+#endif
+
+  rpcPic->setOutputMark(true);
+  rpcPic->setReconMark(true);
+  m_sliceStartCUAddress.clear();
+#if !REMOVE_ALF
+  for(Int compIdx=0; compIdx < 3; compIdx++)
+  {
+    m_sliceAlfEnabled[compIdx].clear();
+  }
+#endif
+  m_LFCrossSliceBoundaryFlag.clear();
+}
+
+/**
+ * Calculate and print hash for pic, compare to picture_digest SEI if
+ * present in seis.  seis may be NULL.  Hash is printed to stdout, in
+ * a manner suitable for the status line. Theformat is:
+ *  [Hash_type:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx,(yyy)]
+ * Where, x..x is the hash
+ *        yyy has the following meanings:
+ *            OK          - calculated hash matches the SEI message
+ *            ***ERROR*** - calculated hash does not match the SEI message
+ *            unk         - no SEI message was available for comparison
+ */
+static void calcAndPrintHashStatus(TComPicYuv& pic, const SEImessages* seis)
+{
+  /* calculate MD5sum for entire reconstructed picture */
+  unsigned char recon_digest[3][16];
+  int numChar=0;
+  const char* hashType = "\0";
+
+  if (seis && seis->picture_digest)
+  {
+    switch (seis->picture_digest->method)
+    {
+    case SEIDecodedPictureHash::MD5:
+      {
+        hashType = "MD5";
+        calcMD5(pic, recon_digest);
+        numChar = 16;
+        break;
+      }
+    case SEIDecodedPictureHash::CRC:
+      {
+        hashType = "CRC";
+        calcCRC(pic, recon_digest);
+        numChar = 2;
+        break;
+      }
+    case SEIDecodedPictureHash::CHECKSUM:
+      {
+        hashType = "Checksum";
+        calcChecksum(pic, recon_digest);
+        numChar = 4;
+        break;
+      }
+    default:
+      {
+        assert (!"unknown hash type");
+      }
+    }
+  }
+
+  /* compare digest against received version */
+  const char* ok = "(unk)";
+  bool mismatch = false;
+
+  if (seis && seis->picture_digest)
+  {
+    ok = "(OK)";
+    for(int yuvIdx = 0; yuvIdx < 3; yuvIdx++)
+    {
+      for (unsigned i = 0; i < numChar; i++)
+      {
+        if (recon_digest[yuvIdx][i] != seis->picture_digest->digest[yuvIdx][i])
+        {
+          ok = "(***ERROR***)";
+          mismatch = true;
+        }
+      }
+    }
+  }
+
+  printf("[%s:%s,%s] ", hashType, digestToString(recon_digest, numChar), ok);
+
+  if (mismatch)
+  {
+    g_md5_mismatch = true;
+    printf("[rx%s:%s] ", hashType, digestToString(seis->picture_digest->digest, numChar));
+  }
+}
+//! \}
Index: /trunk/source/Lib/TLibDecoder/TDecGop.h
===================================================================
--- /trunk/source/Lib/TLibDecoder/TDecGop.h	(revision 2)
+++ /trunk/source/Lib/TLibDecoder/TDecGop.h	(revision 2)
@@ -0,0 +1,143 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TDecGop.h
+    \brief    GOP decoder class (header)
+*/
+
+#ifndef __TDECGOP__
+#define __TDECGOP__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComBitStream.h"
+#include "TLibCommon/TComList.h"
+#include "TLibCommon/TComPicYuv.h"
+#include "TLibCommon/TComPic.h"
+#include "TLibCommon/TComLoopFilter.h"
+#include "TLibCommon/TComAdaptiveLoopFilter.h"
+#include "TLibCommon/TComSampleAdaptiveOffset.h"
+
+#include "TDecEntropy.h"
+#include "TDecSlice.h"
+#include "TDecBinCoder.h"
+#include "TDecBinCoderCABAC.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// GOP decoder class
+class TDecGop
+{
+private:
+  Int                   m_iGopSize;
+  TComList<TComPic*>    m_cListPic;         //  Dynamic buffer
+  
+  //  Access channel
+  TDecEntropy*          m_pcEntropyDecoder;
+  TDecSbac*             m_pcSbacDecoder;
+  TDecBinCABAC*         m_pcBinCABAC;
+  TDecSbac*             m_pcSbacDecoders; // independant CABAC decoders
+  TDecBinCABAC*         m_pcBinCABACs;
+  TDecCavlc*            m_pcCavlcDecoder;
+  TDecSlice*            m_pcSliceDecoder;
+  TComLoopFilter*       m_pcLoopFilter;
+  
+#if !REMOVE_ALF
+  // Adaptive Loop filter
+  TComAdaptiveLoopFilter*       m_pcAdaptiveLoopFilter;
+#endif
+  TComSampleAdaptiveOffset*     m_pcSAO;
+  Double                m_dDecTime;
+  Int                   m_decodedPictureHashSEIEnabled;  ///< Checksum(3)/CRC(2)/MD5(1)/disable(0) acting on decoded picture hash SEI message
+
+  //! list that contains the CU address of each slice plus the end address
+  std::vector<Int> m_sliceStartCUAddress;
+  std::vector<Bool> m_LFCrossSliceBoundaryFlag;
+#if !REMOVE_ALF
+  std::vector<Bool> m_sliceAlfEnabled[3];
+#endif
+
+#if SVC_EXTENSION
+  UInt                  m_layerId;
+  TDecTop**             m_ppcTDecTop;
+#endif
+public:
+  TDecGop();
+  virtual ~TDecGop();
+  
+#if SVC_EXTENSION
+Void  init      ( TDecTop**               ppcDecTop,
+                  TDecEntropy*            pcEntropyDecoder, 
+#else
+  Void  init    ( TDecEntropy*            pcEntropyDecoder, 
+#endif
+                 TDecSbac*               pcSbacDecoder, 
+                 TDecBinCABAC*           pcBinCABAC,
+                 TDecCavlc*              pcCavlcDecoder, 
+                 TDecSlice*              pcSliceDecoder, 
+                 TComLoopFilter*         pcLoopFilter,
+#if !REMOVE_ALF
+                 TComAdaptiveLoopFilter* pcAdaptiveLoopFilter,
+#endif
+                 TComSampleAdaptiveOffset* pcSAO
+                 );
+#if SVC_EXTENSION
+  Void  create  (UInt layerId);
+#else
+  Void  create  ();
+#endif
+  Void  destroy ();
+//  Void  decompressGop(TComInputBitstream* pcBitstream, TComPic*& rpcPic, Bool bExecuteDeblockAndAlf );
+  Void  decompressSlice(TComInputBitstream* pcBitstream, TComPic*& rpcPic );
+  Void  filterPicture  (TComPic*& rpcPic );
+  Void  setGopSize( Int i) { m_iGopSize = i; }
+
+  void setDecodedPictureHashSEIEnabled(Int enabled) { m_decodedPictureHashSEIEnabled = enabled; }
+#if SVC_EXTENSION
+  TDecTop*   getLayerDec(UInt LayerId)  { return m_ppcTDecTop[LayerId]; }
+#endif 
+
+};
+
+//! \}
+
+#endif // !defined(AFX_TDECGOP_H__29440B7A_7CC0_48C7_8DD5_1A531D3CED45__INCLUDED_)
+
Index: /trunk/source/Lib/TLibDecoder/TDecSbac.cpp
===================================================================
--- /trunk/source/Lib/TLibDecoder/TDecSbac.cpp	(revision 2)
+++ /trunk/source/Lib/TLibDecoder/TDecSbac.cpp	(revision 2)
@@ -0,0 +1,1957 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TDecSbac.cpp
+    \brief    Context-adaptive entropy decoder class
+*/
+
+#include "TDecSbac.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+//////////////////////////////////////////////////////////////////////
+// Construction/Destruction
+//////////////////////////////////////////////////////////////////////
+
+TDecSbac::TDecSbac() 
+// new structure here
+: m_pcBitstream               ( 0 )
+, m_pcTDecBinIf               ( NULL )
+, m_numContextModels          ( 0 )
+, m_cCUSplitFlagSCModel       ( 1,             1,               NUM_SPLIT_FLAG_CTX            , m_contextModels + m_numContextModels, m_numContextModels )
+, m_cCUSkipFlagSCModel        ( 1,             1,               NUM_SKIP_FLAG_CTX             , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUMergeFlagExtSCModel    ( 1,             1,               NUM_MERGE_FLAG_EXT_CTX        , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUMergeIdxExtSCModel     ( 1,             1,               NUM_MERGE_IDX_EXT_CTX         , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUPartSizeSCModel        ( 1,             1,               NUM_PART_SIZE_CTX             , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUPredModeSCModel        ( 1,             1,               NUM_PRED_MODE_CTX             , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUAlfCtrlFlagSCModel     ( 1,             1,               NUM_ALF_CTRL_FLAG_CTX         , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUIntraPredSCModel       ( 1,             1,               NUM_ADI_CTX                   , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUChromaPredSCModel      ( 1,             1,               NUM_CHROMA_PRED_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUDeltaQpSCModel         ( 1,             1,               NUM_DELTA_QP_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUInterDirSCModel        ( 1,             1,               NUM_INTER_DIR_CTX             , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCURefPicSCModel          ( 1,             1,               NUM_REF_NO_CTX                , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUMvdSCModel             ( 1,             1,               NUM_MV_RES_CTX                , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUQtCbfSCModel           ( 1,             2,               NUM_QT_CBF_CTX                , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUTransSubdivFlagSCModel ( 1,             1,               NUM_TRANS_SUBDIV_FLAG_CTX     , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUQtRootCbfSCModel       ( 1,             1,               NUM_QT_ROOT_CBF_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUSigCoeffGroupSCModel   ( 1,             2,               NUM_SIG_CG_FLAG_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUSigSCModel             ( 1,             1,               NUM_SIG_FLAG_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCuCtxLastX               ( 1,             2,               NUM_CTX_LAST_FLAG_XY          , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCuCtxLastY               ( 1,             2,               NUM_CTX_LAST_FLAG_XY          , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUOneSCModel             ( 1,             1,               NUM_ONE_FLAG_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUAbsSCModel             ( 1,             1,               NUM_ABS_FLAG_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cMVPIdxSCModel            ( 1,             1,               NUM_MVP_IDX_CTX               , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cALFFlagSCModel           ( 1,             1,               NUM_ALF_FLAG_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cALFUvlcSCModel           ( 1,             1,               NUM_ALF_UVLC_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cALFSvlcSCModel           ( 1,             1,               NUM_ALF_SVLC_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUAMPSCModel             ( 1,             1,               NUM_CU_AMP_CTX                , m_contextModels + m_numContextModels, m_numContextModels)
+#if !SAO_ABS_BY_PASS
+, m_cSaoUvlcSCModel           ( 1,             1,               NUM_SAO_UVLC_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+#endif
+#if SAO_MERGE_ONE_CTX
+, m_cSaoMergeSCModel      ( 1,             1,               NUM_SAO_MERGE_FLAG_CTX   , m_contextModels + m_numContextModels, m_numContextModels)
+#else
+, m_cSaoMergeLeftSCModel      ( 1,             1,               NUM_SAO_MERGE_LEFT_FLAG_CTX   , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSaoMergeUpSCModel        ( 1,             1,               NUM_SAO_MERGE_UP_FLAG_CTX     , m_contextModels + m_numContextModels, m_numContextModels)
+#endif
+#if INTRA_BL
+, m_cIntraBLPredFlagSCModel   (1,              1,               NUM_INTRA_BL_PRED_CTX         , m_contextModels + m_numContextModels, m_numContextModels)
+#endif
+, m_cSaoTypeIdxSCModel        ( 1,             1,               NUM_SAO_TYPE_IDX_CTX          , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cTransformSkipSCModel     ( 1,             2,               NUM_TRANSFORMSKIP_FLAG_CTX    , m_contextModels + m_numContextModels, m_numContextModels)
+, m_CUTransquantBypassFlagSCModel( 1,          1,               NUM_CU_TRANSQUANT_BYPASS_FLAG_CTX, m_contextModels + m_numContextModels, m_numContextModels)
+{
+  assert( m_numContextModels <= MAX_NUM_CTX_MOD );
+#if !REMOVE_FGS
+  m_iSliceGranularity = 0;
+#endif
+}
+
+TDecSbac::~TDecSbac()
+{
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+Void TDecSbac::resetEntropy(TComSlice* pSlice)
+{
+  SliceType sliceType  = pSlice->getSliceType();
+  Int       qp         = pSlice->getSliceQp();
+
+  if (pSlice->getPPS()->getCabacInitPresentFlag() && pSlice->getCabacInitFlag())
+  {
+    switch (sliceType)
+    {
+    case P_SLICE:           // change initialization table to B_SLICE initialization
+      sliceType = B_SLICE; 
+      break;
+    case B_SLICE:           // change initialization table to P_SLICE initialization
+      sliceType = P_SLICE; 
+      break;
+    default     :           // should not occur
+      assert(0);
+    }
+  }
+
+  m_cCUSplitFlagSCModel.initBuffer       ( sliceType, qp, (UChar*)INIT_SPLIT_FLAG );
+  m_cCUSkipFlagSCModel.initBuffer        ( sliceType, qp, (UChar*)INIT_SKIP_FLAG );
+  m_cCUMergeFlagExtSCModel.initBuffer    ( sliceType, qp, (UChar*)INIT_MERGE_FLAG_EXT );
+  m_cCUMergeIdxExtSCModel.initBuffer     ( sliceType, qp, (UChar*)INIT_MERGE_IDX_EXT );
+  m_cCUAlfCtrlFlagSCModel.initBuffer     ( sliceType, qp, (UChar*)INIT_ALF_CTRL_FLAG );
+  m_cCUPartSizeSCModel.initBuffer        ( sliceType, qp, (UChar*)INIT_PART_SIZE );
+  m_cCUAMPSCModel.initBuffer             ( sliceType, qp, (UChar*)INIT_CU_AMP_POS );
+  m_cCUPredModeSCModel.initBuffer        ( sliceType, qp, (UChar*)INIT_PRED_MODE );
+  m_cCUIntraPredSCModel.initBuffer       ( sliceType, qp, (UChar*)INIT_INTRA_PRED_MODE );
+  m_cCUChromaPredSCModel.initBuffer      ( sliceType, qp, (UChar*)INIT_CHROMA_PRED_MODE );
+  m_cCUInterDirSCModel.initBuffer        ( sliceType, qp, (UChar*)INIT_INTER_DIR );
+  m_cCUMvdSCModel.initBuffer             ( sliceType, qp, (UChar*)INIT_MVD );
+  m_cCURefPicSCModel.initBuffer          ( sliceType, qp, (UChar*)INIT_REF_PIC );
+  m_cCUDeltaQpSCModel.initBuffer         ( sliceType, qp, (UChar*)INIT_DQP );
+  m_cCUQtCbfSCModel.initBuffer           ( sliceType, qp, (UChar*)INIT_QT_CBF );
+  m_cCUQtRootCbfSCModel.initBuffer       ( sliceType, qp, (UChar*)INIT_QT_ROOT_CBF );
+  m_cCUSigCoeffGroupSCModel.initBuffer   ( sliceType, qp, (UChar*)INIT_SIG_CG_FLAG );
+  m_cCUSigSCModel.initBuffer             ( sliceType, qp, (UChar*)INIT_SIG_FLAG );
+  m_cCuCtxLastX.initBuffer               ( sliceType, qp, (UChar*)INIT_LAST );
+  m_cCuCtxLastY.initBuffer               ( sliceType, qp, (UChar*)INIT_LAST );
+  m_cCUOneSCModel.initBuffer             ( sliceType, qp, (UChar*)INIT_ONE_FLAG );
+  m_cCUAbsSCModel.initBuffer             ( sliceType, qp, (UChar*)INIT_ABS_FLAG );
+  m_cMVPIdxSCModel.initBuffer            ( sliceType, qp, (UChar*)INIT_MVP_IDX );
+  m_cALFFlagSCModel.initBuffer           ( sliceType, qp, (UChar*)INIT_ALF_FLAG );
+  m_cALFUvlcSCModel.initBuffer           ( sliceType, qp, (UChar*)INIT_ALF_UVLC );
+  m_cALFSvlcSCModel.initBuffer           ( sliceType, qp, (UChar*)INIT_ALF_SVLC );
+#if !SAO_ABS_BY_PASS
+  m_cSaoUvlcSCModel.initBuffer           ( sliceType, qp, (UChar*)INIT_SAO_UVLC );
+#endif
+#if SAO_MERGE_ONE_CTX
+  m_cSaoMergeSCModel.initBuffer      ( sliceType, qp, (UChar*)INIT_SAO_MERGE_FLAG );
+#else
+  m_cSaoMergeLeftSCModel.initBuffer      ( sliceType, qp, (UChar*)INIT_SAO_MERGE_LEFT_FLAG );
+  m_cSaoMergeUpSCModel.initBuffer        ( sliceType, qp, (UChar*)INIT_SAO_MERGE_UP_FLAG );
+#endif
+  m_cSaoTypeIdxSCModel.initBuffer        ( sliceType, qp, (UChar*)INIT_SAO_TYPE_IDX );
+
+  m_cCUTransSubdivFlagSCModel.initBuffer ( sliceType, qp, (UChar*)INIT_TRANS_SUBDIV_FLAG );
+#if INTRA_BL
+  m_cIntraBLPredFlagSCModel.initBuffer ( sliceType, qp, (UChar*)INIT_INTRA_BL_PRED_FLAG );
+#endif
+  m_cTransformSkipSCModel.initBuffer     ( sliceType, qp, (UChar*)INIT_TRANSFORMSKIP_FLAG );
+  m_CUTransquantBypassFlagSCModel.initBuffer( sliceType, qp, (UChar*)INIT_CU_TRANSQUANT_BYPASS_FLAG );
+  m_uiLastDQpNonZero  = 0;
+  
+  // new structure
+  m_uiLastQp          = qp;
+  
+  m_pcTDecBinIf->start();
+}
+
+/** The function does the following: Read out terminate bit. Flush CABAC. Byte-align for next tile.
+ *  Intialize CABAC states. Start CABAC.
+ */
+Void TDecSbac::updateContextTables( SliceType eSliceType, Int iQp )
+{
+  UInt uiBit;
+  m_pcTDecBinIf->decodeBinTrm(uiBit);
+  m_pcTDecBinIf->finish();  
+  m_pcBitstream->readOutTrailingBits();
+  m_cCUSplitFlagSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_SPLIT_FLAG );
+  m_cCUSkipFlagSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_SKIP_FLAG );
+  m_cCUMergeFlagExtSCModel.initBuffer    ( eSliceType, iQp, (UChar*)INIT_MERGE_FLAG_EXT );
+  m_cCUMergeIdxExtSCModel.initBuffer     ( eSliceType, iQp, (UChar*)INIT_MERGE_IDX_EXT );
+  m_cCUAlfCtrlFlagSCModel.initBuffer     ( eSliceType, iQp, (UChar*)INIT_ALF_CTRL_FLAG );
+  m_cCUPartSizeSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_PART_SIZE );
+  m_cCUAMPSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_CU_AMP_POS );
+  m_cCUPredModeSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_PRED_MODE );
+  m_cCUIntraPredSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_INTRA_PRED_MODE );
+  m_cCUChromaPredSCModel.initBuffer      ( eSliceType, iQp, (UChar*)INIT_CHROMA_PRED_MODE );
+  m_cCUInterDirSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_INTER_DIR );
+  m_cCUMvdSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_MVD );
+  m_cCURefPicSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_REF_PIC );
+  m_cCUDeltaQpSCModel.initBuffer         ( eSliceType, iQp, (UChar*)INIT_DQP );
+  m_cCUQtCbfSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_QT_CBF );
+  m_cCUQtRootCbfSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_QT_ROOT_CBF );
+  m_cCUSigCoeffGroupSCModel.initBuffer   ( eSliceType, iQp, (UChar*)INIT_SIG_CG_FLAG );
+  m_cCUSigSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_SIG_FLAG );
+  m_cCuCtxLastX.initBuffer               ( eSliceType, iQp, (UChar*)INIT_LAST );
+  m_cCuCtxLastY.initBuffer               ( eSliceType, iQp, (UChar*)INIT_LAST );
+  m_cCUOneSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_ONE_FLAG );
+  m_cCUAbsSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_ABS_FLAG );
+  m_cMVPIdxSCModel.initBuffer            ( eSliceType, iQp, (UChar*)INIT_MVP_IDX );
+  m_cALFFlagSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_ALF_FLAG );
+  m_cALFUvlcSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_ALF_UVLC );
+  m_cALFSvlcSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_ALF_SVLC );
+#if !SAO_ABS_BY_PASS
+  m_cSaoUvlcSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_SAO_UVLC );
+#endif
+#if SAO_MERGE_ONE_CTX
+  m_cSaoMergeSCModel.initBuffer      ( eSliceType, iQp, (UChar*)INIT_SAO_MERGE_FLAG );
+#else
+  m_cSaoMergeLeftSCModel.initBuffer      ( eSliceType, iQp, (UChar*)INIT_SAO_MERGE_LEFT_FLAG );
+  m_cSaoMergeUpSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_SAO_MERGE_UP_FLAG );
+#endif
+  m_cSaoTypeIdxSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_SAO_TYPE_IDX );
+  m_cCUTransSubdivFlagSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_TRANS_SUBDIV_FLAG );
+#if INTRA_BL
+  m_cIntraBLPredFlagSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_INTRA_BL_PRED_FLAG );
+#endif
+  m_cTransformSkipSCModel.initBuffer     ( eSliceType, iQp, (UChar*)INIT_TRANSFORMSKIP_FLAG );
+  m_CUTransquantBypassFlagSCModel.initBuffer( eSliceType, iQp, (UChar*)INIT_CU_TRANSQUANT_BYPASS_FLAG );
+  m_pcTDecBinIf->start();
+}
+
+Void TDecSbac::parseTerminatingBit( UInt& ruiBit )
+{
+  m_pcTDecBinIf->decodeBinTrm( ruiBit );
+}
+
+
+Void TDecSbac::xReadUnaryMaxSymbol( UInt& ruiSymbol, ContextModel* pcSCModel, Int iOffset, UInt uiMaxSymbol )
+{
+  if (uiMaxSymbol == 0)
+  {
+    ruiSymbol = 0;
+    return;
+  }
+  
+  m_pcTDecBinIf->decodeBin( ruiSymbol, pcSCModel[0] );
+  
+  if( ruiSymbol == 0 || uiMaxSymbol == 1 )
+  {
+    return;
+  }
+  
+  UInt uiSymbol = 0;
+  UInt uiCont;
+  
+  do
+  {
+    m_pcTDecBinIf->decodeBin( uiCont, pcSCModel[ iOffset ] );
+    uiSymbol++;
+  }
+  while( uiCont && ( uiSymbol < uiMaxSymbol - 1 ) );
+  
+  if( uiCont && ( uiSymbol == uiMaxSymbol - 1 ) )
+  {
+    uiSymbol++;
+  }
+  
+  ruiSymbol = uiSymbol;
+}
+
+Void TDecSbac::xReadEpExGolomb( UInt& ruiSymbol, UInt uiCount )
+{
+  UInt uiSymbol = 0;
+  UInt uiBit = 1;
+  
+  while( uiBit )
+  {
+    m_pcTDecBinIf->decodeBinEP( uiBit );
+    uiSymbol += uiBit << uiCount++;
+  }
+  
+  if ( --uiCount )
+  {
+    UInt bins;
+    m_pcTDecBinIf->decodeBinsEP( bins, uiCount );
+    uiSymbol += bins;
+  }
+  
+  ruiSymbol = uiSymbol;
+}
+
+Void TDecSbac::xReadUnarySymbol( UInt& ruiSymbol, ContextModel* pcSCModel, Int iOffset )
+{
+  m_pcTDecBinIf->decodeBin( ruiSymbol, pcSCModel[0] );
+  
+  if( !ruiSymbol )
+  {
+    return;
+  }
+  
+  UInt uiSymbol = 0;
+  UInt uiCont;
+  
+  do
+  {
+    m_pcTDecBinIf->decodeBin( uiCont, pcSCModel[ iOffset ] );
+    uiSymbol++;
+  }
+  while( uiCont );
+  
+  ruiSymbol = uiSymbol;
+}
+
+
+/** Parsing of coeff_abs_level_remaing
+ * \param ruiSymbol reference to coeff_abs_level_remaing
+ * \param ruiParam reference to parameter
+ * \returns Void
+ */
+Void TDecSbac::xReadCoefRemainExGolomb ( UInt &rSymbol, UInt &rParam )
+{
+
+  UInt prefix   = 0;
+  UInt codeWord = 0;
+  do
+  {
+    prefix++;
+    m_pcTDecBinIf->decodeBinEP( codeWord );
+  }
+  while( codeWord);
+  codeWord  = 1 - codeWord;
+  prefix -= codeWord;
+  codeWord=0;
+#if COEF_REMAIN_BIN_REDUCTION
+  if (prefix < COEF_REMAIN_BIN_REDUCTION )
+#else
+  if (prefix < 8 )
+#endif
+  {
+    m_pcTDecBinIf->decodeBinsEP(codeWord,rParam);
+    rSymbol = (prefix<<rParam) + codeWord;
+  }
+  else
+  {
+#if COEF_REMAIN_BIN_REDUCTION
+    m_pcTDecBinIf->decodeBinsEP(codeWord,prefix-COEF_REMAIN_BIN_REDUCTION+rParam);
+    rSymbol = (((1<<(prefix-COEF_REMAIN_BIN_REDUCTION))+COEF_REMAIN_BIN_REDUCTION-1)<<rParam)+codeWord;
+#else
+    m_pcTDecBinIf->decodeBinsEP(codeWord,prefix-8+rParam);
+    rSymbol = (((1<<(prefix-8))+8-1)<<rParam)+codeWord;
+#endif
+  }
+}
+
+/** Parse I_PCM information. 
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \param uiDepth
+ * \returns Void
+ *
+ * If I_PCM flag indicates that the CU is I_PCM, parse its PCM alignment bits and codes. 
+ */
+Void TDecSbac::parseIPCMInfo ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiSymbol;
+  Int numSubseqIPCM = 0;
+  Bool readPCMSampleFlag = false;
+
+  if(pcCU->getNumSucIPCM() > 0) 
+  {
+    readPCMSampleFlag = true;
+  }
+  else
+  {
+    m_pcTDecBinIf->decodeBinTrm(uiSymbol);
+
+    if (uiSymbol)
+    {
+      readPCMSampleFlag = true;
+      m_pcTDecBinIf->decodeNumSubseqIPCM(numSubseqIPCM);
+      pcCU->setNumSucIPCM(numSubseqIPCM + 1);
+      m_pcTDecBinIf->decodePCMAlignBits();
+    }
+  }
+
+  if (readPCMSampleFlag == true)
+  {
+    Bool bIpcmFlag = true;
+
+    pcCU->setPartSizeSubParts  ( SIZE_2Nx2N, uiAbsPartIdx, uiDepth );
+    pcCU->setSizeSubParts      ( g_uiMaxCUWidth>>uiDepth, g_uiMaxCUHeight>>uiDepth, uiAbsPartIdx, uiDepth );
+    pcCU->setTrIdxSubParts     ( 0, uiAbsPartIdx, uiDepth );
+    pcCU->setIPCMFlagSubParts  ( bIpcmFlag, uiAbsPartIdx, uiDepth );
+
+    UInt uiMinCoeffSize = pcCU->getPic()->getMinCUWidth()*pcCU->getPic()->getMinCUHeight();
+    UInt uiLumaOffset   = uiMinCoeffSize*uiAbsPartIdx;
+    UInt uiChromaOffset = uiLumaOffset>>2;
+
+    Pel* piPCMSample;
+    UInt uiWidth;
+    UInt uiHeight;
+    UInt uiSampleBits;
+    UInt uiX, uiY;
+
+    piPCMSample = pcCU->getPCMSampleY() + uiLumaOffset;
+    uiWidth = pcCU->getWidth(uiAbsPartIdx);
+    uiHeight = pcCU->getHeight(uiAbsPartIdx);
+    uiSampleBits = pcCU->getSlice()->getSPS()->getPCMBitDepthLuma();
+
+    for(uiY = 0; uiY < uiHeight; uiY++)
+    {
+      for(uiX = 0; uiX < uiWidth; uiX++)
+      {
+        UInt uiSample;
+        m_pcTDecBinIf->xReadPCMCode(uiSampleBits, uiSample);
+        piPCMSample[uiX] = uiSample;
+      }
+      piPCMSample += uiWidth;
+    }
+
+    piPCMSample = pcCU->getPCMSampleCb() + uiChromaOffset;
+    uiWidth = pcCU->getWidth(uiAbsPartIdx)/2;
+    uiHeight = pcCU->getHeight(uiAbsPartIdx)/2;
+    uiSampleBits = pcCU->getSlice()->getSPS()->getPCMBitDepthChroma();
+
+    for(uiY = 0; uiY < uiHeight; uiY++)
+    {
+      for(uiX = 0; uiX < uiWidth; uiX++)
+      {
+        UInt uiSample;
+        m_pcTDecBinIf->xReadPCMCode(uiSampleBits, uiSample);
+        piPCMSample[uiX] = uiSample;
+      }
+      piPCMSample += uiWidth;
+    }
+
+    piPCMSample = pcCU->getPCMSampleCr() + uiChromaOffset;
+    uiWidth = pcCU->getWidth(uiAbsPartIdx)/2;
+    uiHeight = pcCU->getHeight(uiAbsPartIdx)/2;
+    uiSampleBits = pcCU->getSlice()->getSPS()->getPCMBitDepthChroma();
+
+    for(uiY = 0; uiY < uiHeight; uiY++)
+    {
+      for(uiX = 0; uiX < uiWidth; uiX++)
+      {
+        UInt uiSample;
+        m_pcTDecBinIf->xReadPCMCode(uiSampleBits, uiSample);
+        piPCMSample[uiX] = uiSample;
+      }
+      piPCMSample += uiWidth;
+    }
+
+    pcCU->setNumSucIPCM( pcCU->getNumSucIPCM() - 1);
+    if(pcCU->getNumSucIPCM() == 0)
+    {
+      m_pcTDecBinIf->resetBac();
+    }
+  }
+}
+
+Void TDecSbac::parseCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiSymbol;
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_CUTransquantBypassFlagSCModel.get( 0, 0, 0 ) );
+  pcCU->setCUTransquantBypassSubParts(uiSymbol ? true : false, uiAbsPartIdx, uiDepth);
+}
+
+/** parse skip flag
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \param uiDepth
+ * \returns Void
+ */
+Void TDecSbac::parseSkipFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  if( pcCU->getSlice()->isIntra() )
+  {
+    return;
+  }
+  
+  UInt uiSymbol = 0;
+  UInt uiCtxSkip = pcCU->getCtxSkipFlag( uiAbsPartIdx );
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUSkipFlagSCModel.get( 0, 0, uiCtxSkip ) );
+  DTRACE_CABAC_VL( g_nSymbolCounter++ );
+  DTRACE_CABAC_T( "\tSkipFlag" );
+  DTRACE_CABAC_T( "\tuiCtxSkip: ");
+  DTRACE_CABAC_V( uiCtxSkip );
+  DTRACE_CABAC_T( "\tuiSymbol: ");
+  DTRACE_CABAC_V( uiSymbol );
+  DTRACE_CABAC_T( "\n");
+  
+  if( uiSymbol )
+  {
+#if SKIP_FLAG
+    pcCU->setSkipFlagSubParts( true,        uiAbsPartIdx, uiDepth );
+#endif
+    pcCU->setPredModeSubParts( MODE_INTER,  uiAbsPartIdx, uiDepth );
+    pcCU->setPartSizeSubParts( SIZE_2Nx2N, uiAbsPartIdx, uiDepth );
+    pcCU->setSizeSubParts( g_uiMaxCUWidth>>uiDepth, g_uiMaxCUHeight>>uiDepth, uiAbsPartIdx, uiDepth );
+    pcCU->setMergeFlagSubParts( true , uiAbsPartIdx, 0, uiDepth );
+  }
+}
+
+#if INTRA_BL
+Void TDecSbac::parseIntraBLFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+  if( pcCU->getLayerId() == 0 )
+  {
+    return;
+  }
+
+  UInt uiSymbol = 0;
+
+  UInt uiCtxIntraBL = pcCU->getCtxIntraBLFlag( uiAbsPartIdx ) ;
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cIntraBLPredFlagSCModel.get( 0, 0, uiCtxIntraBL )); 
+  DTRACE_CABAC_VL( g_nSymbolCounter++ );
+  DTRACE_CABAC_T( "\tIntrBLFlag" );
+  DTRACE_CABAC_T( "\tuiSymbol: ");
+  DTRACE_CABAC_V( uiSymbol );
+  DTRACE_CABAC_T( "\n");
+
+  if ( uiSymbol )
+  {
+    pcCU->setPartSizeSubParts( SIZE_2Nx2N, uiAbsPartIdx, uiDepth );
+    pcCU->setPredModeSubParts( MODE_INTRA_BL, uiAbsPartIdx, uiDepth );
+    pcCU->setTrIdxSubParts( 0, uiAbsPartIdx, uiDepth );
+    pcCU->setLumaIntraDirSubParts ( DC_IDX, uiAbsPartIdx, uiDepth );   
+  }
+}
+#endif
+
+/** parse merge flag
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \param uiDepth
+ * \param uiPUIdx
+ * \returns Void
+ */
+Void TDecSbac::parseMergeFlag ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPUIdx )
+{
+  UInt uiSymbol;
+  m_pcTDecBinIf->decodeBin( uiSymbol, *m_cCUMergeFlagExtSCModel.get( 0 ) );
+  pcCU->setMergeFlagSubParts( uiSymbol ? true : false, uiAbsPartIdx, uiPUIdx, uiDepth );
+
+  DTRACE_CABAC_VL( g_nSymbolCounter++ );
+  DTRACE_CABAC_T( "\tMergeFlag: " );
+  DTRACE_CABAC_V( uiSymbol );
+  DTRACE_CABAC_T( "\tAddress: " );
+  DTRACE_CABAC_V( pcCU->getAddr() );
+  DTRACE_CABAC_T( "\tuiAbsPartIdx: " );
+  DTRACE_CABAC_V( uiAbsPartIdx );
+  DTRACE_CABAC_T( "\n" );
+}
+
+Void TDecSbac::parseMergeIndex ( TComDataCU* pcCU, UInt& ruiMergeIndex, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiUnaryIdx = 0;
+  UInt uiNumCand = pcCU->getSlice()->getMaxNumMergeCand();
+  if ( uiNumCand > 1 )
+  {
+    for( ; uiUnaryIdx < uiNumCand - 1; ++uiUnaryIdx )
+    {
+      UInt uiSymbol = 0;
+      if ( uiUnaryIdx==0 )
+      {
+        m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUMergeIdxExtSCModel.get( 0, 0, 0 ) );
+      }
+      else
+      {
+        m_pcTDecBinIf->decodeBinEP( uiSymbol );
+      }
+      if( uiSymbol == 0 )
+      {
+        break;
+      }
+    }
+  }
+  ruiMergeIndex = uiUnaryIdx;
+
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tparseMergeIndex()" )
+  DTRACE_CABAC_T( "\tuiMRGIdx= " )
+  DTRACE_CABAC_V( ruiMergeIndex )
+  DTRACE_CABAC_T( "\n" )
+}
+
+Void TDecSbac::parseMVPIdx      ( Int& riMVPIdx )
+{
+  UInt uiSymbol;
+  xReadUnaryMaxSymbol(uiSymbol, m_cMVPIdxSCModel.get(0), 1, AMVP_MAX_NUM_CANDS-1);
+  riMVPIdx = uiSymbol;
+}
+
+Void TDecSbac::parseSplitFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+  {
+    pcCU->setDepthSubParts( uiDepth, uiAbsPartIdx );
+    return;
+  }
+  
+  UInt uiSymbol;
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUSplitFlagSCModel.get( 0, 0, pcCU->getCtxSplitFlag( uiAbsPartIdx, uiDepth ) ) );
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tSplitFlag\n" )
+  pcCU->setDepthSubParts( uiDepth + uiSymbol, uiAbsPartIdx );
+  
+  return;
+}
+
+/** parse partition size
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \param uiDepth
+ * \returns Void
+ */
+Void TDecSbac::parsePartSize( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiSymbol, uiMode = 0;
+  PartSize eMode;
+  
+#if INTRA_BL
+  if ( pcCU->isIntraBL( uiAbsPartIdx ) )
+  {
+    assert( 0 );
+  }
+#endif
+  if ( pcCU->isIntra( uiAbsPartIdx ) )
+  {
+    uiSymbol = 1;
+    if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+    {
+      m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUPartSizeSCModel.get( 0, 0, 0) );
+    }
+    eMode = uiSymbol ? SIZE_2Nx2N : SIZE_NxN;
+    UInt uiTrLevel = 0;    
+    UInt uiWidthInBit  = g_aucConvertToBit[pcCU->getWidth(uiAbsPartIdx)]+2;
+    UInt uiTrSizeInBit = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxTrSize()]+2;
+    uiTrLevel          = uiWidthInBit >= uiTrSizeInBit ? uiWidthInBit - uiTrSizeInBit : 0;
+    if( eMode == SIZE_NxN )
+    {
+      pcCU->setTrIdxSubParts( 1+uiTrLevel, uiAbsPartIdx, uiDepth );
+    }
+    else
+    {
+      pcCU->setTrIdxSubParts( uiTrLevel, uiAbsPartIdx, uiDepth );
+    }
+  }
+  else
+  {
+    UInt uiMaxNumBits = 2;
+    if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth && !( (g_uiMaxCUWidth>>uiDepth) == 8 && (g_uiMaxCUHeight>>uiDepth) == 8 ) )
+    {
+      uiMaxNumBits ++;
+    }
+    for ( UInt ui = 0; ui < uiMaxNumBits; ui++ )
+    {
+      m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUPartSizeSCModel.get( 0, 0, ui) );
+      if ( uiSymbol )
+      {
+        break;
+      }
+      uiMode++;
+    }
+    eMode = (PartSize) uiMode;
+    if ( pcCU->getSlice()->getSPS()->getAMPAcc( uiDepth ) )
+    {
+      if (eMode == SIZE_2NxN)
+      {
+        m_pcTDecBinIf->decodeBin(uiSymbol, m_cCUAMPSCModel.get( 0, 0, 0 ));
+        if (uiSymbol == 0)
+        {
+          m_pcTDecBinIf->decodeBinEP(uiSymbol);
+          eMode = (uiSymbol == 0? SIZE_2NxnU : SIZE_2NxnD);
+        }
+      }
+      else if (eMode == SIZE_Nx2N)
+      {
+        m_pcTDecBinIf->decodeBin(uiSymbol, m_cCUAMPSCModel.get( 0, 0, 0 ));
+        if (uiSymbol == 0)
+        {
+          m_pcTDecBinIf->decodeBinEP(uiSymbol);
+          eMode = (uiSymbol == 0? SIZE_nLx2N : SIZE_nRx2N);
+        }
+      }
+    }
+  }
+  pcCU->setPartSizeSubParts( eMode, uiAbsPartIdx, uiDepth );
+  pcCU->setSizeSubParts( g_uiMaxCUWidth>>uiDepth, g_uiMaxCUHeight>>uiDepth, uiAbsPartIdx, uiDepth );
+}
+
+/** parse prediction mode
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \param uiDepth
+ * \returns Void
+ */
+Void TDecSbac::parsePredMode( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  if( pcCU->getSlice()->isIntra() )
+  {
+    pcCU->setPredModeSubParts( MODE_INTRA, uiAbsPartIdx, uiDepth );
+    return;
+  }
+  
+  UInt uiSymbol;
+  Int  iPredMode = MODE_INTER;
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUPredModeSCModel.get( 0, 0, 0 ) );
+  iPredMode += uiSymbol;
+  pcCU->setPredModeSubParts( (PredMode)iPredMode, uiAbsPartIdx, uiDepth );
+}
+
+Void TDecSbac::parseIntraDirLumaAng  ( TComDataCU* pcCU, UInt absPartIdx, UInt depth )
+{
+  PartSize mode = pcCU->getPartitionSize( absPartIdx );
+  UInt partNum = mode==SIZE_NxN?4:1;
+  UInt partOffset = ( pcCU->getPic()->getNumPartInCU() >> ( pcCU->getDepth(absPartIdx) << 1 ) ) >> 2;
+  UInt mpmPred[4],symbol;
+  Int j,intraPredMode;    
+  if (mode==SIZE_NxN)
+  {
+    depth++;
+  }
+  for (j=0;j<partNum;j++)
+  {
+    m_pcTDecBinIf->decodeBin( symbol, m_cCUIntraPredSCModel.get( 0, 0, 0) );
+    mpmPred[j] = symbol;
+  }
+  for (j=0;j<partNum;j++)
+  {
+    Int preds[3] = {-1, -1, -1};
+    Int predNum = pcCU->getIntraDirLumaPredictor(absPartIdx+partOffset*j, preds);  
+    if (mpmPred[j])
+    {
+      m_pcTDecBinIf->decodeBinEP( symbol );
+      if (symbol)
+      {
+        m_pcTDecBinIf->decodeBinEP( symbol );
+        symbol++;
+      }
+      intraPredMode = preds[symbol];
+    }
+    else
+    {
+      intraPredMode = 0;
+      m_pcTDecBinIf->decodeBinsEP( symbol, 5 );
+      intraPredMode = symbol;
+        
+      //postponed sorting of MPMs (only in remaining branch)
+      if (preds[0] > preds[1])
+      { 
+        std::swap(preds[0], preds[1]); 
+      }
+      if (preds[0] > preds[2])
+      {
+        std::swap(preds[0], preds[2]);
+      }
+      if (preds[1] > preds[2])
+      {
+        std::swap(preds[1], preds[2]);
+      }
+      for ( Int i = 0; i < predNum; i++ )
+      {
+        intraPredMode += ( intraPredMode >= preds[i] );
+      }
+    }
+    pcCU->setLumaIntraDirSubParts( (UChar)intraPredMode, absPartIdx+partOffset*j, depth );
+  }
+}
+
+Void TDecSbac::parseIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiSymbol;
+
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUChromaPredSCModel.get( 0, 0, 0 ) );
+
+  if( uiSymbol == 0 )
+  {
+    uiSymbol = DM_CHROMA_IDX;
+  } 
+  else 
+  {
+#if !REMOVE_LMCHROMA
+    if( pcCU->getSlice()->getSPS()->getUseLMChroma() )
+    {
+      m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUChromaPredSCModel.get( 0, 0, 1 ) );
+    }
+    else
+    {
+      uiSymbol = 1;
+    }
+
+    if( uiSymbol == 0 )
+    {
+      uiSymbol = LM_CHROMA_IDX;
+    } 
+    else
+#endif
+    {
+      UInt uiIPredMode;
+      m_pcTDecBinIf->decodeBinsEP( uiIPredMode, 2 );
+      UInt uiAllowedChromaDir[ NUM_CHROMA_MODE ];
+      pcCU->getAllowedChromaDir( uiAbsPartIdx, uiAllowedChromaDir );
+      uiSymbol = uiAllowedChromaDir[ uiIPredMode ];
+    }
+  }
+  pcCU->setChromIntraDirSubParts( uiSymbol, uiAbsPartIdx, uiDepth );
+  return;
+}
+
+Void TDecSbac::parseInterDir( TComDataCU* pcCU, UInt& ruiInterDir, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiSymbol;
+  const UInt uiCtx = pcCU->getCtxInterDir( uiAbsPartIdx );
+  ContextModel *pCtx = m_cCUInterDirSCModel.get( 0 );
+#if DISALLOW_BIPRED_IN_8x4_4x8PUS
+  uiSymbol = 0;
+  if (pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_2Nx2N || pcCU->getHeight(uiAbsPartIdx) != 8 )
+  {
+#endif
+    m_pcTDecBinIf->decodeBin( uiSymbol, *( pCtx + uiCtx ) );
+#if DISALLOW_BIPRED_IN_8x4_4x8PUS
+  }
+#endif
+
+  if( uiSymbol )
+  {
+    uiSymbol = 2;
+  }
+  else
+  {
+    m_pcTDecBinIf->decodeBin( uiSymbol, *( pCtx + 4 ) );
+    assert(uiSymbol == 0 || uiSymbol == 1);
+  }
+
+  uiSymbol++;
+  ruiInterDir = uiSymbol;
+  return;
+}
+
+Void TDecSbac::parseRefFrmIdx( TComDataCU* pcCU, Int& riRefFrmIdx, UInt uiAbsPartIdx, UInt uiDepth, RefPicList eRefList )
+{
+  UInt uiSymbol;
+  {
+    ContextModel *pCtx = m_cCURefPicSCModel.get( 0 );
+    m_pcTDecBinIf->decodeBin( uiSymbol, *pCtx );
+
+    if( uiSymbol )
+    {
+#if REF_IDX_BYPASS
+      UInt uiRefNum = pcCU->getSlice()->getNumRefIdx( eRefList ) - 2;
+      pCtx++;
+      UInt ui;
+      for( ui = 0; ui < uiRefNum; ++ui )
+      {
+        if( ui == 0 )
+        {
+          m_pcTDecBinIf->decodeBin( uiSymbol, *pCtx );
+        }
+        else
+        {
+          m_pcTDecBinIf->decodeBinEP( uiSymbol );
+        }
+        if( uiSymbol == 0 )
+        {
+          break;
+        }
+      }
+      uiSymbol = ui + 1;
+#else
+      xReadUnaryMaxSymbol( uiSymbol, pCtx + 1, 1, pcCU->getSlice()->getNumRefIdx( eRefList )-2 );
+      uiSymbol++;
+#endif
+    }
+    riRefFrmIdx = uiSymbol;
+  }
+
+  return;
+}
+
+Void TDecSbac::parseMvd( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth, RefPicList eRefList )
+{
+  UInt uiSymbol;
+  UInt uiHorAbs;
+  UInt uiVerAbs;
+  UInt uiHorSign = 0;
+  UInt uiVerSign = 0;
+  ContextModel *pCtx = m_cCUMvdSCModel.get( 0 );
+
+  if(pcCU->getSlice()->getMvdL1ZeroFlag() && eRefList == REF_PIC_LIST_1 && pcCU->getInterDir(uiAbsPartIdx)==3)
+  {
+    uiHorAbs=0;
+    uiVerAbs=0;
+  }
+  else
+  {
+    m_pcTDecBinIf->decodeBin( uiHorAbs, *pCtx );
+    m_pcTDecBinIf->decodeBin( uiVerAbs, *pCtx );
+
+    const Bool bHorAbsGr0 = uiHorAbs != 0;
+    const Bool bVerAbsGr0 = uiVerAbs != 0;
+    pCtx++;
+
+    if( bHorAbsGr0 )
+    {
+      m_pcTDecBinIf->decodeBin( uiSymbol, *pCtx );
+      uiHorAbs += uiSymbol;
+    }
+
+    if( bVerAbsGr0 )
+    {
+      m_pcTDecBinIf->decodeBin( uiSymbol, *pCtx );
+      uiVerAbs += uiSymbol;
+    }
+
+    if( bHorAbsGr0 )
+    {
+      if( 2 == uiHorAbs )
+      {
+        xReadEpExGolomb( uiSymbol, 1 );
+        uiHorAbs += uiSymbol;
+      }
+
+      m_pcTDecBinIf->decodeBinEP( uiHorSign );
+    }
+
+    if( bVerAbsGr0 )
+    {
+      if( 2 == uiVerAbs )
+      {
+        xReadEpExGolomb( uiSymbol, 1 );
+        uiVerAbs += uiSymbol;
+      }
+
+      m_pcTDecBinIf->decodeBinEP( uiVerSign );
+    }
+
+  }
+
+  const TComMv cMv( uiHorSign ? -Int( uiHorAbs ): uiHorAbs, uiVerSign ? -Int( uiVerAbs ) : uiVerAbs );
+  pcCU->getCUMvField( eRefList )->setAllMvd( cMv, pcCU->getPartitionSize( uiAbsPartIdx ), uiAbsPartIdx, uiDepth, uiPartIdx );
+  return;
+}
+
+
+Void TDecSbac::parseTransformSubdivFlag( UInt& ruiSubdivFlag, UInt uiLog2TransformBlockSize )
+{
+  m_pcTDecBinIf->decodeBin( ruiSubdivFlag, m_cCUTransSubdivFlagSCModel.get( 0, 0, uiLog2TransformBlockSize ) );
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tparseTransformSubdivFlag()" )
+  DTRACE_CABAC_T( "\tsymbol=" )
+  DTRACE_CABAC_V( ruiSubdivFlag )
+  DTRACE_CABAC_T( "\tctx=" )
+  DTRACE_CABAC_V( uiLog2TransformBlockSize )
+  DTRACE_CABAC_T( "\n" )
+}
+
+Void TDecSbac::parseQtRootCbf( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt& uiQtRootCbf )
+{
+  UInt uiSymbol;
+  const UInt uiCtx = 0;
+  m_pcTDecBinIf->decodeBin( uiSymbol , m_cCUQtRootCbfSCModel.get( 0, 0, uiCtx ) );
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tparseQtRootCbf()" )
+  DTRACE_CABAC_T( "\tsymbol=" )
+  DTRACE_CABAC_V( uiSymbol )
+  DTRACE_CABAC_T( "\tctx=" )
+  DTRACE_CABAC_V( uiCtx )
+  DTRACE_CABAC_T( "\tuiAbsPartIdx=" )
+  DTRACE_CABAC_V( uiAbsPartIdx )
+  DTRACE_CABAC_T( "\n" )
+  
+  uiQtRootCbf = uiSymbol;
+}
+
+Void TDecSbac::parseDeltaQP( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  Int qp;
+  UInt uiDQp;
+  Int  iDQp;
+  
+#if CU_DQP_TU_EG
+  UInt uiSymbol;
+
+  xReadUnaryMaxSymbol (uiDQp,  &m_cCUDeltaQpSCModel.get( 0, 0, 0 ), 1, CU_DQP_TU_CMAX);
+
+  if( uiDQp >= CU_DQP_TU_CMAX)
+  {
+    xReadEpExGolomb( uiSymbol, CU_DQP_EG_k );
+    uiDQp+=uiSymbol;
+  }
+
+  if ( uiDQp > 0 )
+  {
+    UInt uiSign;
+    Int qpBdOffsetY = pcCU->getSlice()->getSPS()->getQpBDOffsetY();
+    m_pcTDecBinIf->decodeBinEP(uiSign);
+    iDQp = uiDQp;
+    if(uiSign)
+    {
+      iDQp = -iDQp;
+    }
+    qp = (((Int) pcCU->getRefQP( uiAbsPartIdx ) + iDQp + 52 + 2*qpBdOffsetY )%(52+qpBdOffsetY)) - qpBdOffsetY;
+  }
+  else 
+  {
+    iDQp=0;
+    qp = pcCU->getRefQP(uiAbsPartIdx);
+  }
+#else
+  m_pcTDecBinIf->decodeBin( uiDQp, m_cCUDeltaQpSCModel.get( 0, 0, 0 ) );
+  
+  if ( uiDQp == 0 )
+  {
+    qp = pcCU->getRefQP(uiAbsPartIdx);
+  }
+  else
+  {
+    UInt uiSign;
+    Int qpBdOffsetY = pcCU->getSlice()->getSPS()->getQpBDOffsetY();
+    m_pcTDecBinIf->decodeBinEP(uiSign);
+
+    UInt uiMaxAbsDQpMinus1 = 24 + (qpBdOffsetY/2) + (uiSign);
+    UInt uiAbsDQpMinus1;
+    xReadUnaryMaxSymbol (uiAbsDQpMinus1,  &m_cCUDeltaQpSCModel.get( 0, 0, 1 ), 1, uiMaxAbsDQpMinus1);
+
+    iDQp = uiAbsDQpMinus1 + 1;
+
+    if(uiSign)
+    {
+      iDQp = -iDQp;
+    }
+
+    qp = (((Int) pcCU->getRefQP( uiAbsPartIdx ) + iDQp + 52 + 2*qpBdOffsetY )%(52+qpBdOffsetY)) - qpBdOffsetY;
+  }
+#endif
+  pcCU->setQPSubParts(qp, uiAbsPartIdx, uiDepth);  
+  pcCU->setCodedQP(qp);
+}
+
+Void TDecSbac::parseQtCbf( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth, UInt uiDepth )
+{
+  UInt uiSymbol;
+  const UInt uiCtx = pcCU->getCtxQtCbf( uiAbsPartIdx, eType, uiTrDepth );
+  m_pcTDecBinIf->decodeBin( uiSymbol , m_cCUQtCbfSCModel.get( 0, eType ? TEXT_CHROMA: eType, uiCtx ) );
+  
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tparseQtCbf()" )
+  DTRACE_CABAC_T( "\tsymbol=" )
+  DTRACE_CABAC_V( uiSymbol )
+  DTRACE_CABAC_T( "\tctx=" )
+  DTRACE_CABAC_V( uiCtx )
+  DTRACE_CABAC_T( "\tetype=" )
+  DTRACE_CABAC_V( eType )
+  DTRACE_CABAC_T( "\tuiAbsPartIdx=" )
+  DTRACE_CABAC_V( uiAbsPartIdx )
+  DTRACE_CABAC_T( "\n" )
+  
+  pcCU->setCbfSubParts( uiSymbol << uiTrDepth, eType, uiAbsPartIdx, uiDepth );
+}
+
+void TDecSbac::parseTransformSkipFlags (TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, UInt uiDepth, TextType eTType)
+{
+  if (pcCU->getCUTransquantBypass(uiAbsPartIdx))
+  {
+    return;
+  }
+#if !INTER_TRANSFORMSKIP
+  if(!pcCU->isIntra(uiAbsPartIdx))
+  {
+    return;
+  }
+#endif
+  if(width != 4 || height != 4)
+  {
+    return;
+  }
+  
+  UInt useTransformSkip;
+  m_pcTDecBinIf->decodeBin( useTransformSkip , m_cTransformSkipSCModel.get( 0, eTType? TEXT_CHROMA: TEXT_LUMA, 0 ) );
+  if(eTType!= TEXT_LUMA)
+  {
+    const UInt uiLog2TrafoSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth()] + 2 - uiDepth;
+    if(uiLog2TrafoSize == 2) 
+    { 
+      uiDepth --;
+    }
+  }
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T("\tparseTransformSkip()");
+  DTRACE_CABAC_T( "\tsymbol=" )
+  DTRACE_CABAC_V( useTransformSkip )
+  DTRACE_CABAC_T( "\tAddr=" )
+  DTRACE_CABAC_V( pcCU->getAddr() )
+  DTRACE_CABAC_T( "\tetype=" )
+  DTRACE_CABAC_V( eTType )
+  DTRACE_CABAC_T( "\tuiAbsPartIdx=" )
+  DTRACE_CABAC_V( uiAbsPartIdx )
+  DTRACE_CABAC_T( "\n" )
+
+  pcCU->setTransformSkipSubParts( useTransformSkip, eTType, uiAbsPartIdx, uiDepth);
+}
+
+/** Parse (X,Y) position of the last significant coefficient
+ * \param uiPosLastX reference to X component of last coefficient
+ * \param uiPosLastY reference to Y component of last coefficient
+ * \param width  Block width
+ * \param height Block height
+ * \param eTType plane type / luminance or chrominance
+ * \param uiScanIdx scan type (zig-zag, hor, ver)
+ *
+ * This method decodes the X and Y component within a block of the last significant coefficient.
+ */
+Void TDecSbac::parseLastSignificantXY( UInt& uiPosLastX, UInt& uiPosLastY, Int width, Int height, TextType eTType, UInt uiScanIdx )
+{
+  UInt uiLast;
+  ContextModel *pCtxX = m_cCuCtxLastX.get( 0, eTType );
+  ContextModel *pCtxY = m_cCuCtxLastY.get( 0, eTType );
+
+  Int blkSizeOffsetX, blkSizeOffsetY, shiftX, shiftY;
+  blkSizeOffsetX = eTType ? 0: (g_aucConvertToBit[ width ] *3 + ((g_aucConvertToBit[ width ] +1)>>2));
+  blkSizeOffsetY = eTType ? 0: (g_aucConvertToBit[ height ]*3 + ((g_aucConvertToBit[ height ]+1)>>2));
+  shiftX= eTType ? g_aucConvertToBit[ width  ] :((g_aucConvertToBit[ width  ]+3)>>2);
+  shiftY= eTType ? g_aucConvertToBit[ height ] :((g_aucConvertToBit[ height ]+3)>>2);
+  // posX
+  for( uiPosLastX = 0; uiPosLastX < g_uiGroupIdx[ width - 1 ]; uiPosLastX++ )
+  {
+    m_pcTDecBinIf->decodeBin( uiLast, *( pCtxX + blkSizeOffsetX + (uiPosLastX >>shiftX) ) );
+    if( !uiLast )
+    {
+      break;
+    }
+  }
+
+  // posY
+  for( uiPosLastY = 0; uiPosLastY < g_uiGroupIdx[ height - 1 ]; uiPosLastY++ )
+  {
+    m_pcTDecBinIf->decodeBin( uiLast, *( pCtxY + blkSizeOffsetY + (uiPosLastY >>shiftY)) );
+    if( !uiLast )
+    {
+      break;
+    }
+  }
+  if ( uiPosLastX > 3 )
+  {
+    UInt uiTemp  = 0;
+    UInt uiCount = ( uiPosLastX - 2 ) >> 1;
+    for ( Int i = uiCount - 1; i >= 0; i-- )
+    {
+      m_pcTDecBinIf->decodeBinEP( uiLast );
+      uiTemp += uiLast << i;
+    }
+    uiPosLastX = g_uiMinInGroup[ uiPosLastX ] + uiTemp;
+  }
+  if ( uiPosLastY > 3 )
+  {
+    UInt uiTemp  = 0;
+    UInt uiCount = ( uiPosLastY - 2 ) >> 1;
+    for ( Int i = uiCount - 1; i >= 0; i-- )
+    {
+      m_pcTDecBinIf->decodeBinEP( uiLast );
+      uiTemp += uiLast << i;
+    }
+    uiPosLastY = g_uiMinInGroup[ uiPosLastY ] + uiTemp;
+  }
+  
+  if( uiScanIdx == SCAN_VER )
+  {
+    swap( uiPosLastX, uiPosLastY );
+  }
+}
+
+Void TDecSbac::parseCoeffNxN( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType )
+{
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tparseCoeffNxN()\teType=" )
+  DTRACE_CABAC_V( eTType )
+  DTRACE_CABAC_T( "\twidth=" )
+  DTRACE_CABAC_V( uiWidth )
+  DTRACE_CABAC_T( "\theight=" )
+  DTRACE_CABAC_V( uiHeight )
+  DTRACE_CABAC_T( "\tdepth=" )
+  DTRACE_CABAC_V( uiDepth )
+  DTRACE_CABAC_T( "\tabspartidx=" )
+  DTRACE_CABAC_V( uiAbsPartIdx )
+  DTRACE_CABAC_T( "\ttoCU-X=" )
+  DTRACE_CABAC_V( pcCU->getCUPelX() )
+  DTRACE_CABAC_T( "\ttoCU-Y=" )
+  DTRACE_CABAC_V( pcCU->getCUPelY() )
+  DTRACE_CABAC_T( "\tCU-addr=" )
+  DTRACE_CABAC_V(  pcCU->getAddr() )
+  DTRACE_CABAC_T( "\tinCU-X=" )
+  DTRACE_CABAC_V( g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ] )
+  DTRACE_CABAC_T( "\tinCU-Y=" )
+  DTRACE_CABAC_V( g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ] )
+  DTRACE_CABAC_T( "\tpredmode=" )
+  DTRACE_CABAC_V(  pcCU->getPredictionMode( uiAbsPartIdx ) )
+  DTRACE_CABAC_T( "\n" )
+  
+  if( uiWidth > pcCU->getSlice()->getSPS()->getMaxTrSize() )
+  {
+    uiWidth  = pcCU->getSlice()->getSPS()->getMaxTrSize();
+    uiHeight = pcCU->getSlice()->getSPS()->getMaxTrSize();
+  }
+#if PPS_TS_FLAG
+  if(pcCU->getSlice()->getPPS()->getUseTransformSkip())
+#else
+  if(pcCU->getSlice()->getSPS()->getUseTransformSkip())
+#endif
+  {
+    parseTransformSkipFlags( pcCU, uiAbsPartIdx, uiWidth, uiHeight, uiDepth, eTType);
+  }
+
+  eTType = eTType == TEXT_LUMA ? TEXT_LUMA : ( eTType == TEXT_NONE ? TEXT_NONE : TEXT_CHROMA );
+  
+  //----- parse significance map -----
+  const UInt  uiLog2BlockSize   = g_aucConvertToBit[ uiWidth ] + 2;
+  const UInt  uiMaxNumCoeff     = uiWidth * uiHeight;
+  const UInt  uiMaxNumCoeffM1   = uiMaxNumCoeff - 1;
+  UInt uiScanIdx = pcCU->getCoefScanIdx(uiAbsPartIdx, uiWidth, eTType==TEXT_LUMA, pcCU->isIntra(uiAbsPartIdx));
+  int blockType = uiLog2BlockSize;
+  if (uiWidth != uiHeight)
+  {
+    uiScanIdx = SCAN_DIAG;
+    blockType = 4;
+  }
+  
+  //===== decode last significant =====
+  UInt uiPosLastX, uiPosLastY;
+  parseLastSignificantXY( uiPosLastX, uiPosLastY, uiWidth, uiHeight, eTType, uiScanIdx );
+  UInt uiBlkPosLast      = uiPosLastX + (uiPosLastY<<uiLog2BlockSize);
+  pcCoef[ uiBlkPosLast ] = 1;
+
+  //===== decode significance flags =====
+  UInt uiScanPosLast   = uiBlkPosLast;
+  if (uiScanIdx == SCAN_ZIGZAG)
+  {
+    // Map zigzag to diagonal scan
+    uiScanIdx = SCAN_DIAG;
+  }
+#if REMOVE_NSQT
+  const UInt *scan = g_auiSigLastScan[ uiScanIdx ][ uiLog2BlockSize-1 ];
+#else
+  const UInt * scan;
+  if (uiWidth == uiHeight)
+  {
+    scan = g_auiSigLastScan[ uiScanIdx ][ uiLog2BlockSize-1 ];
+  }
+  else
+  {
+    scan = g_sigScanNSQT[ uiLog2BlockSize - 2 ];
+  }
+#endif
+  for( uiScanPosLast = 0; uiScanPosLast < uiMaxNumCoeffM1; uiScanPosLast++ )
+  {
+    UInt uiBlkPos = scan[ uiScanPosLast ];
+    if( uiBlkPosLast == uiBlkPos )
+    {
+      break;
+    }
+  }
+
+  ContextModel * const baseCoeffGroupCtx = m_cCUSigCoeffGroupSCModel.get( 0, eTType );
+  ContextModel * const baseCtx = (eTType==TEXT_LUMA) ? m_cCUSigSCModel.get( 0, 0 ) : m_cCUSigSCModel.get( 0, 0 ) + NUM_SIG_FLAG_CTX_LUMA;
+
+  const Int  iLastScanSet      = uiScanPosLast >> LOG2_SCAN_SET_SIZE;
+#if REMOVE_NUM_GREATER1
+  UInt c1 = 1;
+#else
+  UInt uiNumOne                = 0;
+#endif
+  UInt uiGoRiceParam           = 0;
+
+  Bool beValid; 
+  if (pcCU->getCUTransquantBypass(uiAbsPartIdx))
+  {
+    beValid = false;
+  }
+  else 
+  {
+    beValid = pcCU->getSlice()->getPPS()->getSignHideFlag() > 0;
+  }
+  UInt absSum = 0;
+
+  UInt uiSigCoeffGroupFlag[ MLS_GRP_NUM ];
+  ::memset( uiSigCoeffGroupFlag, 0, sizeof(UInt) * MLS_GRP_NUM );
+  const UInt uiNumBlkSide = uiWidth >> (MLS_CG_SIZE >> 1);
+  const UInt * scanCG;
+#if !REMOVE_NSQT
+  if (uiWidth == uiHeight)
+#endif
+  {
+    scanCG = g_auiSigLastScan[ uiScanIdx ][ uiLog2BlockSize > 3 ? uiLog2BlockSize-2-1 : 0  ];    
+    if( uiLog2BlockSize == 3 )
+    {
+      scanCG = g_sigLastScan8x8[ uiScanIdx ];
+    }
+    else if( uiLog2BlockSize == 5 )
+    {
+      scanCG = g_sigLastScanCG32x32;
+    }
+  }
+#if !REMOVE_NSQT
+  else
+  {
+    scanCG = g_sigCGScanNSQT[ uiLog2BlockSize - 2 ];
+  }
+#endif
+  Int  iScanPosSig             = (Int) uiScanPosLast;
+  for( Int iSubSet = iLastScanSet; iSubSet >= 0; iSubSet-- )
+  {
+    Int  iSubPos     = iSubSet << LOG2_SCAN_SET_SIZE;
+    uiGoRiceParam    = 0;
+    Int numNonZero = 0;
+    
+    Int lastNZPosInCG = -1, firstNZPosInCG = SCAN_SET_SIZE;
+
+    Int pos[SCAN_SET_SIZE];
+    if( iScanPosSig == (Int) uiScanPosLast )
+    {
+      lastNZPosInCG  = iScanPosSig;
+      firstNZPosInCG = iScanPosSig;
+      iScanPosSig--;
+      pos[ numNonZero ] = uiBlkPosLast;
+      numNonZero = 1;
+    }
+
+    // decode significant_coeffgroup_flag
+    Int iCGBlkPos = scanCG[ iSubSet ];
+    Int iCGPosY   = iCGBlkPos / uiNumBlkSide;
+    Int iCGPosX   = iCGBlkPos - (iCGPosY * uiNumBlkSide);
+#if !REMOVAL_8x2_2x8_CG
+    if( uiWidth == 8 && uiHeight == 8 && (uiScanIdx == SCAN_HOR || uiScanIdx == SCAN_VER) )
+    {
+      iCGPosY = (uiScanIdx == SCAN_HOR ? iCGBlkPos : 0);
+      iCGPosX = (uiScanIdx == SCAN_VER ? iCGBlkPos : 0);
+    }
+#endif
+    if( iSubSet == iLastScanSet || iSubSet == 0)
+    {
+      uiSigCoeffGroupFlag[ iCGBlkPos ] = 1;
+    }
+    else
+    {
+      UInt uiSigCoeffGroup;
+      UInt uiCtxSig  = TComTrQuant::getSigCoeffGroupCtxInc( uiSigCoeffGroupFlag, iCGPosX, iCGPosY, uiScanIdx, uiWidth, uiHeight );
+      m_pcTDecBinIf->decodeBin( uiSigCoeffGroup, baseCoeffGroupCtx[ uiCtxSig ] );
+      uiSigCoeffGroupFlag[ iCGBlkPos ] = uiSigCoeffGroup;
+    }
+
+    // decode significant_coeff_flag
+    Int patternSigCtx = TComTrQuant::calcPatternSigCtx( uiSigCoeffGroupFlag, iCGPosX, iCGPosY, uiWidth, uiHeight );
+    UInt uiBlkPos, uiPosY, uiPosX, uiSig, uiCtxSig;
+    for( ; iScanPosSig >= iSubPos; iScanPosSig-- )
+    {
+      uiBlkPos  = scan[ iScanPosSig ];
+      uiPosY    = uiBlkPos >> uiLog2BlockSize;
+      uiPosX    = uiBlkPos - ( uiPosY << uiLog2BlockSize );
+      uiSig     = 0;
+      
+      if( uiSigCoeffGroupFlag[ iCGBlkPos ] )
+      {
+        if( iScanPosSig > iSubPos || iSubSet == 0  || numNonZero )
+        {
+#if REMOVAL_8x2_2x8_CG
+          uiCtxSig  = TComTrQuant::getSigCtxInc( patternSigCtx, uiScanIdx, uiPosX, uiPosY, blockType, uiWidth, uiHeight, eTType );
+#else
+          uiCtxSig  = TComTrQuant::getSigCtxInc( patternSigCtx, uiPosX, uiPosY, blockType, uiWidth, uiHeight, eTType );
+#endif
+          m_pcTDecBinIf->decodeBin( uiSig, baseCtx[ uiCtxSig ] );
+        }
+        else
+        {
+          uiSig = 1;
+        }
+      }
+      pcCoef[ uiBlkPos ] = uiSig;
+      if( uiSig )
+      {
+        pos[ numNonZero ] = uiBlkPos;
+        numNonZero ++;
+        if( lastNZPosInCG == -1 )
+        {
+          lastNZPosInCG = iScanPosSig;
+        }
+        firstNZPosInCG = iScanPosSig;
+      }
+    }
+    
+    if( numNonZero )
+    {
+      Bool signHidden = ( lastNZPosInCG - firstNZPosInCG >= SBH_THRESHOLD );
+      absSum = 0;
+#if !REMOVE_NUM_GREATER1
+      UInt c1 = 1;
+#endif
+      UInt uiCtxSet    = (iSubSet > 0 && eTType==TEXT_LUMA) ? 2 : 0;
+      UInt uiBin;
+#if REMOVE_NUM_GREATER1
+      if( c1 == 0 )
+#else
+      if( uiNumOne > 0 )
+#endif
+      {
+        uiCtxSet++;
+      }
+#if REMOVE_NUM_GREATER1
+      c1 = 1;
+#else
+      uiNumOne       >>= 1;
+#endif
+      ContextModel *baseCtxMod = ( eTType==TEXT_LUMA ) ? m_cCUOneSCModel.get( 0, 0 ) + 4 * uiCtxSet : m_cCUOneSCModel.get( 0, 0 ) + NUM_ONE_FLAG_CTX_LUMA + 4 * uiCtxSet;
+      Int absCoeff[SCAN_SET_SIZE];
+
+      for ( Int i = 0; i < numNonZero; i++) absCoeff[i] = 1;   
+      Int numC1Flag = min(numNonZero, C1FLAG_NUMBER);
+      Int firstC2FlagIdx = -1;
+
+      for( Int idx = 0; idx < numC1Flag; idx++ )
+      {
+        m_pcTDecBinIf->decodeBin( uiBin, baseCtxMod[c1] );
+        if( uiBin == 1 )
+        {
+          c1 = 0;
+          if (firstC2FlagIdx == -1)
+          {
+            firstC2FlagIdx = idx;
+          }
+        }
+        else if( (c1 < 3) && (c1 > 0) )
+        {
+          c1++;
+        }
+        absCoeff[ idx ] = uiBin + 1;
+      }
+      
+      if (c1 == 0)
+      {
+        baseCtxMod = ( eTType==TEXT_LUMA ) ? m_cCUAbsSCModel.get( 0, 0 ) + uiCtxSet : m_cCUAbsSCModel.get( 0, 0 ) + NUM_ABS_FLAG_CTX_LUMA + uiCtxSet;
+        if ( firstC2FlagIdx != -1)
+        {
+          m_pcTDecBinIf->decodeBin( uiBin, baseCtxMod[0] ); 
+          absCoeff[ firstC2FlagIdx ] = uiBin + 2;
+        }
+      }
+
+      UInt coeffSigns;
+      if ( signHidden && beValid )
+      {
+        m_pcTDecBinIf->decodeBinsEP( coeffSigns, numNonZero-1 );
+        coeffSigns <<= 32 - (numNonZero-1);
+      }
+      else
+      {
+        m_pcTDecBinIf->decodeBinsEP( coeffSigns, numNonZero );
+        coeffSigns <<= 32 - numNonZero;
+      }
+      
+      Int iFirstCoeff2 = 1;    
+      if (c1 == 0 || numNonZero > C1FLAG_NUMBER)
+      {
+        for( Int idx = 0; idx < numNonZero; idx++ )
+        {
+          UInt baseLevel  = (idx < C1FLAG_NUMBER)? (2 + iFirstCoeff2) : 1;
+
+          if( absCoeff[ idx ] == baseLevel)
+          {
+            UInt uiLevel;
+            xReadCoefRemainExGolomb( uiLevel, uiGoRiceParam );
+            absCoeff[ idx ] = uiLevel + baseLevel;
+            if(absCoeff[idx]>3*(1<<uiGoRiceParam))
+            {
+              uiGoRiceParam = min<UInt>(uiGoRiceParam+ 1, 4);
+            }
+          }
+
+          if(absCoeff[ idx ] >= 2)  
+          {
+            iFirstCoeff2 = 0;
+#if !REMOVE_NUM_GREATER1
+            uiNumOne++;
+#endif
+          }
+        }
+      }
+
+      for( Int idx = 0; idx < numNonZero; idx++ )
+      {
+        Int blkPos = pos[ idx ];
+        // Signs applied later.
+        pcCoef[ blkPos ] = absCoeff[ idx ];
+        absSum += absCoeff[ idx ];
+
+        if ( idx == numNonZero-1 && signHidden && beValid )
+        {
+          // Infer sign of 1st element.
+          if (absSum&0x1)
+          {
+            pcCoef[ blkPos ] = -pcCoef[ blkPos ];
+          }
+        }
+        else
+        {
+          Int sign = static_cast<Int>( coeffSigns ) >> 31;
+          pcCoef[ blkPos ] = ( pcCoef[ blkPos ] ^ sign ) - sign;
+          coeffSigns <<= 1;
+        }
+      }
+    }
+#if !REMOVE_NUM_GREATER1
+    else
+    {
+      uiNumOne >>= 1;
+    }
+#endif
+  }
+  
+  return;
+}
+
+
+Void TDecSbac::parseSaoMaxUvlc ( UInt& val, UInt maxSymbol )
+{
+  if (maxSymbol == 0)
+  {
+    val = 0;
+    return;
+  }
+
+  UInt code;
+  Int  i;
+#if SAO_ABS_BY_PASS
+  m_pcTDecBinIf->decodeBinEP( code );
+#else
+  m_pcTDecBinIf->decodeBin( code, m_cSaoUvlcSCModel.get( 0, 0, 0 ) );
+#endif
+  if ( code == 0 )
+  {
+    val = 0;
+    return;
+  }
+
+  i=1;
+  while (1)
+  {
+#if SAO_ABS_BY_PASS
+    m_pcTDecBinIf->decodeBinEP( code );
+#else
+    m_pcTDecBinIf->decodeBin( code, m_cSaoUvlcSCModel.get( 0, 0, 1 ) );
+#endif
+    if ( code == 0 )
+    {
+      break;
+    }
+    i++;
+    if (i == maxSymbol) 
+    {
+      break;
+    }
+  }
+
+  val = i;
+}
+#if SAO_TYPE_CODING
+Void TDecSbac::parseSaoUflc (UInt uiLength, UInt&  riVal)
+{
+  m_pcTDecBinIf->decodeBinsEP ( riVal, uiLength );
+}
+#else
+Void TDecSbac::parseSaoUflc (UInt&  riVal)
+{
+  m_pcTDecBinIf->decodeBinsEP ( riVal, 5 );
+}
+#endif
+#if SAO_MERGE_ONE_CTX
+Void TDecSbac::parseSaoMerge (UInt&  ruiVal)
+#else
+Void TDecSbac::parseSaoMergeLeft (UInt&  ruiVal, UInt uiCompIdx)
+#endif
+{
+  UInt uiCode;
+#if SAO_MERGE_ONE_CTX
+  m_pcTDecBinIf->decodeBin( uiCode, m_cSaoMergeSCModel.get( 0, 0, 0 ) );
+#else
+#if SAO_SINGLE_MERGE
+  m_pcTDecBinIf->decodeBin( uiCode, m_cSaoMergeLeftSCModel.get( 0, 0, 0 ) );
+#else
+  m_pcTDecBinIf->decodeBin( uiCode, m_cSaoMergeLeftSCModel.get( 0, 0, uiCompIdx ) );
+#endif
+#endif
+  ruiVal = (Int)uiCode;
+}
+#if !SAO_MERGE_ONE_CTX
+Void TDecSbac::parseSaoMergeUp (UInt&  ruiVal)
+{
+  UInt uiCode;
+  m_pcTDecBinIf->decodeBin( uiCode, m_cSaoMergeUpSCModel.get( 0, 0, 0 ) );
+  ruiVal = (Int)uiCode;
+}
+#endif
+Void TDecSbac::parseSaoTypeIdx (UInt&  ruiVal)
+{
+  UInt uiCode;
+#if SAO_TYPE_CODING
+  m_pcTDecBinIf->decodeBin( uiCode, m_cSaoTypeIdxSCModel.get( 0, 0, 0 ) );
+  if (uiCode == 0) 
+  {
+    ruiVal = 0;
+  }
+  else
+  {
+    m_pcTDecBinIf->decodeBinEP( uiCode ); 
+    if (uiCode == 0)
+    {
+      ruiVal = 5;
+    }
+    else
+    {
+      ruiVal = 1;
+    }
+  }
+#else
+  Int  i;
+  m_pcTDecBinIf->decodeBin( uiCode, m_cSaoTypeIdxSCModel.get( 0, 0, 0 ) );
+  if ( uiCode == 0 )
+  {
+    ruiVal = 0;
+    return;
+  }
+  i=1;
+  while (1)
+  {
+    m_pcTDecBinIf->decodeBin( uiCode, m_cSaoTypeIdxSCModel.get( 0, 0, 1 ) );
+    if ( uiCode == 0 )
+    {
+      break;
+    }
+    i++;
+  }
+  ruiVal = i;
+#endif
+}
+
+inline Void copySaoOneLcuParam(SaoLcuParam* psDst,  SaoLcuParam* psSrc)
+{
+  Int i;
+  psDst->partIdx = psSrc->partIdx;
+  psDst->typeIdx    = psSrc->typeIdx;
+  if (psDst->typeIdx != -1)
+  {
+#if SAO_TYPE_CODING
+    psDst->subTypeIdx = psSrc->subTypeIdx ;
+#else
+    if (psDst->typeIdx == SAO_BO)
+    {
+      psDst->bandPosition = psSrc->bandPosition ;
+    }
+    else
+    {
+      psDst->bandPosition = 0;
+    }
+#endif
+    psDst->length  = psSrc->length;
+    for (i=0;i<psDst->length;i++)
+    {
+      psDst->offset[i] = psSrc->offset[i];
+    }
+  }
+  else
+  {
+    psDst->length  = 0;
+    for (i=0;i<SAO_BO_LEN;i++)
+    {
+      psDst->offset[i] = 0;
+    }
+  }
+}
+
+#if SAO_TYPE_SHARING
+Void TDecSbac::parseSaoOffset(SaoLcuParam* psSaoLcuParam, UInt compIdx)
+#else
+Void TDecSbac::parseSaoOffset(SaoLcuParam* psSaoLcuParam)
+#endif
+{
+  UInt uiSymbol;
+  static Int iTypeLength[MAX_NUM_SAO_TYPE] =
+  {
+    SAO_EO_LEN,
+    SAO_EO_LEN,
+    SAO_EO_LEN,
+    SAO_EO_LEN,
+    SAO_BO_LEN
+  }; 
+
+#if SAO_TYPE_SHARING
+if (compIdx==2)
+{
+uiSymbol = (UInt)( psSaoLcuParam->typeIdx + 1);
+}
+else
+{
+parseSaoTypeIdx(uiSymbol);
+}
+#else
+  parseSaoTypeIdx(uiSymbol);
+#endif
+  psSaoLcuParam->typeIdx = (Int)uiSymbol - 1;
+  if (uiSymbol)
+  {
+    psSaoLcuParam->length = iTypeLength[psSaoLcuParam->typeIdx];
+#if FULL_NBIT
+    Int offsetTh = 1 << ( min((Int)(g_uiBitDepth + (g_uiBitDepth-8)-5),5) );
+#else
+    Int offsetTh = 1 << ( min((Int)(g_uiBitDepth + g_uiBitIncrement-5),5) );
+#endif
+
+    if( psSaoLcuParam->typeIdx == SAO_BO )
+    {
+#if !SAO_TYPE_CODING
+    // Parse Left Band Index
+    parseSaoUflc( uiSymbol );
+    psSaoLcuParam->bandPosition = uiSymbol;
+#endif
+      for(Int i=0; i< psSaoLcuParam->length; i++)
+      {
+        parseSaoMaxUvlc(uiSymbol, offsetTh -1 );
+        psSaoLcuParam->offset[i] = uiSymbol;
+      }   
+      for(Int i=0; i< psSaoLcuParam->length; i++)
+      {
+        if (psSaoLcuParam->offset[i] != 0) 
+        {
+          m_pcTDecBinIf->decodeBinEP ( uiSymbol);
+          if (uiSymbol)
+          {
+            psSaoLcuParam->offset[i] = -psSaoLcuParam->offset[i] ;
+          }
+        }
+      }
+#if SAO_TYPE_CODING
+      parseSaoUflc(5, uiSymbol );
+      psSaoLcuParam->subTypeIdx = uiSymbol;
+#endif
+    }
+    else if( psSaoLcuParam->typeIdx < 4 )
+    {
+      parseSaoMaxUvlc(uiSymbol, offsetTh -1 ); psSaoLcuParam->offset[0] = uiSymbol;
+      parseSaoMaxUvlc(uiSymbol, offsetTh -1 ); psSaoLcuParam->offset[1] = uiSymbol;
+      parseSaoMaxUvlc(uiSymbol, offsetTh -1 ); psSaoLcuParam->offset[2] = -(Int)uiSymbol;
+      parseSaoMaxUvlc(uiSymbol, offsetTh -1 ); psSaoLcuParam->offset[3] = -(Int)uiSymbol;
+#if SAO_TYPE_CODING
+#if SAO_TYPE_SHARING
+     if (compIdx != 2)
+     {
+       parseSaoUflc(2, uiSymbol );
+       psSaoLcuParam->subTypeIdx = uiSymbol;
+       psSaoLcuParam->typeIdx += psSaoLcuParam->subTypeIdx;
+     }
+#else
+     parseSaoUflc(2, uiSymbol );
+     psSaoLcuParam->subTypeIdx = uiSymbol;
+     psSaoLcuParam->typeIdx += psSaoLcuParam->subTypeIdx;
+#endif
+#endif
+   }
+  }
+  else
+  {
+    psSaoLcuParam->length = 0;
+  }
+}
+
+Void TDecSbac::parseSaoOneLcuInterleaving(Int rx, Int ry, SAOParam* pSaoParam, TComDataCU* pcCU, Int iCUAddrInSlice, Int iCUAddrUpInSlice, Int allowMergeLeft, Int allowMergeUp)
+{
+  Int iAddr = pcCU->getAddr();
+  UInt uiSymbol;
+#if SAO_SINGLE_MERGE
+  for (Int iCompIdx=0; iCompIdx<3; iCompIdx++)
+  {
+    pSaoParam->saoLcuParam[iCompIdx][iAddr].mergeUpFlag    = 0;
+    pSaoParam->saoLcuParam[iCompIdx][iAddr].mergeLeftFlag  = 0;
+#if SAO_TYPE_CODING
+    pSaoParam->saoLcuParam[iCompIdx][iAddr].subTypeIdx     = 0;
+#else
+    pSaoParam->saoLcuParam[iCompIdx][iAddr].bandPosition   = 0;
+#endif
+    pSaoParam->saoLcuParam[iCompIdx][iAddr].typeIdx        = -1;
+    pSaoParam->saoLcuParam[iCompIdx][iAddr].offset[0]     = 0;
+    pSaoParam->saoLcuParam[iCompIdx][iAddr].offset[1]     = 0;
+    pSaoParam->saoLcuParam[iCompIdx][iAddr].offset[2]     = 0;
+    pSaoParam->saoLcuParam[iCompIdx][iAddr].offset[3]     = 0;
+
+  }
+#if SAO_TYPE_SHARING
+ if (pSaoParam->bSaoFlag[0] || pSaoParam->bSaoFlag[1] )
+#else
+ if (pSaoParam->bSaoFlag[0] || pSaoParam->bSaoFlag[1] || pSaoParam->bSaoFlag[2])
+#endif
+  {
+    if (rx>0 && iCUAddrInSlice!=0 && allowMergeLeft)
+    {
+#if SAO_MERGE_ONE_CTX
+      parseSaoMerge(uiSymbol); 
+      pSaoParam->saoLcuParam[0][iAddr].mergeLeftFlag = (Bool)uiSymbol;  
+#else
+      parseSaoMergeLeft(uiSymbol, 0); 
+      pSaoParam->saoLcuParam[0][iAddr].mergeLeftFlag = (Bool)uiSymbol;   
+#endif
+    }
+    if (pSaoParam->saoLcuParam[0][iAddr].mergeLeftFlag==0)
+    {
+      if ((ry > 0) && (iCUAddrUpInSlice>=0) && allowMergeUp)
+      {
+#if SAO_MERGE_ONE_CTX
+        parseSaoMerge(uiSymbol);
+        pSaoParam->saoLcuParam[0][iAddr].mergeUpFlag = (Bool)uiSymbol;
+#else
+        parseSaoMergeUp(uiSymbol);
+        pSaoParam->saoLcuParam[0][iAddr].mergeUpFlag = (Bool)uiSymbol;
+#endif
+      }
+    }
+  }
+#endif
+
+  for (Int iCompIdx=0; iCompIdx<3; iCompIdx++)
+  {
+#if !SAO_SINGLE_MERGE
+    pSaoParam->saoLcuParam[iCompIdx][iAddr].mergeUpFlag    = 0;
+    pSaoParam->saoLcuParam[iCompIdx][iAddr].mergeLeftFlag  = 0;
+    pSaoParam->saoLcuParam[iCompIdx][iAddr].bandPosition   = 0;
+    pSaoParam->saoLcuParam[iCompIdx][iAddr].typeIdx        = -1;
+    pSaoParam->saoLcuParam[iCompIdx][iAddr].offset[0]     = 0;
+    pSaoParam->saoLcuParam[iCompIdx][iAddr].offset[1]     = 0;
+    pSaoParam->saoLcuParam[iCompIdx][iAddr].offset[2]     = 0;
+    pSaoParam->saoLcuParam[iCompIdx][iAddr].offset[3]     = 0;
+#endif
+#if SAO_TYPE_SHARING
+    if ((iCompIdx == 0  && pSaoParam->bSaoFlag[0]) || (iCompIdx > 0  && pSaoParam->bSaoFlag[1]) )
+#else
+    if (pSaoParam->bSaoFlag[iCompIdx])
+#endif
+    {
+      if (rx>0 && iCUAddrInSlice!=0 && allowMergeLeft)
+      {
+#if SAO_SINGLE_MERGE
+        pSaoParam->saoLcuParam[iCompIdx][iAddr].mergeLeftFlag = pSaoParam->saoLcuParam[0][iAddr].mergeLeftFlag;
+#else
+        parseSaoMergeLeft(uiSymbol,iCompIdx); pSaoParam->saoLcuParam[iCompIdx][iAddr].mergeLeftFlag = (Int)uiSymbol;
+#endif
+      }
+      else
+      {
+        pSaoParam->saoLcuParam[iCompIdx][iAddr].mergeLeftFlag = 0;
+      }
+
+      if (pSaoParam->saoLcuParam[iCompIdx][iAddr].mergeLeftFlag==0)
+      {
+        if ((ry > 0) && (iCUAddrUpInSlice>=0) && allowMergeUp)
+        {
+#if SAO_SINGLE_MERGE
+          pSaoParam->saoLcuParam[iCompIdx][iAddr].mergeUpFlag = pSaoParam->saoLcuParam[0][iAddr].mergeUpFlag;
+#else
+          parseSaoMergeUp(uiSymbol);  pSaoParam->saoLcuParam[iCompIdx][iAddr].mergeUpFlag = uiSymbol;
+#endif
+        }
+        else
+        {
+          pSaoParam->saoLcuParam[iCompIdx][iAddr].mergeUpFlag = 0;
+        }
+        if (!pSaoParam->saoLcuParam[iCompIdx][iAddr].mergeUpFlag)
+        {
+#if SAO_TYPE_SHARING
+          pSaoParam->saoLcuParam[2][iAddr].typeIdx = pSaoParam->saoLcuParam[1][iAddr].typeIdx;
+          parseSaoOffset(&(pSaoParam->saoLcuParam[iCompIdx][iAddr]), iCompIdx);
+#else
+          parseSaoOffset(&(pSaoParam->saoLcuParam[iCompIdx][iAddr]));
+#endif
+        }
+        else
+        {
+          copySaoOneLcuParam(&pSaoParam->saoLcuParam[iCompIdx][iAddr], &pSaoParam->saoLcuParam[iCompIdx][iAddr-pSaoParam->numCuInWidth]);
+        }
+      }
+      else
+      {
+        copySaoOneLcuParam(&pSaoParam->saoLcuParam[iCompIdx][iAddr],  &pSaoParam->saoLcuParam[iCompIdx][iAddr-1]);
+      }
+    }
+    else
+    {
+      pSaoParam->saoLcuParam[iCompIdx][iAddr].typeIdx = -1;
+#if SAO_TYPE_CODING
+      pSaoParam->saoLcuParam[iCompIdx][iAddr].subTypeIdx = 0;
+#else
+      pSaoParam->saoLcuParam[iCompIdx][iAddr].bandPosition = 0;
+#endif
+    }
+  }
+}
+
+#if !REMOVE_ALF
+Void TDecSbac::parseAlfCtrlFlag (Int compIdx, UInt& code)
+{
+  UInt decodedSymbol;
+  m_pcTDecBinIf->decodeBin( decodedSymbol, m_cCUAlfCtrlFlagSCModel.get( 0, 0, 0 ) );
+  code = decodedSymbol;
+
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "parseAlfCtrlFlag()" )
+  DTRACE_CABAC_T( "\tsymbol=" )
+  DTRACE_CABAC_V( decodedSymbol )
+  DTRACE_CABAC_T( "\tcompIdx=" )
+  DTRACE_CABAC_V( compIdx )
+  DTRACE_CABAC_T( "\n" )
+}
+#endif
+
+/**
+ - Initialize our contexts from the nominated source.
+ .
+ \param pSrc Contexts to be copied.
+ */
+Void TDecSbac::xCopyContextsFrom( TDecSbac* pSrc )
+{
+  memcpy(m_contextModels, pSrc->m_contextModels, m_numContextModels*sizeof(m_contextModels[0]));
+}
+
+Void TDecSbac::xCopyFrom( TDecSbac* pSrc )
+{
+  m_pcTDecBinIf->copyState( pSrc->m_pcTDecBinIf );
+
+  m_uiLastQp           = pSrc->m_uiLastQp;
+  xCopyContextsFrom( pSrc );
+
+}
+
+Void TDecSbac::load ( TDecSbac* pScr )
+{
+  xCopyFrom(pScr);
+}
+
+Void TDecSbac::loadContexts ( TDecSbac* pScr )
+{
+  xCopyContextsFrom(pScr);
+}
+
+Void TDecSbac::decodeFlush ( )
+{
+  UInt uiBit;
+  m_pcTDecBinIf->decodeBinTrm(uiBit);
+  m_pcTDecBinIf->flush();
+
+}
+//! \}
Index: /trunk/source/Lib/TLibDecoder/TDecSbac.h
===================================================================
--- /trunk/source/Lib/TLibDecoder/TDecSbac.h	(revision 2)
+++ /trunk/source/Lib/TLibDecoder/TDecSbac.h	(revision 2)
@@ -0,0 +1,224 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TDecSbac.h
+    \brief    SBAC decoder class (header)
+*/
+
+#ifndef __TDECSBAC__
+#define __TDECSBAC__
+
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+
+#include "TDecEntropy.h"
+#include "TDecBinCoder.h"
+#include "TLibCommon/ContextTables.h"
+#include "TLibCommon/ContextModel.h"
+#include "TLibCommon/ContextModel3DBuffer.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+class SEImessages;
+
+/// SBAC decoder class
+class TDecSbac : public TDecEntropyIf
+{
+public:
+  TDecSbac();
+  virtual ~TDecSbac();
+  
+  Void  init                      ( TDecBinIf* p )    { m_pcTDecBinIf = p; }
+  Void  uninit                    (              )    { m_pcTDecBinIf = 0; }
+  
+  Void load                          ( TDecSbac* pScr );
+  Void loadContexts                  ( TDecSbac* pScr );
+  Void xCopyFrom           ( TDecSbac* pSrc );
+  Void xCopyContextsFrom       ( TDecSbac* pSrc );
+  Void decodeFlush();
+
+  Void  resetEntropy (TComSlice* pSlice );
+  Void  setBitstream              ( TComInputBitstream* p  ) { m_pcBitstream = p; m_pcTDecBinIf->init( p ); }
+  Void  parseVPS                  ( TComVPS* pcVPS )  {}
+  Void  parseSPS                  ( TComSPS* pcSPS         ) {}
+  Void  parsePPS                  ( TComPPS* pcPPS         ) {}
+#if !REMOVE_APS
+  Void  parseAPS                  ( TComAPS* pAPS          ) {}
+#endif
+
+  Void  parseSliceHeader          ( TComSlice*& rpcSlice, ParameterSetManagerDecoder *parameterSetManager) {}
+  Void  parseTerminatingBit       ( UInt& ruiBit );
+  Void  parseMVPIdx               ( Int& riMVPIdx          );
+  Void  parseSaoMaxUvlc           ( UInt& val, UInt maxSymbol );
+#if SAO_MERGE_ONE_CTX
+  Void  parseSaoMerge         ( UInt&  ruiVal   );
+#else
+  Void  parseSaoMergeLeft         ( UInt&  ruiVal, UInt uiCompIdx   );
+  Void  parseSaoMergeUp           ( UInt&  ruiVal  );
+#endif
+  Void  parseSaoTypeIdx           ( UInt&  ruiVal  );
+#if SAO_TYPE_CODING
+  Void  parseSaoUflc              ( UInt uiLength, UInt& ruiVal     );
+#else
+  Void  parseSaoUflc              ( UInt& ruiVal           );
+#endif
+  Void  parseSaoOneLcuInterleaving(Int rx, Int ry, SAOParam* pSaoParam, TComDataCU* pcCU, Int iCUAddrInSlice, Int iCUAddrUpInSlice, Int allowMergeLeft, Int allowMergeUp);
+#if SAO_TYPE_SHARING
+  Void  parseSaoOffset            (SaoLcuParam* psSaoLcuParam, UInt compIdx);
+#else
+  Void  parseSaoOffset            (SaoLcuParam* psSaoLcuParam);
+#endif
+private:
+  Void  xReadUnarySymbol    ( UInt& ruiSymbol, ContextModel* pcSCModel, Int iOffset );
+  Void  xReadUnaryMaxSymbol ( UInt& ruiSymbol, ContextModel* pcSCModel, Int iOffset, UInt uiMaxSymbol );
+  Void  xReadEpExGolomb     ( UInt& ruiSymbol, UInt uiCount );
+  Void  xReadCoefRemainExGolomb ( UInt &rSymbol, UInt &rParam );
+private:
+  TComInputBitstream* m_pcBitstream;
+  TDecBinIf*        m_pcTDecBinIf;
+ 
+#if !REMOVE_FGS
+  Int           m_iSliceGranularity; //!< slice granularity
+#endif
+  
+public:
+#if !REMOVE_ALF
+  Void parseAlfCtrlFlag   (Int compIdx, UInt& code);
+#endif
+#if !REMOVE_FGS
+  /// set slice granularity
+  Void setSliceGranularity(Int iSliceGranularity)  {m_iSliceGranularity = iSliceGranularity;}
+
+  /// get slice granularity
+  Int  getSliceGranularity()                       {return m_iSliceGranularity;             }
+#endif
+  
+  Void parseSkipFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void parseCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void parseSplitFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void parseMergeFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPUIdx );
+  Void parseMergeIndex    ( TComDataCU* pcCU, UInt& ruiMergeIndex, UInt uiAbsPartIdx, UInt uiDepth );
+  Void parsePartSize      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void parsePredMode      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  
+  Void parseIntraDirLumaAng( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  
+  Void parseIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  
+  Void parseInterDir      ( TComDataCU* pcCU, UInt& ruiInterDir, UInt uiAbsPartIdx, UInt uiDepth );
+  Void parseRefFrmIdx     ( TComDataCU* pcCU, Int& riRefFrmIdx, UInt uiAbsPartIdx, UInt uiDepth, RefPicList eRefList );
+  Void parseMvd           ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth, RefPicList eRefList );
+  
+  Void parseTransformSubdivFlag( UInt& ruiSubdivFlag, UInt uiLog2TransformBlockSize );
+  Void parseQtCbf         ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth, UInt uiDepth );
+  Void parseQtRootCbf     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt& uiQtRootCbf );
+  
+  Void parseDeltaQP       ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  
+  Void parseIPCMInfo      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth);
+
+  Void parseLastSignificantXY( UInt& uiPosLastX, UInt& uiPosLastY, Int width, Int height, TextType eTType, UInt uiScanIdx );
+  Void parseCoeffNxN      ( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType );
+  Void parseTransformSkipFlags ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, UInt uiDepth, TextType eTType);
+
+  Void updateContextTables( SliceType eSliceType, Int iQp );
+
+  Void  parseScalingList ( TComScalingList* scalingList ) {}
+
+#if INTRA_BL
+  Void parseIntraBLFlag    ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
+#endif
+private:
+  UInt m_uiLastDQpNonZero;
+  UInt m_uiLastQp;
+  
+  ContextModel         m_contextModels[MAX_NUM_CTX_MOD];
+  Int                  m_numContextModels;
+  ContextModel3DBuffer m_cCUSplitFlagSCModel;
+  ContextModel3DBuffer m_cCUSkipFlagSCModel;
+  ContextModel3DBuffer m_cCUMergeFlagExtSCModel;
+  ContextModel3DBuffer m_cCUMergeIdxExtSCModel;
+  ContextModel3DBuffer m_cCUPartSizeSCModel;
+  ContextModel3DBuffer m_cCUPredModeSCModel;
+  ContextModel3DBuffer m_cCUAlfCtrlFlagSCModel;
+  ContextModel3DBuffer m_cCUIntraPredSCModel;
+  ContextModel3DBuffer m_cCUChromaPredSCModel;
+  ContextModel3DBuffer m_cCUDeltaQpSCModel;
+  ContextModel3DBuffer m_cCUInterDirSCModel;
+  ContextModel3DBuffer m_cCURefPicSCModel;
+  ContextModel3DBuffer m_cCUMvdSCModel;
+  ContextModel3DBuffer m_cCUQtCbfSCModel;
+  ContextModel3DBuffer m_cCUTransSubdivFlagSCModel;
+  ContextModel3DBuffer m_cCUQtRootCbfSCModel;
+  
+  ContextModel3DBuffer m_cCUSigCoeffGroupSCModel;
+  ContextModel3DBuffer m_cCUSigSCModel;
+  ContextModel3DBuffer m_cCuCtxLastX;
+  ContextModel3DBuffer m_cCuCtxLastY;
+  ContextModel3DBuffer m_cCUOneSCModel;
+  ContextModel3DBuffer m_cCUAbsSCModel;
+  
+  ContextModel3DBuffer m_cMVPIdxSCModel;
+  
+  ContextModel3DBuffer m_cALFFlagSCModel;
+  ContextModel3DBuffer m_cALFUvlcSCModel;
+  ContextModel3DBuffer m_cALFSvlcSCModel;
+  ContextModel3DBuffer m_cCUAMPSCModel;
+#if !SAO_ABS_BY_PASS
+  ContextModel3DBuffer m_cSaoUvlcSCModel;
+#endif
+#if SAO_MERGE_ONE_CTX
+  ContextModel3DBuffer m_cSaoMergeSCModel;
+#else
+  ContextModel3DBuffer m_cSaoMergeLeftSCModel;
+  ContextModel3DBuffer m_cSaoMergeUpSCModel;
+#endif
+#if INTRA_BL
+  ContextModel3DBuffer m_cIntraBLPredFlagSCModel;
+#endif
+  ContextModel3DBuffer m_cSaoTypeIdxSCModel;
+  ContextModel3DBuffer m_cTransformSkipSCModel;
+  ContextModel3DBuffer m_CUTransquantBypassFlagSCModel;
+};
+
+//! \}
+
+#endif // !defined(AFX_TDECSBAC_H__CFCAAA19_8110_47F4_9A16_810C4B5499D5__INCLUDED_)
Index: /trunk/source/Lib/TLibDecoder/TDecSlice.cpp
===================================================================
--- /trunk/source/Lib/TLibDecoder/TDecSlice.cpp	(revision 2)
+++ /trunk/source/Lib/TLibDecoder/TDecSlice.cpp	(revision 2)
@@ -0,0 +1,551 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TDecSlice.cpp
+    \brief    slice decoder class
+*/
+
+#include "TDecSlice.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+//////////////////////////////////////////////////////////////////////
+// Construction/Destruction
+//////////////////////////////////////////////////////////////////////
+
+TDecSlice::TDecSlice()
+{
+  m_pcBufferSbacDecoders = NULL;
+  m_pcBufferBinCABACs    = NULL;
+  m_pcBufferLowLatSbacDecoders = NULL;
+  m_pcBufferLowLatBinCABACs    = NULL;
+}
+
+TDecSlice::~TDecSlice()
+{
+#if DEPENDENT_SLICES
+  for (std::vector<TDecSbac*>::iterator i = CTXMem.begin(); i != CTXMem.end(); i++)
+  {
+    delete (*i);
+  }
+  CTXMem.clear();
+#endif
+}
+
+#if DEPENDENT_SLICES
+Void TDecSlice::initCtxMem(  UInt i )                
+{   
+  for (std::vector<TDecSbac*>::iterator j = CTXMem.begin(); j != CTXMem.end(); j++)
+  {
+    delete (*j);
+  }
+  CTXMem.clear(); 
+  CTXMem.resize(i); 
+}
+#endif
+
+Void TDecSlice::create( TComSlice* pcSlice, Int iWidth, Int iHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth )
+{
+}
+
+Void TDecSlice::destroy()
+{
+  if ( m_pcBufferSbacDecoders )
+  {
+    delete[] m_pcBufferSbacDecoders;
+    m_pcBufferSbacDecoders = NULL;
+  }
+  if ( m_pcBufferBinCABACs )
+  {
+    delete[] m_pcBufferBinCABACs;
+    m_pcBufferBinCABACs = NULL;
+  }
+  if ( m_pcBufferLowLatSbacDecoders )
+  {
+    delete[] m_pcBufferLowLatSbacDecoders;
+    m_pcBufferLowLatSbacDecoders = NULL;
+  }
+  if ( m_pcBufferLowLatBinCABACs )
+  {
+    delete[] m_pcBufferLowLatBinCABACs;
+    m_pcBufferLowLatBinCABACs = NULL;
+  }
+}
+
+#if SVC_EXTENSION
+Void TDecSlice::init(TDecTop** ppcDecTop,TDecEntropy* pcEntropyDecoder, TDecCu* pcCuDecoder)
+#else
+Void TDecSlice::init(TDecEntropy* pcEntropyDecoder, TDecCu* pcCuDecoder)
+#endif
+{
+  m_pcEntropyDecoder  = pcEntropyDecoder;
+  m_pcCuDecoder       = pcCuDecoder;
+#if SVC_EXTENSION   
+  m_ppcTDecTop        = ppcDecTop; 
+#endif
+}
+
+Void TDecSlice::decompressSlice(TComInputBitstream* pcBitstream, TComInputBitstream** ppcSubstreams, TComPic*& rpcPic, TDecSbac* pcSbacDecoder, TDecSbac* pcSbacDecoders)
+{
+  TComDataCU* pcCU;
+  UInt        uiIsLast = 0;
+  Int   iStartCUEncOrder = max(rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getSliceCurStartCUAddr()/rpcPic->getNumPartInCU(), rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getDependentSliceCurStartCUAddr()/rpcPic->getNumPartInCU());
+  Int   iStartCUAddr = rpcPic->getPicSym()->getCUOrderMap(iStartCUEncOrder);
+
+  // decoder don't need prediction & residual frame buffer
+  rpcPic->setPicYuvPred( 0 );
+  rpcPic->setPicYuvResi( 0 );
+  
+#if ENC_DEC_TRACE
+  g_bJustDoIt = g_bEncDecTraceEnable;
+#endif
+  DTRACE_CABAC_VL( g_nSymbolCounter++ );
+  DTRACE_CABAC_T( "\tPOC: " );
+  DTRACE_CABAC_V( rpcPic->getPOC() );
+  DTRACE_CABAC_T( "\n" );
+
+#if ENC_DEC_TRACE
+  g_bJustDoIt = g_bEncDecTraceDisable;
+#endif
+
+  UInt uiTilesAcross   = rpcPic->getPicSym()->getNumColumnsMinus1()+1;
+  TComSlice*  pcSlice = rpcPic->getSlice(rpcPic->getCurrSliceIdx());
+  Int  iNumSubstreams = pcSlice->getPPS()->getNumSubstreams();
+
+  // delete decoders if already allocated in previous slice
+  if (m_pcBufferSbacDecoders)
+  {
+    delete [] m_pcBufferSbacDecoders;
+  }
+  if (m_pcBufferBinCABACs) 
+  {
+    delete [] m_pcBufferBinCABACs;
+  }
+  // allocate new decoders based on tile numbaer
+  m_pcBufferSbacDecoders = new TDecSbac    [uiTilesAcross];  
+  m_pcBufferBinCABACs    = new TDecBinCABAC[uiTilesAcross];
+  for (UInt ui = 0; ui < uiTilesAcross; ui++)
+  {
+    m_pcBufferSbacDecoders[ui].init(&m_pcBufferBinCABACs[ui]);
+  }
+  //save init. state
+  for (UInt ui = 0; ui < uiTilesAcross; ui++)
+  {
+    m_pcBufferSbacDecoders[ui].load(pcSbacDecoder);
+  }
+
+  // free memory if already allocated in previous call
+  if (m_pcBufferLowLatSbacDecoders)
+  {
+    delete [] m_pcBufferLowLatSbacDecoders;
+  }
+  if (m_pcBufferLowLatBinCABACs)
+  {
+    delete [] m_pcBufferLowLatBinCABACs;
+  }
+  m_pcBufferLowLatSbacDecoders = new TDecSbac    [uiTilesAcross];  
+  m_pcBufferLowLatBinCABACs    = new TDecBinCABAC[uiTilesAcross];
+  for (UInt ui = 0; ui < uiTilesAcross; ui++)
+  {
+    m_pcBufferLowLatSbacDecoders[ui].init(&m_pcBufferLowLatBinCABACs[ui]);
+  }
+  //save init. state
+  for (UInt ui = 0; ui < uiTilesAcross; ui++)
+  {
+    m_pcBufferLowLatSbacDecoders[ui].load(pcSbacDecoder);
+  }
+
+  UInt uiWidthInLCUs  = rpcPic->getPicSym()->getFrameWidthInCU();
+  //UInt uiHeightInLCUs = rpcPic->getPicSym()->getFrameHeightInCU();
+  UInt uiCol=0, uiLin=0, uiSubStrm=0;
+
+  UInt uiTileCol;
+  UInt uiTileStartLCU;
+  UInt uiTileLCUX;
+  UInt uiTileLCUY;
+  UInt uiTileWidth;
+  UInt uiTileHeight;
+  Int iNumSubstreamsPerTile = 1; // if independent.
+
+#if INTRA_BL
+  m_pcCuDecoder->setBaseRecPic( rpcPic->getLayerId() > 0 ? rpcPic->getFullPelBaseRec() : NULL);
+#endif
+#if DEPENDENT_SLICES
+  Bool bAllowDependence = false;
+#if TILES_WPP_ENTROPYSLICES_FLAGS
+  if( rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getPPS()->getDependentSliceEnabledFlag()&& (!rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getPPS()->getEntropySliceEnabledFlag()) )
+#else
+  if( rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getPPS()->getDependentSliceEnabledFlag()&& (!rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getPPS()->getCabacIndependentFlag()) )
+#endif
+  {
+    bAllowDependence = true;
+  }
+  if( bAllowDependence )
+  {
+    if( !rpcPic->getSlice(rpcPic->getCurrSliceIdx())->isNextSlice() )
+    {
+      uiTileCol = 0;
+#if TILES_WPP_ENTROPYSLICES_FLAGS
+      if(pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag())
+#else
+      if(pcSlice->getPPS()->getTilesOrEntropyCodingSyncIdc()==2)
+#endif
+      {
+        m_pcBufferSbacDecoders[uiTileCol].loadContexts( CTXMem[1]  );//2.LCU
+      }
+      pcSbacDecoder->loadContexts(CTXMem[0] ); //end of depSlice-1
+      pcSbacDecoders[uiSubStrm].loadContexts(pcSbacDecoder);
+    }
+    else
+    {
+#if TILES_WPP_ENTROPYSLICES_FLAGS
+      if(pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag())
+#else
+      if(pcSlice->getPPS()->getTilesOrEntropyCodingSyncIdc()==2)
+#endif
+      {
+        CTXMem[1]->loadContexts(pcSbacDecoder);
+      }
+      CTXMem[0]->loadContexts(pcSbacDecoder);
+    }
+  }
+#endif
+  for( Int iCUAddr = iStartCUAddr; !uiIsLast && iCUAddr < rpcPic->getNumCUsInFrame(); iCUAddr = rpcPic->getPicSym()->xCalculateNxtCUAddr(iCUAddr) )
+  {
+    pcCU = rpcPic->getCU( iCUAddr );
+    pcCU->initCU( rpcPic, iCUAddr );
+    uiTileCol = rpcPic->getPicSym()->getTileIdxMap(iCUAddr) % (rpcPic->getPicSym()->getNumColumnsMinus1()+1); // what column of tiles are we in?
+    uiTileStartLCU = rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(iCUAddr))->getFirstCUAddr();
+    uiTileLCUX = uiTileStartLCU % uiWidthInLCUs;
+    uiTileLCUY = uiTileStartLCU / uiWidthInLCUs;
+    uiTileWidth = rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(iCUAddr))->getTileWidth();
+    uiTileHeight = rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(iCUAddr))->getTileHeight();
+    uiCol     = iCUAddr % uiWidthInLCUs;
+    // The 'line' is now relative to the 1st line in the slice, not the 1st line in the picture.
+    uiLin     = (iCUAddr/uiWidthInLCUs)-(iStartCUAddr/uiWidthInLCUs);
+    // inherit from TR if necessary, select substream to use.
+#if DEPENDENT_SLICES
+#if TILES_WPP_ENTROPYSLICES_FLAGS
+    if( (pcSlice->getPPS()->getNumSubstreams() > 1) || ( bAllowDependence  && (uiCol == uiTileLCUX)&&(pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag()) ))
+#else
+    if( (pcSlice->getPPS()->getNumSubstreams() > 1) || ( bAllowDependence  && (uiCol == uiTileLCUX)&&(pcSlice->getPPS()->getTilesOrEntropyCodingSyncIdc()==2) ))
+#endif
+#else
+    if( pcSlice->getPPS()->getNumSubstreams() > 1 )
+#endif
+    {
+      // independent tiles => substreams are "per tile".  iNumSubstreams has already been multiplied.
+      iNumSubstreamsPerTile = iNumSubstreams/rpcPic->getPicSym()->getNumTiles();
+      uiSubStrm = rpcPic->getPicSym()->getTileIdxMap(iCUAddr)*iNumSubstreamsPerTile
+                  + uiLin%iNumSubstreamsPerTile;
+      m_pcEntropyDecoder->setBitstream( ppcSubstreams[uiSubStrm] );
+      // Synchronize cabac probabilities with upper-right LCU if it's available and we're at the start of a line.
+#if DEPENDENT_SLICES
+#if TILES_WPP_ENTROPYSLICES_FLAGS
+      if (((pcSlice->getPPS()->getNumSubstreams() > 1) || bAllowDependence ) && (uiCol == uiTileLCUX)&&(pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag()))
+#else
+      if (((pcSlice->getPPS()->getNumSubstreams() > 1) || bAllowDependence ) && (uiCol == uiTileLCUX)&&(pcSlice->getPPS()->getTilesOrEntropyCodingSyncIdc()==2))
+#endif
+#else
+      if (pcSlice->getPPS()->getNumSubstreams() > 1 && uiCol == uiTileLCUX)
+#endif
+      {
+        // We'll sync if the TR is available.
+        TComDataCU *pcCUUp = pcCU->getCUAbove();
+        UInt uiWidthInCU = rpcPic->getFrameWidthInCU();
+        TComDataCU *pcCUTR = NULL;
+        if ( pcCUUp && ((iCUAddr%uiWidthInCU+1) < uiWidthInCU)  )
+        {
+          pcCUTR = rpcPic->getCU( iCUAddr - uiWidthInCU + 1 );
+        }
+        UInt uiMaxParts = 1<<(pcSlice->getSPS()->getMaxCUDepth()<<1);
+
+        if ( (true/*bEnforceSliceRestriction*/ &&
+             ((pcCUTR==NULL) || (pcCUTR->getSlice()==NULL) || 
+             ((pcCUTR->getSCUAddr()+uiMaxParts-1) < pcSlice->getSliceCurStartCUAddr()) ||
+             ((rpcPic->getPicSym()->getTileIdxMap( pcCUTR->getAddr() ) != rpcPic->getPicSym()->getTileIdxMap(iCUAddr)))
+             ))||
+             (true/*bEnforceDependentSliceRestriction*/ &&
+             ((pcCUTR==NULL) || (pcCUTR->getSlice()==NULL) || 
+             ((pcCUTR->getSCUAddr()+uiMaxParts-1) < pcSlice->getDependentSliceCurStartCUAddr()) ||
+             ((rpcPic->getPicSym()->getTileIdxMap( pcCUTR->getAddr() ) != rpcPic->getPicSym()->getTileIdxMap(iCUAddr)))
+             ))
+           )
+        {
+#if DEPENDENT_SLICES
+          if( (iCUAddr!=0) && ((pcCUTR->getSCUAddr()+uiMaxParts-1) >= pcSlice->getSliceCurStartCUAddr()) && bAllowDependence)
+          {
+             pcSbacDecoders[uiSubStrm].loadContexts( &m_pcBufferSbacDecoders[uiTileCol] ); 
+          }
+#endif
+          // TR not available.
+        }
+        else
+        {
+          // TR is available, we use it.
+          pcSbacDecoders[uiSubStrm].loadContexts( &m_pcBufferSbacDecoders[uiTileCol] );
+        }
+      }
+      pcSbacDecoder->load(&pcSbacDecoders[uiSubStrm]);  //this load is used to simplify the code (avoid to change all the call to pcSbacDecoders)
+    }
+    else if ( pcSlice->getPPS()->getNumSubstreams() <= 1 )
+    {
+      // Set variables to appropriate values to avoid later code change.
+      iNumSubstreamsPerTile = 1;
+    }
+
+    if ( (iCUAddr == rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(iCUAddr))->getFirstCUAddr()) && // 1st in tile.
+         (iCUAddr!=0) && (iCUAddr!=rpcPic->getPicSym()->getPicSCUAddr(rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getSliceCurStartCUAddr())/rpcPic->getNumPartInCU())
+#if DEPENDENT_SLICES
+         && (iCUAddr!=rpcPic->getPicSym()->getPicSCUAddr(rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getDependentSliceCurStartCUAddr())/rpcPic->getNumPartInCU())
+#endif
+         ) // !1st in frame && !1st in slice
+    {
+      if (pcSlice->getPPS()->getNumSubstreams() > 1)
+      {
+        // We're crossing into another tile, tiles are independent.
+        // When tiles are independent, we have "substreams per tile".  Each substream has already been terminated, and we no longer
+        // have to perform it here.
+        // For TILES_DECODER, there can be a header at the start of the 1st substream in a tile.  These are read when the substreams
+        // are extracted, not here.
+      }
+      else
+      {
+        SliceType sliceType  = pcSlice->getSliceType();
+        if (pcSlice->getCabacInitFlag())
+        {
+          switch (sliceType)
+          {
+          case P_SLICE:           // change initialization table to B_SLICE intialization
+            sliceType = B_SLICE; 
+            break;
+          case B_SLICE:           // change initialization table to P_SLICE intialization
+            sliceType = P_SLICE; 
+            break;
+          default     :           // should not occur
+            assert(0);
+          }
+        }
+        m_pcEntropyDecoder->updateContextTables( sliceType, pcSlice->getSliceQp() );
+      }
+      
+    }
+
+#if ENC_DEC_TRACE
+    g_bJustDoIt = g_bEncDecTraceEnable;
+#endif
+#if !SAO_LUM_CHROMA_ONOFF_FLAGS
+    if ( pcSlice->getSPS()->getUseSAO() && pcSlice->getSaoEnabledFlag() )
+#else
+    if ( pcSlice->getSPS()->getUseSAO() && (pcSlice->getSaoEnabledFlag()||pcSlice->getSaoEnabledFlagChroma()) )
+#endif
+    {
+#if REMOVE_APS
+      SAOParam *saoParam = rpcPic->getPicSym()->getSaoParam();
+#else
+      SAOParam *saoParam = pcSlice->getAPS()->getSaoParam();
+#endif
+      saoParam->bSaoFlag[0] = pcSlice->getSaoEnabledFlag();
+      if (iCUAddr == iStartCUAddr)
+      {
+#if SAO_TYPE_SHARING
+        saoParam->bSaoFlag[1] = pcSlice->getSaoEnabledFlagChroma();
+#else
+        saoParam->bSaoFlag[1] = pcSlice->getSaoEnabledFlagCb();
+        saoParam->bSaoFlag[2] = pcSlice->getSaoEnabledFlagCr();
+#endif
+      }
+      Int numCuInWidth     = saoParam->numCuInWidth;
+      Int cuAddrInSlice = iCUAddr - rpcPic->getPicSym()->getCUOrderMap(pcSlice->getSliceCurStartCUAddr()/rpcPic->getNumPartInCU());
+      Int cuAddrUpInSlice  = cuAddrInSlice - numCuInWidth;
+      Int rx = iCUAddr % numCuInWidth;
+      Int ry = iCUAddr / numCuInWidth;
+      Int allowMergeLeft = 1;
+      Int allowMergeUp   = 1;
+      if (rx!=0)
+      {
+        if (rpcPic->getPicSym()->getTileIdxMap(iCUAddr-1) != rpcPic->getPicSym()->getTileIdxMap(iCUAddr))
+        {
+          allowMergeLeft = 0;
+        }
+      }
+      if (ry!=0)
+      {
+        if (rpcPic->getPicSym()->getTileIdxMap(iCUAddr-numCuInWidth) != rpcPic->getPicSym()->getTileIdxMap(iCUAddr))
+        {
+          allowMergeUp = 0;
+        }
+      }
+      pcSbacDecoder->parseSaoOneLcuInterleaving(rx, ry, saoParam,pcCU, cuAddrInSlice, cuAddrUpInSlice, allowMergeLeft, allowMergeUp);
+    }
+#if !REMOVE_ALF
+    if(pcSlice->getSPS()->getUseALF())
+    {
+      UInt alfEnabledFlag;
+      for(Int compIdx=0; compIdx< 3; compIdx++)
+      {
+        alfEnabledFlag = 0;
+        if(pcSlice->getAlfEnabledFlag(compIdx))
+        {
+          pcSbacDecoder->parseAlfCtrlFlag(compIdx, alfEnabledFlag);
+        }
+        pcCU->setAlfLCUEnabled((alfEnabledFlag==1)?true:false, compIdx);
+      }
+    }
+#endif
+    m_pcCuDecoder->decodeCU     ( pcCU, uiIsLast );
+    m_pcCuDecoder->decompressCU ( pcCU );
+    
+#if ENC_DEC_TRACE
+    g_bJustDoIt = g_bEncDecTraceDisable;
+#endif
+    /*If at the end of a LCU line but not at the end of a substream, perform CABAC flush*/
+    if (!uiIsLast && pcSlice->getPPS()->getNumSubstreams() > 1)
+    {
+      if ((uiCol == uiTileLCUX+uiTileWidth-1) && (uiLin+iNumSubstreamsPerTile < uiTileLCUY+uiTileHeight))
+      {
+        m_pcEntropyDecoder->decodeFlush();
+      }
+    }
+    pcSbacDecoders[uiSubStrm].load(pcSbacDecoder);
+
+    //Store probabilities of second LCU in line into buffer
+#if DEPENDENT_SLICES
+#if TILES_WPP_ENTROPYSLICES_FLAGS
+    if ( (uiCol == uiTileLCUX+1)&& (bAllowDependence || (pcSlice->getPPS()->getNumSubstreams() > 1)) && (pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag()) )
+#else
+    if ( (uiCol == uiTileLCUX+1)&& (bAllowDependence || (pcSlice->getPPS()->getNumSubstreams() > 1)) && (pcSlice->getPPS()->getTilesOrEntropyCodingSyncIdc() == 2))
+#endif
+#else
+    if (pcSlice->getPPS()->getNumSubstreams() > 1 && (uiCol == uiTileLCUX+1))
+#endif
+    {
+      m_pcBufferSbacDecoders[uiTileCol].loadContexts( &pcSbacDecoders[uiSubStrm] );
+    }
+#if DEPENDENT_SLICES
+    if( uiIsLast && bAllowDependence )
+    {
+#if TILES_WPP_ENTROPYSLICES_FLAGS
+      if (pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag())
+#else
+      if (pcSlice->getPPS()->getTilesOrEntropyCodingSyncIdc()==2)
+#endif
+       {
+         CTXMem[1]->loadContexts( &m_pcBufferSbacDecoders[uiTileCol] );//ctx 2.LCU
+       }
+      CTXMem[0]->loadContexts( pcSbacDecoder );//ctx end of dep.slice
+      return;
+    }
+#endif
+  }
+}
+
+ParameterSetManagerDecoder::ParameterSetManagerDecoder()
+: m_vpsBuffer(MAX_NUM_VPS)
+,m_spsBuffer(256)
+, m_ppsBuffer(16)
+#if !REMOVE_APS
+, m_apsBuffer(64)
+#endif
+{
+
+}
+
+ParameterSetManagerDecoder::~ParameterSetManagerDecoder()
+{
+
+}
+
+TComVPS* ParameterSetManagerDecoder::getPrefetchedVPS  (Int vpsId)
+{
+  if (m_vpsBuffer.getPS(vpsId) != NULL )
+  {
+    return m_vpsBuffer.getPS(vpsId);
+  }
+  else
+  {
+    return getVPS(vpsId);
+  }
+}
+
+
+TComSPS* ParameterSetManagerDecoder::getPrefetchedSPS  (Int spsId)
+{
+  if (m_spsBuffer.getPS(spsId) != NULL )
+  {
+    return m_spsBuffer.getPS(spsId);
+  }
+  else
+  {
+    return getSPS(spsId);
+  }
+}
+
+TComPPS* ParameterSetManagerDecoder::getPrefetchedPPS  (Int ppsId)
+{
+  if (m_ppsBuffer.getPS(ppsId) != NULL )
+  {
+    return m_ppsBuffer.getPS(ppsId);
+  }
+  else
+  {
+    return getPPS(ppsId);
+  }
+}
+
+#if !REMOVE_APS
+TComAPS* ParameterSetManagerDecoder::getPrefetchedAPS  (Int apsId)
+{
+  if (m_apsBuffer.getPS(apsId) != NULL )
+  {
+    return m_apsBuffer.getPS(apsId);
+  }
+  else
+  {
+    return getAPS(apsId);
+  }
+}
+#endif
+
+Void     ParameterSetManagerDecoder::applyPrefetchedPS()
+{
+  m_vpsMap.mergePSList(m_vpsBuffer);
+#if !REMOVE_APS
+  m_apsMap.mergePSList(m_apsBuffer);
+#endif
+  m_ppsMap.mergePSList(m_ppsBuffer);
+  m_spsMap.mergePSList(m_spsBuffer);
+}
+
+//! \}
Index: /trunk/source/Lib/TLibDecoder/TDecSlice.h
===================================================================
--- /trunk/source/Lib/TLibDecoder/TDecSlice.h	(revision 2)
+++ /trunk/source/Lib/TLibDecoder/TDecSlice.h	(revision 2)
@@ -0,0 +1,135 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TDecSlice.h
+    \brief    slice decoder class (header)
+*/
+
+#ifndef __TDECSLICE__
+#define __TDECSLICE__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComBitStream.h"
+#include "TLibCommon/TComPic.h"
+#include "TDecEntropy.h"
+#include "TDecCu.h"
+#include "TDecSbac.h"
+#include "TDecBinCoderCABAC.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// slice decoder class
+class TDecSlice
+{
+private:
+  // access channel
+  TDecEntropy*    m_pcEntropyDecoder;
+  TDecCu*         m_pcCuDecoder;
+  UInt            m_uiCurrSliceIdx;
+
+  TDecSbac*       m_pcBufferSbacDecoders;   ///< line to store temporary contexts, one per column of tiles.
+  TDecBinCABAC*   m_pcBufferBinCABACs;
+  TDecSbac*       m_pcBufferLowLatSbacDecoders;   ///< dependent tiles: line to store temporary contexts, one per column of tiles.
+  TDecBinCABAC*   m_pcBufferLowLatBinCABACs;
+#if DEPENDENT_SLICES
+  std::vector<TDecSbac*> CTXMem;
+#endif
+
+#if SVC_EXTENSION
+  TDecTop**       m_ppcTDecTop;
+#endif  
+  
+public:
+  TDecSlice();
+  virtual ~TDecSlice();
+  
+#if SVC_EXTENSION  
+  Void  init              ( TDecTop** ppcDecTop, TDecEntropy* pcEntropyDecoder, TDecCu* pcMbDecoder );
+#else
+  Void  init              ( TDecEntropy* pcEntropyDecoder, TDecCu* pcMbDecoder );
+#endif
+  Void  create            ( TComSlice* pcSlice, Int iWidth, Int iHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth );
+  Void  destroy           ();
+  
+  Void  decompressSlice   ( TComInputBitstream* pcBitstream, TComInputBitstream** ppcSubstreams,   TComPic*& rpcPic, TDecSbac* pcSbacDecoder, TDecSbac* pcSbacDecoders );
+#if DEPENDENT_SLICES
+  Void      initCtxMem(  UInt i );
+  Void      setCtxMem( TDecSbac* sb, int b )   { CTXMem[b] = sb; }
+#endif
+
+#if SVC_EXTENSION
+  TDecTop*  getLayerDec   ( UInt LayerId )  { return m_ppcTDecTop[LayerId]; }  
+#endif 
+};
+
+
+class ParameterSetManagerDecoder:public ParameterSetManager
+{
+public:
+  ParameterSetManagerDecoder();
+  virtual ~ParameterSetManagerDecoder();
+  Void     storePrefetchedVPS(TComVPS *vps)  { m_vpsBuffer.storePS( vps->getVPSId(), vps); };
+  TComVPS* getPrefetchedVPS  (Int vpsId);
+  Void     storePrefetchedSPS(TComSPS *sps)  { m_spsBuffer.storePS( sps->getSPSId(), sps); };
+  TComSPS* getPrefetchedSPS  (Int spsId);
+  Void     storePrefetchedPPS(TComPPS *pps)  { m_ppsBuffer.storePS( pps->getPPSId(), pps); };
+  TComPPS* getPrefetchedPPS  (Int ppsId);
+#if !REMOVE_APS
+  Void     storePrefetchedAPS(TComAPS *aps)  { m_apsBuffer.storePS( aps->getAPSID(), aps); };
+  TComAPS* getPrefetchedAPS  (Int apsId);
+#endif
+  Void     applyPrefetchedPS();
+
+private:
+  ParameterSetMap<TComVPS> m_vpsBuffer;
+  ParameterSetMap<TComSPS> m_spsBuffer; 
+  ParameterSetMap<TComPPS> m_ppsBuffer;
+#if !REMOVE_APS
+  ParameterSetMap<TComAPS> m_apsBuffer;
+#endif
+};
+
+
+//! \}
+
+#endif
+
Index: /trunk/source/Lib/TLibDecoder/TDecTop.cpp
===================================================================
--- /trunk/source/Lib/TLibDecoder/TDecTop.cpp	(revision 2)
+++ /trunk/source/Lib/TLibDecoder/TDecTop.cpp	(revision 2)
@@ -0,0 +1,1104 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TDecTop.cpp
+    \brief    decoder class
+*/
+
+#include "NALread.h"
+#include "TDecTop.h"
+
+#if SVC_EXTENSION
+ParameterSetManagerDecoder TDecTop::m_parameterSetManagerDecoder;  // storage for parameter sets 
+UInt  TDecTop::m_prevPOC = MAX_UINT;
+UInt  TDecTop::m_uiPrevLayerId = MAX_UINT;
+Bool  TDecTop::m_bFirstSliceInSequence = true;
+#endif
+
+//! \ingroup TLibDecoder
+//! \{
+
+TDecTop::TDecTop()
+: m_SEIs(0)
+{
+  m_pcPic = 0;
+  m_iGopSize      = 0;
+  m_bGopSizeSet   = false;
+  m_iMaxRefPicNum = 0;
+#if ENC_DEC_TRACE
+  g_hTrace = fopen( "TraceDec.txt", "wb" );
+  g_bJustDoIt = g_bEncDecTraceDisable;
+  g_nSymbolCounter = 0;
+#endif
+  m_bRefreshPending = 0;
+  m_pocCRA = 0;
+  m_prevRAPisBLA = false;
+  m_pocRandomAccess = MAX_INT;          
+#if !SVC_EXTENSION
+  m_prevPOC                = MAX_INT;
+#endif
+  m_bFirstSliceInPicture    = true;
+#if !SVC_EXTENSION
+  m_bFirstSliceInSequence   = true;
+#endif
+#if SVC_EXTENSION 
+  m_layerId = 0;
+#if AVC_BASE
+  m_pBLReconFile = NULL;
+#endif
+#endif
+#if REF_IDX_FRAMEWORK
+  memset(m_cIlpPic, 0, sizeof(m_cIlpPic));
+#endif
+
+}
+
+TDecTop::~TDecTop()
+{
+#if ENC_DEC_TRACE
+  fclose( g_hTrace );
+#endif
+}
+
+Void TDecTop::create()
+{
+#if SVC_EXTENSION
+  m_cGopDecoder.create( m_layerId );
+#else
+  m_cGopDecoder.create();
+#endif
+  m_apcSlicePilot = new TComSlice;
+  m_uiSliceIdx = 0;
+}
+
+Void TDecTop::destroy()
+{
+  m_cGopDecoder.destroy();
+  
+  delete m_apcSlicePilot;
+  m_apcSlicePilot = NULL;
+  
+  m_cSliceDecoder.destroy();
+#if REF_IDX_FRAMEWORK
+  for(Int i=0; i<MAX_NUM_REF; i++)
+  {
+    if(m_cIlpPic[i])
+    {
+      //m_cIlpPic[i]->setPicYuvRec(NULL);
+      m_cIlpPic[i]->destroy();
+      delete m_cIlpPic[i];
+      m_cIlpPic[i] = NULL;
+    }
+  }    
+#endif
+}
+
+Void TDecTop::init()
+{
+#if !SVC_EXTENSION
+  // initialize ROM
+  initROM();
+#endif
+#if SVC_EXTENSION
+#if REMOVE_ALF
+  m_cGopDecoder.init( m_ppcTDecTop, &m_cEntropyDecoder, &m_cSbacDecoder, &m_cBinCABAC, &m_cCavlcDecoder, &m_cSliceDecoder, &m_cLoopFilter, &m_cSAO);
+#else
+  m_cGopDecoder.init( m_ppcTDecTop, &m_cEntropyDecoder, &m_cSbacDecoder, &m_cBinCABAC, &m_cCavlcDecoder, &m_cSliceDecoder, &m_cLoopFilter, &m_cAdaptiveLoopFilter, &m_cSAO);
+#endif
+  m_cSliceDecoder.init( m_ppcTDecTop, &m_cEntropyDecoder, &m_cCuDecoder );
+#else
+#if REMOVE_ALF
+  m_cGopDecoder.init( &m_cEntropyDecoder, &m_cSbacDecoder, &m_cBinCABAC, &m_cCavlcDecoder, &m_cSliceDecoder, &m_cLoopFilter, &m_cSAO);
+#else
+  m_cGopDecoder.init( &m_cEntropyDecoder, &m_cSbacDecoder, &m_cBinCABAC, &m_cCavlcDecoder, &m_cSliceDecoder, &m_cLoopFilter, &m_cAdaptiveLoopFilter, &m_cSAO);
+#endif
+  m_cSliceDecoder.init( &m_cEntropyDecoder, &m_cCuDecoder );
+#endif
+  m_cEntropyDecoder.init(&m_cPrediction);
+}
+
+#if REF_IDX_FRAMEWORK
+Void TDecTop::xInitILRP(TComSPS *pcSPS)
+{
+  if(m_layerId>0)
+  {
+    if (m_cIlpPic[0] == NULL)
+    {
+      for (Int j=0; j<1/*MAX_NUM_REF*/; j++)
+      {
+        m_cIlpPic[j] = new  TComPic;
+        //m_cIlpPic[j]->createWithOutYuv(m_iSourceWidth, m_iSourceHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, &m_cSPS, true);
+        m_cIlpPic[j]->create(pcSPS->getPicWidthInLumaSamples(), pcSPS->getPicHeightInLumaSamples(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, pcSPS, true);
+        for (Int i=0; i<m_cIlpPic[j]->getPicSym()->getNumberOfCUsInFrame(); i++)
+        {
+            m_cIlpPic[j]->getPicSym()->getCU(i)->initCU(m_cIlpPic[j], i);
+        }
+      }
+    }
+  }
+}
+
+Void TDecTop::setILRPic(TComPic *pcPic)
+{
+  if(m_cIlpPic[0])
+  {
+    //m_cIlpPic[0]->setPicYuvRec(pcPic->getFullPelBaseRec());
+    m_cIlpPic[0]->copyUpsampledPictureYuv(pcPic->getFullPelBaseRec(), m_cIlpPic[0]->getPicYuvRec());
+    m_cIlpPic[0]->getSlice(0)->setPOC(pcPic->getPOC());
+    m_cIlpPic[0]->getPicYuvRec()->setBorderExtension(false);
+    m_cIlpPic[0]->getPicYuvRec()->extendPicBorder();
+  }
+}
+#endif
+
+Void TDecTop::deletePicBuffer ( )
+{
+  TComList<TComPic*>::iterator  iterPic   = m_cListPic.begin();
+  Int iSize = Int( m_cListPic.size() );
+  
+  for (Int i = 0; i < iSize; i++ )
+  {
+    TComPic* pcPic = *(iterPic++);
+#if SVC_EXTENSION
+    if( pcPic )
+    {
+      pcPic->destroy();
+
+      delete pcPic;
+      pcPic = NULL;
+    }
+#else
+    pcPic->destroy();
+    
+    delete pcPic;
+    pcPic = NULL;
+#endif
+  }
+  
+#if !REMOVE_ALF
+  // destroy ALF temporary buffers
+  m_cAdaptiveLoopFilter.destroy();
+#endif
+  
+  m_cSAO.destroy();
+  
+  m_cLoopFilter.        destroy();
+  
+#if !SVC_EXTENSION
+  // destroy ROM
+  destroyROM();
+#endif
+}
+
+Void TDecTop::xUpdateGopSize (TComSlice* pcSlice)
+{
+  if ( !pcSlice->isIntra() && !m_bGopSizeSet)
+  {
+    m_iGopSize    = pcSlice->getPOC();
+    m_bGopSizeSet = true;
+    
+    m_cGopDecoder.setGopSize(m_iGopSize);
+  }
+}
+
+Void TDecTop::xGetNewPicBuffer ( TComSlice* pcSlice, TComPic*& rpcPic )
+{
+  xUpdateGopSize(pcSlice);
+  
+  m_iMaxRefPicNum = pcSlice->getSPS()->getMaxDecPicBuffering(pcSlice->getTLayer())+pcSlice->getSPS()->getNumReorderPics(pcSlice->getTLayer()) + 1; // +1 to have space for the picture currently being decoded
+  if (m_cListPic.size() < (UInt)m_iMaxRefPicNum)
+  {
+    rpcPic = new TComPic();
+    
+#if SVC_EXTENSION //Temporal solution, should be modified
+    if(m_layerId > 0)
+    {
+      TDecTop *pcTDecTopBase = (TDecTop *)getLayerDec( m_layerId-1 );
+      //TComPic*                      pcPic = *(pcTDecTopBase->getListPic()->begin()); 
+      TComPicYuv* pcPicYuvRecBase = (*(pcTDecTopBase->getListPic()->begin()))->getPicYuvRec(); 
+      if(pcPicYuvRecBase->getWidth() != pcSlice->getSPS()->getPicWidthInLumaSamples() || pcPicYuvRecBase->getHeight() != pcSlice->getSPS()->getPicHeightInLumaSamples() )
+      {
+        rpcPic->setSpatialEnhLayerFlag( true );
+      }
+    }
+#endif
+    
+#if SVC_UPSAMPLING
+    rpcPic->create ( pcSlice->getSPS()->getPicWidthInLumaSamples(), pcSlice->getSPS()->getPicHeightInLumaSamples(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, pcSlice->getSPS(), true);
+#else
+    rpcPic->create ( pcSlice->getSPS()->getPicWidthInLumaSamples(), pcSlice->getSPS()->getPicHeightInLumaSamples(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, true);
+#endif
+
+#if REMOVE_APS
+    rpcPic->getPicSym()->allocSaoParam(&m_cSAO);
+#endif
+    m_cListPic.pushBack( rpcPic );
+    
+    return;
+  }
+  
+  Bool bBufferIsAvailable = false;
+  TComList<TComPic*>::iterator  iterPic   = m_cListPic.begin();
+  while (iterPic != m_cListPic.end())
+  {
+    rpcPic = *(iterPic++);
+    if ( rpcPic->getReconMark() == false && rpcPic->getOutputMark() == false)
+    {
+      rpcPic->setOutputMark(false);
+      bBufferIsAvailable = true;
+      break;
+    }
+
+    if ( rpcPic->getSlice( 0 )->isReferenced() == false  && rpcPic->getOutputMark() == false)
+    {
+#if !SVC_EXTENSION
+      rpcPic->setOutputMark(false);
+#endif
+      rpcPic->setReconMark( false );
+      rpcPic->getPicYuvRec()->setBorderExtension( false );
+      bBufferIsAvailable = true;
+      break;
+    }
+  }
+  
+  if ( !bBufferIsAvailable )
+  {
+    //There is no room for this picture, either because of faulty encoder or dropped NAL. Extend the buffer.
+    m_iMaxRefPicNum++;
+    rpcPic = new TComPic();
+    m_cListPic.pushBack( rpcPic );
+  }
+  rpcPic->destroy();
+
+#if SVC_UPSAMPLING
+  rpcPic->create ( pcSlice->getSPS()->getPicWidthInLumaSamples(), pcSlice->getSPS()->getPicHeightInLumaSamples(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, pcSlice->getSPS(), true);
+#else
+  rpcPic->create ( pcSlice->getSPS()->getPicWidthInLumaSamples(), pcSlice->getSPS()->getPicHeightInLumaSamples(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, true);
+#endif
+#if REMOVE_APS
+  rpcPic->getPicSym()->allocSaoParam(&m_cSAO);
+#endif
+}
+
+Void TDecTop::executeDeblockAndAlf(UInt& ruiPOC, TComList<TComPic*>*& rpcListPic, Int& iSkipFrame, Int& iPOCLastDisplay)
+{
+  if (!m_pcPic)
+  {
+    /* nothing to deblock */
+    return;
+  }
+  
+  TComPic*&   pcPic         = m_pcPic;
+
+  // Execute Deblock and ALF only + Cleanup
+
+  m_cGopDecoder.filterPicture(pcPic);
+
+  TComSlice::sortPicList( m_cListPic ); // sorting for application output
+  ruiPOC              = pcPic->getSlice(m_uiSliceIdx-1)->getPOC();
+  rpcListPic          = &m_cListPic;  
+  m_cCuDecoder.destroy();        
+  m_bFirstSliceInPicture  = true;
+
+  return;
+}
+
+Void TDecTop::xCreateLostPicture(Int iLostPoc) 
+{
+  printf("\ninserting lost poc : %d\n",iLostPoc);
+  TComSlice cFillSlice;
+  cFillSlice.setSPS( m_parameterSetManagerDecoder.getFirstSPS() );
+  cFillSlice.setPPS( m_parameterSetManagerDecoder.getFirstPPS() );
+  cFillSlice.initSlice();
+  TComPic *cFillPic;
+  xGetNewPicBuffer(&cFillSlice,cFillPic);
+  cFillPic->getSlice(0)->setSPS( m_parameterSetManagerDecoder.getFirstSPS() );
+  cFillPic->getSlice(0)->setPPS( m_parameterSetManagerDecoder.getFirstPPS() );
+  cFillPic->getSlice(0)->initSlice();
+  
+  TComList<TComPic*>::iterator iterPic = m_cListPic.begin();
+  Int closestPoc = 1000000;
+  while ( iterPic != m_cListPic.end())
+  {
+    TComPic * rpcPic = *(iterPic++);
+    if(abs(rpcPic->getPicSym()->getSlice(0)->getPOC() -iLostPoc)<closestPoc&&abs(rpcPic->getPicSym()->getSlice(0)->getPOC() -iLostPoc)!=0&&rpcPic->getPicSym()->getSlice(0)->getPOC()!=m_apcSlicePilot->getPOC())
+    {
+      closestPoc=abs(rpcPic->getPicSym()->getSlice(0)->getPOC() -iLostPoc);
+    }
+  }
+  iterPic = m_cListPic.begin();
+  while ( iterPic != m_cListPic.end())
+  {
+    TComPic *rpcPic = *(iterPic++);
+    if(abs(rpcPic->getPicSym()->getSlice(0)->getPOC() -iLostPoc)==closestPoc&&rpcPic->getPicSym()->getSlice(0)->getPOC()!=m_apcSlicePilot->getPOC())
+    {
+      printf("copying picture %d to %d (%d)\n",rpcPic->getPicSym()->getSlice(0)->getPOC() ,iLostPoc,m_apcSlicePilot->getPOC());
+      rpcPic->getPicYuvRec()->copyToPic(cFillPic->getPicYuvRec());
+      break;
+    }
+  }
+  cFillPic->setCurrSliceIdx(0);
+  for(Int i=0; i<cFillPic->getNumCUsInFrame(); i++) 
+  {
+    cFillPic->getCU(i)->initCU(cFillPic,i);
+  }
+  cFillPic->getSlice(0)->setReferenced(true);
+  cFillPic->getSlice(0)->setPOC(iLostPoc);
+  cFillPic->setReconMark(true);
+  cFillPic->setOutputMark(true);
+  if(m_pocRandomAccess == MAX_INT)
+  {
+    m_pocRandomAccess = iLostPoc;
+  }
+}
+
+
+Void TDecTop::xActivateParameterSets()
+{
+  m_parameterSetManagerDecoder.applyPrefetchedPS();
+
+  TComPPS *pps = m_parameterSetManagerDecoder.getPPS(m_apcSlicePilot->getPPSId());
+  assert (pps != 0);
+
+  TComSPS *sps = m_parameterSetManagerDecoder.getSPS(pps->getSPSId());
+  assert (sps != 0);
+
+  m_apcSlicePilot->setPPS(pps);
+  m_apcSlicePilot->setSPS(sps);
+  pps->setSPS(sps);
+#if TILES_WPP_ENTROPYSLICES_FLAGS
+  pps->setNumSubstreams(pps->getEntropyCodingSyncEnabledFlag() ? ((sps->getPicHeightInLumaSamples() + sps->getMaxCUHeight() - 1) / sps->getMaxCUHeight()) * (pps->getNumColumnsMinus1() + 1) : 1);
+#else
+  pps->setNumSubstreams(pps->getTilesOrEntropyCodingSyncIdc() == 2 ? ((sps->getPicHeightInLumaSamples() + sps->getMaxCUHeight() - 1) / sps->getMaxCUHeight()) * (pps->getNumColumnsMinus1() + 1) : 1);
+#endif
+#if !REMOVE_APS
+#if REMOVE_ALF
+  if(sps->getUseSAO())
+#else
+  if(sps->getUseSAO() || sps->getUseALF())
+#endif
+  {
+    m_apcSlicePilot->setAPS( m_parameterSetManagerDecoder.getAPS(m_apcSlicePilot->getAPSId())  );
+  }
+#endif
+  pps->setMinCuDQPSize( sps->getMaxCUWidth() >> ( pps->getMaxCuDQPDepth()) );
+
+  for (Int i = 0; i < sps->getMaxCUDepth() - g_uiAddCUDepth; i++)
+  {
+    sps->setAMPAcc( i, sps->getUseAMP() );
+  }
+
+  for (Int i = sps->getMaxCUDepth() - g_uiAddCUDepth; i < sps->getMaxCUDepth(); i++)
+  {
+    sps->setAMPAcc( i, 0 );
+  }
+
+  m_cSAO.destroy();
+  m_cSAO.create( sps->getPicWidthInLumaSamples(), sps->getPicHeightInLumaSamples(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+  m_cLoopFilter.        create( g_uiMaxCUDepth );
+}
+
+#if SVC_EXTENSION
+Bool TDecTop::xDecodeSlice(InputNALUnit &nalu, Int &iSkipFrame, Int iPOCLastDisplay, UInt& curLayerId, Bool& bNewPOC )
+#else
+Bool TDecTop::xDecodeSlice(InputNALUnit &nalu, Int &iSkipFrame, Int iPOCLastDisplay )
+#endif
+{
+  TComPic*&   pcPic         = m_pcPic;
+  m_apcSlicePilot->initSlice();
+
+  if (m_bFirstSliceInPicture)
+  {
+    m_uiSliceIdx     = 0;
+  }
+  m_apcSlicePilot->setSliceIdx(m_uiSliceIdx);
+  if (!m_bFirstSliceInPicture)
+  {
+    m_apcSlicePilot->copySliceInfo( pcPic->getPicSym()->getSlice(m_uiSliceIdx-1) );
+  }
+
+  m_apcSlicePilot->setNalUnitType(nalu.m_nalUnitType);
+#if TEMPORAL_LAYER_NON_REFERENCE
+  if((m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_TRAIL_N) ||
+     (m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_N) ||
+     (m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_STSA_N))
+  {
+    m_apcSlicePilot->setTemporalLayerNonReferenceFlag(true);
+  }
+#endif
+#if REMOVE_NAL_REF_FLAG
+  m_apcSlicePilot->setReferenced(true); // Putting this as true ensures that picture is referenced the first time it is in an RPS
+#else
+  m_apcSlicePilot->setReferenced(nalu.m_nalRefFlag);
+#endif
+  m_apcSlicePilot->setTLayerInfo(nalu.m_temporalId);
+  m_cEntropyDecoder.decodeSliceHeader (m_apcSlicePilot, &m_parameterSetManagerDecoder);
+#if !BYTE_ALIGNMENT
+  // byte align
+  {
+    Int numBitsForByteAlignment = nalu.m_Bitstream->getNumBitsUntilByteAligned();
+    if ( numBitsForByteAlignment > 0 )
+    {
+      UInt bitsForByteAlignment;
+      nalu.m_Bitstream->read( numBitsForByteAlignment, bitsForByteAlignment );
+      assert( bitsForByteAlignment == ( ( 1 << numBitsForByteAlignment ) - 1 ) );
+    }
+  }
+#endif
+  // exit when a new picture is found
+#if SVC_EXTENSION
+  bNewPOC = (m_apcSlicePilot->getPOC()!= m_prevPOC);
+  if (m_apcSlicePilot->isNextSlice() && (bNewPOC || m_layerId!=m_uiPrevLayerId)
+    && !m_bFirstSliceInSequence )
+  {
+    m_prevPOC = m_apcSlicePilot->getPOC();
+    curLayerId = m_uiPrevLayerId; 
+    m_uiPrevLayerId = m_layerId;
+    return true;
+  }
+#else
+  if (m_apcSlicePilot->isNextSlice() && m_apcSlicePilot->getPOC()!=m_prevPOC && !m_bFirstSliceInSequence)
+  {
+    if (m_prevPOC >= m_pocRandomAccess)
+    {
+      m_prevPOC = m_apcSlicePilot->getPOC();
+      return true;
+    }
+    m_prevPOC = m_apcSlicePilot->getPOC();
+  }
+#endif
+  // actual decoding starts here
+  xActivateParameterSets();
+
+  if (m_apcSlicePilot->isNextSlice()) 
+  {
+    m_prevPOC = m_apcSlicePilot->getPOC();
+#if SVC_EXTENSION
+    curLayerId = m_layerId;
+    m_uiPrevLayerId = m_layerId;
+#endif
+  }
+  m_bFirstSliceInSequence = false;
+  if (m_apcSlicePilot->isNextSlice())
+  {
+    // Skip pictures due to random access
+    if (isRandomAccessSkipPicture(iSkipFrame, iPOCLastDisplay))
+    {
+      return false;
+    }
+    // Skip TFD pictures associated with BLA/BLANT pictures
+    if (isSkipPictureForBLA(iPOCLastDisplay))
+    {
+      return false;
+    }
+  }
+  //detect lost reference picture and insert copy of earlier frame.
+  Int lostPoc;
+  while((lostPoc=m_apcSlicePilot->checkThatAllRefPicsAreAvailable(m_cListPic, m_apcSlicePilot->getRPS(), true, m_pocRandomAccess)) > 0)
+  {
+    xCreateLostPicture(lostPoc-1);
+  }
+  if (m_bFirstSliceInPicture)
+  {
+
+#if AVC_BASE
+  if( m_layerId == 1 )
+  {
+    TComPic* pBLPic = (*m_ppcTDecTop[0]->getListPic()->begin());
+    FILE* pFile = m_ppcTDecTop[0]->getBLReconFile();
+    UInt uiWidth = pBLPic->getPicYuvRec()->getWidth();
+    UInt uiHeight = pBLPic->getPicYuvRec()->getHeight();
+        
+    if( pFile )
+    {
+      fseek( pFile, m_apcSlicePilot->getPOC() * uiWidth * uiHeight * 3 / 2, SEEK_SET );
+
+      Pel* pPel = pBLPic->getPicYuvRec()->getLumaAddr();
+      UInt uiStride = pBLPic->getPicYuvRec()->getStride();
+      for( Int i = 0; i < uiHeight; i++ )
+      {
+        for( Int j = 0; j < uiWidth; j++ )
+        {
+          pPel[j] = fgetc( pFile );
+        }
+        pPel += uiStride;
+      }
+
+      pPel = pBLPic->getPicYuvRec()->getCbAddr();
+      uiStride = pBLPic->getPicYuvRec()->getCStride();
+      for( Int i = 0; i < uiHeight/2; i++ )
+      {
+        for( Int j = 0; j < uiWidth/2; j++ )
+        {
+          pPel[j] = fgetc( pFile );
+        }
+        pPel += uiStride;
+      }
+
+      pPel = pBLPic->getPicYuvRec()->getCrAddr();
+      uiStride = pBLPic->getPicYuvRec()->getCStride();
+      for( Int i = 0; i < uiHeight/2; i++ )
+      {
+        for( Int j = 0; j < uiWidth/2; j++ )
+        {
+          pPel[j] = fgetc( pFile );
+        }
+        pPel += uiStride;
+      }
+    }
+  }
+#endif
+
+    // Buffer initialize for prediction.
+    m_cPrediction.initTempBuff();
+    m_apcSlicePilot->applyReferencePictureSet(m_cListPic, m_apcSlicePilot->getRPS());
+    //  Get a new picture buffer
+    xGetNewPicBuffer (m_apcSlicePilot, pcPic);
+
+    /* transfer any SEI messages that have been received to the picture */
+    pcPic->setSEIs(m_SEIs);
+    m_SEIs = NULL;
+
+    // Recursive structure
+    m_cCuDecoder.create ( g_uiMaxCUDepth, g_uiMaxCUWidth, g_uiMaxCUHeight );
+#if SVC_EXTENSION
+    m_cCuDecoder.init   ( m_ppcTDecTop,&m_cEntropyDecoder, &m_cTrQuant, &m_cPrediction, curLayerId );
+#else
+    m_cCuDecoder.init   ( &m_cEntropyDecoder, &m_cTrQuant, &m_cPrediction );
+#endif
+    m_cTrQuant.init     ( g_uiMaxCUWidth, g_uiMaxCUHeight, m_apcSlicePilot->getSPS()->getMaxTrSize());
+
+    m_cSliceDecoder.create( m_apcSlicePilot, m_apcSlicePilot->getSPS()->getPicWidthInLumaSamples(), m_apcSlicePilot->getSPS()->getPicHeightInLumaSamples(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+  }
+
+  //  Set picture slice pointer
+  TComSlice*  pcSlice = m_apcSlicePilot;
+  Bool bNextSlice     = pcSlice->isNextSlice();
+
+  UInt uiCummulativeTileWidth;
+  UInt uiCummulativeTileHeight;
+  UInt i, j, p;
+
+  //set NumColumnsMins1 and NumRowsMinus1
+  pcPic->getPicSym()->setNumColumnsMinus1( pcSlice->getPPS()->getNumColumnsMinus1() );
+  pcPic->getPicSym()->setNumRowsMinus1( pcSlice->getPPS()->getNumRowsMinus1() );
+
+  //create the TComTileArray
+  pcPic->getPicSym()->xCreateTComTileArray();
+
+  if( pcSlice->getPPS()->getUniformSpacingFlag() )
+  {
+    //set the width for each tile
+    for(j=0; j < pcPic->getPicSym()->getNumRowsMinus1()+1; j++)
+    {
+      for(p=0; p < pcPic->getPicSym()->getNumColumnsMinus1()+1; p++)
+      {
+        pcPic->getPicSym()->getTComTile( j * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + p )->
+          setTileWidth( (p+1)*pcPic->getPicSym()->getFrameWidthInCU()/(pcPic->getPicSym()->getNumColumnsMinus1()+1) 
+          - (p*pcPic->getPicSym()->getFrameWidthInCU())/(pcPic->getPicSym()->getNumColumnsMinus1()+1) );
+      }
+    }
+
+    //set the height for each tile
+    for(j=0; j < pcPic->getPicSym()->getNumColumnsMinus1()+1; j++)
+    {
+      for(p=0; p < pcPic->getPicSym()->getNumRowsMinus1()+1; p++)
+      {
+        pcPic->getPicSym()->getTComTile( p * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + j )->
+          setTileHeight( (p+1)*pcPic->getPicSym()->getFrameHeightInCU()/(pcPic->getPicSym()->getNumRowsMinus1()+1) 
+          - (p*pcPic->getPicSym()->getFrameHeightInCU())/(pcPic->getPicSym()->getNumRowsMinus1()+1) );   
+      }
+    }
+  }
+  else
+  {
+    //set the width for each tile
+    for(j=0; j < pcSlice->getPPS()->getNumRowsMinus1()+1; j++)
+    {
+      uiCummulativeTileWidth = 0;
+      for(i=0; i < pcSlice->getPPS()->getNumColumnsMinus1(); i++)
+      {
+        pcPic->getPicSym()->getTComTile(j * (pcSlice->getPPS()->getNumColumnsMinus1()+1) + i)->setTileWidth( pcSlice->getPPS()->getColumnWidth(i) );
+        uiCummulativeTileWidth += pcSlice->getPPS()->getColumnWidth(i);
+      }
+      pcPic->getPicSym()->getTComTile(j * (pcSlice->getPPS()->getNumColumnsMinus1()+1) + i)->setTileWidth( pcPic->getPicSym()->getFrameWidthInCU()-uiCummulativeTileWidth );
+    }
+
+    //set the height for each tile
+    for(j=0; j < pcSlice->getPPS()->getNumColumnsMinus1()+1; j++)
+    {
+      uiCummulativeTileHeight = 0;
+      for(i=0; i < pcSlice->getPPS()->getNumRowsMinus1(); i++)
+      { 
+        pcPic->getPicSym()->getTComTile(i * (pcSlice->getPPS()->getNumColumnsMinus1()+1) + j)->setTileHeight( pcSlice->getPPS()->getRowHeight(i) );
+        uiCummulativeTileHeight += pcSlice->getPPS()->getRowHeight(i);
+      }
+      pcPic->getPicSym()->getTComTile(i * (pcSlice->getPPS()->getNumColumnsMinus1()+1) + j)->setTileHeight( pcPic->getPicSym()->getFrameHeightInCU()-uiCummulativeTileHeight );
+    }
+  }
+
+  pcPic->getPicSym()->xInitTiles();
+
+  //generate the Coding Order Map and Inverse Coding Order Map
+  UInt uiEncCUAddr;
+  for(i=0, uiEncCUAddr=0; i<pcPic->getPicSym()->getNumberOfCUsInFrame(); i++, uiEncCUAddr = pcPic->getPicSym()->xCalculateNxtCUAddr(uiEncCUAddr))
+  {
+    pcPic->getPicSym()->setCUOrderMap(i, uiEncCUAddr);
+    pcPic->getPicSym()->setInverseCUOrderMap(uiEncCUAddr, i);
+  }
+  pcPic->getPicSym()->setCUOrderMap(pcPic->getPicSym()->getNumberOfCUsInFrame(), pcPic->getPicSym()->getNumberOfCUsInFrame());
+  pcPic->getPicSym()->setInverseCUOrderMap(pcPic->getPicSym()->getNumberOfCUsInFrame(), pcPic->getPicSym()->getNumberOfCUsInFrame());
+
+  //convert the start and end CU addresses of the slice and dependent slice into encoding order
+  pcSlice->setDependentSliceCurStartCUAddr( pcPic->getPicSym()->getPicSCUEncOrder(pcSlice->getDependentSliceCurStartCUAddr()) );
+  pcSlice->setDependentSliceCurEndCUAddr( pcPic->getPicSym()->getPicSCUEncOrder(pcSlice->getDependentSliceCurEndCUAddr()) );
+  if(pcSlice->isNextSlice())
+  {
+    pcSlice->setSliceCurStartCUAddr(pcPic->getPicSym()->getPicSCUEncOrder(pcSlice->getSliceCurStartCUAddr()));
+    pcSlice->setSliceCurEndCUAddr(pcPic->getPicSym()->getPicSCUEncOrder(pcSlice->getSliceCurEndCUAddr()));
+  }
+
+  if (m_bFirstSliceInPicture) 
+  {
+    if(pcPic->getNumAllocatedSlice() != 1)
+    {
+      pcPic->clearSliceBuffer();
+    }
+  }
+  else
+  {
+    pcPic->allocateNewSlice();
+  }
+  assert(pcPic->getNumAllocatedSlice() == (m_uiSliceIdx + 1));
+  m_apcSlicePilot = pcPic->getPicSym()->getSlice(m_uiSliceIdx); 
+  pcPic->getPicSym()->setSlice(pcSlice, m_uiSliceIdx);
+
+  pcPic->setTLayer(nalu.m_temporalId);
+
+#if SVC_EXTENSION
+  pcPic->setLayerId(nalu.m_layerId);
+  pcSlice->setLayerId(nalu.m_layerId);
+#endif
+
+  if (bNextSlice)
+  {
+    pcSlice->checkCRA(pcSlice->getRPS(), m_pocCRA, m_prevRAPisBLA, m_cListPic);
+#if !REF_IDX_FRAMEWORK
+    // Set reference list
+    pcSlice->setRefPicList( m_cListPic );
+#endif
+
+#if SVC_EXTENSION   
+    if(m_layerId > 0)
+    {
+#if AVC_BASE
+      pcSlice->setBaseColPic ( *m_ppcTDecTop[0]->getListPic()->begin() );
+#else
+      TDecTop *pcTDecTop = (TDecTop *)getLayerDec( m_layerId-1 );
+      TComList<TComPic*> *cListPic = pcTDecTop->getListPic();
+      pcSlice->setBaseColPic ( *cListPic, m_layerId );
+#endif
+#if SVC_UPSAMPLING
+      if ( pcPic->isSpatialEnhLayer())
+      {    
+        m_cPrediction.upsampleBasePic( pcPic->getFullPelBaseRec(), pcSlice->getBaseColPic()->getPicYuvRec(), pcPic->getPicYuvRec() );
+      }
+      else
+      {
+        pcPic->setFullPelBaseRec( pcSlice->getBaseColPic()->getPicYuvRec() );
+      }
+      pcSlice->setFullPelBaseRec ( pcPic->getFullPelBaseRec() );
+#endif
+    }
+#endif 
+
+#if REF_IDX_FRAMEWORK
+    // Set reference list
+    pcSlice->setRefPicList( m_cListPic );
+    if(m_layerId > 0)
+    {
+      setILRPic(pcPic);
+      pcSlice->addRefPicList ( m_cIlpPic, 
+                               1, 
+                               ((pcSlice->getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA) && 
+                                (pcSlice->getNalUnitType() <= NAL_UNIT_CODED_SLICE_CRA)) ? 0: -1);
+    }
+#endif
+
+    // For generalized B
+    // note: maybe not existed case (always L0 is copied to L1 if L1 is empty)
+    if (pcSlice->isInterB() && pcSlice->getNumRefIdx(REF_PIC_LIST_1) == 0)
+    {
+      Int iNumRefIdx = pcSlice->getNumRefIdx(REF_PIC_LIST_0);
+      pcSlice->setNumRefIdx        ( REF_PIC_LIST_1, iNumRefIdx );
+
+      for (Int iRefIdx = 0; iRefIdx < iNumRefIdx; iRefIdx++)
+      {
+        pcSlice->setRefPic(pcSlice->getRefPic(REF_PIC_LIST_0, iRefIdx), REF_PIC_LIST_1, iRefIdx);
+      }
+    }
+    if (pcSlice->isInterB())
+    {
+      Bool bLowDelay = true;
+      Int  iCurrPOC  = pcSlice->getPOC();
+      Int iRefIdx = 0;
+
+      for (iRefIdx = 0; iRefIdx < pcSlice->getNumRefIdx(REF_PIC_LIST_0) && bLowDelay; iRefIdx++)
+      {
+        if ( pcSlice->getRefPic(REF_PIC_LIST_0, iRefIdx)->getPOC() > iCurrPOC )
+        {
+          bLowDelay = false;
+        }
+      }
+      for (iRefIdx = 0; iRefIdx < pcSlice->getNumRefIdx(REF_PIC_LIST_1) && bLowDelay; iRefIdx++)
+      {
+        if ( pcSlice->getRefPic(REF_PIC_LIST_1, iRefIdx)->getPOC() > iCurrPOC )
+        {
+          bLowDelay = false;
+        }
+      }
+
+      pcSlice->setCheckLDC(bLowDelay);            
+    }
+
+    //---------------
+    pcSlice->setRefPOCList();
+    pcSlice->setNoBackPredFlag( false );
+    if ( pcSlice->getSliceType() == B_SLICE )
+    {
+      if ( pcSlice->getNumRefIdx(RefPicList( 0 ) ) == pcSlice->getNumRefIdx(RefPicList( 1 ) ) )
+      {
+        pcSlice->setNoBackPredFlag( true );
+        for ( i=0; i < pcSlice->getNumRefIdx(RefPicList( 1 ) ); i++ )
+        {
+          if ( pcSlice->getRefPOC(RefPicList(1), i) != pcSlice->getRefPOC(RefPicList(0), i) ) 
+          {
+            pcSlice->setNoBackPredFlag( false );
+            break;
+          }
+        }
+      }
+    }
+  }
+
+  pcPic->setCurrSliceIdx(m_uiSliceIdx);
+  if(pcSlice->getSPS()->getScalingListFlag())
+  {
+    pcSlice->setScalingList ( pcSlice->getSPS()->getScalingList()  );
+    if(pcSlice->getPPS()->getScalingListPresentFlag())
+    {
+      pcSlice->setScalingList ( pcSlice->getPPS()->getScalingList()  );
+    }
+#if TS_FLAT_QUANTIZATION_MATRIX
+    pcSlice->getScalingList()->setUseTransformSkip(pcSlice->getPPS()->getUseTransformSkip());
+#endif
+    if(!pcSlice->getPPS()->getScalingListPresentFlag() && !pcSlice->getSPS()->getScalingListPresentFlag())
+    {
+      pcSlice->setDefaultScalingList();
+    }
+    m_cTrQuant.setScalingListDec(pcSlice->getScalingList());
+    m_cTrQuant.setUseScalingList(true);
+  }
+  else
+  {
+    m_cTrQuant.setFlatScalingList();
+    m_cTrQuant.setUseScalingList(false);
+  }
+
+  //  Decode a picture
+  m_cGopDecoder.decompressSlice(nalu.m_Bitstream, pcPic);
+
+  m_bFirstSliceInPicture = false;
+  m_uiSliceIdx++;
+
+  return false;
+}
+
+Void TDecTop::xDecodeVPS()
+{
+  TComVPS* vps = new TComVPS();
+  
+  m_cEntropyDecoder.decodeVPS( vps );
+  m_parameterSetManagerDecoder.storePrefetchedVPS(vps);  
+}
+
+Void TDecTop::xDecodeSPS()
+{
+  TComSPS* sps = new TComSPS();
+#if SVC_EXTENSION
+  sps->setLayerId(m_layerId);
+#endif
+  m_cEntropyDecoder.decodeSPS( sps );
+  m_parameterSetManagerDecoder.storePrefetchedSPS(sps);
+#if !REMOVE_ALF
+  m_cAdaptiveLoopFilter.create( sps->getPicWidthInLumaSamples(), sps->getPicHeightInLumaSamples(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+#endif
+#if REF_IDX_FRAMEWORK
+  if(m_numLayer>0)
+  {
+    xInitILRP(sps);
+  }
+#endif
+}
+
+Void TDecTop::xDecodePPS()
+{
+  TComPPS* pps = new TComPPS();
+  m_cEntropyDecoder.decodePPS( pps, &m_parameterSetManagerDecoder );
+  m_parameterSetManagerDecoder.storePrefetchedPPS( pps );
+
+#if DEPENDENT_SLICES
+#if TILES_WPP_ENTROPYSLICES_FLAGS
+  if( pps->getDependentSliceEnabledFlag() && (!pps->getEntropySliceEnabledFlag()) )
+#else
+  if( pps->getDependentSliceEnabledFlag() && (!pps->getCabacIndependentFlag()) )
+#endif
+  {
+#if TILES_WPP_ENTROPYSLICES_FLAGS
+    int NumCtx = pps->getEntropyCodingSyncEnabledFlag()?2:1;
+#else
+    int NumCtx = (pps->getTilesOrEntropyCodingSyncIdc() == 2)?2:1;
+#endif
+    m_cSliceDecoder.initCtxMem(NumCtx);
+    for ( UInt st = 0; st < NumCtx; st++ )
+    {
+      TDecSbac* ctx = NULL;
+      ctx = new TDecSbac;
+      ctx->init( &m_cBinCABAC );
+      m_cSliceDecoder.setCtxMem( ctx, st );
+    }
+  }
+#endif
+}
+
+#if !REMOVE_APS
+Void TDecTop::xDecodeAPS()
+{
+  TComAPS  *aps = new TComAPS();
+  allocAPS (aps);
+  decodeAPS(aps);
+  m_parameterSetManagerDecoder.storePrefetchedAPS(aps);
+}
+#endif
+
+Void TDecTop::xDecodeSEI( TComInputBitstream* bs )
+{
+#if RECOVERY_POINT_SEI || BUFFERING_PERIOD_AND_TIMING_SEI
+  if ( m_SEIs == NULL )
+#endif
+  m_SEIs = new SEImessages;
+#if BUFFERING_PERIOD_AND_TIMING_SEI
+  m_SEIs->m_pSPS = m_parameterSetManagerDecoder.getSPS(0);
+#endif
+  m_seiReader.parseSEImessage( bs, *m_SEIs );
+}
+
+#if SVC_EXTENSION
+Bool TDecTop::decode(InputNALUnit& nalu, Int& iSkipFrame, Int& iPOCLastDisplay, UInt& curLayerId, Bool& bNewPOC)
+#else
+Bool TDecTop::decode(InputNALUnit& nalu, Int& iSkipFrame, Int& iPOCLastDisplay)
+#endif
+{
+  // Initialize entropy decoder
+  m_cEntropyDecoder.setEntropyDecoder (&m_cCavlcDecoder);
+  m_cEntropyDecoder.setBitstream      (nalu.m_Bitstream);
+
+  switch (nalu.m_nalUnitType)
+  {
+    case NAL_UNIT_VPS:
+      xDecodeVPS();
+      return false;
+      
+    case NAL_UNIT_SPS:
+      xDecodeSPS();
+#if AVC_BASE
+      {
+        TComPic* pBLPic = (*m_ppcTDecTop[0]->getListPic()->begin());
+        if( nalu.m_layerId == 1 && pBLPic->getPicYuvRec() == NULL )
+        {
+#if SVC_UPSAMPLING
+          pBLPic->create( m_ppcTDecTop[0]->getBLWidth(), m_ppcTDecTop[0]->getBLHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, NULL, true);
+#else
+          pBLPic->create( m_ppcTDecTop[0]->getBLWidth(), m_ppcTDecTop[0]->getBLHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, true);
+#endif
+        }
+      }
+#endif
+      return false;
+
+    case NAL_UNIT_PPS:
+      xDecodePPS();
+      return false;
+#if !REMOVE_APS
+    case NAL_UNIT_APS:
+      xDecodeAPS();
+      return false;
+#endif
+      
+    case NAL_UNIT_SEI:
+      xDecodeSEI( nalu.m_Bitstream );
+      return false;
+
+#if NAL_UNIT_TYPES_J1003_D7
+    case NAL_UNIT_CODED_SLICE_TRAIL_R:
+    case NAL_UNIT_CODED_SLICE_TRAIL_N:
+    case NAL_UNIT_CODED_SLICE_TLA:
+    case NAL_UNIT_CODED_SLICE_TSA_N:
+    case NAL_UNIT_CODED_SLICE_STSA_R:
+    case NAL_UNIT_CODED_SLICE_STSA_N:
+    case NAL_UNIT_CODED_SLICE_BLA:
+    case NAL_UNIT_CODED_SLICE_BLANT:
+    case NAL_UNIT_CODED_SLICE_BLA_N_LP:
+    case NAL_UNIT_CODED_SLICE_IDR:
+    case NAL_UNIT_CODED_SLICE_IDR_N_LP:
+    case NAL_UNIT_CODED_SLICE_CRA:
+    case NAL_UNIT_CODED_SLICE_DLP:
+    case NAL_UNIT_CODED_SLICE_TFD:
+#else
+    case NAL_UNIT_CODED_SLICE:
+    case NAL_UNIT_CODED_SLICE_TFD:
+    case NAL_UNIT_CODED_SLICE_TLA:
+    case NAL_UNIT_CODED_SLICE_CRA:
+    case NAL_UNIT_CODED_SLICE_CRANT:
+    case NAL_UNIT_CODED_SLICE_BLA:
+    case NAL_UNIT_CODED_SLICE_BLANT:
+    case NAL_UNIT_CODED_SLICE_IDR:
+#endif
+#if SVC_EXTENSION
+      return xDecodeSlice(nalu, iSkipFrame, iPOCLastDisplay, curLayerId, bNewPOC);
+#else
+      return xDecodeSlice(nalu, iSkipFrame, iPOCLastDisplay);
+#endif
+      break;
+    default:
+      assert (1);
+  }
+
+  return false;
+}
+
+/** Function for checking if picture should be skipped because of association with a previous BLA picture
+ * \param iPOCLastDisplay POC of last picture displayed
+ * \returns true if the picture should be skipped
+ * This function skips all TFD pictures that follow a BLA picture
+ * in decoding order and precede it in output order.
+ */
+Bool TDecTop::isSkipPictureForBLA(Int& iPOCLastDisplay)
+{
+  if (m_prevRAPisBLA && m_apcSlicePilot->getPOC() < m_pocCRA && m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_TFD)
+  {
+    iPOCLastDisplay++;
+    return true;
+  }
+  return false;
+}
+
+/** Function for checking if picture should be skipped because of random access
+ * \param iSkipFrame skip frame counter
+ * \param iPOCLastDisplay POC of last picture displayed
+ * \returns true if the picture shold be skipped in the random access.
+ * This function checks the skipping of pictures in the case of -s option random access.
+ * All pictures prior to the random access point indicated by the counter iSkipFrame are skipped.
+ * It also checks the type of Nal unit type at the random access point.
+ * If the random access point is CRA/CRANT/BLA/BLANT, TFD pictures with POC less than the POC of the random access point are skipped.
+ * If the random access point is IDR all pictures after the random access point are decoded.
+ * If the random access point is none of the above, a warning is issues, and decoding of pictures with POC 
+ * equal to or greater than the random access point POC is attempted. For non IDR/CRA/BLA random 
+ * access point there is no guarantee that the decoder will not crash.
+ */
+Bool TDecTop::isRandomAccessSkipPicture(Int& iSkipFrame,  Int& iPOCLastDisplay)
+{
+  if (iSkipFrame) 
+  {
+    iSkipFrame--;   // decrement the counter
+    return true;
+  }
+  else if (m_pocRandomAccess == MAX_INT) // start of random access point, m_pocRandomAccess has not been set yet.
+  {
+    if (   m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA
+#if !NAL_UNIT_TYPES_J1003_D7
+        || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRANT
+#endif
+        || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA
+#if SUPPORT_FOR_RAP_N_LP
+        || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP
+#endif
+        || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLANT )
+    {
+      // set the POC random access since we need to skip the reordered pictures in the case of CRA/CRANT/BLA/BLANT.
+      m_pocRandomAccess = m_apcSlicePilot->getPOC();
+    }
+#if SUPPORT_FOR_RAP_N_LP
+    else if ( m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP )
+#else
+    else if (m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR)
+#endif
+    {
+      m_pocRandomAccess = 0; // no need to skip the reordered pictures in IDR, they are decodable.
+    }
+    else 
+    {
+      static bool warningMessage = false;
+      if(!warningMessage)
+      {
+        printf("\nWarning: this is not a valid random access point and the data is discarded until the first CRA picture");
+        warningMessage = true;
+      }
+      return true;
+    }
+  }
+  // skip the reordered pictures, if necessary
+  else if (m_apcSlicePilot->getPOC() < m_pocRandomAccess && m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_TFD)
+  {
+    iPOCLastDisplay++;
+    return true;
+  }
+  // if we reach here, then the picture is not skipped.
+  return false; 
+}
+
+#if !REMOVE_APS
+Void TDecTop::allocAPS (TComAPS* pAPS)
+{
+  // we don't know the SPS before it has been activated. These fields could exist
+  // depending on the corresponding flags in the APS, but SAO/ALF allocation functions will
+  // have to be moved for that
+  pAPS->createSaoParam();
+  m_cSAO.allocSaoParam(pAPS->getSaoParam());
+#if !REMOVE_ALF
+  pAPS->createAlfParam();
+#endif
+}
+#endif
+
+//! \}
Index: /trunk/source/Lib/TLibDecoder/TDecTop.h
===================================================================
--- /trunk/source/Lib/TLibDecoder/TDecTop.h	(revision 2)
+++ /trunk/source/Lib/TLibDecoder/TDecTop.h	(revision 2)
@@ -0,0 +1,203 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TDecTop.h
+    \brief    decoder class (header)
+*/
+
+#ifndef __TDECTOP__
+#define __TDECTOP__
+
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComList.h"
+#include "TLibCommon/TComPicYuv.h"
+#include "TLibCommon/TComPic.h"
+#include "TLibCommon/TComTrQuant.h"
+#include "TLibCommon/SEI.h"
+
+#include "TDecGop.h"
+#include "TDecEntropy.h"
+#include "TDecSbac.h"
+#include "TDecCAVLC.h"
+#include "SEIread.h"
+
+struct InputNALUnit;
+
+//! \ingroup TLibDecoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// decoder class
+class TDecTop
+{
+private:
+  Int                     m_iGopSize;
+  Bool                    m_bGopSizeSet;
+  Int                     m_iMaxRefPicNum;
+  
+  Bool                    m_bRefreshPending;    ///< refresh pending flag
+  Int                     m_pocCRA;            ///< POC number of the latest CRA picture
+  Bool                    m_prevRAPisBLA;      ///< true if the previous RAP (CRA/CRANT/BLA/BLANT/IDR) picture is a BLA/BLANT picture
+  Int                     m_pocRandomAccess;   ///< POC number of the random access point (the first IDR or CRA picture)
+
+  TComList<TComPic*>      m_cListPic;         //  Dynamic buffer
+#if SVC_EXTENSION
+  static ParameterSetManagerDecoder m_parameterSetManagerDecoder;  // storage for parameter sets 
+#else
+  ParameterSetManagerDecoder m_parameterSetManagerDecoder;  // storage for parameter sets 
+#endif
+  TComSlice*              m_apcSlicePilot;
+  
+  SEImessages *m_SEIs; ///< "all" SEI messages.  If not NULL, we own the object.
+
+  // functional classes
+  TComPrediction          m_cPrediction;
+  TComTrQuant             m_cTrQuant;
+  TDecGop                 m_cGopDecoder;
+  TDecSlice               m_cSliceDecoder;
+  TDecCu                  m_cCuDecoder;
+  TDecEntropy             m_cEntropyDecoder;
+  TDecCavlc               m_cCavlcDecoder;
+  TDecSbac                m_cSbacDecoder;
+  TDecBinCABAC            m_cBinCABAC;
+  SEIReader               m_seiReader;
+  TComLoopFilter          m_cLoopFilter;
+#if !REMOVE_ALF
+  TComAdaptiveLoopFilter  m_cAdaptiveLoopFilter;
+#endif
+  TComSampleAdaptiveOffset m_cSAO;
+
+  Bool isSkipPictureForBLA(Int& iPOCLastDisplay);
+  Bool isRandomAccessSkipPicture(Int& iSkipFrame,  Int& iPOCLastDisplay);
+  TComPic*                m_pcPic;
+  UInt                    m_uiSliceIdx;
+#if !SVC_EXTENSION
+  Int                     m_prevPOC;
+#endif
+  Bool                    m_bFirstSliceInPicture;
+#if !SVC_EXTENSION
+  Bool                    m_bFirstSliceInSequence;
+#endif
+
+#if SVC_EXTENSION
+  static UInt             m_prevPOC;        // POC of the previous slice
+  static UInt             m_uiPrevLayerId;  // LayerId of the previous slice
+  static Bool             m_bFirstSliceInSequence;
+  UInt                    m_layerId;      
+  UInt                    m_numLayer;
+  TDecTop**               m_ppcTDecTop;
+#if AVC_BASE
+  FILE*                   m_pBLReconFile;
+  Int                     m_iBLSourceWidth;
+  Int                     m_iBLSourceHeight;
+#endif
+#endif 
+#if REF_IDX_FRAMEWORK
+  TComPic*                m_cIlpPic[MAX_NUM_REF];                    ///<  Inter layer Prediction picture =  upsampled picture 
+#endif
+
+public:
+  TDecTop();
+  virtual ~TDecTop();
+  
+  Void  create  ();
+  Void  destroy ();
+
+  void setDecodedPictureHashSEIEnabled(Int enabled) { m_cGopDecoder.setDecodedPictureHashSEIEnabled(enabled); }
+
+  Void  init();
+#if SVC_EXTENSION
+  Bool  decode(InputNALUnit& nalu, Int& iSkipFrame, Int& iPOCLastDisplay, UInt& curLayerId, Bool& bNewPOC);
+#else
+  Bool  decode(InputNALUnit& nalu, Int& iSkipFrame, Int& iPOCLastDisplay);
+#endif
+  
+  Void  deletePicBuffer();
+
+  Void executeDeblockAndAlf(UInt& ruiPOC, TComList<TComPic*>*& rpcListPic, Int& iSkipFrame,  Int& iPOCLastDisplay);
+
+#if SVC_EXTENSION
+  UInt      getLayerId            () { return m_layerId;              }
+  Void      setLayerId            (UInt layer) { m_layerId = layer; }
+  UInt      getNumLayer           () { return m_numLayer;             }
+  Void      setNumLayer           (UInt uiNum)   { m_numLayer = uiNum;  }
+  TComList<TComPic*>*      getListPic() { return &m_cListPic; }
+  Void                setLayerDec(TDecTop **p)    { m_ppcTDecTop = p; }
+  TDecTop*            getLayerDec(UInt layer)   { return m_ppcTDecTop[layer]; }
+#if AVC_BASE
+  Void      setBLReconFile( FILE* pFile ) { m_pBLReconFile = pFile; }
+  FILE*     getBLReconFile() { return m_pBLReconFile; }
+  Void      setBLsize( Int iWidth, Int iHeight ) { m_iBLSourceWidth = iWidth; m_iBLSourceHeight = iHeight; }
+  Int       getBLWidth() { return  m_iBLSourceWidth; }
+  Int       getBLHeight() { return  m_iBLSourceHeight; }
+#endif
+#endif
+#if REF_IDX_FRAMEWORK
+  Void      xInitILRP(TComSPS *pcSPS);
+  Void      setILRPic(TComPic *pcPic);
+#endif
+protected:
+  Void  xGetNewPicBuffer  (TComSlice* pcSlice, TComPic*& rpcPic);
+  Void  xUpdateGopSize    (TComSlice* pcSlice);
+  Void  xCreateLostPicture (Int iLostPOC);
+
+#if !REMOVE_APS
+  Void      decodeAPS( TComAPS* cAPS) { m_cEntropyDecoder.decodeAPS(cAPS); };
+#endif
+  Void      xActivateParameterSets();
+#if SVC_EXTENSION
+  Bool      xDecodeSlice(InputNALUnit &nalu, Int &iSkipFrame, Int iPOCLastDisplay, UInt& curLayerId, Bool& bNewPOC);
+#else
+  Bool      xDecodeSlice(InputNALUnit &nalu, Int &iSkipFrame, Int iPOCLastDisplay);
+#endif
+  Void      xDecodeVPS();
+  Void      xDecodeSPS();
+  Void      xDecodePPS();
+#if !REMOVE_APS
+  Void      xDecodeAPS();
+#endif
+  Void      xDecodeSEI( TComInputBitstream* bs );
+
+#if !REMOVE_APS
+  Void      allocAPS (TComAPS* pAPS); //!< memory allocation for APS
+#endif
+};// END CLASS DEFINITION TDecTop
+
+
+//! \}
+
+#endif // __TDECTOP__
+
Index: /trunk/source/Lib/TLibEncoder/AnnexBwrite.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/AnnexBwrite.h	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/AnnexBwrite.h	(revision 2)
@@ -0,0 +1,86 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#pragma once
+
+#include <ostream>
+#include "TLibCommon/AccessUnit.h"
+#include "NALwrite.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+/**
+ * write all NALunits in au to bytestream out in a manner satisfying
+ * AnnexB of AVC.  NALunits are written in the order they are found in au.
+ * the zero_byte word is appended to:
+ *  - the initial startcode in the access unit,
+ *  - any SPS/PPS nal units
+ */
+static std::vector<unsigned> writeAnnexB(std::ostream& out, const AccessUnit& au)
+{
+  std::vector<unsigned> annexBsizes;
+
+  for (AccessUnit::const_iterator it = au.begin(); it != au.end(); it++)
+  {
+    const NALUnitEBSP& nalu = **it;
+    unsigned size = 0; /* size of annexB unit in bytes */
+
+    static const char start_code_prefix[] = {0,0,0,1};
+    if (it == au.begin() || nalu.m_nalUnitType == NAL_UNIT_SPS || nalu.m_nalUnitType == NAL_UNIT_PPS)
+    {
+      /* From AVC, When any of the following conditions are fulfilled, the
+       * zero_byte syntax element shall be present:
+       *  - the nal_unit_type within the nal_unit() is equal to 7 (sequence
+       *    parameter set) or 8 (picture parameter set),
+       *  - the byte stream NAL unit syntax structure contains the first NAL
+       *    unit of an access unit in decoding order, as specified by subclause
+       *    7.4.1.2.3.
+       */
+      out.write(start_code_prefix, 4);
+      size += 4;
+    }
+    else
+    {
+      out.write(start_code_prefix+1, 3);
+      size += 3;
+    }
+    out << nalu.m_nalUnitData.str();
+    size += unsigned(nalu.m_nalUnitData.str().size());
+
+    annexBsizes.push_back(size);
+  }
+
+  return annexBsizes;
+}
+//! \}
Index: /trunk/source/Lib/TLibEncoder/NALwrite.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/NALwrite.cpp	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/NALwrite.cpp	(revision 2)
@@ -0,0 +1,191 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <vector>
+#include <algorithm>
+#include <ostream>
+
+#include "TLibCommon/NAL.h"
+#include "TLibCommon/TComBitStream.h"
+#include "NALwrite.h"
+
+using namespace std;
+
+//! \ingroup TLibEncoder
+//! \{
+
+static const char emulation_prevention_three_byte[] = {3};
+
+#if NAL_UNIT_HEADER
+Void writeNalUnitHeader(ostream& out, OutputNALUnit& nalu)       // nal_unit_header()
+{
+TComOutputBitstream bsNALUHeader;
+
+  bsNALUHeader.write(0,1);                    // forbidden_zero_bit
+  bsNALUHeader.write(nalu.m_nalUnitType, 6);  // nal_unit_type
+#if SVC_EXTENSION
+  bsNALUHeader.write(nalu.m_layerId, 6); // reserved_one_5bits
+#else
+#if TARGET_DECLAYERID_SET
+  bsNALUHeader.write(nalu.m_reservedZero6Bits, 6);                   // nuh_reserved_zero_6bits
+#else
+  bsNALUHeader.write(0, 6);                   // nuh_reserved_zero_6bits
+#endif
+#endif
+  bsNALUHeader.write(nalu.m_temporalId+1, 3); // nuh_temporal_id_plus1
+
+  out.write(bsNALUHeader.getByteStream(), bsNALUHeader.getByteStreamLength());
+}
+#endif
+/**
+ * write nalu to bytestream out, performing RBSP anti startcode
+ * emulation as required.  nalu.m_RBSPayload must be byte aligned.
+ */
+void write(ostream& out, OutputNALUnit& nalu)
+{
+#if NAL_UNIT_HEADER
+  writeNalUnitHeader(out, nalu);
+#else
+  TComOutputBitstream bsNALUHeader;
+
+  bsNALUHeader.write(0,1); // forbidden_zero_flag
+#if !REMOVE_NAL_REF_FLAG
+  bsNALUHeader.write(nalu.m_nalRefFlag? 1 : 0, 1); // nal_ref_flag
+#endif
+  bsNALUHeader.write(nalu.m_nalUnitType, 6);          // nal_unit_type
+#if REMOVE_NAL_REF_FLAG
+    bsNALUHeader.write(0, 6); // reserved_one_5bits
+#endif
+#if TEMPORAL_ID_PLUS1
+  bsNALUHeader.write(nalu.m_temporalId+1, 3); // temporal_id_plus1
+#if !REMOVE_NAL_REF_FLAG
+  bsNALUHeader.write(0, 5); // reserved_one_5bits
+#endif
+#else
+  bsNALUHeader.write(nalu.m_temporalId, 3); // temporal_id
+  bsNALUHeader.write(1, 5); // reserved_one_5bits
+#endif
+
+  out.write(bsNALUHeader.getByteStream(), bsNALUHeader.getByteStreamLength());
+#endif
+  /* write out rsbp_byte's, inserting any required
+   * emulation_prevention_three_byte's */
+  /* 7.4.1 ...
+   * emulation_prevention_three_byte is a byte equal to 0x03. When an
+   * emulation_prevention_three_byte is present in the NAL unit, it shall be
+   * discarded by the decoding process.
+   * The last byte of the NAL unit shall not be equal to 0x00.
+   * Within the NAL unit, the following three-byte sequences shall not occur at
+   * any byte-aligned position:
+   *  - 0x000000
+   *  - 0x000001
+   *  - 0x000002
+   * Within the NAL unit, any four-byte sequence that starts with 0x000003
+   * other than the following sequences shall not occur at any byte-aligned
+   * position:
+   *  - 0x00000300
+   *  - 0x00000301
+   *  - 0x00000302
+   *  - 0x00000303
+   */
+  vector<uint8_t>& rbsp   = nalu.m_Bitstream.getFIFO();
+
+  for (vector<uint8_t>::iterator it = rbsp.begin(); it != rbsp.end();)
+  {
+    /* 1) find the next emulated 00 00 {00,01,02,03}
+     * 2a) if not found, write all remaining bytes out, stop.
+     * 2b) otherwise, write all non-emulated bytes out
+     * 3) insert emulation_prevention_three_byte
+     */
+    vector<uint8_t>::iterator found = it;
+    do
+    {
+      /* NB, end()-1, prevents finding a trailing two byte sequence */
+      found = search_n(found, rbsp.end()-1, 2, 0);
+      found++;
+      /* if not found, found == end, otherwise found = second zero byte */
+      if (found == rbsp.end())
+        break;
+      if (*(++found) <= 3)
+        break;
+    } while (true);
+
+    it = found;
+    if (found != rbsp.end())
+    {
+      it = rbsp.insert(found, emulation_prevention_three_byte[0]);
+    }
+  }
+
+  out.write((char*)&(*rbsp.begin()), rbsp.end() - rbsp.begin());
+
+  /* 7.4.1.1
+   * ... when the last byte of the RBSP data is equal to 0x00 (which can
+   * only occur when the RBSP ends in a cabac_zero_word), a final byte equal
+   * to 0x03 is appended to the end of the data.
+   */
+  if (rbsp.back() == 0x00)
+  {
+    out.write(emulation_prevention_three_byte, 1);
+  }
+}
+
+/**
+ * Write rbsp_trailing_bits to bs causing it to become byte-aligned
+ */
+void writeRBSPTrailingBits(TComOutputBitstream& bs)
+{
+  bs.write( 1, 1 );
+  bs.writeAlignZero();
+}
+
+/**
+ * Copy NALU from naluSrc to naluDest
+ */
+void copyNaluData(OutputNALUnit& naluDest, const OutputNALUnit& naluSrc)
+{
+  naluDest.m_nalUnitType = naluSrc.m_nalUnitType;
+#if !REMOVE_NAL_REF_FLAG
+  naluDest.m_nalRefFlag  = naluSrc.m_nalRefFlag;
+#endif
+#if TARGET_DECLAYERID_SET
+  naluDest.m_reservedZero6Bits  = naluSrc.m_reservedZero6Bits;
+#endif
+  naluDest.m_temporalId  = naluSrc.m_temporalId;
+  naluDest.m_Bitstream   = naluSrc.m_Bitstream;
+#if SVC_EXTENSION
+  naluDest.m_layerId   = naluSrc.m_layerId;
+#endif
+}
+
+//! \}
Index: /trunk/source/Lib/TLibEncoder/NALwrite.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/NALwrite.h	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/NALwrite.h	(revision 2)
@@ -0,0 +1,115 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#pragma once
+
+#include <ostream>
+
+#include "TLibCommon/TypeDef.h"
+#include "TLibCommon/TComBitStream.h"
+#include "TLibCommon/NAL.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+/**
+ * A convenience wrapper to NALUnit that also provides a
+ * bitstream object.
+ */
+struct OutputNALUnit : public NALUnit
+{
+  /**
+   * construct an OutputNALunit structure with given header values and
+   * storage for a bitstream.  Upon construction the NALunit header is
+   * written to the bitstream.
+   */
+  OutputNALUnit(
+    NalUnitType nalUnitType,
+#if !REMOVE_NAL_REF_FLAG
+    Bool nalRefFlag,
+#endif
+#if TARGET_DECLAYERID_SET
+    unsigned temporalID = 0,
+#if SVC_EXTENSION
+    UInt     layerId = 0,
+#endif
+    unsigned reserved_zero_6bits = 0)
+#else
+    unsigned temporalID = 0)
+#endif
+#if SVC_EXTENSION
+#if REMOVE_NAL_REF_FLAG
+#if TARGET_DECLAYERID_SET
+  : NALUnit(nalUnitType, temporalID, layerId, reserved_zero_6bits)
+#else
+  : NALUnit(nalUnitType, temporalID, layerId)
+#endif
+#else
+  : NALUnit(nalUnitType, nalRefFlag, temporalID, layerId)
+#endif
+#else
+#if REMOVE_NAL_REF_FLAG
+#if TARGET_DECLAYERID_SET
+  : NALUnit(nalUnitType, temporalID, reserved_zero_6bits)
+#else
+  : NALUnit(nalUnitType, temporalID)
+#endif
+#else
+  : NALUnit(nalUnitType, nalRefFlag, temporalID)
+#endif
+#endif
+  , m_Bitstream()
+  {}
+
+  OutputNALUnit& operator=(const NALUnit& src)
+  {
+    m_Bitstream.clear();
+    static_cast<NALUnit*>(this)->operator=(src);
+    return *this;
+  }
+
+  TComOutputBitstream m_Bitstream;
+};
+
+void write(std::ostream& out, OutputNALUnit& nalu);
+void writeRBSPTrailingBits(TComOutputBitstream& bs);
+
+inline NALUnitEBSP::NALUnitEBSP(OutputNALUnit& nalu)
+  : NALUnit(nalu)
+{
+  write(m_nalUnitData, nalu);
+}
+
+void copyNaluData(OutputNALUnit& naluDest, const OutputNALUnit& naluSrc);
+
+//! \}
Index: /trunk/source/Lib/TLibEncoder/SEIwrite.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/SEIwrite.cpp	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/SEIwrite.cpp	(revision 2)
@@ -0,0 +1,313 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "TLibCommon/TComBitCounter.h"
+#include "TLibCommon/TComBitStream.h"
+#include "TLibCommon/SEI.h"
+#include "TLibCommon/TComSlice.h"
+#include "SEIwrite.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+#if ENC_DEC_TRACE
+Void  xTraceSEIHeader()
+{
+  fprintf( g_hTrace, "=========== SEI message ===========\n");
+}
+
+Void  xTraceSEIMessageType(SEI::PayloadType payloadType)
+{
+  switch (payloadType)
+  {
+  case SEI::DECODED_PICTURE_HASH:
+    fprintf( g_hTrace, "=========== Decoded picture hash SEI message ===========\n");
+    break;
+  case SEI::USER_DATA_UNREGISTERED:
+    fprintf( g_hTrace, "=========== User Data Unregistered SEI message ===========\n");
+    break;
+#if ACTIVE_PARAMETER_SETS_SEI_MESSAGE
+  case SEI::ACTIVE_PARAMETER_SETS:
+    fprintf( g_hTrace, "=========== Active Parameter sets SEI message ===========\n");
+    break;
+#endif 
+  default:
+    fprintf( g_hTrace, "=========== Unknown SEI message ===========\n");
+    break;
+  }
+}
+#endif
+
+void SEIWriter::xWriteSEIpayloadData(const SEI& sei)
+{
+  switch (sei.payloadType())
+  {
+  case SEI::USER_DATA_UNREGISTERED:
+    xWriteSEIuserDataUnregistered(*static_cast<const SEIuserDataUnregistered*>(&sei));
+    break;
+#if ACTIVE_PARAMETER_SETS_SEI_MESSAGE  
+  case SEI::ACTIVE_PARAMETER_SETS:
+    xWriteSEIActiveParameterSets(*static_cast<const SEIActiveParameterSets*>(& sei)); 
+    break; 
+#endif 
+  case SEI::DECODED_PICTURE_HASH:
+    xWriteSEIDecodedPictureHash(*static_cast<const SEIDecodedPictureHash*>(&sei));
+    break;
+#if BUFFERING_PERIOD_AND_TIMING_SEI
+  case SEI::BUFFERING_PERIOD:
+    xWriteSEIBufferingPeriod(*static_cast<const SEIBufferingPeriod*>(&sei));
+    break;
+  case SEI::PICTURE_TIMING:
+    xWriteSEIPictureTiming(*static_cast<const SEIPictureTiming*>(&sei));
+    break;
+#endif
+#if RECOVERY_POINT_SEI
+  case SEI::RECOVERY_POINT:
+    xWriteSEIRecoveryPoint(*static_cast<const SEIRecoveryPoint*>(&sei));
+    break;
+#endif
+  default:
+    assert(!"Unhandled SEI message");
+  }
+}
+
+/**
+ * marshal a single SEI message sei, storing the marshalled representation
+ * in bitstream bs.
+ */
+Void SEIWriter::writeSEImessage(TComBitIf& bs, const SEI& sei)
+{
+  /* calculate how large the payload data is */
+  /* TODO: this would be far nicer if it used vectored buffers */
+  TComBitCounter bs_count;
+  bs_count.resetBits();
+  setBitstream(&bs_count);
+
+#if ENC_DEC_TRACE
+  g_HLSTraceEnable = false;
+#endif
+  xWriteSEIpayloadData(sei);
+#if ENC_DEC_TRACE
+  g_HLSTraceEnable = true;
+#endif
+  unsigned payload_data_num_bits = bs_count.getNumberOfWrittenBits();
+  assert(0 == payload_data_num_bits % 8);
+
+  setBitstream(&bs);
+
+#if ENC_DEC_TRACE
+  xTraceSEIHeader();
+#endif
+
+  UInt payloadType = sei.payloadType();
+  for (; payloadType >= 0xff; payloadType -= 0xff)
+  {
+    WRITE_CODE(0xff, 8, "payload_type");
+  }
+  WRITE_CODE(payloadType, 8, "payload_type");
+
+  UInt payloadSize = payload_data_num_bits/8;
+  for (; payloadSize >= 0xff; payloadSize -= 0xff)
+  {
+    WRITE_CODE(0xff, 8, "payload_size");
+  }
+  WRITE_CODE(payloadSize, 8, "payload_size");
+
+  /* payloadData */
+#if ENC_DEC_TRACE
+  xTraceSEIMessageType(sei.payloadType());
+#endif
+
+  xWriteSEIpayloadData(sei);
+}
+
+/**
+ * marshal a user_data_unregistered SEI message sei, storing the marshalled
+ * representation in bitstream bs.
+ */
+Void SEIWriter::xWriteSEIuserDataUnregistered(const SEIuserDataUnregistered &sei)
+{
+  for (UInt i = 0; i < 16; i++)
+  {
+    WRITE_CODE(sei.uuid_iso_iec_11578[i], 8 , "sei.uuid_iso_iec_11578[i]");
+  }
+
+  for (UInt i = 0; i < sei.userDataLength; i++)
+  {
+    WRITE_CODE(sei.userData[i], 8 , "user_data");
+  }
+}
+
+/**
+ * marshal a decoded picture hash SEI message, storing the marshalled
+ * representation in bitstream bs.
+ */
+Void SEIWriter::xWriteSEIDecodedPictureHash(const SEIDecodedPictureHash& sei)
+{
+  UInt val;
+
+  WRITE_CODE(sei.method, 8, "hash_type");
+
+  for(int yuvIdx = 0; yuvIdx < 3; yuvIdx++)
+  {
+    if(sei.method == SEIDecodedPictureHash::MD5)
+    {
+      for (unsigned i = 0; i < 16; i++)
+      {
+        WRITE_CODE(sei.digest[yuvIdx][i], 8, "picture_md5");
+      }
+    }
+    else if(sei.method == SEIDecodedPictureHash::CRC)
+    {
+      val = (sei.digest[yuvIdx][0] << 8)  + sei.digest[yuvIdx][1];
+      WRITE_CODE(val, 16, "picture_crc");
+    }
+    else if(sei.method == SEIDecodedPictureHash::CHECKSUM)
+    {
+      val = (sei.digest[yuvIdx][0] << 24)  + (sei.digest[yuvIdx][1] << 16) + (sei.digest[yuvIdx][2] << 8) + sei.digest[yuvIdx][3];
+      WRITE_CODE(val, 32, "picture_checksum");
+    }
+  }
+}
+
+#if ACTIVE_PARAMETER_SETS_SEI_MESSAGE  
+Void SEIWriter::xWriteSEIActiveParameterSets(const SEIActiveParameterSets& sei)
+{
+  WRITE_CODE(sei.activeVPSId, 4, "active_vps_id");
+  WRITE_CODE(sei.activeSPSIdPresentFlag, 1, "active_sps_id_present_flag");
+
+  if (sei.activeSPSIdPresentFlag) 
+  {
+    WRITE_UVLC(sei.activeSeqParamSetId, "active_seq_param_set_id"); 
+  }
+
+  WRITE_CODE(sei.activeParamSetSEIExtensionFlag, 1, "active_param_set_sei_extension_flag"); 
+
+  unsigned uiBits = m_pcBitIf->getNumberOfWrittenBits(); 
+  UInt uiAlignedBits = ( 8 - (uiBits&7) ) % 8;  
+  if(uiAlignedBits) 
+  {
+    WRITE_FLAG(1, "alignment_bit" );
+    uiAlignedBits--; 
+    while(uiAlignedBits--)
+    {
+      WRITE_FLAG(0, "alignment_bit" );
+    }
+  }
+}
+#endif 
+
+#if BUFFERING_PERIOD_AND_TIMING_SEI
+Void SEIWriter::xWriteSEIBufferingPeriod(const SEIBufferingPeriod& sei)
+{
+  Int i, nalOrVcl;
+  TComVUI *vui = sei.m_sps->getVuiParameters();
+  WRITE_UVLC( sei.m_seqParameterSetId, "seq_parameter_set_id" );
+  if( !vui->getSubPicCpbParamsPresentFlag() )
+  {
+    WRITE_FLAG( sei.m_altCpbParamsPresentFlag, "alt_cpb_params_present_flag" );
+  }
+  for( nalOrVcl = 0; nalOrVcl < 2; nalOrVcl ++ )
+  {
+    if( ( ( nalOrVcl == 0 ) && ( vui->getNalHrdParametersPresentFlag() ) ) ||
+        ( ( nalOrVcl == 1 ) && ( vui->getVclHrdParametersPresentFlag() ) ) )
+    {
+      for( i = 0; i < ( vui->getCpbCntMinus1( 0 ) + 1 ); i ++ )
+      {
+        WRITE_CODE( sei.m_initialCpbRemovalDelay[i][nalOrVcl],( vui->getInitialCpbRemovalDelayLengthMinus1() + 1 ) ,           "initial_cpb_removal_delay" );
+        WRITE_CODE( sei.m_initialCpbRemovalDelayOffset[i][nalOrVcl],( vui->getInitialCpbRemovalDelayLengthMinus1() + 1 ),      "initial_cpb_removal_delay_offset" );
+        if( vui->getSubPicCpbParamsPresentFlag() || sei.m_altCpbParamsPresentFlag )
+        {
+          WRITE_CODE( sei.m_initialAltCpbRemovalDelay[i][nalOrVcl], ( vui->getInitialCpbRemovalDelayLengthMinus1() + 1 ) ,     "initial_alt_cpb_removal_delay" );
+          WRITE_CODE( sei.m_initialAltCpbRemovalDelayOffset[i][nalOrVcl], ( vui->getInitialCpbRemovalDelayLengthMinus1() + 1 ),"initial_alt_cpb_removal_delay_offset" );
+        }
+      }
+    }
+  }
+  xWriteByteAlign();
+}
+Void SEIWriter::xWriteSEIPictureTiming(const SEIPictureTiming& sei)
+{
+  Int i;
+  TComVUI *vui = sei.m_sps->getVuiParameters();
+
+  if( !vui->getNalHrdParametersPresentFlag() && !vui->getVclHrdParametersPresentFlag() )
+    return;
+
+  WRITE_CODE( sei.m_auCpbRemovalDelay, ( vui->getCpbRemovalDelayLengthMinus1() + 1 ),                                         "au_cpb_removal_delay" );
+  WRITE_CODE( sei.m_picDpbOutputDelay, ( vui->getDpbOutputDelayLengthMinus1() + 1 ),                                          "pic_dpb_output_delay" );
+  if( sei.m_sps->getVuiParameters()->getSubPicCpbParamsPresentFlag() )
+  {
+    WRITE_UVLC( sei.m_numDecodingUnitsMinus1,     "num_decoding_units_minus1" );
+    WRITE_FLAG( sei.m_duCommonCpbRemovalDelayFlag, "du_common_cpb_removal_delay_flag" );
+    if( sei.m_duCommonCpbRemovalDelayFlag )
+    {
+      WRITE_CODE( sei.m_duCommonCpbRemovalDelayMinus1, ( vui->getDuCpbRemovalDelayLengthMinus1() + 1 ),                       "du_common_cpb_removal_delay_minus1" );
+    }
+    else
+    {
+      for( i = 0; i < ( sei.m_numDecodingUnitsMinus1 + 1 ); i ++ )
+      {
+        WRITE_UVLC( sei.m_numNalusInDuMinus1[ i ],  "num_nalus_in_du_minus1");
+        WRITE_CODE( sei.m_duCpbRemovalDelayMinus1[ i ], ( vui->getDuCpbRemovalDelayLengthMinus1() + 1 ),                        "du_cpb_removal_delay_minus1" );
+      }
+    }
+  }
+  xWriteByteAlign();
+}
+#endif
+#if RECOVERY_POINT_SEI
+Void SEIWriter::xWriteSEIRecoveryPoint(const SEIRecoveryPoint& sei)
+{
+  WRITE_SVLC( sei.m_recoveryPocCnt,    "recovery_poc_cnt"    );
+  WRITE_FLAG( sei.m_exactMatchingFlag, "exact_matching_flag" );
+  WRITE_FLAG( sei.m_brokenLinkFlag,    "broken_link_flag"    );
+  xWriteByteAlign();
+}
+#endif
+
+#if RECOVERY_POINT_SEI || BUFFERING_PERIOD_AND_TIMING_SEI
+Void SEIWriter::xWriteByteAlign()
+{
+  if( m_pcBitIf->getNumberOfWrittenBits() % 8 != 0)
+  {
+    WRITE_FLAG( 1, "bit_equal_to_one" );
+    while( m_pcBitIf->getNumberOfWrittenBits() % 8 != 0 )
+    {
+      WRITE_FLAG( 0, "bit_equal_to_zero" );
+    }
+  }
+};
+#endif
+
+//! \}
Index: /trunk/source/Lib/TLibEncoder/SEIwrite.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/SEIwrite.h	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/SEIwrite.h	(revision 2)
@@ -0,0 +1,71 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#pragma once
+
+#include "SyntaxElementWriter.h"
+#include "TLibCommon/SEI.h"
+
+class TComBitIf;
+
+//! \ingroup TLibEncoder
+//! \{
+class SEIWriter:public SyntaxElementWriter
+{
+public:
+  SEIWriter() {};
+  virtual ~SEIWriter() {};
+
+  void writeSEImessage(TComBitIf& bs, const SEI& sei);
+
+protected:
+  Void xWriteSEIpayloadData(const SEI& sei);
+  Void xWriteSEIuserDataUnregistered(const SEIuserDataUnregistered &sei);
+#if ACTIVE_PARAMETER_SETS_SEI_MESSAGE 
+  Void xWriteSEIActiveParameterSets(const SEIActiveParameterSets& sei);
+#endif
+  Void xWriteSEIDecodedPictureHash(const SEIDecodedPictureHash& sei);
+#if BUFFERING_PERIOD_AND_TIMING_SEI
+  Void xWriteSEIBufferingPeriod(const SEIBufferingPeriod& sei);
+  Void xWriteSEIPictureTiming(const SEIPictureTiming& sei);
+  TComSPS *m_pSPS;
+#endif
+#if RECOVERY_POINT_SEI
+  Void xWriteSEIRecoveryPoint(const SEIRecoveryPoint& sei);
+#endif
+#if RECOVERY_POINT_SEI || BUFFERING_PERIOD_AND_TIMING_SEI
+  Void xWriteByteAlign();
+#endif
+};
+
+//! \}
Index: /trunk/source/Lib/TLibEncoder/SyntaxElementWriter.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/SyntaxElementWriter.cpp	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/SyntaxElementWriter.cpp	(revision 2)
@@ -0,0 +1,132 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     SyntaxElementWriter.cpp
+    \brief    CAVLC encoder class
+*/
+
+#include "TLibCommon/CommonDef.h"
+#include "SyntaxElementWriter.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+#if ENC_DEC_TRACE
+
+Void  SyntaxElementWriter::xWriteCodeTr (UInt value, UInt  length, const Char *pSymbolName)
+{
+  xWriteCode (value,length);
+  if( g_HLSTraceEnable )
+  {
+    fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+    if( length<10 )
+    {
+      fprintf( g_hTrace, "%-50s u(%d)  : %d\n", pSymbolName, length, value ); 
+    }
+    else
+    {
+      fprintf( g_hTrace, "%-50s u(%d) : %d\n", pSymbolName, length, value ); 
+    }
+  }
+}
+
+Void  SyntaxElementWriter::xWriteUvlcTr (UInt value, const Char *pSymbolName)
+{
+  xWriteUvlc (value);
+  if( g_HLSTraceEnable )
+  {
+    fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+    fprintf( g_hTrace, "%-50s ue(v) : %d\n", pSymbolName, value ); 
+  }
+}
+
+Void  SyntaxElementWriter::xWriteSvlcTr (Int value, const Char *pSymbolName)
+{
+  xWriteSvlc(value);
+  if( g_HLSTraceEnable )
+  {
+    fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+    fprintf( g_hTrace, "%-50s se(v) : %d\n", pSymbolName, value ); 
+  }
+}
+
+Void  SyntaxElementWriter::xWriteFlagTr(UInt value, const Char *pSymbolName)
+{
+  xWriteFlag(value);
+  if( g_HLSTraceEnable )
+  {
+    fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+    fprintf( g_hTrace, "%-50s u(1)  : %d\n", pSymbolName, value ); 
+  }
+}
+
+#endif
+
+
+Void SyntaxElementWriter::xWriteCode     ( UInt uiCode, UInt uiLength )
+{
+  assert ( uiLength > 0 );
+  m_pcBitIf->write( uiCode, uiLength );
+}
+
+Void SyntaxElementWriter::xWriteUvlc     ( UInt uiCode )
+{
+  UInt uiLength = 1;
+  UInt uiTemp = ++uiCode;
+  
+  assert ( uiTemp );
+  
+  while( 1 != uiTemp )
+  {
+    uiTemp >>= 1;
+    uiLength += 2;
+  }
+  // Take care of cases where uiLength > 32
+  m_pcBitIf->write( 0, uiLength >> 1);
+  m_pcBitIf->write( uiCode, (uiLength+1) >> 1);
+}
+
+Void SyntaxElementWriter::xWriteSvlc     ( Int iCode )
+{
+  UInt uiCode;
+  
+  uiCode = xConvertToUInt( iCode );
+  xWriteUvlc( uiCode );
+}
+
+Void SyntaxElementWriter::xWriteFlag( UInt uiCode )
+{
+  m_pcBitIf->write( uiCode, 1 );
+}
+
+//! \}
Index: /trunk/source/Lib/TLibEncoder/SyntaxElementWriter.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/SyntaxElementWriter.h	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/SyntaxElementWriter.h	(revision 2)
@@ -0,0 +1,97 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     SyntaxElementWriter.h
+    \brief    CAVLC encoder class (header)
+*/
+
+#ifndef __SYNTAXELEMENTWRITER__
+#define __SYNTAXELEMENTWRITER__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComBitStream.h"
+#include "TLibCommon/TComRom.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+#if ENC_DEC_TRACE
+
+#define WRITE_CODE( value, length, name)    xWriteCodeTr ( value, length, name )
+#define WRITE_UVLC( value,         name)    xWriteUvlcTr ( value,         name )
+#define WRITE_SVLC( value,         name)    xWriteSvlcTr ( value,         name )
+#define WRITE_FLAG( value,         name)    xWriteFlagTr ( value,         name )
+
+#else
+
+#define WRITE_CODE( value, length, name)     xWriteCode ( value, length )
+#define WRITE_UVLC( value,         name)     xWriteUvlc ( value )
+#define WRITE_SVLC( value,         name)     xWriteSvlc ( value )
+#define WRITE_FLAG( value,         name)     xWriteFlag ( value )
+
+#endif
+
+class SyntaxElementWriter
+{
+protected:
+  TComBitIf*    m_pcBitIf;
+
+  SyntaxElementWriter()
+  :m_pcBitIf(NULL)
+  {};
+  virtual ~SyntaxElementWriter() {};
+
+  Void  setBitstream          ( TComBitIf* p )  { m_pcBitIf = p;  }
+
+  Void  xWriteCode            ( UInt uiCode, UInt uiLength );
+  Void  xWriteUvlc            ( UInt uiCode );
+  Void  xWriteSvlc            ( Int  iCode   );
+  Void  xWriteFlag            ( UInt uiCode );
+#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);
+#endif
+
+  UInt  xConvertToUInt        ( Int iValue ) {  return ( iValue <= 0) ? -iValue<<1 : (iValue<<1)-1; }
+};
+
+//! \}
+
+#endif // !defined(__SYNTAXELEMENTWRITER__)
+
Index: /trunk/source/Lib/TLibEncoder/TEncAdaptiveLoopFilter.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncAdaptiveLoopFilter.cpp	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/TEncAdaptiveLoopFilter.cpp	(revision 2)
@@ -0,0 +1,2436 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncAdaptiveLoopFilter.cpp
+ \brief    estimation part of adaptive loop filter class
+ */
+#include "TEncAdaptiveLoopFilter.h"
+#include <string.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <math.h>
+
+#if !REMOVE_ALF
+//! \ingroup TLibEncoder
+//! \{
+// ====================================================================================================================
+// Constructor / destructor
+// ====================================================================================================================
+
+///AlfCorrData
+AlfCorrData::AlfCorrData()
+{
+  this->componentID = -1;
+  this->ECorr  = NULL;
+  this->yCorr  = NULL;
+  this->pixAcc = NULL;
+}
+
+AlfCorrData::AlfCorrData(Int cIdx)
+{
+  const Int numCoef = ALF_MAX_NUM_COEF;
+  const Int maxNumGroups = NO_VAR_BINS;
+
+  Int numGroups = (cIdx == ALF_Y)?(maxNumGroups):(1);
+
+  this->componentID = cIdx;
+
+  this->ECorr = new Double**[numGroups];
+  this->yCorr = new Double*[numGroups];
+  this->pixAcc = new Double[numGroups];
+  for(Int g= 0; g< numGroups; g++)
+  {
+    this->yCorr[g] = new Double[numCoef];
+    for(Int j=0; j< numCoef; j++)
+    {
+      this->yCorr[g][j] = 0;
+    }
+
+    this->ECorr[g] = new Double*[numCoef];
+    for(Int i=0; i< numCoef; i++)
+    {
+      this->ECorr[g][i] = new Double[numCoef];
+      for(Int j=0; j< numCoef; j++)
+      {
+        this->ECorr[g][i][j] = 0;
+      }
+    }
+    this->pixAcc[g] = 0;  
+  }
+}
+
+AlfCorrData::~AlfCorrData()
+{
+  if(this->componentID >=0)
+  {
+    const Int numCoef = ALF_MAX_NUM_COEF;
+    const Int maxNumGroups = NO_VAR_BINS;
+
+    Int numGroups = (this->componentID == ALF_Y)?(maxNumGroups):(1);
+
+    for(Int g= 0; g< numGroups; g++)
+    {
+      for(Int i=0; i< numCoef; i++)
+      {
+        delete[] this->ECorr[g][i];
+      }
+      delete[] this->ECorr[g];
+      delete[] this->yCorr[g];
+    }
+    delete[] this->ECorr;
+    delete[] this->yCorr;
+    delete[] this->pixAcc;
+  }
+
+}
+
+AlfCorrData& AlfCorrData::operator += (const AlfCorrData& src)
+{
+  if(this->componentID >=0)
+  {
+    const Int numCoef = ALF_MAX_NUM_COEF;
+    const Int maxNumGroups = NO_VAR_BINS;
+
+    Int numGroups = (this->componentID == ALF_Y)?(maxNumGroups):(1);
+    for(Int g=0; g< numGroups; g++)
+    {
+      this->pixAcc[g] += src.pixAcc[g];
+
+      for(Int j=0; j< numCoef; j++)
+      {
+        this->yCorr[g][j] += src.yCorr[g][j];
+        for(Int i=0; i< numCoef; i++)
+        {
+          this->ECorr[g][j][i] += src.ECorr[g][j][i];
+        }
+      }
+    }
+  }
+
+  return *this;
+}
+
+
+Void AlfCorrData::reset()
+{
+  if(this->componentID >=0)
+  {
+    const Int numCoef = ALF_MAX_NUM_COEF;
+    const Int maxNumGroups = NO_VAR_BINS;
+
+    Int numGroups = (this->componentID == ALF_Y)?(maxNumGroups):(1);
+    for(Int g=0; g< numGroups; g++)
+    {
+      this->pixAcc[g] = 0;
+
+      for(Int j=0; j< numCoef; j++)
+      {
+        this->yCorr[g][j] = 0;
+        for(Int i=0; i< numCoef; i++)
+        {
+          this->ECorr[g][j][i] = 0;
+        }
+      }
+
+
+    }
+  }
+
+}
+
+Void AlfCorrData::mergeFrom(const AlfCorrData& src, Int* mergeTable, Bool doPixAccMerge)
+{
+  assert(componentID == src.componentID);
+
+  reset();
+
+  const Int numCoef = ALF_MAX_NUM_COEF;
+
+  Double **srcE, **dstE;
+  Double *srcy, *dsty;
+
+  switch(componentID)
+  {
+  case ALF_Cb:
+  case ALF_Cr:
+    {
+      srcE = src.ECorr  [0];
+      dstE = this->ECorr[0];
+
+      srcy  = src.yCorr[0];
+      dsty  = this->yCorr[0];
+
+      for(Int j=0; j< numCoef; j++)
+      {
+        for(Int i=0; i< numCoef; i++)
+        {
+          dstE[j][i] += srcE[j][i];
+        }
+
+        dsty[j] += srcy[j];
+      }
+      if(doPixAccMerge)
+      {
+        this->pixAcc[0] = src.pixAcc[0];
+      }
+    }
+    break;
+  case ALF_Y:
+    {
+      Int maxFilterSetSize = (Int)NO_VAR_BINS;
+      for (Int varInd=0; varInd< maxFilterSetSize; varInd++)
+      {
+        Int filtIdx = (mergeTable == NULL)?(0):(mergeTable[varInd]);
+        srcE = src.ECorr  [varInd];
+        dstE = this->ECorr[ filtIdx ];
+        srcy  = src.yCorr[varInd];
+        dsty  = this->yCorr[ filtIdx ];
+        for(Int j=0; j< numCoef; j++)
+        {
+          for(Int i=0; i< numCoef; i++)
+          {
+            dstE[j][i] += srcE[j][i];
+          }
+          dsty[j] += srcy[j];
+        }
+        if(doPixAccMerge)
+        {
+          this->pixAcc[filtIdx] += src.pixAcc[varInd];
+        }
+      }
+    }
+    break;
+  default:
+    {
+      printf("not a legal component ID\n");
+      assert(0);
+      exit(-1);
+    }
+  }
+}
+
+TEncAdaptiveLoopFilter::TEncAdaptiveLoopFilter()
+{
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+/** create global buffers for ALF encoding
+ */
+Void TEncAdaptiveLoopFilter::createAlfGlobalBuffers()
+{
+  for(Int compIdx =0; compIdx < NUM_ALF_COMPONENT; compIdx++)
+  {
+    m_alfNonSkippedCorr[compIdx] = new AlfCorrData*[m_uiNumCUsInFrame];
+    m_alfCorr[compIdx] = new AlfCorrData*[m_uiNumCUsInFrame];
+    for(Int n=0; n< m_uiNumCUsInFrame; n++)
+    {
+      m_alfCorr[compIdx][n]= new AlfCorrData(compIdx);
+      m_alfCorr[compIdx][n]->reset();
+      m_alfNonSkippedCorr[compIdx][n] = new AlfCorrData(compIdx);
+      m_alfNonSkippedCorr[compIdx][n]->reset();
+    }
+
+    m_alfCorrMerged[compIdx] = new AlfCorrData(compIdx);
+
+  }
+
+  const Int numCoef = (Int)ALF_MAX_NUM_COEF;
+
+  // temporary buffer for filter merge
+  for(Int g=0; g< (Int)NO_VAR_BINS; g++)
+  {
+    m_y_merged[g] = new Double[numCoef];
+
+    m_E_merged[g] = new Double*[numCoef];
+    for(Int i=0; i< numCoef; i++)
+    {
+      m_E_merged[g][i]= new Double[numCoef];
+    }
+  }
+  m_E_temp = new Double*[numCoef];
+  for(Int i=0; i< numCoef; i++)
+  {
+    m_E_temp[i] = new Double[numCoef];
+  }
+
+  //alf params for temporal layers
+  Int maxNumTemporalLayer =   (Int)(logf((float)(m_gopSize))/logf(2.0) + 1);
+  m_alfPictureParam = new ALFParam**[ maxNumTemporalLayer ];
+  for(Int t=0; t< maxNumTemporalLayer; t++)
+  {
+    m_alfPictureParam[t] = new ALFParam*[NUM_ALF_COMPONENT];
+    for(Int compIdx=0; compIdx < NUM_ALF_COMPONENT; compIdx++)
+    {
+      m_alfPictureParam[t][compIdx] = new ALFParam(compIdx);
+    }
+  }
+
+  // identity filter to estimate ALF off distortion
+  for(Int i=0; i< (Int)NO_VAR_BINS; i++)
+  {
+    m_coeffNoFilter[i] = new Int[numCoef];
+    ::memset(&(m_coeffNoFilter[i][0]), 0, sizeof(Int)*numCoef);
+    m_coeffNoFilter[i][numCoef-1] = (1 << ALF_NUM_BIT_SHIFT);
+  }
+  m_numSlicesDataInOneLCU = new Int[m_uiNumCUsInFrame];
+
+}
+
+/** destroy ALF global buffers
+ * This function is used to destroy the global ALF encoder buffers
+ */
+Void TEncAdaptiveLoopFilter::destroyAlfGlobalBuffers()
+{
+  for(Int compIdx =0; compIdx < NUM_ALF_COMPONENT; compIdx++)
+  {
+    for(Int n=0; n< m_uiNumCUsInFrame; n++)
+    {
+      delete m_alfCorr[compIdx][n];
+      delete m_alfNonSkippedCorr[compIdx][n];
+    }
+
+    delete[] m_alfCorr[compIdx];
+
+    m_alfCorr[compIdx] = NULL;
+    delete[] m_alfNonSkippedCorr[compIdx];
+    m_alfNonSkippedCorr[compIdx] = NULL;
+    delete m_alfCorrMerged[compIdx];
+  }
+  const Int numCoef = (Int)ALF_MAX_NUM_COEF;
+
+  // temporary buffer for filter merge
+  for(Int g=0; g< (Int)NO_VAR_BINS; g++)
+  {
+    delete[] m_y_merged[g]; m_y_merged[g] = NULL;
+    for(Int i=0; i< numCoef; i++)
+    {
+      delete[] m_E_merged[g][i];
+    }
+    delete[] m_E_merged[g];            m_E_merged[g] = NULL;
+  }
+  for(Int i=0; i< numCoef; i++)
+  {
+    delete[] m_E_temp[i];
+  }
+  delete[] m_E_temp; m_E_temp = NULL;
+
+  Int maxNumTemporalLayer =   (Int)(logf((float)(m_gopSize))/logf(2.0) + 1);
+  for(Int t=0; t< maxNumTemporalLayer; t++)
+  {
+    for(Int compIdx=0; compIdx < NUM_ALF_COMPONENT; compIdx++)
+    {
+      delete m_alfPictureParam[t][compIdx];
+    }
+    delete[] m_alfPictureParam[t];
+  }
+  delete[] m_alfPictureParam; m_alfPictureParam = NULL;
+  //const Int numCoef = (Int)ALF_MAX_NUM_COEF;
+
+  for(Int i=0; i< (Int)NO_VAR_BINS; i++)
+  {
+    delete[] m_coeffNoFilter[i];
+  }
+
+  delete[] m_numSlicesDataInOneLCU;
+
+}
+
+/** initialize ALF encoder configurations
+ * \param [in, out] alfParamSet ALF parameter set
+ * \param [in, out] alfCtrlParam ALF CU-on/off control parameters
+ */
+Void TEncAdaptiveLoopFilter::initALFEncoderParam()
+{
+  //get last valid slice index
+  for(Int s=0; s< m_uiNumSlicesInPic; s++)
+  {
+    if(m_pcPic->getValidSlice(s))
+    {
+      m_lastSliceIdx = s;
+    }
+  }
+  //get number slices in each LCU
+  if(m_uiNumSlicesInPic == 1 || m_iSGDepth == 0)
+  {
+    for(Int n=0; n< m_uiNumCUsInFrame; n++)
+    {
+      m_numSlicesDataInOneLCU[n] = 1;
+    }
+  }
+  else
+  {
+    Int count;
+    Int prevSliceID = -1;
+
+    for(Int n=0; n< m_uiNumCUsInFrame; n++)
+    {
+      std::vector<NDBFBlockInfo>& vNDBFBlock = *(m_pcPic->getCU(n)->getNDBFilterBlocks());
+
+      count = 0;
+
+      for(Int i=0; i< (Int)vNDBFBlock.size(); i++)
+      {
+        if(vNDBFBlock[i].sliceID != prevSliceID)
+        {
+          prevSliceID = vNDBFBlock[i].sliceID;
+          count++;
+        }
+      }
+
+      m_numSlicesDataInOneLCU[n] = count;
+    }
+  }
+}
+
+/** ALF encoding process top function
+ * \param [in, out] alfParamSet ALF parameter set
+ * \param [in, out] alfCtrlParam ALF CU-on/off control parameters
+ * \param [in] dLambdaLuma lambda value for luma RDO
+ * \param [in] dLambdaChroma lambda value for chroma RDO
+ */
+#if ALF_CHROMA_LAMBDA
+Void TEncAdaptiveLoopFilter::ALFProcess(ALFParam** alfPictureParam, Double lambdaLuma, Double lambdaChroma)
+#else
+Void TEncAdaptiveLoopFilter::ALFProcess(ALFParam** alfPictureParam,  Double lambda)
+#endif
+{
+#if ALF_CHROMA_LAMBDA
+  m_dLambdaLuma   = lambdaLuma;
+  m_dLambdaChroma = lambdaChroma;
+#else
+  m_dLambdaLuma   = lambda;
+  m_dLambdaChroma = lambda;
+#endif
+  TComPicYuv* yuvOrg    = m_pcPic->getPicYuvOrg();
+  TComPicYuv* yuvRec    = m_pcPic->getPicYuvRec();
+  TComPicYuv* yuvExtRec = m_pcTempPicYuv;
+
+  //picture boundary padding
+  yuvRec->copyToPic(yuvExtRec);
+  yuvExtRec->setBorderExtension( false );
+  yuvExtRec->extendPicBorder   ();
+
+  //initialize encoder parameters
+  initALFEncoderParam();
+  //get LCU statistics
+  getStatistics(yuvOrg, yuvExtRec);
+
+  //decide ALF parameters
+  decideParameters(alfPictureParam, yuvOrg, yuvExtRec, yuvRec);
+
+  if(m_alfLowLatencyEncoding)
+  {
+    //derive time-delayed filter for next picture
+    decideAlfPictureParam(m_alfPictureParam[getTemporalLayerNo(m_pcPic->getPOC(), m_gopSize)], false);
+  }
+}
+
+/** Derive filter coefficients
+ * \param [in, out] alfPicQTPart picture quad-tree partition information
+ * \param [in, out] alfPicLCUCorr correlations for LCUs
+ * \param [int] partIdx partition index
+ * \param [int] partLevel partition level
+ */
+Void TEncAdaptiveLoopFilter::deriveFilterInfo(Int compIdx, AlfCorrData* alfCorr, ALFParam* alfFiltParam, Int maxNumFilters, Double lambda)
+{
+  const Int filtNo = 0; 
+  const Int numCoeff = ALF_MAX_NUM_COEF;
+
+  switch(compIdx)
+  {
+  case ALF_Y:
+    {
+      Int lambdaForMerge = ((Int) lambda) * (1<<(2*g_uiBitIncrement));
+      Int numFilters;
+
+      ::memset(m_varIndTab, 0, sizeof(Int)*NO_VAR_BINS);
+      xfindBestFilterVarPred(alfCorr->yCorr, alfCorr->ECorr, alfCorr->pixAcc, m_filterCoeffSym, &numFilters, m_varIndTab, lambdaForMerge, maxNumFilters);
+      xcodeFiltCoeff(m_filterCoeffSym,  m_varIndTab, numFilters, alfFiltParam);
+    }
+    break;
+  case ALF_Cb:
+  case ALF_Cr:
+    {
+      static Double coef[ALF_MAX_NUM_COEF];
+
+      alfFiltParam->filters_per_group = 1;
+
+      gnsSolveByChol(alfCorr->ECorr[0], alfCorr->yCorr[0], coef, numCoeff);
+      xQuantFilterCoef(coef, m_filterCoeffSym[0], filtNo, g_uiBitDepth + g_uiBitIncrement);
+      ::memcpy(alfFiltParam->coeffmulti[0], m_filterCoeffSym[0], sizeof(Int)*numCoeff);
+      predictALFCoeff(alfFiltParam->coeffmulti, numCoeff, alfFiltParam->filters_per_group);
+    }
+    break;
+  default:
+    {
+      printf("Not a legal component ID\n");
+      assert(0);
+      exit(-1);
+    }
+  }
+}
+
+/** Estimate filtering distortion
+ * \param [in] compIdx luma/chroma component index
+ * \param [in] alfCorr correlations
+ * \param [in] coeffSet filter coefficients
+ * \param [in] filterSetSize number of filter set
+ * \param [in] mergeTable merge table of filter set (only for luma BA)
+ * \param [in] doPixAccMerge calculate pixel squared value (true) or not (false)
+ */
+Int64 TEncAdaptiveLoopFilter::estimateFilterDistortion(Int compIdx, AlfCorrData* alfCorr, Int** coeffSet, Int filterSetSize, Int* mergeTable, Bool doPixAccMerge)
+{
+  const Int numCoeff = (Int)ALF_MAX_NUM_COEF;
+  AlfCorrData* alfMerged = m_alfCorrMerged[compIdx];
+
+  alfMerged->mergeFrom(*alfCorr, mergeTable, doPixAccMerge);
+
+  Int**     coeff = (coeffSet == NULL)?(m_coeffNoFilter):(coeffSet);
+  Int64     iDist = 0;
+  for(Int f=0; f< filterSetSize; f++)
+  {
+    iDist += xFastFiltDistEstimation(alfMerged->ECorr[f], alfMerged->yCorr[f], coeff[f], numCoeff);
+  }
+  return iDist;
+}
+
+/** Calculate distortion for ALF LCU
+ * \param [in] skipLCUBottomLines true for considering skipping bottom LCU lines
+ * \param [in] compIdx luma/chroma component index
+ * \param [in] alfLCUInfo ALF LCU information
+ * \param [in] picSrc source picture buffer
+ * \param [in] picCmp to-be-compared picture buffer
+ * \param [in] stride buffer stride size for 1-D pictrue memory
+ * \param [in] formatShift 0 for luma and 1 for chroma (4:2:0)
+ * \return the distortion
+ */
+Int64 TEncAdaptiveLoopFilter::calcAlfLCUDist(Bool skipLCUBottomLines, Int compIdx, AlfLCUInfo& alfLCUInfo, Pel* picSrc, Pel* picCmp, Int stride, Int formatShift)
+{
+  Int64 dist = 0;  
+  Int  posOffset, ypos, xpos, height, width;
+  Pel* pelCmp;
+  Pel* pelSrc;
+#if LCUALF_AVOID_USING_BOTTOM_LINES_ENCODER || LCUALF_AVOID_USING_RIGHT_LINES_ENCODER
+  Int endypos;
+  Bool notSkipLinesBelowVB = true;
+  Int lcuAddr = alfLCUInfo.pcCU->getAddr();
+  if(skipLCUBottomLines)
+  {
+    if(lcuAddr + m_numLCUInPicWidth < m_uiNumCUsInFrame)
+    {
+      notSkipLinesBelowVB = false;
+    }
+  }
+#endif
+#if LCUALF_AVOID_USING_RIGHT_LINES_ENCODER
+  Bool notSkipLinesRightVB = true;
+  Int endxpos;
+  if(skipLCUBottomLines)
+  {
+    if((lcuAddr + 1) % m_numLCUInPicWidth != 0 )
+    {
+      notSkipLinesRightVB = false;
+    }
+  }
+#endif
+
+  switch(compIdx)
+  {
+  case ALF_Cb:
+  case ALF_Cr:
+    {
+      for(Int n=0; n< alfLCUInfo.numSGU; n++)
+      {
+        ypos    = (Int)(alfLCUInfo[n].posY   >> formatShift);
+        xpos    = (Int)(alfLCUInfo[n].posX   >> formatShift);
+        height  = (Int)(alfLCUInfo[n].height >> formatShift);
+        width   = (Int)(alfLCUInfo[n].width  >> formatShift);
+
+#if LCUALF_AVOID_USING_BOTTOM_LINES_ENCODER
+        if(!notSkipLinesBelowVB )
+        {
+          endypos = ypos+ height -1;
+          Int iLineVBPos = m_lcuHeightChroma - 2;
+          Int yEndLineInLCU = endypos % m_lcuHeightChroma;
+          height = (yEndLineInLCU >= iLineVBPos) ? (height - 2) : height ; 
+        }
+#endif
+#if LCUALF_AVOID_USING_RIGHT_LINES_ENCODER
+        if( !notSkipLinesRightVB)
+        {
+          endxpos = xpos+ width -1;
+          Int iLineVBPos = m_lcuWidthChroma - 7;
+          Int xEndLineInLCU = endxpos % m_lcuWidthChroma;
+          width = (xEndLineInLCU >= iLineVBPos) ? (width - 7) : width ; 
+        }
+#endif
+        posOffset = (ypos * stride) + xpos;
+        pelCmp    = picCmp + posOffset;    
+        pelSrc    = picSrc + posOffset;    
+
+
+        dist  += xCalcSSD( pelSrc, pelCmp,  width, height, stride );
+      }
+
+    }
+    break;
+  case ALF_Y:
+    {
+      for(Int n=0; n< alfLCUInfo.numSGU; n++)
+      {
+        ypos    = (Int)(alfLCUInfo[n].posY);
+        xpos    = (Int)(alfLCUInfo[n].posX);
+        height  = (Int)(alfLCUInfo[n].height);
+        width   = (Int)(alfLCUInfo[n].width);
+
+#if LCUALF_AVOID_USING_BOTTOM_LINES_ENCODER
+        if(!notSkipLinesBelowVB)
+        {
+          endypos = ypos+ height -1;
+          Int iLineVBPos = m_lcuHeight - 4;
+          Int yEndLineInLCU = endypos % m_lcuHeight;
+          height = (yEndLineInLCU >= iLineVBPos) ? (height - 4) : height ; 
+        }
+#endif
+#if LCUALF_AVOID_USING_RIGHT_LINES_ENCODER
+        if( !notSkipLinesRightVB)
+        {
+          endxpos = xpos+ width -1;
+          Int iLineVBPos = m_lcuWidth - 9;
+          Int xEndLineInLCU = endxpos % m_lcuWidth;
+          width = (xEndLineInLCU >= iLineVBPos) ? (width - 9) : width ; 
+        }
+#endif
+        posOffset = (ypos * stride) + xpos;
+        pelCmp    = picCmp + posOffset;    
+        pelSrc    = picSrc + posOffset;    
+
+        dist  += xCalcSSD( pelSrc, pelCmp,  width, height, stride );
+      }
+
+    }
+    break;
+  default:
+    {
+      printf("not a legal component ID for ALF \n");
+      assert(0);
+      exit(-1);
+    }
+  }
+
+  return dist;
+}
+
+/** Copy one ALF LCU region
+ * \param [in] alfLCUInfo ALF LCU information
+ * \param [out] picDst to-be-compared picture buffer
+ * \param [in] picSrc source picture buffer
+ * \param [in] stride buffer stride size for 1-D pictrue memory
+ * \param [in] formatShift 0 for luma and 1 for chroma (4:2:0)
+ */
+Void TEncAdaptiveLoopFilter::copyOneAlfLCU(AlfLCUInfo& alfLCUInfo, Pel* picDst, Pel* picSrc, Int stride, Int formatShift)
+{
+  Int posOffset, ypos, xpos, height, width;
+  Pel* pelDst;
+  Pel* pelSrc;
+
+  for(Int n=0; n< alfLCUInfo.numSGU; n++)
+  {
+    ypos    = (Int)(alfLCUInfo[n].posY   >> formatShift);
+    xpos    = (Int)(alfLCUInfo[n].posX   >> formatShift);
+    height  = (Int)(alfLCUInfo[n].height >> formatShift);
+    width   = (Int)(alfLCUInfo[n].width  >> formatShift);
+
+    posOffset  = ( ypos * stride)+ xpos;
+    pelDst   = picDst  + posOffset;    
+    pelSrc   = picSrc  + posOffset;    
+
+    for(Int j=0; j< height; j++)
+    {
+      ::memcpy(pelDst, pelSrc, sizeof(Pel)*width);
+      pelDst += stride;
+      pelSrc += stride;
+    }
+  }
+
+}
+
+/** Reconstruct ALF LCU pixels
+ * \param [in] compIdx luma/chroma component index
+ * \param [in] alfLCUInfo ALF LCU information
+ * \param [in] alfUnitParam ALF unit parameters
+ * \param [in] picDec picture buffer for un-filtered picture 
+ * \param [out] picRest picture buffer for reconstructed picture
+ * \param [in] stride buffer stride size for 1-D pictrue memory
+ * \param [in] formatShift 0 for luma and 1 for chroma (4:2:0)
+ */
+Void TEncAdaptiveLoopFilter::reconstructOneAlfLCU(Int compIdx, AlfLCUInfo& alfLCUInfo, Bool alfEnabled, ALFParam* alfParam, Pel* picDec, Pel* picRest, Int stride, Int formatShift)
+{
+  Int ypos, xpos, height, width;
+
+  if(alfEnabled)
+  {
+    assert(alfParam->alf_flag == 1);
+
+    //reconstruct ALF coefficients & related parameters 
+    reconstructCoefInfo(compIdx, alfParam, m_filterCoeffSym, m_varIndTab);
+
+    //filtering process
+    for(Int n=0; n< alfLCUInfo.numSGU; n++)
+    {
+      ypos    = (Int)(alfLCUInfo[n].posY   >> formatShift);
+      xpos    = (Int)(alfLCUInfo[n].posX   >> formatShift);
+      height  = (Int)(alfLCUInfo[n].height >> formatShift);
+      width   = (Int)(alfLCUInfo[n].width  >> formatShift);
+
+      filterOneCompRegion(picRest, picDec, stride, (compIdx!=ALF_Y), ypos, ypos+height, xpos, xpos+width, m_filterCoeffSym, m_varIndTab, m_varImg);
+    }
+  }
+  else
+  {
+    copyOneAlfLCU(alfLCUInfo, picRest, picDec, stride, formatShift);
+  }
+}
+
+/** LCU-based mode decision
+ * \param [in, out] alfParamSet ALF parameter set
+ * \param [in] compIdx luma/chroma component index
+ * \param [in] pOrg picture buffer for original picture
+ * \param [in] pDec picture buffer for un-filtered picture 
+ * \param [out] pRest picture buffer for reconstructed picture
+ * \param [in] stride buffer stride size for 1-D pictrue memory
+ * \param [in] formatShift 0 for luma and 1 for chroma (4:2:0)
+ * \param [in] alfCorrLCUs correlations for LCUs
+ */
+Void TEncAdaptiveLoopFilter::executeLCUOnOffDecision(Int compIdx, ALFParam* alfParam, Pel* pOrg, Pel* pDec, Pel* pRest, Int stride, Int formatShift,AlfCorrData** alfCorrLCUs)
+{
+  Double lambda = (compIdx == ALF_Y)?(m_dLambdaLuma):(m_dLambdaChroma);
+  static Int* isProcessed = NULL;
+
+  Int64  distEnc, distOff;
+  Int    rateEnc, rateOff;
+  Double costEnc, costOff;
+  isProcessed = new Int[m_uiNumCUsInFrame];
+  ::memset(isProcessed, 0, sizeof(Int)*m_uiNumCUsInFrame);
+
+  //reset LCU enabled flags
+  for(Int i=0; i< m_uiNumCUsInFrame; i++)
+  {
+    m_pcPic->getCU(i)->setAlfLCUEnabled(false, compIdx);
+  }
+  for(Int s=0; s<= m_lastSliceIdx; s++)
+  {
+    if(!m_pcPic->getValidSlice(s))
+    {
+      continue;
+    }
+    Int numTilesInSlice = (Int)m_pvpSliceTileAlfLCU[s].size();
+    for(Int t=0; t< numTilesInSlice; t++)
+    {
+      std::vector<AlfLCUInfo*> & vpAlfLCU = m_pvpSliceTileAlfLCU[s][t];
+      Pel* pSrc = pDec;
+
+      if(m_bUseNonCrossALF)
+      {
+        pSrc = getPicBuf(m_pcSliceYuvTmp, compIdx);
+        copyRegion(vpAlfLCU, pSrc, pDec, stride, formatShift);
+        extendRegionBorder(vpAlfLCU, pSrc, stride, formatShift);
+      }
+
+      Int numLCUs = (Int)vpAlfLCU.size();
+      for(Int n=0; n< numLCUs; n++)
+      {
+        AlfLCUInfo*   alfLCU       = vpAlfLCU[n];                  //ALF LCU information
+        TComDataCU*   pcCU         = alfLCU->pcCU;
+        Int           addr         = pcCU->getAddr();              //real LCU addr
+        if(isProcessed[addr] == 0)
+        {
+          Bool lcuAlfDisabled = true;
+          if(alfParam->alf_flag == 1)
+          {
+            //ALF on
+            reconstructOneAlfLCU(compIdx, *alfLCU, true, alfParam, pSrc, pRest, stride, formatShift);
+            distEnc = calcAlfLCUDist(m_alfLowLatencyEncoding, compIdx, *alfLCU, pOrg, pRest, stride, formatShift);
+            rateEnc = 1;
+            costEnc = (Double)distEnc + lambda*((Double)rateEnc);
+            costEnc += ((lambda* 1.5)*1.0);  //RDCO
+
+            //ALF off
+            distOff = calcAlfLCUDist(m_alfLowLatencyEncoding, compIdx, *alfLCU, pOrg, pSrc, stride, formatShift);
+            rateOff = 1;
+            costOff = (Double)distOff + lambda*((Double)rateOff);
+
+            lcuAlfDisabled = (costOff < costEnc);
+
+            pcCU->setAlfLCUEnabled( (lcuAlfDisabled?0:1) , compIdx);
+          }
+
+          if(lcuAlfDisabled)
+          {
+            copyOneAlfLCU(*alfLCU, pRest, pSrc, stride, formatShift);
+          }
+        }
+        else
+        {
+          reconstructOneAlfLCU(compIdx, *alfLCU, pcCU->getAlfLCUEnabled(compIdx), alfParam, pSrc, pRest, stride, formatShift);
+        }
+      } //LCU
+    } //tile
+
+  } //slice
+
+
+  delete[] isProcessed;
+  isProcessed = NULL;
+}
+
+Int TEncAdaptiveLoopFilter::getTemporalLayerNo(Int poc, Int picDistance)
+{
+  Int layer = 0;
+  while(picDistance > 0)
+  {
+    if(poc % picDistance == 0)
+    {
+      break;
+    }
+    picDistance = (Int)(picDistance/2);
+    layer++;
+  }
+  return layer;
+}
+
+Void TEncAdaptiveLoopFilter::setCurAlfParam(ALFParam** alfPictureParam)
+{
+  if(m_alfLowLatencyEncoding)
+  {
+    Int temporalLayer = getTemporalLayerNo(m_pcPic->getPOC(), m_gopSize);
+    for(Int compIdx=0; compIdx< 3; compIdx++)
+    {
+      *(alfPictureParam[compIdx]) = *(m_alfPictureParam[temporalLayer][compIdx]);
+    }
+  }
+  else
+  {
+    decideAlfPictureParam(alfPictureParam, true);
+    estimateLcuControl(alfPictureParam);
+    decideAlfPictureParam(alfPictureParam, false);    
+  }
+}
+
+Void TEncAdaptiveLoopFilter::decideAlfPictureParam(ALFParam** alfPictureParam, Bool useAllLCUs)
+{
+  AlfCorrData*** lcuCorr = (m_alfLowLatencyEncoding?m_alfNonSkippedCorr:m_alfCorr);
+  for(Int compIdx =0; compIdx < NUM_ALF_COMPONENT; compIdx++)
+  {
+    Double      lambda   = ((compIdx == ALF_Y)?m_dLambdaLuma:m_dLambdaChroma)*1.5;
+    ALFParam *alfParam   = alfPictureParam[compIdx];
+    AlfCorrData* picCorr = new AlfCorrData(compIdx);
+
+    if(!useAllLCUs)
+    {
+      Int numStatLCU =0;
+      for(Int addr=0; addr < m_uiNumCUsInFrame; addr++)
+      {
+        if(m_pcPic->getCU(addr)->getAlfLCUEnabled(compIdx))
+        {
+          numStatLCU++;
+          break;
+        }
+      }
+      if(numStatLCU ==0)
+      {
+        useAllLCUs = true;
+      }
+    }
+
+    for(Int addr=0; addr< (Int)m_uiNumCUsInFrame; addr++)
+    {
+      if(useAllLCUs || (m_pcPic->getCU(addr)->getAlfLCUEnabled(compIdx)) )
+      {
+        *picCorr += *(lcuCorr[compIdx][addr]);
+      }
+    }
+
+    Int64 offDist = estimateFilterDistortion(compIdx, picCorr);
+    alfParam->alf_flag = 1;
+    deriveFilterInfo(compIdx, picCorr, alfParam, NO_VAR_BINS, lambda);
+    Int64 dist = estimateFilterDistortion(compIdx, picCorr, m_filterCoeffSym, alfParam->filters_per_group, m_varIndTab, false);
+    UInt rate = ALFParamBitrateEstimate(alfParam);
+    Double cost = dist - offDist + lambda * rate;
+    if(cost >= 0)
+    {
+      alfParam->alf_flag = 0;
+    }
+    delete picCorr;
+  }
+}
+
+Void TEncAdaptiveLoopFilter::estimateLcuControl(ALFParam** alfPictureParam)
+{
+  for(Int compIdx = 0; compIdx < NUM_ALF_COMPONENT; compIdx++)
+  {
+    if(alfPictureParam[compIdx]->alf_flag == 1)
+    {
+      reconstructCoefInfo(compIdx, alfPictureParam[compIdx], m_filterCoeffSym, m_varIndTab);
+      for(Int addr = 0; addr < m_uiNumCUsInFrame; addr++)
+      {
+        Int64 offDist = estimateFilterDistortion(compIdx, m_alfCorr[compIdx][addr]);
+        Int64 dist    = estimateFilterDistortion(compIdx, m_alfCorr[compIdx][addr], m_filterCoeffSym, alfPictureParam[compIdx]->filters_per_group, m_varIndTab, false);
+        m_pcPic->getCU(addr)->setAlfLCUEnabled( ((offDist <= dist)?0:1) , compIdx);
+      }
+    }
+  }
+}
+
+/** Decide ALF parameter set for luma/chroma components (top function) 
+ * \param [in] pPicOrg picture buffer for original picture
+ * \param [in] pPicDec picture buffer for un-filtered picture 
+ * \param [out] pPicRest picture buffer for reconstructed picture
+ * \param [in, out] alfParamSet ALF parameter set
+ * \param [in, out] alfCtrlParam ALF CU-on/off control parameters
+ */
+Void TEncAdaptiveLoopFilter::decideParameters(ALFParam** alfPictureParam, TComPicYuv* pPicOrg, TComPicYuv* pPicDec, TComPicYuv* pPicRest)
+{
+  static Int lumaStride        = pPicOrg->getStride();
+  static Int chromaStride      = pPicOrg->getCStride();
+
+  Pel *pOrg, *pDec, *pRest;
+  Int stride, formatShift;
+
+  setCurAlfParam(alfPictureParam);
+  for(Int compIdx = 0; compIdx < NUM_ALF_COMPONENT; compIdx++)
+  {
+    pOrg        = getPicBuf(pPicOrg, compIdx);
+    pDec        = getPicBuf(pPicDec, compIdx);
+    pRest       = getPicBuf(pPicRest, compIdx);
+    stride      = (compIdx == ALF_Y)?(lumaStride):(chromaStride);
+    formatShift = (compIdx == ALF_Y)?(0):(1);
+
+    AlfCorrData** alfCorrComp     = m_alfCorr[compIdx];
+    executeLCUOnOffDecision(compIdx, alfPictureParam[compIdx], pOrg, pDec, pRest, stride, formatShift, alfCorrComp);
+  } //component
+
+}
+
+/** Gather correlations for all LCUs in picture
+ * \param [in] pPicOrg picture buffer for original picture
+ * \param [in] pPicDec picture buffer for un-filtered picture 
+ */
+Void TEncAdaptiveLoopFilter::getStatistics(TComPicYuv* pPicOrg, TComPicYuv* pPicDec)
+{
+  Int lumaStride   = pPicOrg->getStride();
+  Int chromaStride = pPicOrg->getCStride();
+  const  Int chromaFormatShift = 1;
+  for(Int compIdx = 0; compIdx < NUM_ALF_COMPONENT; compIdx++)
+  {
+    AlfCorrData** alfCorrComp = m_alfCorr[compIdx];
+    Int          formatShift = (compIdx == ALF_Y)?(0):(chromaFormatShift);
+    Int          stride      = (compIdx == ALF_Y)?(lumaStride):(chromaStride);
+    getOneCompStatistics(alfCorrComp, compIdx, getPicBuf(pPicOrg, compIdx), getPicBuf(pPicDec, compIdx), stride, formatShift);
+  } 
+}
+
+/** Gather correlations for all LCUs of one luma/chroma component in picture
+ * \param [out] alfCorrComp correlations for LCUs
+ * \param [in] compIdx luma/chroma component index
+ * \param [in] imgOrg picture buffer for original picture
+ * \param [in] imgDec picture buffer for un-filtered picture 
+ * \param [in] stride buffer stride size for 1-D pictrue memory
+ * \param [in] formatShift 0 for luma and 1 for chroma (4:2:0)
+ * \param [in] isRedesignPhase at re-design filter stage (true) or not (false)
+ */
+Void TEncAdaptiveLoopFilter::getOneCompStatistics(AlfCorrData** alfCorrComp, Int compIdx, Pel* imgOrg, Pel* imgDec, Int stride, Int formatShift)
+{
+
+  // initialize to zero
+  for(Int n=0; n< m_uiNumCUsInFrame; n++)
+  {
+    alfCorrComp[n]->reset();
+    if(m_alfLowLatencyEncoding)
+    {
+      m_alfNonSkippedCorr[compIdx][n]->reset();
+    }
+  }
+
+  for(Int s=0; s<= m_lastSliceIdx; s++)
+  {
+    if(!m_pcPic->getValidSlice(s))
+    {
+      continue;
+    }
+    Int numTilesInSlice = (Int)m_pvpSliceTileAlfLCU[s].size();
+    for(Int t=0; t< numTilesInSlice; t++)
+    {
+      std::vector<AlfLCUInfo*> & vpAlfLCU = m_pvpSliceTileAlfLCU[s][t];
+      Pel* pSrc = imgDec;
+
+      if(m_bUseNonCrossALF)
+      {
+        pSrc = getPicBuf(m_pcSliceYuvTmp, compIdx);
+        copyRegion(vpAlfLCU, pSrc, imgDec, stride, formatShift);
+        extendRegionBorder(vpAlfLCU, pSrc, stride, formatShift);
+      }
+
+      Int numLCUs = (Int)vpAlfLCU.size();
+      for(Int n=0; n< numLCUs; n++)
+      {
+        AlfLCUInfo* alfLCU = vpAlfLCU[n];
+        Int addr = alfLCU->pcCU->getAddr();
+        getStatisticsOneLCU(m_alfLowLatencyEncoding, compIdx, alfLCU, alfCorrComp[addr], imgOrg, pSrc, stride, formatShift);
+        if(m_alfLowLatencyEncoding)
+        {
+          getStatisticsOneLCU( false, compIdx, alfLCU, m_alfNonSkippedCorr[compIdx][addr], imgOrg, pSrc, stride, formatShift);
+        }
+      } //LCU
+    } //tile
+  } //slice
+
+}
+
+/** Gather correlations for one LCU
+ * \param [out] alfCorrComp correlations for LCUs
+ * \param [in] compIdx luma/chroma component index
+ * \param [in] imgOrg picture buffer for original picture
+ * \param [in] imgDec picture buffer for un-filtered picture 
+ * \param [in] stride buffer stride size for 1-D pictrue memory
+ * \param [in] formatShift 0 for luma and 1 for chroma (4:2:0)
+ * \param [in] isRedesignPhase at re-design filter stage (true) or not (false)
+ */
+Void TEncAdaptiveLoopFilter::getStatisticsOneLCU(Bool skipLCUBottomLines, Int compIdx, AlfLCUInfo* alfLCU, AlfCorrData* alfCorr, Pel* pPicOrg, Pel* pPicSrc, Int stride, Int formatShift)
+{
+  Int numBlocks = alfLCU->numSGU;
+#if LCUALF_AVOID_USING_BOTTOM_LINES_ENCODER || LCUALF_AVOID_USING_RIGHT_LINES_ENCODER
+  Int  lcuAddr = alfLCU->pcCU->getAddr();
+  Bool notSkipLinesBelowVB = true;
+  Int  endypos;
+#endif
+#if LCUALF_AVOID_USING_RIGHT_LINES_ENCODER
+  Bool notSkipLinesRightVB = true;
+  Int endxpos;
+#endif
+  Bool isLastBlock;
+  Int ypos, xpos, height, width;
+
+#if LCUALF_AVOID_USING_BOTTOM_LINES_ENCODER
+  if(skipLCUBottomLines)
+  {
+    if(lcuAddr + m_numLCUInPicWidth < m_uiNumCUsInFrame)
+    {
+      notSkipLinesBelowVB = false;
+    }
+  }
+#endif
+#if LCUALF_AVOID_USING_RIGHT_LINES_ENCODER
+  if(skipLCUBottomLines)
+  {
+    if((lcuAddr + 1) % m_numLCUInPicWidth != 0 )
+    {
+      notSkipLinesRightVB = false;
+    }
+  }
+#endif
+  switch(compIdx)
+  {
+  case ALF_Cb:
+  case ALF_Cr:
+    {
+      for(Int n=0; n< numBlocks; n++)
+      {
+        isLastBlock = (n== numBlocks-1);
+        NDBFBlockInfo& AlfSGU = (*alfLCU)[n];
+
+        ypos   = (Int)(AlfSGU.posY  >> formatShift);
+        xpos   = (Int)(AlfSGU.posX  >> formatShift);
+        height = (Int)(AlfSGU.height>> formatShift);
+        width  = (Int)(AlfSGU.width >> formatShift);
+
+#if LCUALF_AVOID_USING_BOTTOM_LINES_ENCODER
+        if(!notSkipLinesBelowVB )
+        {
+          endypos = ypos+ height -1;
+          Int iLineVBPos = m_lcuHeightChroma - 2;
+          Int yEndLineInLCU = endypos % m_lcuHeightChroma;
+          height = (yEndLineInLCU >= iLineVBPos) ? (height - 2) : height ; 
+        }
+#endif
+#if LCUALF_AVOID_USING_RIGHT_LINES_ENCODER
+        if( !notSkipLinesRightVB)
+        {
+          endxpos = xpos+ width -1;
+          Int iLineVBPos = m_lcuWidthChroma - 7;
+          Int xEndLineInLCU = endxpos % m_lcuWidthChroma;
+          width = (xEndLineInLCU >= iLineVBPos) ? (width - 7) : width ; 
+        }
+#endif
+        calcCorrOneCompRegionChma(pPicOrg, pPicSrc, stride, ypos, xpos, height, width, alfCorr->ECorr[0], alfCorr->yCorr[0], isLastBlock);
+      }
+    }
+    break;
+  case ALF_Y:
+    {
+      for(Int n=0; n< numBlocks; n++)
+      {
+        isLastBlock = (n== numBlocks-1);
+        NDBFBlockInfo& AlfSGU = (*alfLCU)[n];
+
+        ypos   = (Int)(AlfSGU.posY  );
+        xpos   = (Int)(AlfSGU.posX  );
+        height = (Int)(AlfSGU.height);
+        width  = (Int)(AlfSGU.width );
+
+#if LCUALF_AVOID_USING_BOTTOM_LINES_ENCODER
+        endypos = ypos+ height -1;
+        if(!notSkipLinesBelowVB)
+        {
+          Int iLineVBPos = m_lcuHeight - 4;
+          Int yEndLineInLCU = endypos % m_lcuHeight;
+          height = (yEndLineInLCU >= iLineVBPos) ? (height - 4) : height ; 
+        }
+#endif
+#if LCUALF_AVOID_USING_RIGHT_LINES_ENCODER
+        if( !notSkipLinesRightVB)
+        {
+          endxpos = xpos+ width -1;
+          Int iLineVBPos = m_lcuWidth - 9;
+          Int xEndLineInLCU = endxpos % m_lcuWidth;
+          width = (xEndLineInLCU >= iLineVBPos) ? (width - 9) : width ; 
+        }
+#endif
+        calcCorrOneCompRegionLuma(pPicOrg, pPicSrc, stride, ypos, xpos, height, width, alfCorr->ECorr, alfCorr->yCorr, alfCorr->pixAcc, isLastBlock);
+      }
+    }
+    break;
+  default:
+    {
+      printf("Not a legal component index for ALF\n");
+      assert(0);
+      exit(-1);
+    }
+  }
+}
+
+
+/** Gather correlations for one region for chroma component
+ * \param [in] imgOrg picture buffer for original picture
+ * \param [in] imgPad picture buffer for un-filtered picture 
+ * \param [in] stride buffer stride size for 1-D pictrue memory
+ * \param [in] yPos region starting y position
+ * \param [in] xPos region starting x position
+ * \param [in] height region height
+ * \param [in] width region width
+ * \param [out] eCorr auto-correlation matrix
+ * \param [out] yCorr cross-correlation array
+ * \param [in] isSymmCopyBlockMatrix symmetrically copy correlation values in eCorr (true) or not (false)
+ */
+Void TEncAdaptiveLoopFilter::calcCorrOneCompRegionChma(Pel* imgOrg, Pel* imgPad, Int stride 
+                                                     , Int yPos, Int xPos, Int height, Int width
+                                                     , Double **eCorr, Double *yCorr, Bool isSymmCopyBlockMatrix
+                                                      )
+{
+  Int yPosEnd = yPos + height;
+  Int xPosEnd = xPos + width;
+  Int N = ALF_MAX_NUM_COEF; //m_sqrFiltLengthTab[0];
+
+  Int imgHeightChroma = m_img_height>>1;
+
+  Int yLineInLCU, paddingLine;
+  Int ELocal[ALF_MAX_NUM_COEF];
+  Pel *imgPad1, *imgPad2, *imgPad3, *imgPad4, *imgPad5, *imgPad6;
+  Int i, j, k, l, yLocal;
+
+  imgPad += (yPos*stride);
+  imgOrg += (yPos*stride);
+
+  for (i= yPos; i< yPosEnd; i++)
+  {
+    yLineInLCU = i % m_lcuHeightChroma;
+
+    if (yLineInLCU==0 && i>0)
+    {
+      paddingLine = yLineInLCU + 2 ;
+      imgPad1 = imgPad + stride;
+      imgPad2 = imgPad - stride;
+      imgPad3 = imgPad + 2*stride;
+      imgPad4 = imgPad - 2*stride;
+      imgPad5 = (paddingLine < 3) ? imgPad : imgPad + 3*stride;
+      imgPad6 = (paddingLine < 3) ? imgPad : imgPad - min(paddingLine, 3)*stride;;
+    }
+    else if (yLineInLCU < m_lineIdxPadBotChroma || i-yLineInLCU+m_lcuHeightChroma >= imgHeightChroma )
+    {
+      imgPad1 = imgPad + stride;
+      imgPad2 = imgPad - stride;
+      imgPad3 = imgPad + 2*stride;
+      imgPad4 = imgPad - 2*stride;
+      imgPad5 = imgPad + 3*stride;
+      imgPad6 = imgPad - 3*stride;
+    }
+    else if (yLineInLCU < m_lineIdxPadTopChroma)
+    {
+      paddingLine = - yLineInLCU + m_lineIdxPadTopChroma - 1;
+      imgPad1 = (paddingLine < 1) ? imgPad : imgPad + min(paddingLine, 1)*stride;
+      imgPad2 = (paddingLine < 1) ? imgPad : imgPad - stride;
+      imgPad3 = (paddingLine < 2) ? imgPad : imgPad + min(paddingLine, 2)*stride;
+      imgPad4 = (paddingLine < 2) ? imgPad : imgPad - 2*stride;
+      imgPad5 = (paddingLine < 3) ? imgPad : imgPad + min(paddingLine, 3)*stride;
+      imgPad6 = (paddingLine < 3) ? imgPad : imgPad - 3*stride;
+    }
+    else
+    {
+      paddingLine = yLineInLCU - m_lineIdxPadTopChroma ;
+      imgPad1 = (paddingLine < 1) ? imgPad : imgPad + stride;
+      imgPad2 = (paddingLine < 1) ? imgPad : imgPad - min(paddingLine, 1)*stride;
+      imgPad3 = (paddingLine < 2) ? imgPad : imgPad + 2*stride;
+      imgPad4 = (paddingLine < 2) ? imgPad : imgPad - min(paddingLine, 2)*stride;
+      imgPad5 = (paddingLine < 3) ? imgPad : imgPad + 3*stride;
+      imgPad6 = (paddingLine < 3) ? imgPad : imgPad - min(paddingLine, 3)*stride;
+    }
+
+    for (j= xPos; j< xPosEnd; j++)
+    {
+      memset(ELocal, 0, N*sizeof(Int));
+
+      ELocal[0] = (imgPad5[j] + imgPad6[j]);
+
+      ELocal[1] = (imgPad3[j] + imgPad4[j]);
+
+      ELocal[2] = (imgPad1[j+1] + imgPad2[j-1]);
+      ELocal[3] = (imgPad1[j  ] + imgPad2[j  ]);
+      ELocal[4] = (imgPad1[j-1] + imgPad2[j+1]);
+
+      ELocal[5] = (imgPad[j+4] + imgPad[j-4]);
+      ELocal[6] = (imgPad[j+3] + imgPad[j-3]);
+      ELocal[7] = (imgPad[j+2] + imgPad[j-2]);
+      ELocal[8] = (imgPad[j+1] + imgPad[j-1]);
+      ELocal[9] = (imgPad[j  ]);
+
+      yLocal= (Int)imgOrg[j];
+
+      for(k=0; k<N; k++)
+      {
+        eCorr[k][k] += ELocal[k]*ELocal[k];
+        for(l=k+1; l<N; l++)
+        {
+          eCorr[k][l] += ELocal[k]*ELocal[l];
+        }
+
+        yCorr[k] += yLocal*ELocal[k];
+      }
+    }
+
+    imgPad+= stride;
+    imgOrg+= stride;
+  }
+
+  if(isSymmCopyBlockMatrix)
+  {
+    for(j=0; j<N-1; j++)
+    {
+      for(i=j+1; i<N; i++)
+      {
+        eCorr[i][j] = eCorr[j][i];
+      }
+    }
+  }
+}
+
+/** Gather correlations for one region for luma component
+ * \param [in] imgOrg picture buffer for original picture
+ * \param [in] imgPad picture buffer for un-filtered picture 
+ * \param [in] stride buffer stride size for 1-D pictrue memory
+ * \param [in] yPos region starting y position
+ * \param [in] xPos region starting x position
+ * \param [in] height region height
+ * \param [in] width region width
+ * \param [out] eCorr auto-correlation matrix
+ * \param [out] yCorr cross-correlation array
+ * \param [out] pixAcc pixel squared value
+ * \param [in] isforceCollection all pixel are used for correlation calculation (true) or not (false)
+ * \param [in] isSymmCopyBlockMatrix symmetrically copy correlation values in eCorr (true) or not (false)
+ */
+Void TEncAdaptiveLoopFilter::calcCorrOneCompRegionLuma(Pel* imgOrg, Pel* imgPad, Int stride,Int yPos, Int xPos, Int height, Int width
+                                                      ,Double ***eCorr, Double **yCorr, Double *pixAcc
+                                                      ,Bool isSymmCopyBlockMatrix
+                                                      )
+
+{
+  Int yPosEnd = yPos + height;
+  Int xPosEnd = xPos + width;
+  Int yLineInLCU;
+  Int paddingLine ;
+  Int N = ALF_MAX_NUM_COEF; //m_sqrFiltLengthTab[0];
+
+  Int ELocal[ALF_MAX_NUM_COEF];
+  Pel *imgPad1, *imgPad2, *imgPad3, *imgPad4, *imgPad5, *imgPad6;
+  Int i, j, k, l, yLocal, varInd;
+  Double **E;
+  Double *yy;
+
+  imgPad += (yPos*stride);
+  imgOrg += (yPos*stride);
+
+  for (i= yPos; i< yPosEnd; i++)
+  {
+    yLineInLCU = i % m_lcuHeight;
+
+    if (yLineInLCU<m_lineIdxPadBot || i-yLineInLCU+m_lcuHeight >= m_img_height)
+    {
+      imgPad1 = imgPad + stride;
+      imgPad2 = imgPad - stride;
+      imgPad3 = imgPad + 2*stride;
+      imgPad4 = imgPad - 2*stride;
+      imgPad5 = imgPad + 3*stride;
+      imgPad6 = imgPad - 3*stride;
+    }
+    else if (yLineInLCU<m_lineIdxPadTop)
+    {
+      paddingLine = - yLineInLCU + m_lineIdxPadTop - 1;
+      imgPad1 = (paddingLine < 1) ? imgPad : imgPad + min(paddingLine, 1)*stride;
+      imgPad2 = (paddingLine < 1) ? imgPad : imgPad - stride;
+      imgPad3 = (paddingLine < 2) ? imgPad : imgPad + min(paddingLine, 2)*stride;
+      imgPad4 = (paddingLine < 2) ? imgPad : imgPad - 2*stride;
+      imgPad5 = (paddingLine < 3) ? imgPad : imgPad + min(paddingLine, 3)*stride;
+      imgPad6 = (paddingLine < 3) ? imgPad : imgPad - 3*stride;
+    }
+    else
+    {
+      paddingLine = yLineInLCU - m_lineIdxPadTop;
+      imgPad1 = (paddingLine < 1) ? imgPad : imgPad + stride;
+      imgPad2 = (paddingLine < 1) ? imgPad : imgPad - min(paddingLine, 1)*stride;
+      imgPad3 = (paddingLine < 2) ? imgPad : imgPad + 2*stride;
+      imgPad4 = (paddingLine < 2) ? imgPad : imgPad - min(paddingLine, 2)*stride;
+      imgPad5 = (paddingLine < 3) ? imgPad : imgPad + 3*stride;
+      imgPad6 = (paddingLine < 3) ? imgPad : imgPad - min(paddingLine, 3)*stride;
+    }         
+
+    for (j= xPos; j< xPosEnd; j++)
+    {
+        varInd = m_varImg[i/VAR_SIZE_H][j/VAR_SIZE_W];
+        memset(ELocal, 0, N*sizeof(Int));
+
+        ELocal[0] = (imgPad5[j] + imgPad6[j]);
+        ELocal[1] = (imgPad3[j] + imgPad4[j]);
+
+        ELocal[2] = (imgPad1[j+1] + imgPad2[j-1]);
+        ELocal[3] = (imgPad1[j  ] + imgPad2[j  ]);
+        ELocal[4] = (imgPad1[j-1] + imgPad2[j+1]);
+
+        ELocal[5] = (imgPad[j+4] + imgPad[j-4]);
+        ELocal[6] = (imgPad[j+3] + imgPad[j-3]);
+        ELocal[7] = (imgPad[j+2] + imgPad[j-2]);
+        ELocal[8] = (imgPad[j+1] + imgPad[j-1]);
+        ELocal[9] = (imgPad[j  ]);
+
+        yLocal= imgOrg[j];
+        pixAcc[varInd] += (yLocal*yLocal);
+        E  = eCorr[varInd];
+        yy = yCorr[varInd];
+
+        for (k=0; k<N; k++)
+        {
+          for (l=k; l<N; l++)
+          {
+            E[k][l]+=(double)(ELocal[k]*ELocal[l]);
+          }
+          yy[k]+=(double)(ELocal[k]*yLocal);
+        }
+    }
+    imgPad += stride;
+    imgOrg += stride;
+  }
+
+  if(isSymmCopyBlockMatrix)
+  {
+    for (varInd=0; varInd<NO_VAR_BINS; varInd++)
+    {
+      E = eCorr[varInd];
+      for (k=1; k<N; k++)
+      {
+        for (l=0; l<k; l++)
+        {
+          E[k][l] = E[l][k];
+        }
+      }
+    }
+  }
+
+}
+
+/** PCM LF disable process.
+ * \param pcPic picture (TComPic) pointer
+ * \returns Void
+ *
+ * \note Replace filtered sample values of PCM mode blocks with the transmitted and reconstructed ones.
+ */
+Void TEncAdaptiveLoopFilter::PCMLFDisableProcess (TComPic* pcPic)
+{
+  xPCMRestoration(pcPic);
+}
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+// ====================================================================================================================
+// Private member functions
+// ====================================================================================================================
+
+#if IBDI_DISTORTION
+UInt64 TEncAdaptiveLoopFilter::xCalcSSD(Pel* pOrg, Pel* pCmp, Int iWidth, Int iHeight, Int iStride )
+{
+  UInt64 uiSSD = 0;
+  Int x, y;
+
+  Int iShift = g_uiBitIncrement;
+  Int iOffset = (g_uiBitIncrement>0)? (1<<(g_uiBitIncrement-1)):0;
+  Int iTemp;
+
+  for( y = 0; y < iHeight; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+      iTemp = ((pOrg[x]+iOffset)>>iShift) - ((pCmp[x]+iOffset)>>iShift); uiSSD += iTemp * iTemp;
+    }
+    pOrg += iStride;
+    pCmp += iStride;
+  }
+
+  return uiSSD;;
+}
+#else
+UInt64 TEncAdaptiveLoopFilter::xCalcSSD(Pel* pOrg, Pel* pCmp, Int iWidth, Int iHeight, Int iStride )
+{
+  UInt64 uiSSD = 0;
+  Int x, y;
+  
+  UInt uiShift = g_uiBitIncrement<<1;
+  Int iTemp;
+  
+  for( y = 0; y < iHeight; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+      iTemp = pOrg[x] - pCmp[x]; uiSSD += ( iTemp * iTemp ) >> uiShift;
+    }
+    pOrg += iStride;
+    pCmp += iStride;
+  }
+  
+  return uiSSD;;
+}
+#endif
+
+Int TEncAdaptiveLoopFilter::xGauss(Double **a, Int N)
+{
+  Int i, j, k;
+  Double t;
+  
+  for(k=0; k<N; k++)
+  {
+    if (a[k][k] <0.000001)
+    {
+      return 1;
+    }
+  }
+  
+  for(k=0; k<N-1; k++)
+  {
+    for(i=k+1;i<N; i++)
+    {
+      t=a[i][k]/a[k][k];
+      for(j=k+1; j<=N; j++)
+      {
+        a[i][j] -= t * a[k][j];
+        if(i==j && fabs(a[i][j])<0.000001) return 1;
+      }
+    }
+  }
+  for(i=N-1; i>=0; i--)
+  {
+    t = a[i][N];
+    for(j=i+1; j<N; j++)
+    {
+      t -= a[i][j] * a[j][N];
+    }
+    a[i][N] = t / a[i][i];
+  }
+  return 0;
+}
+
+Void TEncAdaptiveLoopFilter::xFilterCoefQuickSort( Double *coef_data, Int *coef_num, Int upper, Int lower )
+{
+  Double mid, tmp_data;
+  Int i, j, tmp_num;
+  
+  i = upper;
+  j = lower;
+  mid = coef_data[(lower+upper)>>1];
+  do
+  {
+    while( coef_data[i] < mid ) i++;
+    while( mid < coef_data[j] ) j--;
+    if( i <= j )
+    {
+      tmp_data = coef_data[i];
+      tmp_num  = coef_num[i];
+      coef_data[i] = coef_data[j];
+      coef_num[i]  = coef_num[j];
+      coef_data[j] = tmp_data;
+      coef_num[j]  = tmp_num;
+      i++;
+      j--;
+    }
+  } while( i <= j );
+  if ( upper < j ) 
+  {
+    xFilterCoefQuickSort(coef_data, coef_num, upper, j);
+  }
+  if ( i < lower ) 
+  {
+    xFilterCoefQuickSort(coef_data, coef_num, i, lower);
+  }
+}
+
+Void TEncAdaptiveLoopFilter::xQuantFilterCoef(Double* h, Int* qh, Int tap, int bit_depth)
+{
+  Int i, N;
+  Int max_value, min_value;
+  Double dbl_total_gain;
+  Int total_gain, q_total_gain;
+  Int upper, lower;
+  Double *dh;
+  Int    *nc;
+  const Int    *pFiltMag;
+  N = (Int)ALF_MAX_NUM_COEF;
+  pFiltMag = weightsShape1Sym;
+
+  dh = new Double[N];
+  nc = new Int[N];
+  max_value =   (1<<(1+ALF_NUM_BIT_SHIFT))-1;
+  min_value = 0-(1<<(1+ALF_NUM_BIT_SHIFT));
+  dbl_total_gain=0.0;
+  q_total_gain=0;
+  for(i=0; i<N; i++)
+  {
+    if(h[i]>=0.0)
+    {
+      qh[i] =  (Int)( h[i]*(1<<ALF_NUM_BIT_SHIFT)+0.5);
+    }
+    else
+    {
+      qh[i] = -(Int)(-h[i]*(1<<ALF_NUM_BIT_SHIFT)+0.5);
+    }
+    dh[i] = (Double)qh[i]/(Double)(1<<ALF_NUM_BIT_SHIFT) - h[i];
+    dh[i]*=pFiltMag[i];
+    dbl_total_gain += h[i]*pFiltMag[i];
+    q_total_gain   += qh[i]*pFiltMag[i];
+    nc[i] = i;
+  }
+  
+  // modification of quantized filter coefficients
+  total_gain = (Int)(dbl_total_gain*(1<<ALF_NUM_BIT_SHIFT)+0.5);
+  if( q_total_gain != total_gain )
+  {
+    xFilterCoefQuickSort(dh, nc, 0, N-1);
+    if( q_total_gain > total_gain )
+    {
+      upper = N-1;
+      while( q_total_gain > total_gain+1 )
+      {
+        i = nc[upper%N];
+        qh[i]--;
+        q_total_gain -= pFiltMag[i];
+        upper--;
+      }
+      if( q_total_gain == total_gain+1 )
+      {
+        if(dh[N-1]>0)
+        {
+          qh[N-1]--;
+        }
+        else
+        {
+          i=nc[upper%N];
+          qh[i]--;
+          qh[N-1]++;
+        }
+      }
+    }
+    else if( q_total_gain < total_gain )
+    {
+      lower = 0;
+      while( q_total_gain < total_gain-1 )
+      {
+        i=nc[lower%N];
+        qh[i]++;
+        q_total_gain += pFiltMag[i];
+        lower++;
+      }
+      if( q_total_gain == total_gain-1 )
+      {
+        if(dh[N-1]<0)
+        {
+          qh[N-1]++;
+        }
+        else
+        {
+          i=nc[lower%N];
+          qh[i]++;
+          qh[N-1]--;
+        }
+      }
+    }
+  }
+  
+  // set of filter coefficients
+  for(i=0; i<N; i++)
+  {
+    qh[i] = max(min_value,min(max_value, qh[i]));
+  }
+
+  checkFilterCoeffValue(qh, N, true);
+
+  delete[] dh;
+  dh = NULL;
+  
+  delete[] nc;
+  nc = NULL;
+}
+
+
+double TEncAdaptiveLoopFilter::xfindBestCoeffCodMethod(int **filterCoeffSymQuant, int filter_shape, int sqrFiltLength, int filters_per_fr, double errorForce0CoeffTab[NO_VAR_BINS][2], 
+  double lambda)
+{
+  Int coeffBits, i;
+  Double error=0, lagrangian;
+  static Bool  isFirst = true;
+  static Int** coeffmulti = NULL;
+  if(isFirst)
+  {
+    coeffmulti = new Int*[NO_VAR_BINS];
+    for(Int g=0; g< NO_VAR_BINS; g++)
+    {
+      coeffmulti[g] = new Int[ALF_MAX_NUM_COEF];
+    }
+    isFirst = false;
+  }
+
+  for(Int g=0; g< filters_per_fr; g++)
+  {
+    for(i=0; i< sqrFiltLength; i++)
+    {
+      coeffmulti[g][i] = filterCoeffSymQuant[g][i];
+    }
+  }
+  predictALFCoeff(coeffmulti, sqrFiltLength, filters_per_fr);
+  //golomb encode bitrate estimation
+  coeffBits = 0;
+  for(Int g=0; g< filters_per_fr; g++)
+  {
+    coeffBits += filterCoeffBitrateEstimate(ALF_Y, coeffmulti[g]);
+  }
+  for(i=0;i<filters_per_fr;i++)
+  {
+    error += errorForce0CoeffTab[i][1];
+  }
+  lagrangian = error + lambda * coeffBits;
+  return (lagrangian);
+}
+
+Void TEncAdaptiveLoopFilter::predictALFCoeff(Int** coeff, Int numCoef, Int numFilters)
+{
+  for(Int g=0; g< numFilters; g++ )
+  {
+    Int sum=0;
+    for(Int i=0; i< numCoef-1;i++)
+    {
+      sum += (2* coeff[g][i]);
+    }
+
+    Int pred = (1<<ALF_NUM_BIT_SHIFT) - (sum);
+    coeff[g][numCoef-1] = coeff[g][numCoef-1] - pred;
+  }
+}
+
+Void TEncAdaptiveLoopFilter::xfindBestFilterVarPred(double **ySym, double ***ESym, double *pixAcc, Int **filterCoeffSym, Int *filters_per_fr_best, Int varIndTab[], double lambda_val, Int numMaxFilters)
+{
+  static Bool isFirst = true;
+  static Int* filterCoeffSymQuant[NO_VAR_BINS];
+  if(isFirst)
+  {
+    for(Int g=0; g< NO_VAR_BINS; g++)
+    {
+      filterCoeffSymQuant[g] = new Int[ALF_MAX_NUM_COEF];
+    }
+    isFirst = false;
+  }
+  Int filter_shape = 0;
+  Int filters_per_fr, firstFilt, interval[NO_VAR_BINS][2], intervalBest[NO_VAR_BINS][2];
+  int i;
+  double  lagrangian, lagrangianMin;
+  int sqrFiltLength;
+  int *weights;
+  double errorForce0CoeffTab[NO_VAR_BINS][2];
+  
+  sqrFiltLength= (Int)ALF_MAX_NUM_COEF;
+  weights = weightsShape1Sym;
+  // zero all variables 
+  memset(varIndTab,0,sizeof(int)*NO_VAR_BINS);
+
+  for(i = 0; i < NO_VAR_BINS; i++)
+  {
+    memset(filterCoeffSym[i],0,sizeof(int)*ALF_MAX_NUM_COEF);
+    memset(filterCoeffSymQuant[i],0,sizeof(int)*ALF_MAX_NUM_COEF);
+  }
+
+  firstFilt=1;  lagrangianMin=0;
+  filters_per_fr=NO_FILTERS;
+
+  while(filters_per_fr>=1)
+  {
+    mergeFiltersGreedy(ySym, ESym, pixAcc, interval, sqrFiltLength, filters_per_fr);
+    findFilterCoeff(ESym, ySym, pixAcc, filterCoeffSym, filterCoeffSymQuant, interval,
+      varIndTab, sqrFiltLength, filters_per_fr, weights, errorForce0CoeffTab);
+
+    lagrangian=xfindBestCoeffCodMethod(filterCoeffSymQuant, filter_shape, sqrFiltLength, filters_per_fr, errorForce0CoeffTab, lambda_val);
+    if (lagrangian<lagrangianMin || firstFilt==1 || filters_per_fr == numMaxFilters)
+    {
+      firstFilt=0;
+      lagrangianMin=lagrangian;
+
+      (*filters_per_fr_best)=filters_per_fr;
+      memcpy(intervalBest, interval, NO_VAR_BINS*2*sizeof(int));
+    }
+    filters_per_fr--;
+  }
+  findFilterCoeff(ESym, ySym, pixAcc, filterCoeffSym, filterCoeffSymQuant, intervalBest,
+    varIndTab, sqrFiltLength, (*filters_per_fr_best), weights, errorForce0CoeffTab);
+
+  if( *filters_per_fr_best == 1)
+  {
+    ::memset(varIndTab, 0, sizeof(Int)*NO_VAR_BINS);
+  }
+}
+
+/** code filter coefficients
+ * \param filterCoeffSymQuant filter coefficients buffer
+ * \param filtNo filter No.
+ * \param varIndTab[] merge index information
+ * \param filters_per_fr_best the number of filters used in this picture
+ * \param frNo 
+ * \param ALFp ALF parameters
+ * \returns bitrate
+ */
+Void TEncAdaptiveLoopFilter::xcodeFiltCoeff(Int **filterCoeff, Int* varIndTab, Int numFilters, ALFParam* alfParam)
+{
+  Int filterPattern[NO_VAR_BINS], startSecondFilter=0;
+  ::memset(filterPattern, 0, NO_VAR_BINS * sizeof(Int)); 
+
+  alfParam->filter_shape=0;
+  alfParam->num_coeff = (Int)ALF_MAX_NUM_COEF;
+  alfParam->filters_per_group = numFilters;
+
+  //merge table assignment
+  if(alfParam->filters_per_group > 1)
+  {
+    for(Int i = 1; i < NO_VAR_BINS; ++i)
+    {
+      if(varIndTab[i] != varIndTab[i-1])
+      {
+        filterPattern[i] = 1;
+        startSecondFilter = i;
+      }
+    }
+  }
+  ::memcpy (alfParam->filterPattern, filterPattern, NO_VAR_BINS * sizeof(Int));
+  alfParam->startSecondFilter = startSecondFilter;
+
+  //coefficient prediction
+  for(Int g=0; g< alfParam->filters_per_group; g++)
+  {
+    for(Int i=0; i< alfParam->num_coeff; i++)
+    {
+      alfParam->coeffmulti[g][i] = filterCoeff[g][i];
+    }
+  }
+  predictALFCoeff(alfParam->coeffmulti, alfParam->num_coeff, alfParam->filters_per_group);
+}
+
+#define ROUND(a)  (((a) < 0)? (int)((a) - 0.5) : (int)((a) + 0.5))
+#define REG              0.0001
+#define REG_SQR          0.0000001
+
+//Find filter coeff related
+Int TEncAdaptiveLoopFilter::gnsCholeskyDec(Double **inpMatr, Double outMatr[ALF_MAX_NUM_COEF][ALF_MAX_NUM_COEF], Int noEq)
+{ 
+  Int i, j, k;     /* Looping Variables */
+  Double scale;       /* scaling factor for each row */
+  Double invDiag[ALF_MAX_NUM_COEF];  /* Vector of the inverse of diagonal entries of outMatr */
+  
+  //  Cholesky decomposition starts
+  
+  for(i = 0; i < noEq; i++)
+  {
+    for(j = i; j < noEq; j++)
+    {
+      /* Compute the scaling factor */
+      scale = inpMatr[i][j];
+      if ( i > 0) 
+      {
+        for( k = i - 1 ; k >= 0 ; k--)
+        {
+          scale -= outMatr[k][j] * outMatr[k][i];
+        }
+      }
+      /* Compute i'th row of outMatr */
+      if(i == j)
+      {
+        if(scale <= REG_SQR ) // if(scale <= 0 )  /* If inpMatr is singular */
+        {
+          return 0;
+        }
+        else
+        {
+           /* Normal operation */
+           invDiag[i] =  1.0 / (outMatr[i][i] = sqrt(scale));
+        }
+      }
+      else
+      {
+        outMatr[i][j] = scale * invDiag[i]; /* Upper triangular part          */
+        outMatr[j][i] = 0.0;              /* Lower triangular part set to 0 */
+      }                    
+    }
+  }
+  return 1; /* Signal that Cholesky factorization is successfully performed */
+}
+
+
+Void TEncAdaptiveLoopFilter::gnsTransposeBacksubstitution(Double U[ALF_MAX_NUM_COEF][ALF_MAX_NUM_COEF], Double rhs[], Double x[], Int order)
+{
+  Int i,j;              /* Looping variables */
+  Double sum;              /* Holds backsubstitution from already handled rows */
+  
+  /* Backsubstitution starts */
+  x[0] = rhs[0] / U[0][0];               /* First row of U'                   */
+  for (i = 1; i < order; i++)
+  {         /* For the rows 1..order-1           */
+    
+    for (j = 0, sum = 0.0; j < i; j++) /* Backsubst already solved unknowns */
+    {
+      sum += x[j] * U[j][i];
+    }
+    x[i] = (rhs[i] - sum) / U[i][i];       /* i'th component of solution vect.  */
+  }
+}
+Void  TEncAdaptiveLoopFilter::gnsBacksubstitution(Double R[ALF_MAX_NUM_COEF][ALF_MAX_NUM_COEF], Double z[ALF_MAX_NUM_COEF], Int R_size, Double A[ALF_MAX_NUM_COEF])
+{
+  Int i, j;
+  Double sum;
+  
+  R_size--;
+  
+  A[R_size] = z[R_size] / R[R_size][R_size];
+  
+  for (i = R_size-1; i >= 0; i--)
+  {
+    for (j = i + 1, sum = 0.0; j <= R_size; j++)
+    {
+      sum += R[i][j] * A[j];
+    }
+    
+    A[i] = (z[i] - sum) / R[i][i];
+  }
+}
+
+
+Int TEncAdaptiveLoopFilter::gnsSolveByChol(Double **LHS, Double *rhs, Double *x, Int noEq)
+{
+  assert(noEq > 0);
+
+  Double aux[ALF_MAX_NUM_COEF];     /* Auxiliary vector */
+  Double U[ALF_MAX_NUM_COEF][ALF_MAX_NUM_COEF];    /* Upper triangular Cholesky factor of LHS */
+  Int  i, singular;          /* Looping variable */
+  
+  /* The equation to be solved is LHSx = rhs */
+  
+  /* Compute upper triangular U such that U'*U = LHS */
+  if(gnsCholeskyDec(LHS, U, noEq)) /* If Cholesky decomposition has been successful */
+  {
+    singular = 1;
+    /* Now, the equation is  U'*U*x = rhs, where U is upper triangular
+     * Solve U'*aux = rhs for aux
+     */
+    gnsTransposeBacksubstitution(U, rhs, aux, noEq);         
+    
+    /* The equation is now U*x = aux, solve it for x (new motion coefficients) */
+    gnsBacksubstitution(U, aux, noEq, x);   
+    
+  }
+  else /* LHS was singular */ 
+  {
+    singular = 0;
+    
+    /* Regularize LHS */
+    for(i=0; i < noEq; i++)
+    {
+      LHS[i][i] += REG;
+    }
+    /* Compute upper triangular U such that U'*U = regularized LHS */
+    singular = gnsCholeskyDec(LHS, U, noEq);
+    if ( singular == 1 )
+    {
+      /* Solve  U'*aux = rhs for aux */  
+      gnsTransposeBacksubstitution(U, rhs, aux, noEq);   
+      
+      /* Solve U*x = aux for x */
+      gnsBacksubstitution(U, aux, noEq, x);      
+    }
+    else
+    {
+      x[0] = 1.0;
+      for (i = 1; i < noEq; i++ )
+      {
+        x[i] = 0.0;
+      }
+    }
+  }  
+  return singular;
+}
+
+Void TEncAdaptiveLoopFilter::add_A(Double **Amerged, Double ***A, Int start, Int stop, Int size)
+{ 
+  Int i, j, ind;          /* Looping variable */
+  
+  for (i = 0; i < size; i++)
+  {
+    for (j = 0; j < size; j++)
+    {
+      Amerged[i][j] = 0;
+      for (ind = start; ind <= stop; ind++)
+      {
+        Amerged[i][j] += A[ind][i][j];
+      }
+    }
+  }
+}
+
+Void TEncAdaptiveLoopFilter::add_b(Double *bmerged, Double **b, Int start, Int stop, Int size)
+{ 
+  Int i, ind;          /* Looping variable */
+  
+  for (i = 0; i < size; i++)
+  {
+    bmerged[i] = 0;
+    for (ind = start; ind <= stop; ind++)
+    {
+      bmerged[i] += b[ind][i];
+    }
+  }
+}
+
+Double TEncAdaptiveLoopFilter::calculateErrorCoeffProvided(Double **A, Double *b, Double *c, Int size)
+{
+  Int i, j;
+  Double error, sum = 0;
+  
+  error = 0;
+  for (i = 0; i < size; i++)   //diagonal
+  {
+    sum = 0;
+    for (j = i + 1; j < size; j++)
+    {
+      sum += (A[j][i] + A[i][j]) * c[j];
+    }
+    error += (A[i][i] * c[i] + sum - 2 * b[i]) * c[i];
+  }
+  
+  return error;
+}
+
+Double TEncAdaptiveLoopFilter::calculateErrorAbs(Double **A, Double *b, Double y, Int size)
+{
+  Int i;
+  Double error, sum;
+  Double c[ALF_MAX_NUM_COEF];
+  
+  gnsSolveByChol(A, b, c, size);
+  
+  sum = 0;
+  for (i = 0; i < size; i++)
+  {
+    sum += c[i] * b[i];
+  }
+  error = y - sum;
+  
+  return error;
+}
+
+Double TEncAdaptiveLoopFilter::mergeFiltersGreedy(Double **yGlobalSeq, Double ***EGlobalSeq, Double *pixAccGlobalSeq, Int intervalBest[NO_VAR_BINS][2], Int sqrFiltLength, Int noIntervals)
+{
+  Int first, ind, ind1, ind2, i, j, bestToMerge ;
+  Double error, error1, error2, errorMin;
+  static Double pixAcc_temp, error_tab[NO_VAR_BINS],error_comb_tab[NO_VAR_BINS];
+  static Int indexList[NO_VAR_BINS], available[NO_VAR_BINS], noRemaining;
+  if (noIntervals == NO_FILTERS)
+  {
+    noRemaining = NO_VAR_BINS;
+    for (ind=0; ind<NO_VAR_BINS; ind++)
+    {
+      indexList[ind] = ind; 
+      available[ind] = 1;
+      m_pixAcc_merged[ind] = pixAccGlobalSeq[ind];
+      memcpy(m_y_merged[ind], yGlobalSeq[ind], sizeof(Double)*sqrFiltLength);
+      for (i=0; i < sqrFiltLength; i++)
+      {
+        memcpy(m_E_merged[ind][i], EGlobalSeq[ind][i], sizeof(Double)*sqrFiltLength);
+      }
+    }
+  }
+  // Try merging different matrices
+  if (noIntervals == NO_FILTERS)
+  {
+    for (ind = 0; ind < NO_VAR_BINS; ind++)
+    {
+      error_tab[ind] = calculateErrorAbs(m_E_merged[ind], m_y_merged[ind], m_pixAcc_merged[ind], sqrFiltLength);
+    }
+    for (ind = 0; ind < NO_VAR_BINS - 1; ind++)
+    {
+      ind1 = indexList[ind];
+      ind2 = indexList[ind+1];
+      
+      error1 = error_tab[ind1];
+      error2 = error_tab[ind2];
+      
+      pixAcc_temp = m_pixAcc_merged[ind1] + m_pixAcc_merged[ind2];
+      for (i = 0; i < sqrFiltLength; i++)
+      {
+        m_y_temp[i] = m_y_merged[ind1][i] + m_y_merged[ind2][i];
+        for (j = 0; j < sqrFiltLength; j++)
+        {
+          m_E_temp[i][j] = m_E_merged[ind1][i][j] + m_E_merged[ind2][i][j];
+        }
+      }
+      error_comb_tab[ind1] = calculateErrorAbs(m_E_temp, m_y_temp, pixAcc_temp, sqrFiltLength) - error1 - error2;
+    }
+  }
+  while (noRemaining > noIntervals)
+  {
+    errorMin = 0; 
+    first = 1;
+    bestToMerge = 0;
+    for (ind = 0; ind < noRemaining - 1; ind++)
+    {
+      error = error_comb_tab[indexList[ind]];
+      if ((error < errorMin || first == 1))
+      {
+        errorMin = error;
+        bestToMerge = ind;
+        first = 0;
+      }
+    }
+    ind1 = indexList[bestToMerge];
+    ind2 = indexList[bestToMerge+1];
+    m_pixAcc_merged[ind1] += m_pixAcc_merged[ind2];
+    for (i = 0; i < sqrFiltLength; i++)
+    {
+      m_y_merged[ind1][i] += m_y_merged[ind2][i];
+      for (j = 0; j < sqrFiltLength; j++)
+      {
+        m_E_merged[ind1][i][j] += m_E_merged[ind2][i][j];
+      }
+    }
+    available[ind2] = 0;
+    
+    //update error tables
+    error_tab[ind1] = error_comb_tab[ind1] + error_tab[ind1] + error_tab[ind2];
+    if (indexList[bestToMerge] > 0)
+    {
+      ind1 = indexList[bestToMerge-1];
+      ind2 = indexList[bestToMerge];
+      error1 = error_tab[ind1];
+      error2 = error_tab[ind2];
+      pixAcc_temp = m_pixAcc_merged[ind1] + m_pixAcc_merged[ind2];
+      for (i = 0; i < sqrFiltLength; i++)
+      {
+        m_y_temp[i] = m_y_merged[ind1][i] + m_y_merged[ind2][i];
+        for (j = 0; j < sqrFiltLength; j++)
+        {
+          m_E_temp[i][j] = m_E_merged[ind1][i][j] + m_E_merged[ind2][i][j];
+        }
+      }
+      error_comb_tab[ind1] = calculateErrorAbs(m_E_temp, m_y_temp, pixAcc_temp, sqrFiltLength) - error1 - error2;
+    }
+    if (indexList[bestToMerge+1] < NO_VAR_BINS - 1)
+    {
+      ind1 = indexList[bestToMerge];
+      ind2 = indexList[bestToMerge+2];
+      error1 = error_tab[ind1];
+      error2 = error_tab[ind2];
+      pixAcc_temp = m_pixAcc_merged[ind1] + m_pixAcc_merged[ind2];
+      for (i=0; i<sqrFiltLength; i++)
+      {
+        m_y_temp[i] = m_y_merged[ind1][i] + m_y_merged[ind2][i];
+        for (j=0; j < sqrFiltLength; j++)
+        {
+          m_E_temp[i][j] = m_E_merged[ind1][i][j] + m_E_merged[ind2][i][j];
+        }
+      }
+      error_comb_tab[ind1] = calculateErrorAbs(m_E_temp, m_y_temp, pixAcc_temp, sqrFiltLength) - error1 - error2;
+    }
+    
+    ind=0;
+    for (i = 0; i < NO_VAR_BINS; i++)
+    {
+      if (available[i] == 1)
+      {
+        indexList[ind] = i;
+        ind++;
+      }
+    }
+    noRemaining--;
+  }
+  
+  errorMin = 0;
+  for (ind = 0; ind < noIntervals; ind++)
+  {
+    errorMin += error_tab[indexList[ind]];
+  }
+  
+  for (ind = 0; ind < noIntervals - 1; ind++)
+  {
+    intervalBest[ind][0] = indexList[ind]; 
+    intervalBest[ind][1] = indexList[ind+1] - 1;
+  }
+  
+  intervalBest[noIntervals-1][0] = indexList[noIntervals-1]; 
+  intervalBest[noIntervals-1][1] = NO_VAR_BINS-1;
+  
+  return(errorMin);
+}
+
+Void TEncAdaptiveLoopFilter::roundFiltCoeff(Int *FilterCoeffQuan, Double *FilterCoeff, Int sqrFiltLength, Int factor)
+{
+  Int i;
+  Double diff; 
+  Int diffInt, sign; 
+  
+  for(i = 0; i < sqrFiltLength; i++)
+  {
+    sign = (FilterCoeff[i] > 0)? 1 : -1; 
+    diff = FilterCoeff[i] * sign; 
+    diffInt = (Int)(diff * (Double)factor + 0.5); 
+    FilterCoeffQuan[i] = diffInt * sign;
+  }
+}
+
+Double TEncAdaptiveLoopFilter::QuantizeIntegerFilterPP(Double *filterCoeff, Int *filterCoeffQuant, Double **E, Double *y, Int sqrFiltLength, Int *weights)
+{
+  double error;
+  static Bool isFirst = true;
+  static Int* filterCoeffQuantMod= NULL;
+  if(isFirst)
+  {
+    filterCoeffQuantMod = new Int[ALF_MAX_NUM_COEF];
+    isFirst = false;
+  }
+  Int factor = (1<<  ((Int)ALF_NUM_BIT_SHIFT)  );
+  Int i;
+  int quantCoeffSum, minInd, targetCoeffSumInt, k, diff;
+  double targetCoeffSum, errMin;
+  
+  gnsSolveByChol(E, y, filterCoeff, sqrFiltLength);
+  targetCoeffSum=0;
+  for (i=0; i<sqrFiltLength; i++)
+  {
+    targetCoeffSum+=(weights[i]*filterCoeff[i]*factor);
+  }
+  targetCoeffSumInt=ROUND(targetCoeffSum);
+  roundFiltCoeff(filterCoeffQuant, filterCoeff, sqrFiltLength, factor);
+  quantCoeffSum=0;
+  for (i=0; i<sqrFiltLength; i++)
+  {
+    quantCoeffSum+=weights[i]*filterCoeffQuant[i];
+  }
+  
+  int count=0;
+  while(quantCoeffSum!=targetCoeffSumInt && count < 10)
+  {
+    if (quantCoeffSum>targetCoeffSumInt)
+    {
+      diff=quantCoeffSum-targetCoeffSumInt;
+      errMin=0; minInd=-1;
+      for (k=0; k<sqrFiltLength; k++)
+      {
+        if (weights[k]<=diff)
+        {
+          for (i=0; i<sqrFiltLength; i++)
+          {
+            filterCoeffQuantMod[i]=filterCoeffQuant[i];
+          }
+          filterCoeffQuantMod[k]--;
+          for (i=0; i<sqrFiltLength; i++)
+          {
+            filterCoeff[i]=(double)filterCoeffQuantMod[i]/(double)factor;
+          }
+          error=calculateErrorCoeffProvided(E, y, filterCoeff, sqrFiltLength);
+          if (error<errMin || minInd==-1)
+          {
+            errMin=error;
+            minInd=k;
+          }
+        } // if (weights(k)<=diff)
+      } // for (k=0; k<sqrFiltLength; k++)
+      filterCoeffQuant[minInd]--;
+    }
+    else
+    {
+      diff=targetCoeffSumInt-quantCoeffSum;
+      errMin=0; minInd=-1;
+      for (k=0; k<sqrFiltLength; k++)
+      {
+        if (weights[k]<=diff)
+        {
+          for (i=0; i<sqrFiltLength; i++)
+          {
+            filterCoeffQuantMod[i]=filterCoeffQuant[i];
+          }
+          filterCoeffQuantMod[k]++;
+          for (i=0; i<sqrFiltLength; i++)
+          {
+            filterCoeff[i]=(double)filterCoeffQuantMod[i]/(double)factor;
+          }
+          error=calculateErrorCoeffProvided(E, y, filterCoeff, sqrFiltLength);
+          if (error<errMin || minInd==-1)
+          {
+            errMin=error;
+            minInd=k;
+          }
+        } // if (weights(k)<=diff)
+      } // for (k=0; k<sqrFiltLength; k++)
+      filterCoeffQuant[minInd]++;
+    }
+    
+    quantCoeffSum=0;
+    for (i=0; i<sqrFiltLength; i++)
+    {
+      quantCoeffSum+=weights[i]*filterCoeffQuant[i];
+    }
+  }
+  if( count == 10 )
+  {
+    for (i=0; i<sqrFiltLength; i++)
+    {
+      filterCoeffQuant[i] = 0;
+    }
+  }
+  
+  checkFilterCoeffValue(filterCoeffQuant, sqrFiltLength, false);
+
+  for (i=0; i<sqrFiltLength; i++)
+  {
+    filterCoeff[i]=(double)filterCoeffQuant[i]/(double)factor;
+  }
+  
+  error=calculateErrorCoeffProvided(E, y, filterCoeff, sqrFiltLength);
+  return(error);
+}
+Double TEncAdaptiveLoopFilter::findFilterCoeff(double ***EGlobalSeq, double **yGlobalSeq, double *pixAccGlobalSeq, int **filterCoeffSeq, int **filterCoeffQuantSeq, int intervalBest[NO_VAR_BINS][2], int varIndTab[NO_VAR_BINS], int sqrFiltLength, int filters_per_fr, int *weights, double errorTabForce0Coeff[NO_VAR_BINS][2])
+{
+  static double pixAcc_temp;
+  static Bool isFirst = true;
+  static Int* filterCoeffQuant = NULL;
+  static Double* filterCoeff = NULL;
+  if(isFirst)
+  {
+    filterCoeffQuant = new Int[ALF_MAX_NUM_COEF];
+    filterCoeff = new Double[ALF_MAX_NUM_COEF];
+    isFirst = false;
+  }
+  double error;
+  int k, filtNo;
+  
+  error = 0;
+  for(filtNo = 0; filtNo < filters_per_fr; filtNo++)
+  {
+    add_A(m_E_temp, EGlobalSeq, intervalBest[filtNo][0], intervalBest[filtNo][1], sqrFiltLength);
+    add_b(m_y_temp, yGlobalSeq, intervalBest[filtNo][0], intervalBest[filtNo][1], sqrFiltLength);
+    
+    pixAcc_temp = 0;    
+    for(k = intervalBest[filtNo][0]; k <= intervalBest[filtNo][1]; k++)
+      pixAcc_temp += pixAccGlobalSeq[k];
+    
+    // Find coeffcients
+    errorTabForce0Coeff[filtNo][1] = pixAcc_temp + QuantizeIntegerFilterPP(filterCoeff, filterCoeffQuant, m_E_temp, m_y_temp, sqrFiltLength, weights);
+    errorTabForce0Coeff[filtNo][0] = pixAcc_temp;
+    error += errorTabForce0Coeff[filtNo][1];
+    
+    for(k = 0; k < sqrFiltLength; k++)
+    {
+      filterCoeffSeq[filtNo][k] = filterCoeffQuant[k];
+      filterCoeffQuantSeq[filtNo][k] = filterCoeffQuant[k];
+    }
+  }
+  
+  for(filtNo = 0; filtNo < filters_per_fr; filtNo++)
+  {
+    for(k = intervalBest[filtNo][0]; k <= intervalBest[filtNo][1]; k++)
+      varIndTab[k] = filtNo;
+  }
+  
+  return(error);
+}
+
+
+/** Estimate filtering distortion by correlation values and filter coefficients
+ * \param ppdE auto-correlation matrix
+ * \param pdy cross-correlation array
+ * \param piCoeff  filter coefficients
+ * \param iFiltLength numbr of filter taps
+ * \returns estimated distortion
+ */
+Int64 TEncAdaptiveLoopFilter::xFastFiltDistEstimation(Double** ppdE, Double* pdy, Int* piCoeff, Int iFiltLength)
+{
+  //static memory
+  Double pdcoeff[ALF_MAX_NUM_COEF];
+  //variable
+  Int    i,j;
+  Int64  iDist;
+  Double dDist, dsum;
+
+  for(i=0; i< iFiltLength; i++)
+  {
+    pdcoeff[i]= (Double)piCoeff[i] / (Double)(1<< ((Int)ALF_NUM_BIT_SHIFT) );
+  }
+
+  dDist =0;
+  for(i=0; i< iFiltLength; i++)
+  {
+    dsum= ((Double)ppdE[i][i]) * pdcoeff[i];
+    for(j=i+1; j< iFiltLength; j++)
+    {
+      dsum += (Double)(2*ppdE[i][j])* pdcoeff[j];
+    }
+
+    dDist += ((dsum - 2.0 * pdy[i])* pdcoeff[i] );
+  }
+
+
+  UInt uiShift = g_uiBitIncrement<<1;
+  if(dDist < 0)
+  {
+    iDist = -(((Int64)(-dDist + 0.5)) >> uiShift);
+  }
+  else //dDist >=0
+  {
+    iDist= ((Int64)(dDist+0.5)) >> uiShift;
+  }
+
+  return iDist;
+
+}
+
+UInt TEncAdaptiveLoopFilter::uvlcBitrateEstimate(Int val)
+{
+  val++;
+  assert ( val );
+  UInt length = 1;
+  while( 1 != val )
+  {
+    val >>= 1;
+    length += 2;
+  }
+  return ((length >> 1) + ((length+1) >> 1));
+}
+
+UInt TEncAdaptiveLoopFilter::golombBitrateEstimate(Int coeff, Int k)
+{
+  UInt symbol = (UInt)abs(coeff);
+  UInt bitcnt = 0;
+
+  while( symbol >= (UInt)(1<<k) )
+  {
+    bitcnt++;
+    symbol -= (1<<k);
+    k  ++;
+  }
+  bitcnt++;
+  while( k-- )
+  {
+    bitcnt++;
+  }
+  if(coeff != 0)
+  {
+    bitcnt++;
+  }
+  return bitcnt;
+}
+
+UInt TEncAdaptiveLoopFilter::filterCoeffBitrateEstimate(Int compIdx, Int* coeff)
+{
+  UInt bitrate =0;
+  for(Int i=0; i< (Int)ALF_MAX_NUM_COEF; i++)
+  {
+    bitrate += (compIdx == ALF_Y)?(golombBitrateEstimate(coeff[i], kTableTabShapes[ALF_CROSS9x7_SQUARE3x3][i])):(svlcBitrateEsitmate(coeff[i]));
+  }
+  return bitrate;
+}
+
+UInt TEncAdaptiveLoopFilter::ALFParamBitrateEstimate(ALFParam* alfParam)
+{
+  UInt bitrate = 1; //alf enabled flag
+  if(alfParam->alf_flag == 1)
+  {
+    if(alfParam->componentID == ALF_Y)
+    {
+      Int noFilters = min(alfParam->filters_per_group-1, 2);
+      bitrate += uvlcBitrateEstimate(noFilters);
+      if(noFilters == 1)
+      {
+        bitrate += uvlcBitrateEstimate(alfParam->startSecondFilter);
+      }
+      else if (noFilters == 2)
+      {
+        bitrate += ((Int)NO_VAR_BINS -1);
+      }
+    }
+    for(Int g=0; g< alfParam->filters_per_group; g++)
+    {
+      bitrate += filterCoeffBitrateEstimate(alfParam->componentID, alfParam->coeffmulti[g]);
+    }
+  }
+  return bitrate;
+}
+#endif
+//! \}
Index: /trunk/source/Lib/TLibEncoder/TEncAdaptiveLoopFilter.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncAdaptiveLoopFilter.h	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/TEncAdaptiveLoopFilter.h	(revision 2)
@@ -0,0 +1,167 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncAdaptiveLoopFilter.h
+ \brief    estimation part of adaptive loop filter class (header)
+ */
+
+#ifndef __TENCADAPTIVELOOPFILTER__
+#define __TENCADAPTIVELOOPFILTER__
+
+#include "TLibCommon/TComAdaptiveLoopFilter.h"
+#include "TLibCommon/TComPic.h"
+
+#include "TEncEntropy.h"
+#include "TEncSbac.h"
+#include "TLibCommon/TComBitCounter.h"
+
+#if !REMOVE_ALF
+//! \ingroup TLibEncoder
+//! \{
+#define LCUALF_AVOID_USING_BOTTOM_LINES_ENCODER 1 //!< avoid using LCU bottom lines when lcu-based encoder RDO is used
+#define LCUALF_AVOID_USING_RIGHT_LINES_ENCODER 1  //!< Avoid using right-most lines per LCU during encoder LCU on/off decision
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// correlation info
+struct AlfCorrData
+{
+  Double*** ECorr; //!< auto-correlation matrix
+  Double**  yCorr; //!< cross-correlation
+  Double*   pixAcc;
+  Int componentID;
+
+  //constructor & operator
+  AlfCorrData();
+  AlfCorrData(Int cIdx);
+  ~AlfCorrData();
+  Void reset();
+  Void mergeFrom(const AlfCorrData& src, Int* mergeTable, Bool doPixAccMerge);
+  AlfCorrData& operator += (const AlfCorrData& src);
+};
+
+/// estimation part of adaptive loop filter class
+class TEncAdaptiveLoopFilter : public TComAdaptiveLoopFilter
+{
+private:
+  ///
+  /// variables for correlation calculation
+  ///
+  Double*  m_y_merged[NO_VAR_BINS];
+  Double** m_E_merged[NO_VAR_BINS];
+  Double   m_pixAcc_merged[NO_VAR_BINS];
+  Double   m_y_temp[ALF_MAX_NUM_COEF];
+  double **m_E_temp;
+  Int    m_lastSliceIdx;
+  Bool   m_alfLowLatencyEncoding;  
+  Int*   m_numSlicesDataInOneLCU;
+  Int*   m_coeffNoFilter[NO_VAR_BINS]; //!< used for RDO
+  AlfCorrData** m_alfCorr[NUM_ALF_COMPONENT];
+  AlfCorrData*  m_alfCorrMerged[NUM_ALF_COMPONENT]; //!< used for RDO
+  AlfCorrData** m_alfNonSkippedCorr[NUM_ALF_COMPONENT];
+  ALFParam*** m_alfPictureParam;
+  Int         m_gopSize;                
+  Double      m_dLambdaLuma;
+  Double      m_dLambdaChroma;
+private:
+
+  Void initALFEncoderParam();
+  Void getStatistics(TComPicYuv* pPicOrg, TComPicYuv* pPicDec);
+  Void getOneCompStatistics(AlfCorrData** alfCorrComp, Int compIdx, Pel* imgOrg, Pel* imgDec, Int stride, Int formatShift);
+  Void getStatisticsOneLCU(Bool skipLCUBottomLines, Int compIdx, AlfLCUInfo* alfLCU, AlfCorrData* alfCorr, Pel* pPicOrg, Pel* pPicSrc, Int stride, Int formatShift);
+  Void decideParameters(ALFParam** alfPictureParam, TComPicYuv* pPicOrg, TComPicYuv* pPicDec, TComPicYuv* pPicRest);
+  Void setCurAlfParam(ALFParam** alfPictureParam);
+  Int  getTemporalLayerNo(Int poc, Int gopSize);
+  Void decideAlfPictureParam(ALFParam** alfPictureParam, Bool useAllLCUs);
+  Void estimateLcuControl(ALFParam** alfPictureParam);
+  Void deriveFilterInfo(Int compIdx, AlfCorrData* alfCorr, ALFParam* alfFiltParam, Int maxNumFilters, Double lambda);
+  Void calcCorrOneCompRegionChma(Pel* imgOrg, Pel* imgPad, Int stride, Int yPos, Int xPos, Int height, Int width, Double **eCorr, Double *yCorr, Bool isSymmCopyBlockMatrix); //!< Calculate correlations for chroma                                        
+  Void calcCorrOneCompRegionLuma(Pel* imgOrg, Pel* imgPad, Int stride, Int yPos, Int xPos, Int height, Int width, Double ***eCorr, Double **yCorr, Double *pixAcc, Bool isSymmCopyBlockMatrix);
+
+  //LCU-based mode decision
+  Void  executeLCUOnOffDecision(Int compIdx, ALFParam* alfParam, Pel* pOrg, Pel* pDec, Pel* pRest, Int stride, Int formatShift, AlfCorrData** alfCorrLCUs);
+  Int64 estimateFilterDistortion(Int compIdx, AlfCorrData* alfCorr, Int** coeff = NULL, Int filterSetSize = 1, Int* mergeTable = NULL, Bool doPixAccMerge = false);
+  Int64 calcAlfLCUDist(Bool skipLCUBottomLines, Int compIdx, AlfLCUInfo& alfLCUInfo, Pel* picSrc, Pel* picCmp, Int stride, Int formatShift);
+  Void  reconstructOneAlfLCU(Int compIdx, AlfLCUInfo& alfLCUInfo, Bool alfEnabled, ALFParam* alfParam, Pel* picDec, Pel* picRest, Int stride, Int formatShift);
+  Void  copyOneAlfLCU(AlfLCUInfo& alfLCUInfo, Pel* picDst, Pel* picSrc, Int stride, Int formatShift);
+  // functions related to filtering
+  Void xFilterCoefQuickSort   ( Double *coef_data, Int *coef_num, Int upper, Int lower );
+  Void xQuantFilterCoef       ( Double* h, Int* qh, Int tap, int bit_depth );
+  // distortion / misc functions
+  UInt64 xCalcSSD             ( Pel* pOrg, Pel* pCmp, Int iWidth, Int iHeight, Int iStride );
+  Int64 xFastFiltDistEstimation(Double** ppdE, Double* pdy, Int* piCoeff, Int iFiltLength); //!< Estimate filtering distortion by correlation values and filter coefficients
+
+  /// code filter coefficients
+  Void xcodeFiltCoeff(Int **filterCoeff, Int* varIndTab, Int numFilters, ALFParam* alfParam);
+  Void xfindBestFilterVarPred(double **ySym, double ***ESym, double *pixAcc, Int **filterCoeffSym, Int *filters_per_fr_best, Int varIndTab[], double lambda_val, Int numMaxFilters);
+  double xfindBestCoeffCodMethod(int **filterCoeffSymQuant, int filter_shape, int sqrFiltLength, int filters_per_fr, double errorForce0CoeffTab[NO_VAR_BINS][2], double lambda);
+  UInt uvlcBitrateEstimate(Int val);
+  UInt svlcBitrateEsitmate(Int val) {  return uvlcBitrateEstimate (( val <= 0) ? (-val<<1) : ((val<<1)-1));}
+  UInt golombBitrateEstimate(Int coeff, Int k);
+  UInt ALFParamBitrateEstimate(ALFParam* alfParam);
+  UInt filterCoeffBitrateEstimate(Int compIdx, Int* coeff);
+  Void predictALFCoeff(Int** coeff, Int numCoef, Int numFilters);
+  //cholesky related
+  Int   xGauss( Double **a, Int N );
+  Double findFilterCoeff(double ***EGlobalSeq, double **yGlobalSeq, double *pixAccGlobalSeq, int **filterCoeffSeq,int **filterCoeffQuantSeq, int intervalBest[NO_VAR_BINS][2], int varIndTab[NO_VAR_BINS], int sqrFiltLength, int filters_per_fr, int *weights, double errorTabForce0Coeff[NO_VAR_BINS][2]);
+  Double QuantizeIntegerFilterPP(Double *filterCoeff, Int *filterCoeffQuant, Double **E, Double *y, Int sqrFiltLength, Int *weights);
+  Void roundFiltCoeff(int *FilterCoeffQuan, double *FilterCoeff, int sqrFiltLength, int factor);
+  double mergeFiltersGreedy(double **yGlobalSeq, double ***EGlobalSeq, double *pixAccGlobalSeq, int intervalBest[NO_VAR_BINS][2], int sqrFiltLength, int noIntervals);
+  double calculateErrorAbs(double **A, double *b, double y, int size);
+  double calculateErrorCoeffProvided(double **A, double *b, double *c, int size);
+  Void add_b(double *bmerged, double **b, int start, int stop, int size);
+  Void add_A(double **Amerged, double ***A, int start, int stop, int size);
+  Int  gnsSolveByChol(double **LHS, double *rhs, double *x, int noEq);
+  Void gnsBacksubstitution(double R[ALF_MAX_NUM_COEF][ALF_MAX_NUM_COEF], double z[ALF_MAX_NUM_COEF], int R_size, double A[ALF_MAX_NUM_COEF]);
+  Void gnsTransposeBacksubstitution(double U[ALF_MAX_NUM_COEF][ALF_MAX_NUM_COEF], double rhs[], double x[],int order);
+  Int  gnsCholeskyDec(double **inpMatr, double outMatr[ALF_MAX_NUM_COEF][ALF_MAX_NUM_COEF], int noEq);
+
+public:
+  TEncAdaptiveLoopFilter          ();
+  virtual ~TEncAdaptiveLoopFilter () {}
+  Void setALFLowLatencyEncoding(Bool b) {m_alfLowLatencyEncoding = b;}
+#if ALF_CHROMA_LAMBDA
+  Void ALFProcess(ALFParam** alfPictureParam, Double lambdaLuma, Double lambdaChroma);
+#else
+  Void ALFProcess(ALFParam** alfPictureParam, Double lambda);
+#endif
+  Void setGOPSize(Int val) { m_gopSize = val; } //!< set GOP size
+  Void createAlfGlobalBuffers(); //!< create ALF global buffers
+  Void destroyAlfGlobalBuffers(); //!< destroy ALF global buffers
+  Void PCMLFDisableProcess (TComPic* pcPic);
+};
+
+//! \}
+#endif
+#endif
Index: /trunk/source/Lib/TLibEncoder/TEncAnalyze.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncAnalyze.cpp	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/TEncAnalyze.cpp	(revision 2)
@@ -0,0 +1,59 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncAnalyze.cpp
+    \brief    encoder analyzer class
+*/
+
+#include "TEncAnalyze.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+//////////////////////////////////////////////////////////////////////
+// Construction/Destruction
+//////////////////////////////////////////////////////////////////////
+
+#if SVC_EXTENSION
+TEncAnalyze             m_gcAnalyzeAll [MAX_LAYERS];
+TEncAnalyze             m_gcAnalyzeI [MAX_LAYERS];
+TEncAnalyze             m_gcAnalyzeP [MAX_LAYERS];
+TEncAnalyze             m_gcAnalyzeB [MAX_LAYERS];
+#else
+TEncAnalyze             m_gcAnalyzeAll;
+TEncAnalyze             m_gcAnalyzeI;
+TEncAnalyze             m_gcAnalyzeP;
+TEncAnalyze             m_gcAnalyzeB;
+#endif
+
+//! \}
Index: /trunk/source/Lib/TLibEncoder/TEncAnalyze.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncAnalyze.h	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/TEncAnalyze.h	(revision 2)
@@ -0,0 +1,182 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncAnalyze.h
+    \brief    encoder analyzer class (header)
+*/
+
+#ifndef __TENCANALYZE__
+#define __TENCANALYZE__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include <stdio.h>
+#include <memory.h>
+#include <assert.h>
+#include "TLibCommon/CommonDef.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// encoder analyzer class
+class TEncAnalyze
+{
+private:
+  Double    m_dPSNRSumY;
+  Double    m_dPSNRSumU;
+  Double    m_dPSNRSumV;
+  Double    m_dAddBits;
+  UInt      m_uiNumPic;
+  Double    m_dFrmRate; //--CFG_KDY
+  
+public:
+  TEncAnalyze() { m_dPSNRSumY = m_dPSNRSumU = m_dPSNRSumV = m_dAddBits = m_uiNumPic = 0;  }
+  virtual ~TEncAnalyze()  {}
+  
+  Void  addResult( Double psnrY, Double psnrU, Double psnrV, Double bits)
+  {
+    m_dPSNRSumY += psnrY;
+    m_dPSNRSumU += psnrU;
+    m_dPSNRSumV += psnrV;
+    m_dAddBits  += bits;
+    
+    m_uiNumPic++;
+  }
+  
+  Double  getPsnrY()  { return  m_dPSNRSumY;  }
+  Double  getPsnrU()  { return  m_dPSNRSumU;  }
+  Double  getPsnrV()  { return  m_dPSNRSumV;  }
+  Double  getBits()   { return  m_dAddBits;   }
+  UInt    getNumPic() { return  m_uiNumPic;   }
+  
+  Void    setFrmRate  (Double dFrameRate) { m_dFrmRate = dFrameRate; } //--CFG_KDY
+  Void    clear() { m_dPSNRSumY = m_dPSNRSumU = m_dPSNRSumV = m_dAddBits = m_uiNumPic = 0;  }
+#if SVC_EXTENSION
+  Void    printOut ( Char cDelim, UInt layer )
+  {
+    Double dFps     =   m_dFrmRate; //--CFG_KDY
+    Double dScale   = dFps / 1000 / (Double)m_uiNumPic;
+    
+    printf( "    L%d\t %8d    %c"          "%12.4lf  "    "%8.4lf  "   "%8.4lf  "    "%8.4lf\n",
+           layer,
+           getNumPic(), cDelim,
+           getBits() * dScale,
+           getPsnrY() / (Double)getNumPic(),
+           getPsnrU() / (Double)getNumPic(),
+           getPsnrV() / (Double)getNumPic() );
+  }
+#else
+  Void    printOut ( Char cDelim )
+  {
+    Double dFps     =   m_dFrmRate; //--CFG_KDY
+    Double dScale   = dFps / 1000 / (Double)m_uiNumPic;
+    
+    printf( "\tTotal Frames |  "   "Bitrate    "  "Y-PSNR    "  "U-PSNR    "  "V-PSNR \n" );
+    //printf( "\t------------ "  " ----------"   " -------- "  " -------- "  " --------\n" );
+    printf( "\t %8d    %c"          "%12.4lf  "    "%8.4lf  "   "%8.4lf  "    "%8.4lf\n",
+           getNumPic(), cDelim,
+           getBits() * dScale,
+           getPsnrY() / (Double)getNumPic(),
+           getPsnrU() / (Double)getNumPic(),
+           getPsnrV() / (Double)getNumPic() );
+  }
+#endif
+  
+  Void    printSummaryOut ()
+  {
+    FILE* pFile = fopen ("summaryTotal.txt", "at");
+    Double dFps     =   m_dFrmRate; //--CFG_KDY
+    Double dScale   = dFps / 1000 / (Double)m_uiNumPic;
+    
+    fprintf(pFile, "%f\t %f\t %f\t %f\n", getBits() * dScale,
+            getPsnrY() / (Double)getNumPic(),
+            getPsnrU() / (Double)getNumPic(),
+            getPsnrV() / (Double)getNumPic() );
+    fclose(pFile);
+  }
+  
+  Void    printSummary(Char ch)
+  {
+    FILE* pFile = NULL;
+    
+    switch( ch ) 
+    {
+      case 'I':
+        pFile = fopen ("summary_I.txt", "at");
+        break;
+      case 'P':
+        pFile = fopen ("summary_P.txt", "at");
+        break;
+      case 'B':
+        pFile = fopen ("summary_B.txt", "at");
+        break;
+      default:
+        assert(0);
+        return;
+        break;
+    }
+    
+    Double dFps     =   m_dFrmRate; //--CFG_KDY
+    Double dScale   = dFps / 1000 / (Double)m_uiNumPic;
+    
+    fprintf(pFile, "%f\t %f\t %f\t %f\n",
+            getBits() * dScale,
+            getPsnrY() / (Double)getNumPic(),
+            getPsnrU() / (Double)getNumPic(),
+            getPsnrV() / (Double)getNumPic() );
+    
+    fclose(pFile);
+  }
+};
+
+#if SVC_EXTENSION
+extern TEncAnalyze             m_gcAnalyzeAll [MAX_LAYERS];
+extern TEncAnalyze             m_gcAnalyzeI [MAX_LAYERS];
+extern TEncAnalyze             m_gcAnalyzeP [MAX_LAYERS];
+extern TEncAnalyze             m_gcAnalyzeB [MAX_LAYERS];
+#else
+extern TEncAnalyze             m_gcAnalyzeAll;
+extern TEncAnalyze             m_gcAnalyzeI;
+extern TEncAnalyze             m_gcAnalyzeP;
+extern TEncAnalyze             m_gcAnalyzeB;
+#endif
+
+//! \}
+
+#endif // !defined(AFX_TENCANALYZE_H__C79BCAA2_6AC8_4175_A0FE_CF02F5829233__INCLUDED_)
Index: /trunk/source/Lib/TLibEncoder/TEncBinCoder.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncBinCoder.h	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/TEncBinCoder.h	(revision 2)
@@ -0,0 +1,83 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncBinCoder.h
+    \brief    binary entropy encoder interface
+*/
+
+#ifndef __TENC_BIN_CODER__
+#define __TENC_BIN_CODER__
+
+#include "TLibCommon/ContextModel.h"
+#include "TLibCommon/TComBitStream.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+class TEncBinCABAC;
+
+class TEncBinIf
+{
+public:
+  virtual Void  init              ( TComBitIf* pcTComBitIf )                  = 0;
+  virtual Void  uninit            ()                                          = 0;
+
+  virtual Void  start             ()                                          = 0;
+  virtual Void  finish            ()                                          = 0;
+  virtual Void  copyState         ( TEncBinIf* pcTEncBinIf )                  = 0;
+  virtual Void  flush            ()                                           = 0;
+
+  virtual Void  encodeFlush     (Bool bEnd) = 0;
+
+  virtual Void  resetBac          ()                                          = 0;
+  virtual Void  encodeNumSubseqIPCM( Int numSubseqIPCM )                   = 0;
+  virtual Void  encodePCMAlignBits()                                          = 0;
+  virtual Void  xWritePCMCode     ( UInt uiCode, UInt uiLength )              = 0;
+
+  virtual Void  resetBits         ()                                          = 0;
+  virtual UInt  getNumWrittenBits ()                                          = 0;
+
+  virtual Void  encodeBin         ( UInt  uiBin,  ContextModel& rcCtxModel )  = 0;
+  virtual Void  encodeBinEP       ( UInt  uiBin                            )  = 0;
+  virtual Void  encodeBinsEP      ( UInt  uiBins, Int numBins              )  = 0;
+  virtual Void  encodeBinTrm      ( UInt  uiBin                            )  = 0;
+
+  virtual TEncBinCABAC*   getTEncBinCABAC   ()  { return 0; }
+  
+  virtual ~TEncBinIf() {}
+};
+
+//! \}
+
+#endif
+
Index: /trunk/source/Lib/TLibEncoder/TEncBinCoderCABAC.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncBinCoderCABAC.cpp	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/TEncBinCoderCABAC.cpp	(revision 2)
@@ -0,0 +1,405 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncBinCoderCABAC.cpp
+    \brief    binary entropy encoder of CABAC
+*/
+
+#include "TEncBinCoderCABAC.h"
+#include "TLibCommon/TComRom.h"
+
+
+//! \ingroup TLibEncoder
+//! \{
+
+
+TEncBinCABAC::TEncBinCABAC()
+: m_pcTComBitIf( 0 )
+, m_binCountIncrement( 0 )
+#if FAST_BIT_EST
+, m_fracBits( 0 )
+#endif
+{
+}
+
+TEncBinCABAC::~TEncBinCABAC()
+{
+}
+
+Void TEncBinCABAC::init( TComBitIf* pcTComBitIf )
+{
+  m_pcTComBitIf = pcTComBitIf;
+}
+
+Void TEncBinCABAC::uninit()
+{
+  m_pcTComBitIf = 0;
+}
+
+Void TEncBinCABAC::start()
+{
+  m_uiLow            = 0;
+  m_uiRange          = 510;
+  m_bitsLeft         = 23;
+  m_numBufferedBytes = 0;
+  m_bufferedByte     = 0xff;
+}
+
+Void TEncBinCABAC::finish()
+{
+  if ( m_uiLow >> ( 32 - m_bitsLeft ) )
+  {
+    //assert( m_numBufferedBytes > 0 );
+    //assert( m_bufferedByte != 0xff );
+    m_pcTComBitIf->write( m_bufferedByte + 1, 8 );
+    while ( m_numBufferedBytes > 1 )
+    {
+      m_pcTComBitIf->write( 0x00, 8 );
+      m_numBufferedBytes--;
+    }
+    m_uiLow -= 1 << ( 32 - m_bitsLeft );
+  }
+  else
+  {
+    if ( m_numBufferedBytes > 0 )
+    {
+      m_pcTComBitIf->write( m_bufferedByte, 8 );
+    }
+    while ( m_numBufferedBytes > 1 )
+    {
+      m_pcTComBitIf->write( 0xff, 8 );
+      m_numBufferedBytes--;
+    }    
+  }
+  m_pcTComBitIf->write( m_uiLow >> 8, 24 - m_bitsLeft );
+}
+
+Void TEncBinCABAC::flush()
+{
+  encodeBinTrm(1);
+  finish();
+  m_pcTComBitIf->write(1, 1);
+  m_pcTComBitIf->writeAlignZero();
+
+  start();
+}
+
+/** Reset BAC register and counter values.
+ * \returns Void
+ */
+Void TEncBinCABAC::resetBac()
+{
+  start();
+}
+
+/** Encode # of subsequent IPCM blocks.
+ * \param numSubseqIPCM 
+ * \returns Void
+ */
+Void TEncBinCABAC::encodeNumSubseqIPCM( Int numSubseqIPCM )
+{
+  finish();
+  m_pcTComBitIf->write( 1, 1 ); // stop bit
+
+  m_pcTComBitIf->write( numSubseqIPCM ? 1 : 0, 1);
+
+  if ( numSubseqIPCM > 0)
+  {
+    Bool bCodeLast = ( 3 > numSubseqIPCM );
+
+    while( --numSubseqIPCM )
+    {
+      m_pcTComBitIf->write( 1, 1 );
+    }
+    if( bCodeLast )
+    {
+      m_pcTComBitIf->write( 0, 1 );
+    }
+  }
+}
+
+/** Encode PCM alignment zero bits.
+ * \returns Void
+ */
+Void TEncBinCABAC::encodePCMAlignBits()
+{
+  m_pcTComBitIf->writeAlignZero(); // pcm align zero
+}
+
+/** Write a PCM code.
+ * \param uiCode code value
+ * \param uiLength code bit-depth
+ * \returns Void
+ */
+Void TEncBinCABAC::xWritePCMCode(UInt uiCode, UInt uiLength)
+{
+  m_pcTComBitIf->write(uiCode, uiLength);
+}
+
+Void TEncBinCABAC::copyState( TEncBinIf* pcTEncBinIf )
+{
+  TEncBinCABAC* pcTEncBinCABAC = pcTEncBinIf->getTEncBinCABAC();
+  m_uiLow           = pcTEncBinCABAC->m_uiLow;
+  m_uiRange         = pcTEncBinCABAC->m_uiRange;
+  m_bitsLeft        = pcTEncBinCABAC->m_bitsLeft;
+  m_bufferedByte    = pcTEncBinCABAC->m_bufferedByte;
+  m_numBufferedBytes = pcTEncBinCABAC->m_numBufferedBytes;
+#if FAST_BIT_EST
+  m_fracBits = pcTEncBinCABAC->m_fracBits;
+#endif
+}
+
+Void TEncBinCABAC::resetBits()
+{
+  m_uiLow            = 0;
+  m_bitsLeft         = 23;
+  m_numBufferedBytes = 0;
+  m_bufferedByte     = 0xff;
+  if ( m_binCountIncrement )
+  {
+    m_uiBinsCoded = 0;
+  }
+#if FAST_BIT_EST
+  m_fracBits &= 32767;
+#endif
+}
+
+UInt TEncBinCABAC::getNumWrittenBits()
+{
+  return m_pcTComBitIf->getNumberOfWrittenBits() + 8 * m_numBufferedBytes + 23 - m_bitsLeft;
+}
+
+/**
+ * \brief Encode bin
+ *
+ * \param binValue   bin value
+ * \param rcCtxModel context model
+ */
+Void TEncBinCABAC::encodeBin( UInt binValue, ContextModel &rcCtxModel )
+{
+  {
+    DTRACE_CABAC_VL( g_nSymbolCounter++ )
+    DTRACE_CABAC_T( "\tstate=" )
+    DTRACE_CABAC_V( ( rcCtxModel.getState() << 1 ) + rcCtxModel.getMps() )
+    DTRACE_CABAC_T( "\tsymbol=" )
+    DTRACE_CABAC_V( binValue )
+    DTRACE_CABAC_T( "\n" )
+  }
+  m_uiBinsCoded += m_binCountIncrement;
+  rcCtxModel.setBinsCoded( 1 );
+  
+  UInt  uiLPS   = TComCABACTables::sm_aucLPSTable[ rcCtxModel.getState() ][ ( m_uiRange >> 6 ) & 3 ];
+  m_uiRange    -= uiLPS;
+  
+  if( binValue != rcCtxModel.getMps() )
+  {
+    Int numBits = TComCABACTables::sm_aucRenormTable[ uiLPS >> 3 ];
+    m_uiLow     = ( m_uiLow + m_uiRange ) << numBits;
+    m_uiRange   = uiLPS << numBits;
+    rcCtxModel.updateLPS();
+    
+    m_bitsLeft -= numBits;
+  }
+  else
+  {
+    rcCtxModel.updateMPS();
+    if ( m_uiRange >= 256 )
+    {
+      return;
+    }
+    
+    m_uiLow <<= 1;
+    m_uiRange <<= 1;
+    m_bitsLeft--;
+  }
+  
+  testAndWriteOut();
+}
+
+/**
+ * \brief Encode equiprobable bin
+ *
+ * \param binValue bin value
+ */
+Void TEncBinCABAC::encodeBinEP( UInt binValue )
+{
+  {
+    DTRACE_CABAC_VL( g_nSymbolCounter++ )
+    DTRACE_CABAC_T( "\tEPsymbol=" )
+    DTRACE_CABAC_V( binValue )
+    DTRACE_CABAC_T( "\n" )
+  }
+  m_uiBinsCoded += m_binCountIncrement;
+  m_uiLow <<= 1;
+  if( binValue )
+  {
+    m_uiLow += m_uiRange;
+  }
+  m_bitsLeft--;
+  
+  testAndWriteOut();
+}
+
+/**
+ * \brief Encode equiprobable bins
+ *
+ * \param binValues bin values
+ * \param numBins number of bins
+ */
+Void TEncBinCABAC::encodeBinsEP( UInt binValues, Int numBins )
+{
+  m_uiBinsCoded += numBins & -m_binCountIncrement;
+  
+  for ( Int i = 0; i < numBins; i++ )
+  {
+    DTRACE_CABAC_VL( g_nSymbolCounter++ )
+    DTRACE_CABAC_T( "\tEPsymbol=" )
+    DTRACE_CABAC_V( ( binValues >> ( numBins - 1 - i ) ) & 1 )
+    DTRACE_CABAC_T( "\n" )
+  }
+  
+  while ( numBins > 8 )
+  {
+    numBins -= 8;
+    UInt pattern = binValues >> numBins; 
+    m_uiLow <<= 8;
+    m_uiLow += m_uiRange * pattern;
+    binValues -= pattern << numBins;
+    m_bitsLeft -= 8;
+    
+    testAndWriteOut();
+  }
+  
+  m_uiLow <<= numBins;
+  m_uiLow += m_uiRange * binValues;
+  m_bitsLeft -= numBins;
+  
+  testAndWriteOut();
+}
+
+/**
+ * \brief Encode terminating bin
+ *
+ * \param binValue bin value
+ */
+Void TEncBinCABAC::encodeBinTrm( UInt binValue )
+{
+  m_uiBinsCoded += m_binCountIncrement;
+  m_uiRange -= 2;
+  if( binValue )
+  {
+    m_uiLow  += m_uiRange;
+    m_uiLow <<= 7;
+    m_uiRange = 2 << 7;
+    m_bitsLeft -= 7;
+  }
+  else if ( m_uiRange >= 256 )
+  {
+    return;
+  }
+  else
+  {
+    m_uiLow   <<= 1;
+    m_uiRange <<= 1;
+    m_bitsLeft--;    
+  }
+  
+  testAndWriteOut();
+}
+
+Void TEncBinCABAC::testAndWriteOut()
+{
+  if ( m_bitsLeft < 12 )
+  {
+    writeOut();
+  }
+}
+
+/**
+ * \brief Move bits from register into bitstream
+ */
+Void TEncBinCABAC::writeOut()
+{
+  UInt leadByte = m_uiLow >> (24 - m_bitsLeft);
+  m_bitsLeft += 8;
+  m_uiLow &= 0xffffffffu >> m_bitsLeft;
+  
+  if ( leadByte == 0xff )
+  {
+    m_numBufferedBytes++;
+  }
+  else
+  {
+    if ( m_numBufferedBytes > 0 )
+    {
+      UInt carry = leadByte >> 8;
+      UInt byte = m_bufferedByte + carry;
+      m_bufferedByte = leadByte & 0xff;
+      m_pcTComBitIf->write( byte, 8 );
+      
+      byte = ( 0xff + carry ) & 0xff;
+      while ( m_numBufferedBytes > 1 )
+      {
+        m_pcTComBitIf->write( byte, 8 );
+        m_numBufferedBytes--;
+      }
+    }
+    else
+    {
+      m_numBufferedBytes = 1;
+      m_bufferedByte = leadByte;
+    }      
+  }    
+}
+
+/** flush bits when CABAC termination
+  * \param [in] bEnd true means this flushing happens at the end of RBSP. No need to encode stop bit
+  */
+Void TEncBinCABAC::encodeFlush(Bool bEnd)
+{
+  m_uiRange = 2;
+
+  m_uiLow  += 2;
+  m_uiLow <<= 7;
+  m_uiRange = 2 << 7;
+  m_bitsLeft -= 7;
+  testAndWriteOut();
+  finish();
+
+  if(!bEnd)
+  {
+    m_pcTComBitIf->write( 1, 1 ); // stop bit
+  }
+}
+
+//! \}
Index: /trunk/source/Lib/TLibEncoder/TEncBinCoderCABAC.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncBinCoderCABAC.h	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/TEncBinCoderCABAC.h	(revision 2)
@@ -0,0 +1,107 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncBinCoderCABAC.h
+    \brief    binary entropy encoder of CABAC
+*/
+
+#ifndef __TENC_BIN_CODER_CABAC__
+#define __TENC_BIN_CODER_CABAC__
+
+#include "TLibCommon/TComCABACTables.h"
+#include "TEncBinCoder.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+class TEncBinCABAC : public TEncBinIf
+{
+public:
+  TEncBinCABAC ();
+  virtual ~TEncBinCABAC();
+  
+  Void  init              ( TComBitIf* pcTComBitIf );
+  Void  uninit            ();
+  
+  Void  start             ();
+  Void  finish            ();
+  Void  copyState         ( TEncBinIf* pcTEncBinIf );
+  Void  flush            ();
+
+  Void  resetBac          ();
+  Void  encodeNumSubseqIPCM( Int numSubseqIPCM );
+  Void  encodePCMAlignBits();
+  Void  xWritePCMCode     ( UInt uiCode, UInt uiLength );
+  
+  Void encodeFlush(Bool bEnd);  //!< flush bits when CABAC termination
+
+  Void  resetBits         ();
+  UInt  getNumWrittenBits ();
+  
+  Void  encodeBin         ( UInt  binValue,  ContextModel& rcCtxModel );
+  Void  encodeBinEP       ( UInt  binValue                            );
+  Void  encodeBinsEP      ( UInt  binValues, Int numBins              );
+  Void  encodeBinTrm      ( UInt  binValue                            );
+  
+  TEncBinCABAC* getTEncBinCABAC()  { return this; }
+  
+  Void  setBinsCoded              ( UInt uiVal )  { m_uiBinsCoded = uiVal;               }
+  UInt  getBinsCoded              ()              { return m_uiBinsCoded;                }
+  Void  setBinCountingEnableFlag  ( Bool bFlag )  { m_binCountIncrement = bFlag ? 1 : 0; }
+  Bool  getBinCountingEnableFlag  ()              { return m_binCountIncrement != 0;     }
+  
+#if FAST_BIT_EST
+protected:
+#else
+private:
+#endif
+  Void testAndWriteOut();
+  Void writeOut();
+  
+  TComBitIf*          m_pcTComBitIf;
+  UInt                m_uiLow;
+  UInt                m_uiRange;
+  UInt                m_bufferedByte;
+  Int                 m_numBufferedBytes;
+  Int                 m_bitsLeft;
+  UInt                m_uiBinsCoded;
+  Int                 m_binCountIncrement;
+#if FAST_BIT_EST
+  UInt64 m_fracBits;
+#endif
+};
+
+//! \}
+
+#endif
+
Index: /trunk/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.cpp	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.cpp	(revision 2)
@@ -0,0 +1,116 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncBinCoderCABAC.cpp
+    \brief    binary entropy encoder of CABAC
+*/
+
+#include "TEncBinCoderCABACCounter.h"
+#include "TLibCommon/TComRom.h"
+
+#if FAST_BIT_EST
+
+//! \ingroup TLibEncoder
+//! \{
+
+
+TEncBinCABACCounter::TEncBinCABACCounter()
+{
+}
+
+TEncBinCABACCounter::~TEncBinCABACCounter()
+{
+}
+
+Void TEncBinCABACCounter::finish()
+{
+  m_pcTComBitIf->write(0, UInt(m_fracBits >> 15) );
+  m_fracBits &= 32767;
+}
+
+UInt TEncBinCABACCounter::getNumWrittenBits()
+{
+  return m_pcTComBitIf->getNumberOfWrittenBits() + UInt( m_fracBits >> 15 );
+}
+
+/**
+ * \brief Encode bin
+ *
+ * \param binValue   bin value
+ * \param rcCtxModel context model
+ */
+Void TEncBinCABACCounter::encodeBin( UInt binValue, ContextModel &rcCtxModel )
+{
+  m_uiBinsCoded += m_binCountIncrement;
+  
+  m_fracBits += rcCtxModel.getEntropyBits( binValue );
+  rcCtxModel.update( binValue );
+}
+
+/**
+ * \brief Encode equiprobable bin
+ *
+ * \param binValue bin value
+ */
+Void TEncBinCABACCounter::encodeBinEP( UInt binValue )
+{
+  m_uiBinsCoded += m_binCountIncrement;
+  m_fracBits += 32768;
+}
+
+/**
+ * \brief Encode equiprobable bins
+ *
+ * \param binValues bin values
+ * \param numBins number of bins
+ */
+Void TEncBinCABACCounter::encodeBinsEP( UInt binValues, Int numBins )
+{
+  m_uiBinsCoded += numBins & -m_binCountIncrement;
+  m_fracBits += 32768 * numBins;
+}
+
+/**
+ * \brief Encode terminating bin
+ *
+ * \param binValue bin value
+ */
+Void TEncBinCABACCounter::encodeBinTrm( UInt binValue )
+{
+  m_uiBinsCoded += m_binCountIncrement;
+  m_fracBits += ContextModel::getEntropyBitsTrm( binValue );
+}
+
+//! \}
+#endif
+
Index: /trunk/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.h	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.h	(revision 2)
@@ -0,0 +1,72 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncBinCoderCABAC.h
+    \brief    binary entropy encoder of CABAC
+*/
+
+#ifndef __TENC_BIN_CODER_CABAC_COUNTER__
+#define __TENC_BIN_CODER_CABAC_COUNTER__
+
+
+#include "TEncBinCoderCABAC.h"
+
+#if FAST_BIT_EST
+
+//! \ingroup TLibEncoder
+//! \{
+
+
+class TEncBinCABACCounter : public TEncBinCABAC
+{
+public:
+  TEncBinCABACCounter ();
+  virtual ~TEncBinCABACCounter();
+  
+  Void  finish            ();
+  UInt  getNumWrittenBits ();
+
+  Void  encodeBin         ( UInt  binValue,  ContextModel& rcCtxModel );
+  Void  encodeBinEP       ( UInt  binValue                            );
+  Void  encodeBinsEP      ( UInt  binValues, Int numBins              );
+  Void  encodeBinTrm      ( UInt  binValue                            );
+  
+private:
+};
+
+//! \}
+
+#endif
+
+#endif
+
Index: /trunk/source/Lib/TLibEncoder/TEncCavlc.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 2)
@@ -0,0 +1,1771 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncCavlc.cpp
+    \brief    CAVLC encoder class
+*/
+
+#include "../TLibCommon/CommonDef.h"
+#include "TEncCavlc.h"
+#include "SEIwrite.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+#if ENC_DEC_TRACE
+
+Void  xTraceSPSHeader (TComSPS *pSPS)
+{
+  fprintf( g_hTrace, "=========== Sequence Parameter Set ID: %d ===========\n", pSPS->getSPSId() );
+}
+
+Void  xTracePPSHeader (TComPPS *pPPS)
+{
+  fprintf( g_hTrace, "=========== Picture Parameter Set ID: %d ===========\n", pPPS->getPPSId() );
+}
+
+#if !REMOVE_APS
+Void  xTraceAPSHeader (TComAPS *pAPS)
+{
+  fprintf( g_hTrace, "=========== Adaptation Parameter Set ===========\n");
+}
+#endif
+
+Void  xTraceSliceHeader (TComSlice *pSlice)
+{
+  fprintf( g_hTrace, "=========== Slice ===========\n");
+}
+
+#endif
+
+
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TEncCavlc::TEncCavlc()
+{
+  m_pcBitIf           = NULL;
+  m_uiCoeffCost       = 0;
+#if !REMOVE_FGS
+  m_iSliceGranularity = 0;
+#endif
+}
+
+TEncCavlc::~TEncCavlc()
+{
+}
+
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+Void TEncCavlc::resetEntropy()
+{
+}
+
+
+#if !REMOVE_APS
+Void  TEncCavlc::codeAPSInitInfo(TComAPS* pcAPS)
+{
+
+#if ENC_DEC_TRACE  
+  xTraceAPSHeader(pcAPS);
+#endif
+  //APS ID
+  WRITE_UVLC( pcAPS->getAPSID(), "aps_id" );
+}
+#endif
+
+Void TEncCavlc::codeDFFlag(UInt uiCode, const Char *pSymbolName)
+{
+  WRITE_FLAG(uiCode, pSymbolName);
+}
+Void TEncCavlc::codeDFSvlc(Int iCode, const Char *pSymbolName)
+{
+  WRITE_SVLC(iCode, pSymbolName);
+}
+
+#if J0234_INTER_RPS_SIMPL
+Void TEncCavlc::codeShortTermRefPicSet( TComSPS* pcSPS, TComReferencePictureSet* rps, Bool calledFromSliceHeader)
+#else
+Void TEncCavlc::codeShortTermRefPicSet( TComSPS* pcSPS, TComReferencePictureSet* rps )
+#endif
+{
+#if PRINT_RPS_INFO
+  int lastBits = getNumberOfWrittenBits();
+#endif
+  WRITE_FLAG( rps->getInterRPSPrediction(), "inter_ref_pic_set_prediction_flag" ); // inter_RPS_prediction_flag
+  if (rps->getInterRPSPrediction()) 
+  {
+    Int deltaRPS = rps->getDeltaRPS();
+#if J0234_INTER_RPS_SIMPL
+    if(calledFromSliceHeader)
+    {
+      WRITE_UVLC( rps->getDeltaRIdxMinus1(), "delta_idx_minus1" ); // delta index of the Reference Picture Set used for prediction minus 1
+    }
+#else
+    WRITE_UVLC( rps->getDeltaRIdxMinus1(), "delta_idx_minus1" ); // delta index of the Reference Picture Set used for prediction minus 1
+#endif
+
+    WRITE_CODE( (deltaRPS >=0 ? 0: 1), 1, "delta_rps_sign" ); //delta_rps_sign
+    WRITE_UVLC( abs(deltaRPS) - 1, "abs_delta_rps_minus1"); // absolute delta RPS minus 1
+
+    for(Int j=0; j < rps->getNumRefIdc(); j++)
+    {
+      Int refIdc = rps->getRefIdc(j);
+      WRITE_CODE( (refIdc==1? 1: 0), 1, "used_by_curr_pic_flag" ); //first bit is "1" if Idc is 1 
+      if (refIdc != 1) 
+      {
+        WRITE_CODE( refIdc>>1, 1, "use_delta_flag" ); //second bit is "1" if Idc is 2, "0" otherwise.
+      }
+    }
+  }
+  else
+  {
+    WRITE_UVLC( rps->getNumberOfNegativePictures(), "num_negative_pics" );
+    WRITE_UVLC( rps->getNumberOfPositivePictures(), "num_positive_pics" );
+    Int prev = 0;
+    for(Int j=0 ; j < rps->getNumberOfNegativePictures(); j++)
+    {
+      WRITE_UVLC( prev-rps->getDeltaPOC(j)-1, "delta_poc_s0_minus1" );
+      prev = rps->getDeltaPOC(j);
+      WRITE_FLAG( rps->getUsed(j), "used_by_curr_pic_s0_flag"); 
+    }
+    prev = 0;
+    for(Int j=rps->getNumberOfNegativePictures(); j < rps->getNumberOfNegativePictures()+rps->getNumberOfPositivePictures(); j++)
+    {
+      WRITE_UVLC( rps->getDeltaPOC(j)-prev-1, "delta_poc_s1_minus1" );
+      prev = rps->getDeltaPOC(j);
+      WRITE_FLAG( rps->getUsed(j), "used_by_curr_pic_s1_flag" ); 
+    }
+  }
+
+#if PRINT_RPS_INFO
+  printf("irps=%d (%2d bits) ", rps->getInterRPSPrediction(), getNumberOfWrittenBits() - lastBits);
+  rps->printDeltaPOC();
+#endif
+}
+
+
+Void TEncCavlc::codePPS( TComPPS* pcPPS )
+{
+#if ENC_DEC_TRACE  
+  xTracePPSHeader (pcPPS);
+#endif
+  
+  WRITE_UVLC( pcPPS->getPPSId(),                             "pic_parameter_set_id" );
+  WRITE_UVLC( pcPPS->getSPSId(),                             "seq_parameter_set_id" );
+
+  WRITE_FLAG( pcPPS->getSignHideFlag(), "sign_data_hiding_flag" );
+  WRITE_FLAG( pcPPS->getCabacInitPresentFlag() ? 1 : 0,   "cabac_init_present_flag" );
+  WRITE_UVLC( pcPPS->getNumRefIdxL0DefaultActive()-1,     "num_ref_idx_l0_default_active_minus1");
+  WRITE_UVLC( pcPPS->getNumRefIdxL1DefaultActive()-1,     "num_ref_idx_l1_default_active_minus1");
+
+  WRITE_SVLC( pcPPS->getPicInitQPMinus26(),                  "pic_init_qp_minus26");
+  WRITE_FLAG( pcPPS->getConstrainedIntraPred() ? 1 : 0,      "constrained_intra_pred_flag" );
+#if PPS_TS_FLAG
+  WRITE_FLAG( pcPPS->getUseTransformSkip() ? 1 : 0,  "transform_skip_enabled_flag" ); 
+#endif
+#if !REMOVE_FGS
+  WRITE_CODE( pcPPS->getSliceGranularity(), 2,               "slice_granularity");
+#endif
+#if CU_DQP_ENABLE_FLAG
+  WRITE_FLAG( pcPPS->getUseDQP() ? 1 : 0, "cu_qp_delta_enabled_flag" );
+  if ( pcPPS->getUseDQP() )
+  {
+#if REMOVE_FGS
+    WRITE_UVLC( pcPPS->getMaxCuDQPDepth(), "diff_cu_qp_delta_depth" );
+#else
+    WRITE_UVLC( pcPPS->getMaxCuDQPDepth() - pcPPS->getSliceGranularity(), "diff_cu_qp_delta_depth" );
+#endif
+  }
+#else
+#if REMOVE_FGS
+  WRITE_UVLC( pcPPS->getMaxCuDQPDepth() + pcPPS->getUseDQP(),                   "diff_cu_qp_delta_depth" );
+#else
+  WRITE_UVLC( pcPPS->getMaxCuDQPDepth() - pcPPS->getSliceGranularity() + pcPPS->getUseDQP(),                   "diff_cu_qp_delta_depth" );
+#endif
+#endif
+  WRITE_SVLC( pcPPS->getChromaCbQpOffset(),                   "cb_qp_offset" );
+  WRITE_SVLC( pcPPS->getChromaCrQpOffset(),                   "cr_qp_offset" );
+#if CHROMA_QP_EXTENSION
+  WRITE_FLAG( pcPPS->getSliceChromaQpFlag() ? 1 : 0,          "slicelevel_chroma_qp_flag" );
+#endif
+
+  WRITE_FLAG( pcPPS->getUseWP() ? 1 : 0,  "weighted_pred_flag" );   // Use of Weighting Prediction (P_SLICE)
+  WRITE_FLAG( pcPPS->getWPBiPred() ? 1 : 0, "weighted_bipred_flag" );  // Use of Weighting Bi-Prediction (B_SLICE)
+  WRITE_FLAG( pcPPS->getOutputFlagPresentFlag() ? 1 : 0,  "output_flag_present_flag" );
+#if !TILES_WPP_ENTROPYSLICES_FLAGS
+#if DEPENDENT_SLICES
+  WRITE_FLAG( pcPPS->getDependentSliceEnabledFlag() ? 1 : 0, "dependent_slices_enabled_flag" );
+#endif
+#endif
+  WRITE_FLAG( pcPPS->getTransquantBypassEnableFlag() ? 1 : 0, "transquant_bypass_enable_flag" );
+
+#if TILES_WPP_ENTROPYSLICES_FLAGS
+#if DEPENDENT_SLICES
+  WRITE_FLAG( pcPPS->getDependentSliceEnabledFlag()    ? 1 : 0, "dependent_slice_enabled_flag" );
+#endif
+  WRITE_FLAG( pcPPS->getTilesEnabledFlag()             ? 1 : 0, "tiles_enabled_flag" );
+  WRITE_FLAG( pcPPS->getEntropyCodingSyncEnabledFlag() ? 1 : 0, "entropy_coding_sync_enabled_flag" );
+  WRITE_FLAG( pcPPS->getEntropySliceEnabledFlag()      ? 1 : 0, "entropy_slice_enabled_flag" );
+  if( pcPPS->getTilesEnabledFlag() )
+#else
+  Int tilesOrEntropyCodingSyncIdc = 0;
+  if ( pcPPS->getNumColumnsMinus1() > 0 || pcPPS->getNumRowsMinus1() > 0)
+  {
+    tilesOrEntropyCodingSyncIdc = 1;
+  }
+  else if ( pcPPS->getNumSubstreams() > 1 )
+  {
+    tilesOrEntropyCodingSyncIdc = 2;
+  }
+#if DEPENDENT_SLICES
+  else if( pcPPS->getDependentSliceEnabledFlag() )
+  {
+    if(pcPPS->getTilesOrEntropyCodingSyncIdc() != 2)
+    {
+      tilesOrEntropyCodingSyncIdc = 3;
+    }
+    else
+    {
+      tilesOrEntropyCodingSyncIdc = 2;
+    }
+  }
+#endif
+  pcPPS->setTilesOrEntropyCodingSyncIdc( tilesOrEntropyCodingSyncIdc );
+  WRITE_CODE(tilesOrEntropyCodingSyncIdc, 2, "tiles_or_entropy_coding_sync_idc");
+
+  if(pcPPS->getTilesOrEntropyCodingSyncIdc()==1)
+#endif
+  {
+    WRITE_UVLC( pcPPS->getNumColumnsMinus1(),                                    "num_tile_columns_minus1" );
+    WRITE_UVLC( pcPPS->getNumRowsMinus1(),                                       "num_tile_rows_minus1" );
+    WRITE_FLAG( pcPPS->getUniformSpacingFlag(),                                  "uniform_spacing_flag" );
+    if( pcPPS->getUniformSpacingFlag() == 0 )
+    {
+      for(UInt i=0; i<pcPPS->getNumColumnsMinus1(); i++)
+      {
+        WRITE_UVLC( pcPPS->getColumnWidth(i)-1,                                  "column_width_minus1" );
+      }
+      for(UInt i=0; i<pcPPS->getNumRowsMinus1(); i++)
+      {
+        WRITE_UVLC( pcPPS->getRowHeight(i)-1,                                    "row_height_minus1" );
+      }
+    }
+    if(pcPPS->getNumColumnsMinus1() !=0 || pcPPS->getNumRowsMinus1() !=0)
+    {
+      WRITE_FLAG( pcPPS->getLoopFilterAcrossTilesEnabledFlag()?1 : 0,          "loop_filter_across_tiles_enabled_flag");
+    }
+  }
+#if !TILES_WPP_ENTROPYSLICES_FLAGS
+#if DEPENDENT_SLICES
+  else if( pcPPS->getTilesOrEntropyCodingSyncIdc()==3 )
+  {
+    WRITE_FLAG( pcPPS->getCabacIndependentFlag()? 1 : 0,            "cabac_independent_flag" );
+  }
+#endif
+#endif
+#if MOVE_LOOP_FILTER_SLICES_FLAG
+  WRITE_FLAG( pcPPS->getLoopFilterAcrossSlicesEnabledFlag()?1 : 0,        "loop_filter_across_slices_enabled_flag");
+#endif
+  WRITE_FLAG( pcPPS->getDeblockingFilterControlPresentFlag()?1 : 0,       "deblocking_filter_control_present_flag");
+  if(pcPPS->getDeblockingFilterControlPresentFlag())
+  {
+    WRITE_FLAG( pcPPS->getDeblockingFilterOverrideEnabledFlag() ? 1 : 0,  "deblocking_filter_override_enabled_flag" ); 
+    WRITE_FLAG( pcPPS->getPicDisableDeblockingFilterFlag(),               "pic_disable_deblocking_filter_flag" );
+    if(!pcPPS->getPicDisableDeblockingFilterFlag())
+    {
+      WRITE_SVLC( pcPPS->getDeblockingFilterBetaOffsetDiv2(),             "pps_beta_offset_div2" );
+      WRITE_SVLC( pcPPS->getDeblockingFilterTcOffsetDiv2(),               "pps_tc_offset_div2" );
+    }
+  }
+  WRITE_FLAG( pcPPS->getScalingListPresentFlag() ? 1 : 0,                          "pps_scaling_list_data_present_flag" ); 
+  if( pcPPS->getScalingListPresentFlag() )
+  {
+#if SCALING_LIST_OUTPUT_RESULT
+    printf("PPS\n");
+#endif
+    codeScalingList( m_pcSlice->getScalingList() );
+  }
+  WRITE_UVLC( pcPPS->getLog2ParallelMergeLevelMinus2(), "log2_parallel_merge_level_minus2");
+#if SLICE_HEADER_EXTENSION
+  WRITE_FLAG( pcPPS->getSliceHeaderExtensionPresentFlag(), "slice_header_extension_present_flag");
+#endif
+  WRITE_FLAG( 0, "pps_extension_flag" );
+}
+
+#if SUPPORT_FOR_VUI
+Void TEncCavlc::codeVUI( TComVUI *pcVUI, TComSPS* pcSPS )
+{
+#if ENC_DEC_TRACE
+  fprintf( g_hTrace, "----------- vui_parameters -----------\n");
+#endif
+  WRITE_FLAG(pcVUI->getAspectRatioInfoPresentFlag(),            "aspect_ratio_info_present_flag");
+  if (pcVUI->getAspectRatioInfoPresentFlag())
+  {
+    WRITE_CODE(pcVUI->getAspectRatioIdc(), 8,                   "aspect_ratio_idc" );
+    if (pcVUI->getAspectRatioIdc() == 255)
+    {
+      WRITE_CODE(pcVUI->getSarWidth(), 16,                      "sar_width");
+      WRITE_CODE(pcVUI->getSarHeight(), 16,                     "sar_height");
+    }
+  }
+  WRITE_FLAG(pcVUI->getOverscanInfoPresentFlag(),               "overscan_info_present_flag");
+  if (pcVUI->getOverscanInfoPresentFlag())
+  {
+    WRITE_FLAG(pcVUI->getOverscanAppropriateFlag(),             "overscan_appropriate_flag");
+  }
+  WRITE_FLAG(pcVUI->getVideoSignalTypePresentFlag(),            "video_signal_type_present_flag");
+  if (pcVUI->getVideoSignalTypePresentFlag())
+  {
+    WRITE_CODE(pcVUI->getVideoFormat(), 3,                      "video_format");
+    WRITE_FLAG(pcVUI->getVideoFullRangeFlag(),                  "video_full_range_flag");
+    WRITE_FLAG(pcVUI->getColourDescriptionPresentFlag(),        "colour_description_present_flag");
+    if (pcVUI->getColourDescriptionPresentFlag())
+    {
+      WRITE_CODE(pcVUI->getColourPrimaries(), 8,                "colour_primaries");
+      WRITE_CODE(pcVUI->getTransferCharacteristics(), 8,        "transfer_characteristics");
+      WRITE_CODE(pcVUI->getMatrixCoefficients(), 8,             "matrix_coefficients");
+    }
+  }
+
+  WRITE_FLAG(pcVUI->getChromaLocInfoPresentFlag(),              "chroma_loc_info_present_flag");
+  if (pcVUI->getChromaLocInfoPresentFlag())
+  {
+    WRITE_UVLC(pcVUI->getChromaSampleLocTypeTopField(),         "chroma_sample_loc_type_top_field");
+    WRITE_UVLC(pcVUI->getChromaSampleLocTypeBottomField(),      "chroma_sample_loc_type_bottom_field");
+  }
+
+  WRITE_FLAG(pcVUI->getNeutralChromaIndicationFlag(),           "neutral_chroma_indication_flag");
+  WRITE_FLAG(pcVUI->getFieldSeqFlag(),                          "field_seq_flag");
+  assert(pcVUI->getFieldSeqFlag() == 0);                        // not currently supported
+  WRITE_FLAG(pcVUI->getHrdParametersPresentFlag(),              "hrd_parameters_present_flag");
+#if !BUFFERING_PERIOD_AND_TIMING_SEI
+  assert(pcVUI->getHrdParametersPresentFlag() == 0);            // not currently supported
+#else
+  if( pcVUI->getHrdParametersPresentFlag() )
+  {
+    WRITE_FLAG(pcVUI->getTimingInfoPresentFlag(),               "timing_info_present_flag");
+    if( pcVUI->getTimingInfoPresentFlag() )
+    {
+      WRITE_CODE(pcVUI->getNumUnitsInTick(), 32,                "num_units_in_tick");
+      WRITE_CODE(pcVUI->getTimeScale(),      32,                "time_scale");
+    }
+    WRITE_FLAG(pcVUI->getNalHrdParametersPresentFlag(),         "nal_hrd_parameters_present_flag");
+    WRITE_FLAG(pcVUI->getVclHrdParametersPresentFlag(),         "vcl_hrd_parameters_present_flag");
+    if( pcVUI->getNalHrdParametersPresentFlag() || pcVUI->getVclHrdParametersPresentFlag() )
+    {
+      WRITE_FLAG(pcVUI->getSubPicCpbParamsPresentFlag(),        "sub_pic_cpb_params_present_flag");
+      if( pcVUI->getSubPicCpbParamsPresentFlag() )
+      {
+        WRITE_CODE(pcVUI->getTickDivisorMinus2(), 8,            "tick_divisor_minus2");
+        WRITE_CODE(pcVUI->getDuCpbRemovalDelayLengthMinus1(), 5,  "du_cpb_removal_delay_length_minus1");
+      }
+      WRITE_CODE(pcVUI->getBitRateScale(), 4,                   "bit_rate_scale");
+      WRITE_CODE(pcVUI->getCpbSizeScale(), 4,                   "cpb_size_scale");
+      WRITE_CODE(pcVUI->getInitialCpbRemovalDelayLengthMinus1(), 5, "initial_cpb_removal_delay_length_minus1");
+      WRITE_CODE(pcVUI->getCpbRemovalDelayLengthMinus1(),        5, "cpb_removal_delay_length_minus1");
+      WRITE_CODE(pcVUI->getDpbOutputDelayLengthMinus1(),         5, "dpb_output_delay_length_minus1");
+    }
+    Int i, j, nalOrVcl;
+    for( i = 0; i <= pcSPS->getMaxTLayers(); i ++ )
+    {
+      WRITE_FLAG(pcVUI->getFixedPicRateFlag(i),                 "fixed_pic_rate_flag");
+      if( pcVUI->getFixedPicRateFlag( i ) )
+      {
+        WRITE_UVLC(pcVUI->getPicDurationInTcMinus1(i),          "pic_duration_in_tc_minus1");
+      }
+      WRITE_FLAG(pcVUI->getLowDelayHrdFlag(i),                  "low_delay_hrd_flag");
+      WRITE_UVLC(pcVUI->getCpbCntMinus1(i),                     "cpb_cnt_minus1");
+     
+      for( nalOrVcl = 0; nalOrVcl < 2; nalOrVcl ++ )
+      {
+        if( ( ( nalOrVcl == 0 ) && ( pcVUI->getNalHrdParametersPresentFlag() ) ) ||
+            ( ( nalOrVcl == 1 ) && ( pcVUI->getVclHrdParametersPresentFlag() ) ) )
+        {
+          for( j = 0; j < ( pcVUI->getCpbCntMinus1( i ) + 1 ); j ++ )
+          {
+            WRITE_UVLC(pcVUI->getBitRateValueMinus1(i, j, nalOrVcl), "bit_size_value_minus1");
+            WRITE_UVLC(pcVUI->getCpbSizeValueMinus1(i, j, nalOrVcl), "cpb_size_value_minus1");
+            WRITE_FLAG(pcVUI->getCbrFlag(i, j, nalOrVcl),            "cbr_flag");
+          }
+        }
+      }
+    }
+  }
+#endif
+  WRITE_FLAG(pcVUI->getBitstreamRestrictionFlag(),              "bitstream_restriction_flag");
+  if (pcVUI->getBitstreamRestrictionFlag())
+  {
+    WRITE_FLAG(pcVUI->getTilesFixedStructureFlag(),             "tiles_fixed_structure_flag");
+    WRITE_FLAG(pcVUI->getMotionVectorsOverPicBoundariesFlag(),  "motion_vectors_over_pic_boundaries_flag");
+    WRITE_UVLC(pcVUI->getMaxBytesPerPicDenom(),                 "max_bytes_per_pic_denom");
+    WRITE_UVLC(pcVUI->getMaxBitsPerMinCuDenom(),                "max_bits_per_mincu_denom");
+    WRITE_UVLC(pcVUI->getLog2MaxMvLengthHorizontal(),           "log2_max_mv_length_horizontal");
+    WRITE_UVLC(pcVUI->getLog2MaxMvLengthVertical(),             "log2_max_mv_length_vertical");
+  }
+
+}
+#endif
+
+Void TEncCavlc::codeSPS( TComSPS* pcSPS )
+{
+#if ENC_DEC_TRACE  
+  xTraceSPSHeader (pcSPS);
+#endif
+#if SPS_SYNTAX_CHANGES
+  WRITE_CODE( pcSPS->getVPSId (),          4,       "video_parameter_set_id" );
+  WRITE_CODE( pcSPS->getMaxTLayers() - 1,  3,       "sps_max_sub_layers_minus1" );
+  WRITE_FLAG( 0,                                    "sps_reserved_zero_bit");
+  codePTL(pcSPS->getPTL(), 1, pcSPS->getMaxTLayers() - 1);
+  WRITE_UVLC( pcSPS->getSPSId (),                   "seq_parameter_set_id" );
+  WRITE_UVLC( pcSPS->getChromaFormatIdc (),         "chroma_format_idc" );
+  assert(pcSPS->getChromaFormatIdc () == 1);
+  // in the first version chroma_format_idc can only be equal to 1 (4:2:0)
+  if( pcSPS->getChromaFormatIdc () == 3 )
+  {
+    WRITE_FLAG( 0,                                  "separate_colour_plane_flag");
+  }
+
+#else
+  WRITE_CODE( pcSPS->getProfileSpace (),   3,       "profile_space" );
+  WRITE_CODE( pcSPS->getProfileIdc (),     5,       "profile_idc" );
+  WRITE_CODE( pcSPS->getRsvdIndFlags(),   16,       "reserved_indicator_flags" );
+  WRITE_CODE( pcSPS->getLevelIdc (),       8,       "level_idc" );
+  WRITE_CODE( pcSPS->getProfileCompat (), 32,       "profile_compatibility" );
+  WRITE_UVLC( pcSPS->getSPSId (),                   "seq_parameter_set_id" );
+  WRITE_UVLC( pcSPS->getVPSId (),                   "video_parameter_set_id" );
+  WRITE_UVLC( pcSPS->getChromaFormatIdc (),         "chroma_format_idc" );
+  WRITE_CODE( pcSPS->getMaxTLayers() - 1,  3,       "max_temporal_layers_minus1" );
+#endif
+  WRITE_UVLC( pcSPS->getPicWidthInLumaSamples (),   "pic_width_in_luma_samples" );
+  WRITE_UVLC( pcSPS->getPicHeightInLumaSamples(),   "pic_height_in_luma_samples" );
+  WRITE_FLAG( pcSPS->getPicCroppingFlag(),          "pic_cropping_flag" );
+  if (pcSPS->getPicCroppingFlag())
+  {
+    WRITE_UVLC( pcSPS->getPicCropLeftOffset()   / TComSPS::getCropUnitX(pcSPS->getChromaFormatIdc() ), "pic_crop_left_offset" );
+    WRITE_UVLC( pcSPS->getPicCropRightOffset()  / TComSPS::getCropUnitX(pcSPS->getChromaFormatIdc() ), "pic_crop_right_offset" );
+    WRITE_UVLC( pcSPS->getPicCropTopOffset()    / TComSPS::getCropUnitY(pcSPS->getChromaFormatIdc() ), "pic_crop_top_offset" );
+    WRITE_UVLC( pcSPS->getPicCropBottomOffset() / TComSPS::getCropUnitY(pcSPS->getChromaFormatIdc() ), "pic_crop_bottom_offset" );
+  }
+
+#if FULL_NBIT
+  WRITE_UVLC( pcSPS->getBitDepth() - 8,             "bit_depth_luma_minus8" );
+#else
+  WRITE_UVLC( pcSPS->getBitIncrement(),             "bit_depth_luma_minus8" );
+#endif
+#if FULL_NBIT
+  WRITE_UVLC( pcSPS->getBitDepth() - 8,             "bit_depth_chroma_minus8" );
+#else
+  WRITE_UVLC( pcSPS->getBitIncrement(),             "bit_depth_chroma_minus8" );
+#endif
+
+  WRITE_FLAG( pcSPS->getUsePCM() ? 1 : 0,                   "pcm_enabled_flag");
+
+  if( pcSPS->getUsePCM() )
+  {
+  WRITE_CODE( pcSPS->getPCMBitDepthLuma() - 1, 4,   "pcm_bit_depth_luma_minus1" );
+  WRITE_CODE( pcSPS->getPCMBitDepthChroma() - 1, 4, "pcm_bit_depth_chroma_minus1" );
+  }
+
+  WRITE_UVLC( pcSPS->getBitsForPOC()-4,                 "log2_max_pic_order_cnt_lsb_minus4" );
+  for(UInt i=0; i <= pcSPS->getMaxTLayers()-1; i++)
+  {
+    WRITE_UVLC( pcSPS->getMaxDecPicBuffering(i),           "max_dec_pic_buffering[i]" );
+    WRITE_UVLC( pcSPS->getNumReorderPics(i),               "num_reorder_pics[i]" );
+    WRITE_UVLC( pcSPS->getMaxLatencyIncrease(i),           "max_latency_increase[i]" );
+  }
+  assert( pcSPS->getMaxCUWidth() == pcSPS->getMaxCUHeight() );
+  
+  UInt MinCUSize = pcSPS->getMaxCUWidth() >> ( pcSPS->getMaxCUDepth()-g_uiAddCUDepth );
+  UInt log2MinCUSize = 0;
+  while(MinCUSize > 1)
+  {
+    MinCUSize >>= 1;
+    log2MinCUSize++;
+  }
+
+  WRITE_FLAG( pcSPS->getRestrictedRefPicListsFlag(),                                 "restricted_ref_pic_lists_flag" );
+  if( pcSPS->getRestrictedRefPicListsFlag() )
+  {
+    WRITE_FLAG( pcSPS->getListsModificationPresentFlag(),                            "lists_modification_present_flag" );
+  }
+  WRITE_UVLC( log2MinCUSize - 3,                                                     "log2_min_coding_block_size_minus3" );
+  WRITE_UVLC( pcSPS->getMaxCUDepth()-g_uiAddCUDepth,                                 "log2_diff_max_min_coding_block_size" );
+  WRITE_UVLC( pcSPS->getQuadtreeTULog2MinSize() - 2,                                 "log2_min_transform_block_size_minus2" );
+  WRITE_UVLC( pcSPS->getQuadtreeTULog2MaxSize() - pcSPS->getQuadtreeTULog2MinSize(), "log2_diff_max_min_transform_block_size" );
+  if( pcSPS->getUsePCM() )
+  {
+    WRITE_UVLC( pcSPS->getPCMLog2MinSize() - 3,                                      "log2_min_pcm_coding_block_size_minus3" );
+    WRITE_UVLC( pcSPS->getPCMLog2MaxSize() - pcSPS->getPCMLog2MinSize(),             "log2_diff_max_min_pcm_coding_block_size" );
+  }
+  WRITE_UVLC( pcSPS->getQuadtreeTUMaxDepthInter() - 1,                               "max_transform_hierarchy_depth_inter" );
+  WRITE_UVLC( pcSPS->getQuadtreeTUMaxDepthIntra() - 1,                               "max_transform_hierarchy_depth_intra" );
+  WRITE_FLAG( pcSPS->getScalingListFlag() ? 1 : 0,                                   "scaling_list_enabled_flag" ); 
+  if(pcSPS->getScalingListFlag())
+  {
+    WRITE_FLAG( pcSPS->getScalingListPresentFlag() ? 1 : 0,                          "sps_scaling_list_data_present_flag" ); 
+    if(pcSPS->getScalingListPresentFlag())
+    {
+#if SCALING_LIST_OUTPUT_RESULT
+    printf("SPS\n");
+#endif
+      codeScalingList( m_pcSlice->getScalingList() );
+    }
+  }
+#if !REMOVE_LMCHROMA
+  WRITE_FLAG( pcSPS->getUseLMChroma () ? 1 : 0,                                      "chroma_pred_from_luma_enabled_flag" );
+#endif
+#if !PPS_TS_FLAG
+  WRITE_FLAG( pcSPS->getUseTransformSkip () ? 1 : 0,                                 "transform_skip_enabled_flag" );
+#endif
+#if !MOVE_LOOP_FILTER_SLICES_FLAG
+  WRITE_FLAG( pcSPS->getLFCrossSliceBoundaryFlag()?1 : 0,                            "seq_loop_filter_across_slices_enabled_flag");
+#endif
+  WRITE_FLAG( pcSPS->getUseAMP(),                                                    "asymmetric_motion_partitions_enabled_flag" );
+#if !REMOVE_NSQT
+  WRITE_FLAG( pcSPS->getUseNSQT(),                                                   "non_square_quadtree_enabled_flag" );
+#endif
+  WRITE_FLAG( pcSPS->getUseSAO() ? 1 : 0,                                            "sample_adaptive_offset_enabled_flag");
+#if !REMOVE_ALF
+  WRITE_FLAG( pcSPS->getUseALF () ? 1 : 0,                                           "adaptive_loop_filter_enabled_flag");
+#endif
+  if( pcSPS->getUsePCM() )
+  {
+  WRITE_FLAG( pcSPS->getPCMFilterDisableFlag()?1 : 0,                                "pcm_loop_filter_disable_flag");
+  }
+
+  assert( pcSPS->getMaxTLayers() > 0 );         
+
+  WRITE_FLAG( pcSPS->getTemporalIdNestingFlag() ? 1 : 0,                             "temporal_id_nesting_flag" );
+
+  TComRPSList* rpsList = pcSPS->getRPSList();
+  TComReferencePictureSet*      rps;
+
+  WRITE_UVLC(rpsList->getNumberOfReferencePictureSets(), "num_short_term_ref_pic_sets" );
+  for(Int i=0; i < rpsList->getNumberOfReferencePictureSets(); i++)
+  {
+    rps = rpsList->getReferencePictureSet(i);
+#if J0234_INTER_RPS_SIMPL
+    codeShortTermRefPicSet(pcSPS,rps,false);
+#else
+    codeShortTermRefPicSet(pcSPS,rps);
+#endif
+  }    
+  WRITE_FLAG( pcSPS->getLongTermRefsPresent() ? 1 : 0,         "long_term_ref_pics_present_flag" );
+#if LTRP_IN_SPS
+  if (pcSPS->getLongTermRefsPresent()) 
+  {
+    WRITE_UVLC(pcSPS->getNumLongTermRefPicSPS(), "num_long_term_ref_pic_sps" );
+    for (UInt k = 0; k < pcSPS->getNumLongTermRefPicSPS(); k++)
+    {
+      WRITE_CODE( pcSPS->getLtRefPicPocLsbSps(k), pcSPS->getBitsForPOC(), "lt_ref_pic_poc_lsb_sps");
+      WRITE_FLAG( pcSPS->getUsedByCurrPicLtSPSFlag(k), "used_by_curr_pic_lt_sps_flag");
+    }
+  }
+#endif
+  WRITE_FLAG( pcSPS->getTMVPFlagsPresent()  ? 1 : 0,           "sps_temporal_mvp_enable_flag" );
+#if SUPPORT_FOR_VUI
+  WRITE_FLAG( pcSPS->getVuiParametersPresentFlag(),             "vui_parameters_present_flag" );
+  if (pcSPS->getVuiParametersPresentFlag())
+  {
+      codeVUI(pcSPS->getVuiParameters(), pcSPS);
+  }
+#endif
+#if !SPS_AMVP_CLEANUP
+  // AMVP mode for each depth
+  for (Int i = 0; i < pcSPS->getMaxCUDepth(); i++)
+  {
+    xWriteFlag( pcSPS->getAMVPMode(i) ? 1 : 0);
+  }
+#endif
+  WRITE_FLAG( 0, "sps_extension_flag" );
+}
+
+Void TEncCavlc::codeVPS( TComVPS* pcVPS )
+{
+#if VPS_SYNTAX_CHANGES
+  WRITE_CODE( pcVPS->getVPSId(),                    4,        "video_parameter_set_id" );
+  WRITE_FLAG( pcVPS->getTemporalNestingFlag(),                "vps_temporal_id_nesting_flag" );
+  WRITE_CODE( 0,                                    2,        "vps_reserved_zero_2bits" );
+  WRITE_CODE( 0,                                    6,        "vps_reserved_zero_6bits" );
+  WRITE_CODE( pcVPS->getMaxTLayers() - 1,           3,        "vps_max_sub_layers_minus1" );
+  codePTL( pcVPS->getPTL(), true, pcVPS->getMaxTLayers() - 1 );
+  WRITE_CODE( 0,                                   12,        "vps_reserved_zero_12bits" );
+#else
+  WRITE_CODE( pcVPS->getMaxTLayers() - 1,     3,        "vps_max_temporal_layers_minus1" );
+  WRITE_CODE( pcVPS->getMaxLayers() - 1,      5,        "vps_max_layers_minus1" );
+  WRITE_UVLC( pcVPS->getVPSId(),                        "video_parameter_set_id" );
+  WRITE_FLAG( pcVPS->getTemporalNestingFlag(),          "vps_temporal_id_nesting_flag" );
+#endif
+  for(UInt i=0; i <= pcVPS->getMaxTLayers()-1; i++)
+  {
+    WRITE_UVLC( pcVPS->getMaxDecPicBuffering(i),           "vps_max_dec_pic_buffering[i]" );
+    WRITE_UVLC( pcVPS->getNumReorderPics(i),               "vps_num_reorder_pics[i]" );
+    WRITE_UVLC( pcVPS->getMaxLatencyIncrease(i),           "vps_max_latency_increase[i]" );
+  }
+#if VPS_SYNTAX_CHANGES
+  WRITE_UVLC( 0,                                           "vps_num_hrd_parameters" );
+  // hrd_parameters
+#endif
+  WRITE_FLAG( 0,                     "vps_extension_flag" );
+  
+  //future extensions here..
+  
+  return;
+}
+
+Void TEncCavlc::codeSliceHeader         ( TComSlice* pcSlice )
+{
+#if ENC_DEC_TRACE  
+  xTraceSliceHeader (pcSlice);
+#endif
+
+  //calculate number of bits required for slice address
+  Int maxAddrOuter = pcSlice->getPic()->getNumCUsInFrame();
+  Int reqBitsOuter = 0;
+  while(maxAddrOuter>(1<<reqBitsOuter)) 
+  {
+    reqBitsOuter++;
+  }
+  Int maxAddrInner = pcSlice->getPic()->getNumPartInCU()>>(2);
+#if REMOVE_FGS
+  maxAddrInner = 1;
+#else
+  maxAddrInner = (1<<(pcSlice->getPPS()->getSliceGranularity()<<1));
+#endif
+  Int reqBitsInner = 0;
+  
+  while(maxAddrInner>(1<<reqBitsInner))
+  {
+    reqBitsInner++;
+  }
+  Int lCUAddress;
+  Int innerAddress;
+  if (pcSlice->isNextSlice())
+  {
+    // Calculate slice address
+    lCUAddress = (pcSlice->getSliceCurStartCUAddr()/pcSlice->getPic()->getNumPartInCU());
+#if REMOVE_FGS
+    innerAddress = 0;
+#else
+    innerAddress = (pcSlice->getSliceCurStartCUAddr()%(pcSlice->getPic()->getNumPartInCU()))>>((pcSlice->getSPS()->getMaxCUDepth()-pcSlice->getPPS()->getSliceGranularity())<<1);
+#endif
+  }
+  else
+  {
+    // Calculate slice address
+    lCUAddress = (pcSlice->getDependentSliceCurStartCUAddr()/pcSlice->getPic()->getNumPartInCU());
+#if REMOVE_FGS
+    innerAddress = 0;
+#else
+    innerAddress = (pcSlice->getDependentSliceCurStartCUAddr()%(pcSlice->getPic()->getNumPartInCU()))>>((pcSlice->getSPS()->getMaxCUDepth()-pcSlice->getPPS()->getSliceGranularity())<<1);
+#endif
+    
+  }
+  //write slice address
+  Int address = (pcSlice->getPic()->getPicSym()->getCUOrderMap(lCUAddress) << reqBitsInner) + innerAddress;
+  WRITE_FLAG( address==0, "first_slice_in_pic_flag" );
+#if SPLICING_FRIENDLY_PARAMS
+  if ( pcSlice->getRapPicFlag() )
+  {
+    WRITE_FLAG( 0, "no_output_of_prior_pics_flag" );
+  }
+#endif
+  WRITE_UVLC( pcSlice->getPPS()->getPPSId(), "pic_parameter_set_id" );
+  if(address>0) 
+  {
+    WRITE_CODE( address, reqBitsOuter+reqBitsInner, "slice_address" );
+  }
+
+#if SLICEHEADER_SYNTAX_FIX
+  pcSlice->setDependentSliceFlag(!pcSlice->isNextSlice());
+  if ( pcSlice->getPPS()->getDependentSliceEnabledFlag() && (address!=0) )
+  {
+    WRITE_FLAG( pcSlice->getDependentSliceFlag() ? 1 : 0, "dependent_slice_flag" );
+  }
+  if ( !pcSlice->getDependentSliceFlag() )
+  {
+#endif
+
+    WRITE_UVLC( pcSlice->getSliceType(),       "slice_type" );
+
+#if !SLICEHEADER_SYNTAX_FIX
+  Bool bDependentSlice = (!pcSlice->isNextSlice());
+  WRITE_FLAG( bDependentSlice ? 1 : 0, "dependent_slice_flag" );
+  
+#if DEPENDENT_SLICES
+  if( pcSlice->getPPS()->getDependentSliceEnabledFlag() && bDependentSlice )
+    return;
+#endif
+
+  if (!bDependentSlice)
+  {
+#endif
+    if( pcSlice->getPPS()->getOutputFlagPresentFlag() )
+    {
+      WRITE_FLAG( pcSlice->getPicOutputFlag() ? 1 : 0, "pic_output_flag" );
+    }
+
+    // in the first version chroma_format_idc is equal to one, thus colour_plane_id will not be present
+    assert (pcSlice->getSPS()->getChromaFormatIdc() == 1 );
+    // if( separate_colour_plane_flag  ==  1 )
+    //   colour_plane_id                                      u(2)
+
+#if !SPLICING_FRIENDLY_PARAMS
+    if(   pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR
+#if SUPPORT_FOR_RAP_N_LP
+       || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP
+       || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP
+#endif
+       || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLANT
+       || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA
+#if !NAL_UNIT_TYPES_J1003_D7
+       || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRANT
+#endif
+       || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA )
+    {
+      WRITE_UVLC( 0, "rap_pic_id" );
+      WRITE_FLAG( 0, "no_output_of_prior_pics_flag" );
+    }
+#endif
+#if SUPPORT_FOR_RAP_N_LP
+    if( !pcSlice->getIdrPicFlag() )
+#else
+    if( pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_IDR )
+#endif
+    {
+      Int picOrderCntLSB = (pcSlice->getPOC()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC()))%(1<<pcSlice->getSPS()->getBitsForPOC());
+      WRITE_CODE( picOrderCntLSB, pcSlice->getSPS()->getBitsForPOC(), "pic_order_cnt_lsb");
+      TComReferencePictureSet* rps = pcSlice->getRPS();
+      if(pcSlice->getRPSidx() < 0)
+      {
+        WRITE_FLAG( 0, "short_term_ref_pic_set_sps_flag");
+#if J0234_INTER_RPS_SIMPL
+        codeShortTermRefPicSet(pcSlice->getSPS(), rps, true);
+#else
+        codeShortTermRefPicSet(pcSlice->getSPS(), rps);
+#endif
+      }
+      else
+      {
+        WRITE_FLAG( 1, "short_term_ref_pic_set_sps_flag");
+        WRITE_UVLC( pcSlice->getRPSidx(), "short_term_ref_pic_set_idx" );
+      }
+      if(pcSlice->getSPS()->getLongTermRefsPresent())
+      {
+#if LTRP_IN_SPS
+        Int numLtrpInSH = rps->getNumberOfLongtermPictures();
+        Int ltrpInSPS[MAX_NUM_REF_PICS];
+        Int numLtrpInSPS = 0;
+        UInt ltrpIndex;
+        Int counter = 0;
+        for(Int k = rps->getNumberOfPictures()-1; k > rps->getNumberOfPictures()-rps->getNumberOfLongtermPictures()-1; k--) 
+        {
+          if (findMatchingLTRP(pcSlice, &ltrpIndex, rps->getPOC(k), rps->getUsed(k))) 
+          {
+            ltrpInSPS[numLtrpInSPS] = ltrpIndex;
+            numLtrpInSPS++;
+          }
+          else
+          {
+            counter++;
+          }
+        }
+        numLtrpInSH -= numLtrpInSPS;
+
+        Int bitsForLtrpInSPS = 1;
+        while (pcSlice->getSPS()->getNumLongTermRefPicSPS() > (1 << bitsForLtrpInSPS))
+        {
+          bitsForLtrpInSPS++;
+        }
+        if (pcSlice->getSPS()->getNumLongTermRefPicSPS() > 0) 
+        {
+          WRITE_UVLC( numLtrpInSPS, "num_long_term_sps");
+        }
+        WRITE_UVLC( numLtrpInSH, "num_long_term_pics");
+#else
+        WRITE_UVLC( rps->getNumberOfLongtermPictures(), "num_long_term_pics");
+#endif
+        // Note that the LSBs of the LT ref. pic. POCs must be sorted before.
+        // Not sorted here because LT ref indices will be used in setRefPicList()
+        Int prevDeltaMSB = 0, prevLSB = 0;
+        Int offset = rps->getNumberOfNegativePictures() + rps->getNumberOfPositivePictures();
+        for(Int i=rps->getNumberOfPictures()-1 ; i > offset-1; i--)
+        {
+#if LTRP_IN_SPS
+          if (counter < numLtrpInSPS)
+          {
+            WRITE_CODE( ltrpInSPS[counter], bitsForLtrpInSPS, "lt_idx_sps[i]");
+          }
+          else 
+          {
+            WRITE_CODE( rps->getPocLSBLT(i), pcSlice->getSPS()->getBitsForPOC(), "poc_lsb_lt");
+            WRITE_FLAG( rps->getUsed(i), "used_by_curr_pic_lt_flag"); 
+          }
+#else
+          WRITE_CODE( rps->getPocLSBLT(i), pcSlice->getSPS()->getBitsForPOC(), "poc_lsb_lt");
+#endif
+          WRITE_FLAG( rps->getDeltaPocMSBPresentFlag(i), "delta_poc_msb_present_flag");
+
+          if(rps->getDeltaPocMSBPresentFlag(i))
+          {
+            Bool deltaFlag = false;
+#if LTRP_IN_SPS
+            //  First LTRP from SPS                 ||  First LTRP from SH                              || curr LSB            != prev LSB
+            if( (i == rps->getNumberOfPictures()-1) || (i == rps->getNumberOfPictures()-1-numLtrpInSPS) || (rps->getPocLSBLT(i) != prevLSB) )
+#else
+            //   First LTRP                         ||  curr LSB            != prev LSB
+            if( (i == rps->getNumberOfPictures()-1) || (rps->getPocLSBLT(i) != prevLSB) )
+#endif
+            {
+              deltaFlag = true;
+            }
+            if(deltaFlag)
+            {
+              WRITE_UVLC( rps->getDeltaPocMSBCycleLT(i), "delta_poc_msb_cycle_lt[i]" );
+            }
+            else
+            {              
+              Int differenceInDeltaMSB = rps->getDeltaPocMSBCycleLT(i) - prevDeltaMSB;
+              assert(differenceInDeltaMSB >= 0);
+              WRITE_UVLC( differenceInDeltaMSB, "delta_poc_msb_cycle_lt[i]" );
+            }
+            prevLSB = rps->getPocLSBLT(i);
+            prevDeltaMSB = rps->getDeltaPocMSBCycleLT(i);
+          }
+#if !LTRP_IN_SPS
+          WRITE_FLAG( rps->getUsed(i), "used_by_curr_pic_lt_flag"); 
+#endif
+        }
+      }
+    }
+#if REMOVE_ALF
+    if(pcSlice->getSPS()->getUseSAO())
+#else
+    if(pcSlice->getSPS()->getUseSAO() || pcSlice->getSPS()->getUseALF())
+#endif
+    {
+      if (pcSlice->getSPS()->getUseSAO())
+      {
+         WRITE_FLAG( pcSlice->getSaoEnabledFlag(), "slice_sao_luma_flag" );
+#if !SAO_LUM_CHROMA_ONOFF_FLAGS
+         if (pcSlice->getSaoEnabledFlag() )
+#endif
+         {
+#if REMOVE_APS
+           SAOParam *saoParam = pcSlice->getPic()->getPicSym()->getSaoParam();
+#else
+           SAOParam *saoParam = pcSlice->getAPS()->getSaoParam();
+#endif
+#if SAO_TYPE_SHARING 
+          WRITE_FLAG( saoParam->bSaoFlag[1], "slice_sao_chroma_flag" );
+#else
+          WRITE_FLAG( saoParam->bSaoFlag[1], "SAO on/off flag for Cb in slice header" );
+          WRITE_FLAG( saoParam->bSaoFlag[2], "SAO on/off flag for Cr in slice header" );
+#endif
+         }
+      }
+#if !REMOVE_APS
+      WRITE_UVLC( pcSlice->getAPS()->getAPSID(), "aps_id");
+#endif
+    }
+
+    //check if numrefidxes match the defaults. If not, override
+    if (!pcSlice->isIntra())
+    {
+      if (pcSlice->getSPS()->getTMVPFlagsPresent())
+      {
+        WRITE_FLAG( pcSlice->getEnableTMVPFlag(), "enable_temporal_mvp_flag" );
+      }
+      Bool overrideFlag = (pcSlice->getNumRefIdx( REF_PIC_LIST_0 )!=pcSlice->getPPS()->getNumRefIdxL0DefaultActive()||(pcSlice->isInterB()&&pcSlice->getNumRefIdx( REF_PIC_LIST_1 )!=pcSlice->getPPS()->getNumRefIdxL1DefaultActive()));
+      WRITE_FLAG( overrideFlag ? 1 : 0,                               "num_ref_idx_active_override_flag");
+      if (overrideFlag) 
+      {
+        WRITE_UVLC( pcSlice->getNumRefIdx( REF_PIC_LIST_0 ) - 1,      "num_ref_idx_l0_active_minus1" );
+        if (pcSlice->isInterB())
+        {
+          WRITE_UVLC( pcSlice->getNumRefIdx( REF_PIC_LIST_1 ) - 1,    "num_ref_idx_l1_active_minus1" );
+        }
+        else
+        {
+          pcSlice->setNumRefIdx(REF_PIC_LIST_1, 0);
+        }
+      }
+    }
+    else
+    {
+      pcSlice->setNumRefIdx(REF_PIC_LIST_0, 0);
+      pcSlice->setNumRefIdx(REF_PIC_LIST_1, 0);
+    }
+    if( pcSlice->getSPS()->getListsModificationPresentFlag() )
+    {
+      TComRefPicListModification* refPicListModification = pcSlice->getRefPicListModification();
+      if(!pcSlice->isIntra())
+      {
+        WRITE_FLAG(pcSlice->getRefPicListModification()->getRefPicListModificationFlagL0() ? 1 : 0,       "ref_pic_list_modification_flag_l0" );
+        if (pcSlice->getRefPicListModification()->getRefPicListModificationFlagL0())
+        {
+          Int numRpsCurrTempList0 = pcSlice->getNumRpsCurrTempList();
+          if (numRpsCurrTempList0 > 1)
+          {
+            Int length = 1;
+            numRpsCurrTempList0 --;
+            while ( numRpsCurrTempList0 >>= 1) 
+            {
+              length ++;
+            }
+            for(Int i = 0; i < pcSlice->getNumRefIdx( REF_PIC_LIST_0 ); i++)
+            {
+              WRITE_CODE( refPicListModification->getRefPicSetIdxL0(i), length, "list_entry_l0");
+            }
+          }
+        }
+      }
+      if(pcSlice->isInterB())
+      {    
+        WRITE_FLAG(pcSlice->getRefPicListModification()->getRefPicListModificationFlagL1() ? 1 : 0,       "ref_pic_list_modification_flag_l1" );
+        if (pcSlice->getRefPicListModification()->getRefPicListModificationFlagL1())
+        {
+          Int numRpsCurrTempList1 = pcSlice->getNumRpsCurrTempList();
+          if ( numRpsCurrTempList1 > 1 )
+          {
+            Int length = 1;
+            numRpsCurrTempList1 --;
+            while ( numRpsCurrTempList1 >>= 1)
+            {
+              length ++;
+            }
+            for(Int i = 0; i < pcSlice->getNumRefIdx( REF_PIC_LIST_1 ); i++)
+            {
+              WRITE_CODE( refPicListModification->getRefPicSetIdxL1(i), length, "list_entry_l1");
+            }
+          }
+        }
+      }
+    }
+#if !SLICEHEADER_SYNTAX_FIX
+  }
+#endif
+    
+    if (pcSlice->isInterB())
+    {
+      WRITE_FLAG( pcSlice->getMvdL1ZeroFlag() ? 1 : 0,   "mvd_l1_zero_flag");
+    }
+
+    if(!pcSlice->isIntra())
+    {
+      if (!pcSlice->isIntra() && pcSlice->getPPS()->getCabacInitPresentFlag())
+      {
+        SliceType sliceType   = pcSlice->getSliceType();
+        Int  encCABACTableIdx = pcSlice->getPPS()->getEncCABACTableIdx();
+        Bool encCabacInitFlag = (sliceType!=encCABACTableIdx && encCABACTableIdx!=I_SLICE) ? true : false;
+        pcSlice->setCabacInitFlag( encCabacInitFlag );
+        WRITE_FLAG( encCabacInitFlag?1:0, "cabac_init_flag" );
+      }
+    }
+
+#if !SLICEHEADER_SYNTAX_FIX
+  // if( !lightweight_slice_flag ) {
+  if (!bDependentSlice)
+  {
+#else
+    if ( pcSlice->getEnableTMVPFlag() )
+    {
+      if ( pcSlice->getSliceType() == B_SLICE )
+      {
+        WRITE_FLAG( pcSlice->getColFromL0Flag(), "collocated_from_l0_flag" );
+      }
+
+      if ( pcSlice->getSliceType() != I_SLICE &&
+        ((pcSlice->getColFromL0Flag()==1 && pcSlice->getNumRefIdx(REF_PIC_LIST_0)>1)||
+        (pcSlice->getColFromL0Flag()==0  && pcSlice->getNumRefIdx(REF_PIC_LIST_1)>1)))
+      {
+        WRITE_UVLC( pcSlice->getColRefIdx(), "collocated_ref_idx" );
+      }
+    }
+    if ( (pcSlice->getPPS()->getUseWP() && pcSlice->getSliceType()==P_SLICE) || (pcSlice->getPPS()->getWPBiPred() && pcSlice->getSliceType()==B_SLICE) )
+    {
+      xCodePredWeightTable( pcSlice );
+    }
+    assert(pcSlice->getMaxNumMergeCand()<=MRG_MAX_NUM_CANDS);
+    WRITE_UVLC(MRG_MAX_NUM_CANDS - pcSlice->getMaxNumMergeCand(), "five_minus_max_num_merge_cand");
+#endif
+    Int iCode = pcSlice->getSliceQp() - ( pcSlice->getPPS()->getPicInitQPMinus26() + 26 );
+    WRITE_SVLC( iCode, "slice_qp_delta" ); 
+#if CHROMA_QP_EXTENSION
+    if (pcSlice->getPPS()->getSliceChromaQpFlag())
+    {
+      iCode = pcSlice->getSliceQpDeltaCb();
+      WRITE_SVLC( iCode, "slice_qp_delta_cb" );
+      iCode = pcSlice->getSliceQpDeltaCr();
+      WRITE_SVLC( iCode, "slice_qp_delta_cr" );
+    }
+#endif
+    if (pcSlice->getPPS()->getDeblockingFilterControlPresentFlag())
+    {
+      if (pcSlice->getPPS()->getDeblockingFilterOverrideEnabledFlag() )
+      {
+        WRITE_FLAG(pcSlice->getDeblockingFilterOverrideFlag(), "deblocking_filter_override_flag");
+      }
+      if (pcSlice->getDeblockingFilterOverrideFlag())
+      {
+        WRITE_FLAG(pcSlice->getDeblockingFilterDisable(), "slice_disable_deblocking_filter_flag");
+        if(!pcSlice->getDeblockingFilterDisable())
+        {
+          WRITE_SVLC (pcSlice->getDeblockingFilterBetaOffsetDiv2(), "beta_offset_div2");
+          WRITE_SVLC (pcSlice->getDeblockingFilterTcOffsetDiv2(),   "tc_offset_div2");
+        }
+      }
+    }
+#if !SLICEHEADER_SYNTAX_FIX
+    if ( pcSlice->getEnableTMVPFlag() )
+    {
+      if ( pcSlice->getSliceType() == B_SLICE )
+      {
+        WRITE_FLAG( pcSlice->getColFromL0Flag(), "collocated_from_l0_flag" );
+      }
+
+      if ( pcSlice->getSliceType() != I_SLICE &&
+         ((pcSlice->getColFromL0Flag()==1 && pcSlice->getNumRefIdx(REF_PIC_LIST_0)>1)||
+         (pcSlice->getColFromL0Flag()==0  && pcSlice->getNumRefIdx(REF_PIC_LIST_1)>1)))
+      {
+        WRITE_UVLC( pcSlice->getColRefIdx(), "collocated_ref_idx" );
+      }
+    }
+    if ( (pcSlice->getPPS()->getUseWP() && pcSlice->getSliceType()==P_SLICE) || (pcSlice->getPPS()->getWPBiPred() && pcSlice->getSliceType()==B_SLICE) )
+    {
+      xCodePredWeightTable( pcSlice );
+    }
+  }
+    assert(pcSlice->getMaxNumMergeCand()<=MRG_MAX_NUM_CANDS);
+    WRITE_UVLC(MRG_MAX_NUM_CANDS - pcSlice->getMaxNumMergeCand(), "five_minus_max_num_merge_cand");
+#endif
+
+#if !REMOVE_ALF
+  if (!bDependentSlice)
+  {
+    if (pcSlice->getSPS()->getUseALF())
+    {
+      char syntaxString[50];
+      for(Int compIdx=0; compIdx< 3; compIdx++)
+      {
+        sprintf(syntaxString, "alf_slice_filter_flag[%d]", compIdx);
+        WRITE_FLAG( pcSlice->getAlfEnabledFlag(compIdx)?1:0, syntaxString );
+      }
+    }
+  }
+#endif
+#if !SLICEHEADER_SYNTAX_FIX
+  if(!bDependentSlice)
+  {
+#endif
+#if !REMOVE_ALF
+    Bool isAlfEnabled = (!pcSlice->getSPS()->getUseALF())?(false):(pcSlice->getAlfEnabledFlag(0)||pcSlice->getAlfEnabledFlag(1)||pcSlice->getAlfEnabledFlag(2));
+#endif
+#if !SAO_LUM_CHROMA_ONOFF_FLAGS
+    Bool isSAOEnabled = (!pcSlice->getSPS()->getUseSAO())?(false):(pcSlice->getSaoEnabledFlag());
+#else
+    Bool isSAOEnabled = (!pcSlice->getSPS()->getUseSAO())?(false):(pcSlice->getSaoEnabledFlag()||pcSlice->getSaoEnabledFlagChroma());
+#endif
+    Bool isDBFEnabled = (!pcSlice->getDeblockingFilterDisable());
+
+#if REMOVE_ALF
+#if MOVE_LOOP_FILTER_SLICES_FLAG
+    if(pcSlice->getPPS()->getLoopFilterAcrossSlicesEnabledFlag() && ( isSAOEnabled || isDBFEnabled ))
+#else
+    if(pcSlice->getSPS()->getLFCrossSliceBoundaryFlag() && ( isSAOEnabled || isDBFEnabled ))
+#endif
+#else
+    if(pcSlice->getSPS()->getLFCrossSliceBoundaryFlag() && ( isAlfEnabled || isSAOEnabled || isDBFEnabled ))
+#endif
+    {
+      WRITE_FLAG(pcSlice->getLFCrossSliceBoundaryFlag()?1:0, "slice_loop_filter_across_slices_enabled_flag");
+    }
+  }
+#if SLICE_HEADER_EXTENSION
+  if(pcSlice->getPPS()->getSliceHeaderExtensionPresentFlag())
+  {
+    WRITE_UVLC(0,"slice_header_extension_length");
+  }
+#endif
+}
+
+#if PROFILE_TIER_LEVEL_SYNTAX
+Void TEncCavlc::codePTL( TComPTL* pcPTL, Bool profilePresentFlag, Int maxNumSubLayersMinus1)
+{
+  if(profilePresentFlag)
+  {
+    codeProfileTier(pcPTL->getGeneralPTL());    // general_...
+  }
+  WRITE_CODE( pcPTL->getGeneralPTL()->getLevelIdc(), 8, "general_level_idc" );
+
+  for(Int i = 0; i < maxNumSubLayersMinus1; i++)
+  {
+    WRITE_FLAG( pcPTL->getSubLayerProfilePresentFlag(i), "sub_layer_profile_present_flag[i]" );
+    WRITE_FLAG( pcPTL->getSubLayerLevelPresentFlag(i),   "sub_layer_level_present_flag[i]" );
+    if( profilePresentFlag && pcPTL->getSubLayerProfilePresentFlag(i) )
+    {
+      codeProfileTier(pcPTL->getSubLayerPTL(i));  // sub_layer_...
+    }
+    if( pcPTL->getSubLayerLevelPresentFlag(i) )
+    {
+      WRITE_CODE( pcPTL->getSubLayerPTL(i)->getLevelIdc(), 8, "sub_layer_level_idc[i]" );
+    }
+  }
+}
+Void TEncCavlc::codeProfileTier( ProfileTierLevel* ptl )
+{
+  WRITE_CODE( ptl->getProfileSpace(), 2 ,     "XXX_profile_space[]");
+  WRITE_FLAG( ptl->getTierFlag    (),         "XXX_tier_flag[]"    );
+  WRITE_CODE( ptl->getProfileIdc  (), 5 ,     "XXX_profile_idc[]"  );   
+  for(Int j = 0; j < 32; j++)
+  {
+    WRITE_FLAG( ptl->getProfileCompatibilityFlag(j), "XXX_profile_compatibility_flag[][j]");   
+  }
+  WRITE_CODE(0 , 16, "XXX_reserved_zero_16bits[]");  
+}
+#endif
+
+/**
+ - write wavefront substreams sizes for the slice header.
+ .
+ \param pcSlice Where we find the substream size information.
+ */
+Void  TEncCavlc::codeTilesWPPEntryPoint( TComSlice* pSlice )
+{
+#if TILES_WPP_ENTROPYSLICES_FLAGS
+  if (!pSlice->getPPS()->getTilesEnabledFlag() && !pSlice->getPPS()->getEntropyCodingSyncEnabledFlag())
+#else
+  Int tilesOrEntropyCodingSyncIdc = pSlice->getPPS()->getTilesOrEntropyCodingSyncIdc();
+  if ( tilesOrEntropyCodingSyncIdc == 0 )
+#endif
+  {
+    return;
+  }
+  UInt numEntryPointOffsets = 0, offsetLenMinus1 = 0, maxOffset = 0;
+  Int  numZeroSubstreamsAtStartOfSlice  = 0;
+  UInt *entryPointOffset = NULL;
+#if TILES_WPP_ENTROPYSLICES_FLAGS
+  if ( pSlice->getPPS()->getTilesEnabledFlag() )
+#else
+  if (tilesOrEntropyCodingSyncIdc == 1) // tiles
+#endif
+  {
+    numEntryPointOffsets = pSlice->getTileLocationCount();
+    entryPointOffset     = new UInt[numEntryPointOffsets];
+    for (Int idx=0; idx<pSlice->getTileLocationCount(); idx++)
+    {
+      if ( idx == 0 )
+      {
+        entryPointOffset [ idx ] = pSlice->getTileLocation( 0 );
+      }
+      else
+      {
+        entryPointOffset [ idx ] = pSlice->getTileLocation( idx ) - pSlice->getTileLocation( idx-1 );
+      }
+
+      if ( entryPointOffset[ idx ] > maxOffset )
+      {
+        maxOffset = entryPointOffset[ idx ];
+      }
+    }
+  }
+#if TILES_WPP_ENTROPYSLICES_FLAGS
+  else if ( pSlice->getPPS()->getEntropyCodingSyncEnabledFlag() )
+#else
+  else if (tilesOrEntropyCodingSyncIdc == 2) // wavefront
+#endif
+  {
+    UInt* pSubstreamSizes               = pSlice->getSubstreamSizes();
+    Int maxNumParts                       = pSlice->getPic()->getNumPartInCU();
+#if DEPENDENT_SLICES
+    numZeroSubstreamsAtStartOfSlice       = pSlice->getDependentSliceCurStartCUAddr()/maxNumParts/pSlice->getPic()->getFrameWidthInCU();
+    Int  numZeroSubstreamsAtEndOfSlice    = pSlice->getPic()->getFrameHeightInCU()-1 - ((pSlice->getDependentSliceCurEndCUAddr()-1)/maxNumParts/pSlice->getPic()->getFrameWidthInCU());
+#else
+    numZeroSubstreamsAtStartOfSlice       = pSlice->getSliceCurStartCUAddr()/maxNumParts/pSlice->getPic()->getFrameWidthInCU();
+    Int  numZeroSubstreamsAtEndOfSlice    = pSlice->getPic()->getFrameHeightInCU()-1 - ((pSlice->getSliceCurEndCUAddr()-1)/maxNumParts/pSlice->getPic()->getFrameWidthInCU());
+#endif
+    numEntryPointOffsets                  = pSlice->getPPS()->getNumSubstreams() - numZeroSubstreamsAtStartOfSlice - numZeroSubstreamsAtEndOfSlice - 1;
+    pSlice->setNumEntryPointOffsets(numEntryPointOffsets);
+    entryPointOffset           = new UInt[numEntryPointOffsets];
+    for (Int idx=0; idx<numEntryPointOffsets; idx++)
+    {
+      entryPointOffset[ idx ] = ( pSubstreamSizes[ idx+numZeroSubstreamsAtStartOfSlice ] >> 3 ) ;
+      if ( entryPointOffset[ idx ] > maxOffset )
+      {
+        maxOffset = entryPointOffset[ idx ];
+      }
+    }
+  }
+  // Determine number of bits "offsetLenMinus1+1" required for entry point information
+  offsetLenMinus1 = 0;
+  while (maxOffset >= (1u << (offsetLenMinus1 + 1)))
+  {
+    offsetLenMinus1++;
+    assert(offsetLenMinus1 + 1 < 32);    
+  }
+
+  WRITE_UVLC(numEntryPointOffsets, "num_entry_point_offsets");
+  if (numEntryPointOffsets>0)
+  {
+    WRITE_UVLC(offsetLenMinus1, "offset_len_minus1");
+  }
+
+  for (UInt idx=0; idx<numEntryPointOffsets; idx++)
+  {
+    WRITE_CODE(entryPointOffset[ idx ], offsetLenMinus1+1, "entry_point_offset");
+  }
+
+  delete [] entryPointOffset;
+}
+
+Void TEncCavlc::codeTerminatingBit      ( UInt uilsLast )
+{
+}
+
+Void TEncCavlc::codeSliceFinish ()
+{
+}
+
+Void TEncCavlc::codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codePartSize( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codePredMode( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeMergeFlag    ( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeMergeIndex    ( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeApsExtensionFlag ()
+{
+  WRITE_FLAG(0, "aps_extension_flag");
+}
+
+Void TEncCavlc::codeInterModeFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiEncMode )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeSkipFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+
+#if INTRA_BL
+Void TEncCavlc::codeIntraBLFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+
+#endif
+Void TEncCavlc::codeSplitFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeTransformSubdivFlag( UInt uiSymbol, UInt uiCtx )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeQtCbf( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeQtRootCbf( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+
+#if TU_ZERO_CBF_RDO
+Void TEncCavlc::codeQtCbfZero( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth )
+{
+  assert(0);
+}
+Void TEncCavlc::codeQtRootCbfZero( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+#endif
+
+Void TEncCavlc::codeTransformSkipFlags (TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, UInt uiDepth, TextType eTType )
+{
+  assert(0);
+}
+
+/** Code I_PCM information. 
+ * \param pcCU pointer to CU
+ * \param uiAbsPartIdx CU index
+ * \param numIPCM the number of succesive IPCM blocks with the same size 
+ * \param firstIPCMFlag 
+ * \returns Void
+ */
+Void TEncCavlc::codeIPCMInfo( TComDataCU* pcCU, UInt uiAbsPartIdx, Int numIPCM, Bool firstIPCMFlag)
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeIntraDirLumaAng( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool isMultiple)
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeInterDir( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeRefFrmIdx( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeMvd( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeDeltaQP( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  Int iDQp  = pcCU->getQP( uiAbsPartIdx ) - pcCU->getRefQP( uiAbsPartIdx );
+
+  Int qpBdOffsetY =  pcCU->getSlice()->getSPS()->getQpBDOffsetY();
+  iDQp = (iDQp + 78 + qpBdOffsetY + (qpBdOffsetY/2)) % (52 + qpBdOffsetY) - 26 - (qpBdOffsetY/2);
+
+  xWriteSvlc( iDQp );
+  
+  return;
+}
+
+Void TEncCavlc::codeCoeffNxN    ( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType )
+{
+  assert(0);
+}
+
+Void TEncCavlc::xGolombEncode(Int coeff, Int k)
+{
+  xWriteEpExGolomb((UInt)abs(coeff), k);
+  if(coeff != 0)
+  {
+    Int sign = (coeff > 0)? 1: 0;
+    xWriteFlag(sign);
+  }
+#if ENC_DEC_TRACE
+  fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+  fprintf( g_hTrace, "%-40s se(v) : %d\n", "alf_filt_coeff", coeff ); 
+#endif
+
+}
+
+#if !REMOVE_ALF
+Void TEncCavlc::codeAlfParam(ALFParam* alfParam)
+{
+  char syntaxString[50];
+  sprintf(syntaxString, "alf_aps_filter_flag[%d]", alfParam->componentID);
+  WRITE_FLAG(alfParam->alf_flag, syntaxString);
+  if(alfParam->alf_flag == 0)
+  {
+    return;
+  }
+
+  const Int numCoeff = (Int)ALF_MAX_NUM_COEF;
+  switch(alfParam->componentID)
+  {
+  case ALF_Cb:
+  case ALF_Cr:
+    {
+      for(Int pos=0; pos< numCoeff; pos++)
+      {
+        WRITE_SVLC(alfParam->coeffmulti[0][pos], "alf_filt_coeff");
+      }
+    }
+    break;
+  case ALF_Y:
+    {
+      Int noFilters = min(alfParam->filters_per_group-1, 2);
+      WRITE_UVLC(noFilters, "alf_no_filters_minus1");
+      if(noFilters == 1)
+      {
+        WRITE_UVLC(alfParam->startSecondFilter, "alf_start_second_filter");
+      }
+      else if (noFilters == 2)
+      {
+        Int numMergeFlags = 16;
+        for (Int i=1; i<numMergeFlags; i++) 
+        {
+          WRITE_FLAG(alfParam->filterPattern[i], "alf_filter_pattern");
+        }
+      }
+      for(Int f=0; f< alfParam->filters_per_group; f++)
+      {
+        for(Int pos=0; pos< numCoeff; pos++)
+        {
+          xGolombEncode(alfParam->coeffmulti[f][pos], kTableTabShapes[ALF_CROSS9x7_SQUARE3x3][pos]);
+        }
+      }
+    }
+    break;
+  default:
+    {
+      printf("Not a legal component ID\n");
+      assert(0);
+      exit(-1);
+    }
+  }
+
+}
+#endif
+
+Void TEncCavlc::estBit( estBitsSbacStruct* pcEstBitsCabac, Int width, Int height, TextType eTType )
+{
+  // printf("error : no VLC mode support in this version\n");
+  return;
+}
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+
+/** Write PCM alignment bits. 
+ * \returns Void
+ */
+Void  TEncCavlc::xWritePCMAlignZero    ()
+{
+  m_pcBitIf->writeAlignZero();
+}
+
+Void TEncCavlc::xWriteUnaryMaxSymbol( UInt uiSymbol, UInt uiMaxSymbol )
+{
+  if (uiMaxSymbol == 0)
+  {
+    return;
+  }
+  xWriteFlag( uiSymbol ? 1 : 0 );
+  if ( uiSymbol == 0 )
+  {
+    return;
+  }
+  
+  Bool bCodeLast = ( uiMaxSymbol > uiSymbol );
+  
+  while( --uiSymbol )
+  {
+    xWriteFlag( 1 );
+  }
+  if( bCodeLast )
+  {
+    xWriteFlag( 0 );
+  }
+  return;
+}
+
+Void TEncCavlc::xWriteExGolombLevel( UInt uiSymbol )
+{
+  if( uiSymbol )
+  {
+    xWriteFlag( 1 );
+    UInt uiCount = 0;
+    Bool bNoExGo = (uiSymbol < 13);
+    
+    while( --uiSymbol && ++uiCount < 13 )
+    {
+      xWriteFlag( 1 );
+    }
+    if( bNoExGo )
+    {
+      xWriteFlag( 0 );
+    }
+    else
+    {
+      xWriteEpExGolomb( uiSymbol, 0 );
+    }
+  }
+  else
+  {
+    xWriteFlag( 0 );
+  }
+  return;
+}
+
+Void TEncCavlc::xWriteEpExGolomb( UInt uiSymbol, UInt uiCount )
+{
+  while( uiSymbol >= (UInt)(1<<uiCount) )
+  {
+    xWriteFlag( 1 );
+    uiSymbol -= 1<<uiCount;
+    uiCount  ++;
+  }
+  xWriteFlag( 0 );
+  while( uiCount-- )
+  {
+    xWriteFlag( (uiSymbol>>uiCount) & 1 );
+  }
+  return;
+}
+
+/** code explicit wp tables
+ * \param TComSlice* pcSlice
+ * \returns Void
+ */
+Void TEncCavlc::xCodePredWeightTable( TComSlice* pcSlice )
+{
+  wpScalingParam  *wp;
+  Bool            bChroma     = true; // color always present in HEVC ?
+  Int             iNbRef       = (pcSlice->getSliceType() == B_SLICE ) ? (2) : (1);
+  Bool            bDenomCoded  = false;
+  UInt            uiMode = 0;
+#if NUM_WP_LIMIT
+  UInt            uiTotalSignalledWeightFlags = 0;
+#endif
+  if ( (pcSlice->getSliceType()==P_SLICE && pcSlice->getPPS()->getUseWP()) || (pcSlice->getSliceType()==B_SLICE && pcSlice->getPPS()->getWPBiPred()) )
+  {
+    uiMode = 1; // explicit
+  }
+  if(uiMode == 1)
+  {
+
+    for ( Int iNumRef=0 ; iNumRef<iNbRef ; iNumRef++ ) 
+    {
+      RefPicList  eRefPicList = ( iNumRef ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
+
+      for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) 
+      {
+        pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
+        if ( !bDenomCoded ) 
+        {
+          Int iDeltaDenom;
+          WRITE_UVLC( wp[0].uiLog2WeightDenom, "luma_log2_weight_denom" );     // ue(v): luma_log2_weight_denom
+
+          if( bChroma )
+          {
+            iDeltaDenom = (wp[1].uiLog2WeightDenom - wp[0].uiLog2WeightDenom);
+            WRITE_SVLC( iDeltaDenom, "delta_chroma_log2_weight_denom" );       // se(v): delta_chroma_log2_weight_denom
+          }
+          bDenomCoded = true;
+        }
+        WRITE_FLAG( wp[0].bPresentFlag, "luma_weight_lX_flag" );               // u(1): luma_weight_lX_flag
+#if NUM_WP_LIMIT
+        uiTotalSignalledWeightFlags += wp[0].bPresentFlag;
+      }
+      if (bChroma) 
+      {
+        for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) 
+        {
+          pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
+          WRITE_FLAG( wp[1].bPresentFlag, "chroma_weight_lX_flag" );           // u(1): chroma_weight_lX_flag
+          uiTotalSignalledWeightFlags += 2*wp[1].bPresentFlag;
+        }
+      }
+
+      for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) 
+      {
+        pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
+#endif
+        if ( wp[0].bPresentFlag ) 
+        {
+          Int iDeltaWeight = (wp[0].iWeight - (1<<wp[0].uiLog2WeightDenom));
+          WRITE_SVLC( iDeltaWeight, "delta_luma_weight_lX" );                  // se(v): delta_luma_weight_lX
+          WRITE_SVLC( wp[0].iOffset, "luma_offset_lX" );                       // se(v): luma_offset_lX
+        }
+
+        if ( bChroma ) 
+        {
+#if !NUM_WP_LIMIT
+          WRITE_FLAG( wp[1].bPresentFlag, "chroma_weight_lX_flag" );           // u(1): chroma_weight_lX_flag
+#endif
+          if ( wp[1].bPresentFlag )
+          {
+            for ( Int j=1 ; j<3 ; j++ ) 
+            {
+              Int iDeltaWeight = (wp[j].iWeight - (1<<wp[1].uiLog2WeightDenom));
+              WRITE_SVLC( iDeltaWeight, "delta_chroma_weight_lX" );            // se(v): delta_chroma_weight_lX
+
+              Int shift = ((1<<(g_uiBitDepth+g_uiBitIncrement-1)));
+              Int pred = ( shift - ( ( shift*wp[j].iWeight)>>(wp[j].uiLog2WeightDenom) ) );
+              Int iDeltaChroma = (wp[j].iOffset - pred);
+              WRITE_SVLC( iDeltaChroma, "delta_chroma_offset_lX" );            // se(v): delta_chroma_offset_lX
+            }
+          }
+        }
+      }
+    }
+#if NUM_WP_LIMIT
+    assert(uiTotalSignalledWeightFlags<=24);
+#endif
+  }
+}
+
+/** code quantization matrix
+ *  \param scalingList quantization matrix information
+ */
+Void TEncCavlc::codeScalingList( TComScalingList* scalingList )
+{
+  UInt listId,sizeId;
+  Bool scalingListPredModeFlag;
+
+#if SCALING_LIST_OUTPUT_RESULT
+  Int startBit;
+  Int startTotalBit;
+  startBit = m_pcBitIf->getNumberOfWrittenBits();
+  startTotalBit = m_pcBitIf->getNumberOfWrittenBits();
+#endif
+
+    //for each size
+    for(sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
+    {
+      for(listId = 0; listId < g_scalingListNum[sizeId]; listId++)
+      {
+#if SCALING_LIST_OUTPUT_RESULT
+        startBit = m_pcBitIf->getNumberOfWrittenBits();
+#endif
+        scalingListPredModeFlag = scalingList->checkPredMode( sizeId, listId );
+        WRITE_FLAG( scalingListPredModeFlag, "scaling_list_pred_mode_flag" );
+        if(!scalingListPredModeFlag)// Copy Mode
+        {
+          WRITE_UVLC( (Int)listId - (Int)scalingList->getRefMatrixId (sizeId,listId), "scaling_list_pred_matrix_id_delta");
+        }
+        else// DPCM Mode
+        {
+          xCodeScalingList(scalingList, sizeId, listId);
+        }
+#if SCALING_LIST_OUTPUT_RESULT
+        printf("Matrix [%d][%d] Bit %d\n",sizeId,listId,m_pcBitIf->getNumberOfWrittenBits() - startBit);
+#endif
+      }
+    }
+#if SCALING_LIST_OUTPUT_RESULT
+  printf("Total Bit %d\n",m_pcBitIf->getNumberOfWrittenBits()-startTotalBit);
+#endif
+  return;
+}
+/** code DPCM
+ * \param scalingList quantization matrix information
+ * \param sizeIdc size index
+ * \param listIdc list index
+ */
+Void TEncCavlc::xCodeScalingList(TComScalingList* scalingList, UInt sizeId, UInt listId)
+{
+  Int coefNum = min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]);
+#if REMOVE_ZIGZAG_SCAN
+  UInt* scan  = (sizeId == 0) ? g_auiSigLastScan [ SCAN_DIAG ] [ 1 ] :  g_sigLastScanCG32x32;
+#else
+  UInt* scan    = g_auiFrameScanXY [ (sizeId == 0)? 1 : 2];
+#endif
+  Int nextCoef = SCALING_LIST_START_VALUE;
+  Int data;
+  Int *src = scalingList->getScalingListAddress(sizeId, listId);
+    if( sizeId > SCALING_LIST_8x8 )
+    {
+      WRITE_SVLC( scalingList->getScalingListDC(sizeId,listId) - 8, "scaling_list_dc_coef_minus8");
+      nextCoef = scalingList->getScalingListDC(sizeId,listId);
+    }
+    for(Int i=0;i<coefNum;i++)
+    {
+      data = src[scan[i]] - nextCoef;
+      nextCoef = src[scan[i]];
+      if(data > 127)
+      {
+        data = data - 256;
+      }
+      if(data < -128)
+      {
+        data = data + 256;
+      }
+
+      WRITE_SVLC( data,  "scaling_list_delta_coef");
+    }
+}
+#if LTRP_IN_SPS
+Bool TEncCavlc::findMatchingLTRP ( TComSlice* pcSlice, UInt *ltrpsIndex, Int ltrpPOC, Bool usedFlag )
+{
+  // bool state = true, state2 = false;
+  Int lsb = ltrpPOC % (1<<pcSlice->getSPS()->getBitsForPOC());
+  for (Int k = 0; k < pcSlice->getSPS()->getNumLongTermRefPicSPS(); k++)
+  {
+    if ( (lsb == pcSlice->getSPS()->getLtRefPicPocLsbSps(k)) && (usedFlag == pcSlice->getSPS()->getUsedByCurrPicLtSPSFlag(k)) )
+    {
+      *ltrpsIndex = k;
+      return true;
+    }
+  }
+  return false;
+}
+#endif
+Bool TComScalingList::checkPredMode(UInt sizeId, UInt listId)
+{
+  for(Int predListIdx = (Int)listId ; predListIdx >= 0; predListIdx--)
+  {
+    if( !memcmp(getScalingListAddress(sizeId,listId),((listId == predListIdx) ?
+      getScalingListDefaultAddress(sizeId, predListIdx): getScalingListAddress(sizeId, predListIdx)),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId])) // check value of matrix
+     && ((sizeId < SCALING_LIST_16x16) || (getScalingListDC(sizeId,listId) == getScalingListDC(sizeId,predListIdx)))) // check DC value
+    {
+      setRefMatrixId(sizeId, listId, predListIdx);
+      return false;
+    }
+  }
+  return true;
+}
+//! \}
Index: /trunk/source/Lib/TLibEncoder/TEncCavlc.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncCavlc.h	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/TEncCavlc.h	(revision 2)
@@ -0,0 +1,200 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncCavlc.h
+    \brief    CAVLC encoder class (header)
+*/
+
+#ifndef __TENCCAVLC__
+#define __TENCCAVLC__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComBitStream.h"
+#include "TLibCommon/TComRom.h"
+#include "TEncEntropy.h"
+#include "SyntaxElementWriter.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+class TEncTop;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// CAVLC encoder class
+class TEncCavlc : public SyntaxElementWriter, public TEncEntropyIf
+{
+public:
+  TEncCavlc();
+  virtual ~TEncCavlc();
+  
+protected:
+  TComSlice*    m_pcSlice;
+  UInt          m_uiCoeffCost;
+#if !REMOVE_FGS
+  Int           m_iSliceGranularity;  //!< slice granularity
+#endif
+
+  Void  xWritePCMAlignZero    ();
+  Void  xWriteEpExGolomb      ( UInt uiSymbol, UInt uiCount );
+  Void  xWriteExGolombLevel    ( UInt uiSymbol );
+  Void  xWriteUnaryMaxSymbol  ( UInt uiSymbol, UInt uiMaxSymbol );
+
+#if J0234_INTER_RPS_SIMPL
+  Void codeShortTermRefPicSet              ( TComSPS* pcSPS, TComReferencePictureSet* pcRPS, Bool calledFromSliceHeader );
+#else
+  Void codeShortTermRefPicSet              ( TComSPS* pcSPS, TComReferencePictureSet* pcRPS );
+#endif
+#if LTRP_IN_SPS
+  Bool findMatchingLTRP ( TComSlice* pcSlice, UInt *ltrpsIndex, Int ltrpPOC, Bool usedFlag );
+#endif  
+  
+public:
+  
+  Void  resetEntropy          ();
+  Void  determineCabacInitIdx  () {};
+
+  Void  setBitstream          ( TComBitIf* p )  { m_pcBitIf = p;  }
+  Void  setSlice              ( TComSlice* p )  { m_pcSlice = p;  }
+  Void  resetBits             ()                { m_pcBitIf->resetBits(); }
+  Void  resetCoeffCost        ()                { m_uiCoeffCost = 0;  }
+  UInt  getNumberOfWrittenBits()                { return  m_pcBitIf->getNumberOfWrittenBits();  }
+  UInt  getCoeffCost          ()                { return  m_uiCoeffCost;  }
+  Void  codeVPS                 ( TComVPS* pcVPS );
+#if SUPPORT_FOR_VUI
+  Void  codeVUI                 ( TComVUI *pcVUI, TComSPS* pcSPS );
+#endif
+  Void  codeSPS                 ( TComSPS* pcSPS );
+  Void  codePPS                 ( TComPPS* pcPPS );
+  Void  codeSliceHeader         ( TComSlice* pcSlice );
+#if PROFILE_TIER_LEVEL_SYNTAX
+  Void  codePTL                 ( TComPTL* pcPTL, Bool profilePresentFlag, Int maxNumSubLayersMinus1);
+  Void  codeProfileTier         ( ProfileTierLevel* ptl );
+#endif
+  Void  codeTilesWPPEntryPoint( TComSlice* pSlice );
+  Void  codeTerminatingBit      ( UInt uilsLast );
+  Void  codeSliceFinish         ();
+  Void  codeFlush               () {}
+  Void  encodeStart             () {}
+  
+  Void codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList );
+  Void xGolombEncode(Int coeff, Int k);
+#if !REMOVE_ALF
+  Void codeAlfParam(ALFParam* alfParam);
+#endif
+  Void codeSAOSign       ( UInt code   ) { printf("Not supported\n"); assert (0); }
+  Void codeSaoMaxUvlc    ( UInt   code, UInt maxSymbol ){printf("Not supported\n"); assert (0);}
+#if SAO_MERGE_ONE_CTX
+  Void codeSaoMerge  ( UInt uiCode ){printf("Not supported\n"); assert (0);}
+#else
+  Void codeSaoMergeLeft  ( UInt uiCode, UInt compIdx ){printf("Not supported\n"); assert (0);}
+  Void codeSaoMergeUp    ( UInt uiCode ){printf("Not supported\n"); assert (0);}
+#endif
+  Void codeSaoTypeIdx    ( UInt uiCode ){printf("Not supported\n"); assert (0);}
+#if SAO_TYPE_CODING
+  Void codeSaoUflc       ( UInt uiLength, UInt   uiCode ){ assert(uiCode < 32); printf("Not supported\n"); assert (0);}
+#else
+  Void codeSaoUflc       ( UInt uiCode ){ assert(uiCode < 32); printf("Not supported\n"); assert (0);}
+#endif
+
+  Void codeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeSkipFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeMergeFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeMergeIndex    ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#if INTRA_BL
+  Void codeIntraBLFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#endif
+  Void codeApsExtensionFlag ();
+
+#if !REMOVE_FGS
+  /// set slice granularity
+  Void setSliceGranularity(Int iSliceGranularity)  {m_iSliceGranularity = iSliceGranularity;}
+
+  ///get slice granularity
+  Int  getSliceGranularity()                       {return m_iSliceGranularity;             }
+#endif
+  
+  Void codeAlfCtrlFlag   ( Int compIdx, UInt code ) {printf("Not supported\n"); assert(0);}
+  Void codeInterModeFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiEncMode );
+  Void codeSplitFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  
+  Void codePartSize      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void codePredMode      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  
+  Void codeIPCMInfo      ( TComDataCU* pcCU, UInt uiAbsPartIdx, Int numIPCM, Bool firstIPCMFlag);
+
+  Void codeTransformSubdivFlag( UInt uiSymbol, UInt uiCtx );
+  Void codeQtCbf         ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth );
+  Void codeQtRootCbf     ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#if TU_ZERO_CBF_RDO
+  Void codeQtCbfZero     ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth );
+  Void codeQtRootCbfZero ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#endif
+  Void codeIntraDirLumaAng( TComDataCU* pcCU, UInt absPartIdx, Bool isMultiple);
+  Void codeIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeInterDir      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeRefFrmIdx     ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList );
+  Void codeMvd           ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList );
+  
+  Void codeDeltaQP       ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  
+  Void codeCoeffNxN      ( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType );
+  Void codeTransformSkipFlags ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, UInt uiDepth, TextType eTType );
+
+  Void estBit               (estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType);
+  
+  Void xCodePredWeightTable          ( TComSlice* pcSlice );
+  Void updateContextTables           ( SliceType eSliceType, Int iQp, Bool bExecuteFinish=true ) { return;   }
+  Void updateContextTables           ( SliceType eSliceType, Int iQp  )                          { return;   }
+
+#if !REMOVE_APS
+  Void  codeAPSInitInfo(TComAPS* pcAPS);  //!< code APS flags before encoding SAO and ALF parameters
+#endif
+  Void  codeFinish(Bool bEnd) { /*do nothing*/}
+  Void codeScalingList  ( TComScalingList* scalingList );
+  Void xCodeScalingList ( TComScalingList* scalingList, UInt sizeId, UInt listId);
+  Void codeDFFlag       ( UInt uiCode, const Char *pSymbolName );
+  Void codeDFSvlc       ( Int   iCode, const Char *pSymbolName );
+
+};
+
+//! \}
+
+#endif // !defined(AFX_TENCCAVLC_H__EE8A0B30_945B_4169_B290_24D3AD52296F__INCLUDED_)
+
Index: /trunk/source/Lib/TLibEncoder/TEncCfg.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncCfg.h	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/TEncCfg.h	(revision 2)
@@ -0,0 +1,724 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncCfg.h
+    \brief    encoder configuration class (header)
+*/
+
+#ifndef __TENCCFG__
+#define __TENCCFG__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComSlice.h"
+#include <assert.h>
+
+struct GOPEntry
+{
+  Int m_POC;
+  Int m_QPOffset;
+  Double m_QPFactor;
+  Int m_temporalId;
+  Bool m_refPic;
+  Int m_numRefPicsActive;
+  Char m_sliceType;
+  Int m_numRefPics;
+  Int m_referencePics[MAX_NUM_REF_PICS];
+  Int m_usedByCurrPic[MAX_NUM_REF_PICS];
+#if AUTO_INTER_RPS
+  Int m_interRPSPrediction;
+#else
+  Bool m_interRPSPrediction;
+#endif
+#if !J0234_INTER_RPS_SIMPL
+  Int m_deltaRIdxMinus1;
+#endif
+  Int m_deltaRPS;
+  Int m_numRefIdc;
+  Int m_refIdc[MAX_NUM_REF_PICS+1];
+  GOPEntry()
+  : m_POC(-1)
+  , m_QPOffset(0)
+  , m_QPFactor(0)
+  , m_temporalId(0)
+  , m_refPic(false)
+  , m_numRefPicsActive(0)
+  , m_sliceType('P')
+  , m_numRefPics(0)
+  , m_interRPSPrediction(false)
+#if !J0234_INTER_RPS_SIMPL
+  , m_deltaRIdxMinus1(0)
+#endif
+  , m_deltaRPS(0)
+  , m_numRefIdc(0)
+  {
+    ::memset( m_referencePics, 0, sizeof(m_referencePics) );
+    ::memset( m_usedByCurrPic, 0, sizeof(m_usedByCurrPic) );
+    ::memset( m_refIdc,        0, sizeof(m_refIdc) );
+  }
+};
+
+std::istringstream &operator>>(std::istringstream &in, GOPEntry &entry);     //input
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// encoder configuration class
+class TEncCfg
+{
+protected:
+  //==== File I/O ========
+  Int       m_iFrameRate;
+  Int       m_FrameSkip;
+  Int       m_iSourceWidth;
+  Int       m_iSourceHeight;
+  Int       m_croppingMode;
+  Int       m_cropLeft;
+  Int       m_cropRight;
+  Int       m_cropTop;
+  Int       m_cropBottom;
+  Int       m_iFrameToBeEncoded;
+  Double    m_adLambdaModifier[ MAX_TLAYER ];
+
+  //====== Coding Structure ========
+  UInt      m_uiIntraPeriod;
+  UInt      m_uiDecodingRefreshType;            ///< the type of decoding refresh employed for the random access.
+  Int       m_iGOPSize;
+  GOPEntry  m_GOPList[MAX_GOP];
+  Int       m_extraRPSs;
+  Int       m_maxDecPicBuffering[MAX_TLAYER];
+  Int       m_numReorderPics[MAX_TLAYER];
+  
+  Int       m_iQP;                              //  if (AdaptiveQP == OFF)
+  
+  Int       m_aiPad[2];
+  
+
+  Int       m_iMaxRefPicNum;                     ///< this is used to mimic the sliding mechanism used by the decoder
+                                                 // TODO: We need to have a common sliding mechanism used by both the encoder and decoder
+
+  Int       m_maxTempLayer;                      ///< Max temporal layer
+  Bool m_useAMP;
+  //======= Transform =============
+  UInt      m_uiQuadtreeTULog2MaxSize;
+  UInt      m_uiQuadtreeTULog2MinSize;
+  UInt      m_uiQuadtreeTUMaxDepthInter;
+  UInt      m_uiQuadtreeTUMaxDepthIntra;
+  
+#if !REMOVE_NSQT
+  Bool      m_useNSQT;
+#endif
+  
+  //====== Loop/Deblock Filter ========
+  Bool      m_bLoopFilterDisable;
+  Bool      m_loopFilterOffsetInPPS;
+  Int       m_loopFilterBetaOffsetDiv2;
+  Int       m_loopFilterTcOffsetDiv2;
+  Bool      m_DeblockingFilterControlPresent;
+  Bool      m_bUseSAO;
+  Int       m_maxNumOffsetsPerPic;
+#if SAO_LCU_BOUNDARY
+  Bool      m_saoLcuBoundary;
+#endif
+  Bool      m_saoLcuBasedOptimization;
+
+  //====== Lossless ========
+  Bool      m_useLossless;
+  //====== Motion search ========
+  Int       m_iFastSearch;                      //  0:Full search  1:Diamond  2:PMVFAST
+  Int       m_iSearchRange;                     //  0:Full frame
+  Int       m_bipredSearchRange;
+
+  //====== Quality control ========
+  Int       m_iMaxDeltaQP;                      //  Max. absolute delta QP (1:default)
+  Int       m_iMaxCuDQPDepth;                   //  Max. depth for a minimum CuDQP (0:default)
+
+  Int       m_chromaCbQpOffset;                 //  Chroma Cb QP Offset (0:default)
+  Int       m_chromaCrQpOffset;                 //  Chroma Cr Qp Offset (0:default)
+
+#if ADAPTIVE_QP_SELECTION
+  Bool      m_bUseAdaptQpSelect;
+#endif
+
+  Bool      m_bUseAdaptiveQP;
+  Int       m_iQPAdaptationRange;
+  
+  //====== Tool list ========
+  Bool      m_bUseSBACRD;
+#if !REMOVE_ALF
+  Bool      m_bUseALF;
+  Bool      m_alfLowLatencyEncoding;
+#endif
+  Bool      m_bUseASR;
+  Bool      m_bUseHADME;
+  Bool      m_bUseLComb;
+  Bool      m_bUseRDOQ;
+  Bool      m_bUseFastEnc;
+  Bool      m_bUseEarlyCU;
+  Bool      m_useFastDecisionForMerge;
+  Bool      m_bUseCbfFastMode;
+  Bool      m_useEarlySkipDetection;
+#if !REMOVE_LMCHROMA
+  Bool      m_bUseLMChroma;
+#endif
+  Bool      m_useTransformSkip;
+  Bool      m_useTransformSkipFast;
+  Int*      m_aidQP;
+  UInt      m_uiDeltaQpRD;
+  
+  Bool      m_bUseConstrainedIntraPred;
+  Bool      m_usePCM;
+  UInt      m_pcmLog2MaxSize;
+  UInt      m_uiPCMLog2MinSize;
+  //====== Slice ========
+  Int       m_iSliceMode;
+  Int       m_iSliceArgument; 
+  //====== Dependent Slice ========
+  Int       m_iDependentSliceMode;
+  Int       m_iDependentSliceArgument;
+#if DEPENDENT_SLICES
+#if TILES_WPP_ENTROPYSLICES_FLAGS
+  Bool      m_entropySliceEnabledFlag;
+#else
+  Bool      m_bCabacIndependentFlag;
+#endif
+#endif
+#if !REMOVE_FGS
+  Int       m_iSliceGranularity;
+#endif
+  Bool      m_bLFCrossSliceBoundaryFlag;
+
+  Bool      m_bPCMInputBitDepthFlag;
+  UInt      m_uiPCMBitDepthLuma;
+  UInt      m_uiPCMBitDepthChroma;
+  Bool      m_bPCMFilterDisableFlag;
+  Bool      m_loopFilterAcrossTilesEnabledFlag;
+  Int       m_iUniformSpacingIdr;
+  Int       m_iNumColumnsMinus1;
+  UInt*     m_puiColumnWidth;
+  Int       m_iNumRowsMinus1;
+  UInt*     m_puiRowHeight;
+
+  Int       m_iWaveFrontSynchro;
+  Int       m_iWaveFrontSubstreams;
+
+  Int       m_decodedPictureHashSEIEnabled;              ///< Checksum(3)/CRC(2)/MD5(1)/disable(0) acting on decoded picture hash SEI message
+#if BUFFERING_PERIOD_AND_TIMING_SEI
+  Int       m_bufferingPeriodSEIEnabled;
+  Int       m_pictureTimingSEIEnabled;
+#endif
+#if RECOVERY_POINT_SEI
+  Int       m_recoveryPointSEIEnabled;
+#endif
+  //====== Weighted Prediction ========
+  Bool      m_bUseWeightPred;       //< Use of Weighting Prediction (P_SLICE)
+  Bool      m_useWeightedBiPred;    //< Use of Bi-directional Weighting Prediction (B_SLICE)
+  UInt      m_log2ParallelMergeLevelMinus2;       ///< Parallel merge estimation region
+  UInt      m_maxNumMergeCand;                    ///< Maximum number of merge candidates
+  Int       m_useScalingListId;            ///< Using quantization matrix i.e. 0=off, 1=default, 2=file.
+  char*     m_scalingListFile;          ///< quantization matrix file name
+  Int       m_TMVPModeId;
+  Int       m_signHideFlag;
+  Bool      m_enableRateCtrl;                                ///< Flag for using rate control algorithm
+  Int       m_targetBitrate;                                 ///< target bitrate
+  Int       m_numLCUInUnit;                                  ///< Total number of LCUs in a frame should be divided by the NumLCUInUnit
+  Bool      m_TransquantBypassEnableFlag;                     ///< transquant_bypass_enable_flag setting in PPS.
+  Bool      m_CUTransquantBypassFlagValue;                    ///< if transquant_bypass_enable_flag, the fixed value to use for the per-CU cu_transquant_bypass_flag.
+  TComVPS                    m_cVPS;
+#if RECALCULATE_QP_ACCORDING_LAMBDA
+  Bool      m_recalculateQPAccordingToLambda;                 ///< recalculate QP value according to the lambda value
+#endif
+#if ACTIVE_PARAMETER_SETS_SEI_MESSAGE  
+  Int       m_activeParameterSetsSEIEnabled;                  ///< enable active parameter set SEI message 
+#endif 
+#if SUPPORT_FOR_VUI
+  Bool      m_vuiParametersPresentFlag;                       ///< enable generation of VUI parameters
+  Bool      m_aspectRatioInfoPresentFlag;                     ///< Signals whether aspect_ratio_idc is present
+  Int       m_aspectRatioIdc;                                 ///< aspect_ratio_idc
+  Int       m_sarWidth;                                       ///< horizontal size of the sample aspect ratio
+  Int       m_sarHeight;                                      ///< vertical size of the sample aspect ratio
+  Bool      m_overscanInfoPresentFlag;                        ///< Signals whether overscan_appropriate_flag is present
+  Bool      m_overscanAppropriateFlag;                        ///< Indicates whether cropped decoded pictures are suitable for display using overscan
+  Bool      m_videoSignalTypePresentFlag;                     ///< Signals whether video_format, video_full_range_flag, and colour_description_present_flag are present
+  Int       m_videoFormat;                                    ///< Indicates representation of pictures
+  Bool      m_videoFullRangeFlag;                             ///< Indicates the black level and range of luma and chroma signals
+  Bool      m_colourDescriptionPresentFlag;                   ///< Signals whether colour_primaries, transfer_characteristics and matrix_coefficients are present
+  Int       m_colourPrimaries;                                ///< Indicates chromaticity coordinates of the source primaries
+  Int       m_transferCharacteristics;                        ///< Indicates the opto-electronic transfer characteristics of the source
+  Int       m_matrixCoefficients;                             ///< Describes the matrix coefficients used in deriving luma and chroma from RGB primaries
+  Bool      m_chromaLocInfoPresentFlag;                       ///< Signals whether chroma_sample_loc_type_top_field and chroma_sample_loc_type_bottom_field are present
+  Int       m_chromaSampleLocTypeTopField;                    ///< Specifies the location of chroma samples for top field
+  Int       m_chromaSampleLocTypeBottomField;                 ///< Specifies the location of chroma samples for bottom field
+  Bool      m_neutralChromaIndicationFlag;                    ///< Indicates that the value of all decoded chroma samples is equal to 1<<(BitDepthCr-1)
+  Bool      m_bitstreamRestrictionFlag;                       ///< Signals whether bitstream restriction parameters are present
+  Bool      m_tilesFixedStructureFlag;                        ///< Indicates that each active picture parameter set has the same values of the syntax elements related to tiles
+  Bool      m_motionVectorsOverPicBoundariesFlag;             ///< Indicates that no samples outside the picture boundaries are used for inter prediction
+  Int       m_maxBytesPerPicDenom;                            ///< Indicates a number of bytes not exceeded by the sum of the sizes of the VCL NAL units associated with any coded picture
+  Int       m_maxBitsPerMinCuDenom;                           ///< Indicates an upper bound for the number of bits of coding_unit() data
+  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
+#endif
+
+#if SVC_EXTENSION
+  UInt      m_layerId;   
+  UInt      m_numLayer;
+#endif 
+#if REF_IDX_FRAMEWORK
+  Int      m_elRapSliceBEnabled;
+#endif
+
+public:
+  TEncCfg()
+  : m_puiColumnWidth()
+  , m_puiRowHeight()
+  {}
+
+  virtual ~TEncCfg()
+  {
+    delete[] m_puiColumnWidth;
+    delete[] m_puiRowHeight;
+  }
+  
+  Void      setFrameRate                    ( Int   i )      { m_iFrameRate = i; }
+  Void      setFrameSkip                    ( unsigned int i ) { m_FrameSkip = i; }
+  Void      setSourceWidth                  ( Int   i )      { m_iSourceWidth = i; }
+  Void      setSourceHeight                 ( Int   i )      { m_iSourceHeight = i; }
+  Void      setCroppingMode                 ( Int   i )      { m_croppingMode = i; }
+  Void      setCropLeft                     ( Int   i )      { m_cropLeft = i; }
+  Void      setCropRight                    ( Int   i )      { m_cropRight = i; }
+  Void      setCropTop                      ( Int   i )      { m_cropTop = i; }
+  Void      setCropBottom                   ( Int   i )      { m_cropBottom = i; }
+  Void      setFrameToBeEncoded             ( Int   i )      { m_iFrameToBeEncoded = i; }
+  
+  //====== Coding Structure ========
+  Void      setIntraPeriod                  ( Int   i )      { m_uiIntraPeriod = (UInt)i; }
+  Void      setDecodingRefreshType          ( Int   i )      { m_uiDecodingRefreshType = (UInt)i; }
+  Void      setGOPSize                      ( Int   i )      { m_iGOPSize = i; }
+  Void      setGopList                      ( GOPEntry*  GOPList ) {  for ( Int i = 0; i < MAX_GOP; i++ ) m_GOPList[i] = GOPList[i]; }
+  Void      setExtraRPSs                    ( Int   i )      { m_extraRPSs = i; }
+  GOPEntry  getGOPEntry                     ( Int   i )      { return m_GOPList[i]; }
+  Void      setMaxDecPicBuffering           ( UInt u, UInt tlayer ) { m_maxDecPicBuffering[tlayer] = u;    }
+  Void      setNumReorderPics               ( Int  i, UInt tlayer ) { m_numReorderPics[tlayer] = i;    }
+  
+  Void      setQP                           ( Int   i )      { m_iQP = i; }
+  
+  Void      setPad                          ( Int*  iPad                   )      { for ( Int i = 0; i < 2; i++ ) m_aiPad[i] = iPad[i]; }
+  
+  Int       getMaxRefPicNum                 ()                              { return m_iMaxRefPicNum;           }
+  Void      setMaxRefPicNum                 ( Int iMaxRefPicNum )           { m_iMaxRefPicNum = iMaxRefPicNum;  }
+
+  Bool      getMaxTempLayer                 ()                              { return m_maxTempLayer;              } 
+  Void      setMaxTempLayer                 ( Int maxTempLayer )            { m_maxTempLayer = maxTempLayer;      }
+  //======== Transform =============
+  Void      setQuadtreeTULog2MaxSize        ( UInt  u )      { m_uiQuadtreeTULog2MaxSize = u; }
+  Void      setQuadtreeTULog2MinSize        ( UInt  u )      { m_uiQuadtreeTULog2MinSize = u; }
+  Void      setQuadtreeTUMaxDepthInter      ( UInt  u )      { m_uiQuadtreeTUMaxDepthInter = u; }
+  Void      setQuadtreeTUMaxDepthIntra      ( UInt  u )      { m_uiQuadtreeTUMaxDepthIntra = u; }
+  
+#if !REMOVE_NSQT
+  Void setUseNSQT( Bool b ) { m_useNSQT = b; }
+#endif
+  Void setUseAMP( Bool b ) { m_useAMP = b; }
+  
+  //====== Loop/Deblock Filter ========
+  Void      setLoopFilterDisable            ( Bool  b )      { m_bLoopFilterDisable       = b; }
+  Void      setLoopFilterOffsetInPPS        ( Bool  b )      { m_loopFilterOffsetInPPS      = b; }
+  Void      setLoopFilterBetaOffset         ( Int   i )      { m_loopFilterBetaOffsetDiv2  = i; }
+  Void      setLoopFilterTcOffset           ( Int   i )      { m_loopFilterTcOffsetDiv2    = i; }
+  Void      setDeblockingFilterControlPresent ( Bool b ) { m_DeblockingFilterControlPresent = b; }
+
+  //====== Motion search ========
+  Void      setFastSearch                   ( Int   i )      { m_iFastSearch = i; }
+  Void      setSearchRange                  ( Int   i )      { m_iSearchRange = i; }
+  Void      setBipredSearchRange            ( Int   i )      { m_bipredSearchRange = i; }
+
+  //====== Quality control ========
+  Void      setMaxDeltaQP                   ( Int   i )      { m_iMaxDeltaQP = i; }
+  Void      setMaxCuDQPDepth                ( Int   i )      { m_iMaxCuDQPDepth = i; }
+
+  Void      setChromaCbQpOffset             ( Int   i )      { m_chromaCbQpOffset = i; }
+  Void      setChromaCrQpOffset             ( Int   i )      { m_chromaCrQpOffset = i; }
+
+#if ADAPTIVE_QP_SELECTION
+  Void      setUseAdaptQpSelect             ( Bool   i ) { m_bUseAdaptQpSelect    = i; }
+  Bool      getUseAdaptQpSelect             ()           { return   m_bUseAdaptQpSelect; }
+#endif
+
+  Void      setUseAdaptiveQP                ( Bool  b )      { m_bUseAdaptiveQP = b; }
+  Void      setQPAdaptationRange            ( Int   i )      { m_iQPAdaptationRange = i; }
+  
+  //====== Lossless ========
+  Void      setUseLossless                  (Bool    b  )        { m_useLossless = b;  }
+  //====== Sequence ========
+  Int       getFrameRate                    ()      { return  m_iFrameRate; }
+  unsigned int getFrameSkip                 ()      { return  m_FrameSkip; }
+  Int       getSourceWidth                  ()      { return  m_iSourceWidth; }
+  Int       getSourceHeight                 ()      { return  m_iSourceHeight; }
+  Int       getCroppingMode                 ()      { return  m_croppingMode; }
+  Int       getCropLeft                     ()      { return  m_cropLeft; }
+  Int       getCropRight                    ()      { return  m_cropRight; }
+  Int       getCropTop                      ()      { return  m_cropTop; }
+  Int       getCropBottom                   ()      { return  m_cropBottom; }
+  Int       getFrameToBeEncoded             ()      { return  m_iFrameToBeEncoded; }
+  void setLambdaModifier                    ( UInt uiIndex, Double dValue ) { m_adLambdaModifier[ uiIndex ] = dValue; }
+  Double getLambdaModifier                  ( UInt uiIndex ) const { return m_adLambdaModifier[ uiIndex ]; }
+
+  //==== Coding Structure ========
+  UInt      getIntraPeriod                  ()      { return  m_uiIntraPeriod; }
+  UInt      getDecodingRefreshType          ()      { return  m_uiDecodingRefreshType; }
+  Int       getGOPSize                      ()      { return  m_iGOPSize; }
+  Int       getMaxDecPicBuffering           (UInt tlayer) { return m_maxDecPicBuffering[tlayer]; }
+  Int       getNumReorderPics               (UInt tlayer) { return m_numReorderPics[tlayer]; }
+  Int       getQP                           ()      { return  m_iQP; }
+  
+  Int       getPad                          ( Int i )      { assert (i < 2 );                      return  m_aiPad[i]; }
+  
+  //======== Transform =============
+  UInt      getQuadtreeTULog2MaxSize        ()      const { return m_uiQuadtreeTULog2MaxSize; }
+  UInt      getQuadtreeTULog2MinSize        ()      const { return m_uiQuadtreeTULog2MinSize; }
+  UInt      getQuadtreeTUMaxDepthInter      ()      const { return m_uiQuadtreeTUMaxDepthInter; }
+  UInt      getQuadtreeTUMaxDepthIntra      ()      const { return m_uiQuadtreeTUMaxDepthIntra; }
+  
+  //==== Loop/Deblock Filter ========
+  Bool      getLoopFilterDisable            ()      { return  m_bLoopFilterDisable;       }
+  Bool      getLoopFilterOffsetInPPS        ()      { return m_loopFilterOffsetInPPS; }
+  Int       getLoopFilterBetaOffset         ()      { return m_loopFilterBetaOffsetDiv2; }
+  Int       getLoopFilterTcOffset           ()      { return m_loopFilterTcOffsetDiv2; }
+  Bool      getDeblockingFilterControlPresent()  { return  m_DeblockingFilterControlPresent; }
+
+  //==== Motion search ========
+  Int       getFastSearch                   ()      { return  m_iFastSearch; }
+  Int       getSearchRange                  ()      { return  m_iSearchRange; }
+
+  //==== Quality control ========
+  Int       getMaxDeltaQP                   ()      { return  m_iMaxDeltaQP; }
+  Int       getMaxCuDQPDepth                ()      { return  m_iMaxCuDQPDepth; }
+  Bool      getUseAdaptiveQP                ()      { return  m_bUseAdaptiveQP; }
+  Int       getQPAdaptationRange            ()      { return  m_iQPAdaptationRange; }
+  //====== Lossless ========
+  Bool      getUseLossless                  ()      { return  m_useLossless;  }
+  
+  //==== Tool list ========
+  Void      setUseSBACRD                    ( Bool  b )     { m_bUseSBACRD  = b; }
+  Void      setUseASR                       ( Bool  b )     { m_bUseASR     = b; }
+  Void      setUseHADME                     ( Bool  b )     { m_bUseHADME   = b; }
+#if !REMOVE_ALF
+  Void      setUseALF                       ( Bool  b )     { m_bUseALF   = b; }
+#endif
+  Void      setUseLComb                     ( Bool  b )     { m_bUseLComb   = b; }
+  Void      setUseRDOQ                      ( Bool  b )     { m_bUseRDOQ    = b; }
+  Void      setUseFastEnc                   ( Bool  b )     { m_bUseFastEnc = b; }
+  Void      setUseEarlyCU                   ( Bool  b )     { m_bUseEarlyCU = b; }
+  Void      setUseFastDecisionForMerge      ( Bool  b )     { m_useFastDecisionForMerge = b; }
+  Void      setUseCbfFastMode            ( Bool  b )     { m_bUseCbfFastMode = b; }
+  Void      setUseEarlySkipDetection        ( Bool  b )     { m_useEarlySkipDetection = b; }
+  Void      setUseConstrainedIntraPred      ( Bool  b )     { m_bUseConstrainedIntraPred = b; }
+  Void      setPCMInputBitDepthFlag         ( Bool  b )     { m_bPCMInputBitDepthFlag = b; }
+  Void      setPCMFilterDisableFlag         ( Bool  b )     {  m_bPCMFilterDisableFlag = b; }
+  Void      setUsePCM                       ( Bool  b )     {  m_usePCM = b;               }
+  Void      setPCMLog2MaxSize               ( UInt u )      { m_pcmLog2MaxSize = u;      }
+  Void      setPCMLog2MinSize               ( UInt u )     { m_uiPCMLog2MinSize = u;      }
+  Void      setdQPs                         ( Int*  p )     { m_aidQP       = p; }
+  Void      setDeltaQpRD                    ( UInt  u )     {m_uiDeltaQpRD  = u; }
+  Bool      getUseSBACRD                    ()      { return m_bUseSBACRD;  }
+  Bool      getUseASR                       ()      { return m_bUseASR;     }
+  Bool      getUseHADME                     ()      { return m_bUseHADME;   }
+#if !REMOVE_ALF
+  Bool      getUseALF                       ()      { return m_bUseALF;     }
+  Void      setALFLowLatencyEncoding        (Bool b) {m_alfLowLatencyEncoding = b;    }
+  Bool      getALFLowLatencyEncoding        ()       { return m_alfLowLatencyEncoding;}
+#endif
+  Bool      getUseLComb                     ()      { return m_bUseLComb;   }
+  Bool      getUseRDOQ                      ()      { return m_bUseRDOQ;    }
+  Bool      getUseFastEnc                   ()      { return m_bUseFastEnc; }
+  Bool      getUseEarlyCU                   ()      { return m_bUseEarlyCU; }
+  Bool      getUseFastDecisionForMerge      ()      { return m_useFastDecisionForMerge; }
+  Bool      getUseCbfFastMode           ()      { return m_bUseCbfFastMode; }
+  Bool      getUseEarlySkipDetection        ()      { return m_useEarlySkipDetection; }
+  Bool      getUseConstrainedIntraPred      ()      { return m_bUseConstrainedIntraPred; }
+#if !REMOVE_NSQT
+#if NS_HAD
+  Bool      getUseNSQT                      ()      { return m_useNSQT; }
+#endif
+#endif
+  Bool      getPCMInputBitDepthFlag         ()      { return m_bPCMInputBitDepthFlag;   }
+  Bool      getPCMFilterDisableFlag         ()      { return m_bPCMFilterDisableFlag;   } 
+  Bool      getUsePCM                       ()      { return m_usePCM;                 }
+  UInt      getPCMLog2MaxSize               ()      { return m_pcmLog2MaxSize;  }
+  UInt      getPCMLog2MinSize               ()      { return  m_uiPCMLog2MinSize;  }
+
+#if !REMOVE_LMCHROMA
+  Bool getUseLMChroma                       ()      { return m_bUseLMChroma;        }
+  Void setUseLMChroma                       ( Bool b ) { m_bUseLMChroma  = b;       }
+#endif
+  Bool getUseTransformSkip                             ()      { return m_useTransformSkip;        }
+  Void setUseTransformSkip                             ( Bool b ) { m_useTransformSkip  = b;       }
+  Bool getUseTransformSkipFast                         ()      { return m_useTransformSkipFast;    }
+  Void setUseTransformSkipFast                         ( Bool b ) { m_useTransformSkipFast  = b;   }
+  Int*      getdQPs                         ()      { return m_aidQP;       }
+  UInt      getDeltaQpRD                    ()      { return m_uiDeltaQpRD; }
+
+  //====== Slice ========
+  Void  setSliceMode                   ( Int  i )       { m_iSliceMode = i;              }
+  Void  setSliceArgument               ( Int  i )       { m_iSliceArgument = i;          }
+  Int   getSliceMode                   ()              { return m_iSliceMode;           }
+  Int   getSliceArgument               ()              { return m_iSliceArgument;       }
+  //====== Dependent Slice ========
+  Void  setDependentSliceMode            ( Int  i )      { m_iDependentSliceMode = i;       }
+  Void  setDependentSliceArgument        ( Int  i )      { m_iDependentSliceArgument = i;   }
+  Int   getDependentSliceMode            ()              { return m_iDependentSliceMode;    }
+  Int   getDependentSliceArgument        ()              { return m_iDependentSliceArgument;}
+#if DEPENDENT_SLICES
+#if TILES_WPP_ENTROPYSLICES_FLAGS
+  Void  setEntropySliceEnabledFlag       ( Bool  b )     { m_entropySliceEnabledFlag = b;    }
+  Bool  getEntropySliceEnabledFlag       ()              { return m_entropySliceEnabledFlag; }
+#else
+  Void  setCabacIndependentFlag            ( Bool  i )      { m_bCabacIndependentFlag = i;       }
+  Bool  getCabacIndependentFlag     ()                    { return m_bCabacIndependentFlag;   }
+#endif
+#endif
+#if !REMOVE_FGS
+  Void  setSliceGranularity            ( Int  i )      { m_iSliceGranularity = i;       }
+  Int   getSliceGranularity            ()              { return m_iSliceGranularity;    }
+#endif
+  Void      setLFCrossSliceBoundaryFlag     ( Bool   bValue  )    { m_bLFCrossSliceBoundaryFlag = bValue; }
+  Bool      getLFCrossSliceBoundaryFlag     ()                    { return m_bLFCrossSliceBoundaryFlag;   }
+
+  Void      setUseSAO                  (Bool bVal)     {m_bUseSAO = bVal;}
+  Bool      getUseSAO                  ()              {return m_bUseSAO;}
+  Void  setMaxNumOffsetsPerPic                   (Int iVal)            { m_maxNumOffsetsPerPic = iVal; }
+  Int   getMaxNumOffsetsPerPic                   ()                    { return m_maxNumOffsetsPerPic; }
+#if SAO_LCU_BOUNDARY
+  Void  setSaoLcuBoundary              (Bool val)      { m_saoLcuBoundary = val; }
+  Bool  getSaoLcuBoundary              ()              { return m_saoLcuBoundary; }
+#endif
+  Void  setSaoLcuBasedOptimization               (Bool val)            { m_saoLcuBasedOptimization = val; }
+  Bool  getSaoLcuBasedOptimization               ()                    { return m_saoLcuBasedOptimization; }
+  Void  setLFCrossTileBoundaryFlag               ( Bool   val  )       { m_loopFilterAcrossTilesEnabledFlag = val; }
+  Bool  getLFCrossTileBoundaryFlag               ()                    { return m_loopFilterAcrossTilesEnabledFlag;   }
+  Void  setUniformSpacingIdr           ( Int i )           { m_iUniformSpacingIdr = i; }
+  Int   getUniformSpacingIdr           ()                  { return m_iUniformSpacingIdr; }
+  Void  setNumColumnsMinus1            ( Int i )           { m_iNumColumnsMinus1 = i; }
+  Int   getNumColumnsMinus1            ()                  { return m_iNumColumnsMinus1; }
+  Void  setColumnWidth ( char* str )
+  {
+    char *columnWidth;
+    int  i=0;
+    Int  m_iWidthInCU = ( m_iSourceWidth%g_uiMaxCUWidth ) ? m_iSourceWidth/g_uiMaxCUWidth + 1 : m_iSourceWidth/g_uiMaxCUWidth;
+
+    if( m_iUniformSpacingIdr == 0 && m_iNumColumnsMinus1 > 0 )
+    {
+      m_puiColumnWidth = new UInt[m_iNumColumnsMinus1];
+
+      columnWidth = strtok(str, " ,-");
+      while(columnWidth!=NULL)
+      {
+        if( i>=m_iNumColumnsMinus1 )
+        {
+          printf( "The number of columns whose width are defined is larger than the allowed number of columns.\n" );
+          exit( EXIT_FAILURE );
+        }
+        *( m_puiColumnWidth + i ) = atoi( columnWidth );
+        printf("col: m_iWidthInCU= %4d i=%4d width= %4d\n",m_iWidthInCU,i,m_puiColumnWidth[i]); //AFU
+        columnWidth = strtok(NULL, " ,-");
+        i++;
+      }
+      if( i<m_iNumColumnsMinus1 )
+      {
+        printf( "The width of some columns is not defined.\n" );
+        exit( EXIT_FAILURE );
+      }
+    }
+  }
+  UInt  getColumnWidth                 ( UInt columnidx )  { return *( m_puiColumnWidth + columnidx ); }
+  Void  setNumRowsMinus1               ( Int i )           { m_iNumRowsMinus1 = i; }
+  Int   getNumRowsMinus1               ()                  { return m_iNumRowsMinus1; }
+  Void  setRowHeight (char* str)
+  {
+    char *rowHeight;
+    int  i=0;
+    Int  m_iHeightInCU = ( m_iSourceHeight%g_uiMaxCUHeight ) ? m_iSourceHeight/g_uiMaxCUHeight + 1 : m_iSourceHeight/g_uiMaxCUHeight;
+
+    if( m_iUniformSpacingIdr == 0 && m_iNumRowsMinus1 > 0 )
+    {
+      m_puiRowHeight = new UInt[m_iNumRowsMinus1];
+
+      rowHeight = strtok(str, " ,-");
+      while(rowHeight!=NULL)
+      {
+        if( i>=m_iNumRowsMinus1 )
+        {
+          printf( "The number of rows whose height are defined is larger than the allowed number of rows.\n" );
+          exit( EXIT_FAILURE );
+        }
+        *( m_puiRowHeight + i ) = atoi( rowHeight );
+        printf("row: m_iHeightInCU=%4d i=%4d height=%4d\n",m_iHeightInCU,i,m_puiRowHeight[i]); //AFU
+        rowHeight = strtok(NULL, " ,-");
+        i++;
+      }
+      if( i<m_iNumRowsMinus1 )
+      {
+        printf( "The height of some rows is not defined.\n" );
+        exit( EXIT_FAILURE );
+     }
+    }
+  }
+  UInt  getRowHeight                   ( UInt rowIdx )     { return *( m_puiRowHeight + rowIdx ); }
+  Void  xCheckGSParameters();
+  Void  setWaveFrontSynchro(Int iWaveFrontSynchro)       { m_iWaveFrontSynchro = iWaveFrontSynchro; }
+  Int   getWaveFrontsynchro()                            { return m_iWaveFrontSynchro; }
+  Void  setWaveFrontSubstreams(Int iWaveFrontSubstreams) { m_iWaveFrontSubstreams = iWaveFrontSubstreams; }
+  Int   getWaveFrontSubstreams()                         { return m_iWaveFrontSubstreams; }
+  Void  setDecodedPictureHashSEIEnabled(Int b)           { m_decodedPictureHashSEIEnabled = b; }
+  Int   getDecodedPictureHashSEIEnabled()                { return m_decodedPictureHashSEIEnabled; }
+#if BUFFERING_PERIOD_AND_TIMING_SEI
+  Void  setBufferingPeriodSEIEnabled(Int b)              { m_bufferingPeriodSEIEnabled = b; }
+  Int   getBufferingPeriodSEIEnabled()                   { return m_bufferingPeriodSEIEnabled; }
+  Void  setPictureTimingSEIEnabled(Int b)                { m_pictureTimingSEIEnabled = b; }
+  Int   getPictureTimingSEIEnabled()                     { return m_pictureTimingSEIEnabled; }
+#endif
+#if RECOVERY_POINT_SEI
+  Void  setRecoveryPointSEIEnabled(Int b)                { m_recoveryPointSEIEnabled = b; }
+  Int   getRecoveryPointSEIEnabled()                     { return m_recoveryPointSEIEnabled; }
+#endif
+  Void      setUseWP               ( Bool  b )   { m_bUseWeightPred    = b;    }
+  Void      setWPBiPred            ( Bool b )    { m_useWeightedBiPred = b;    }
+  Bool      getUseWP               ()            { return m_bUseWeightPred;    }
+  Bool      getWPBiPred            ()            { return m_useWeightedBiPred; }
+  Void      setLog2ParallelMergeLevelMinus2   ( UInt u )    { m_log2ParallelMergeLevelMinus2       = u;    }
+  UInt      getLog2ParallelMergeLevelMinus2   ()            { return m_log2ParallelMergeLevelMinus2;       }
+  Void      setMaxNumMergeCand                ( UInt u )    { m_maxNumMergeCand = u;      }
+  UInt      getMaxNumMergeCand                ()            { return m_maxNumMergeCand;   }
+  Void      setUseScalingListId    ( Int  u )    { m_useScalingListId       = u;   }
+  Int       getUseScalingListId    ()            { return m_useScalingListId;      }
+  Void      setScalingListFile     ( char*  pch ){ m_scalingListFile     = pch; }
+  char*     getScalingListFile     ()            { return m_scalingListFile;    }
+  Void      setTMVPModeId ( Int  u ) { m_TMVPModeId = u;    }
+  Int       getTMVPModeId ()         { return m_TMVPModeId; }
+  Void      setSignHideFlag( Int signHideFlag ) { m_signHideFlag = signHideFlag; }
+  Int       getSignHideFlag()                    { return m_signHideFlag; }
+  Bool      getUseRateCtrl    ()                { return m_enableRateCtrl;    }
+  Void      setUseRateCtrl    (Bool flag)       { m_enableRateCtrl = flag;    }
+  Int       getTargetBitrate  ()                { return m_targetBitrate;     }
+  Void      setTargetBitrate  (Int target)      { m_targetBitrate  = target;  }
+  Int       getNumLCUInUnit   ()                { return m_numLCUInUnit;      }
+  Void      setNumLCUInUnit   (Int numLCUs)     { m_numLCUInUnit   = numLCUs; }
+  Bool      getTransquantBypassEnableFlag()           { return m_TransquantBypassEnableFlag; }
+  Void      setTransquantBypassEnableFlag(Bool flag)  { m_TransquantBypassEnableFlag = flag; }
+  Bool      getCUTransquantBypassFlagValue()          { return m_CUTransquantBypassFlagValue; }
+  Void      setCUTransquantBypassFlagValue(Bool flag) { m_CUTransquantBypassFlagValue = flag; }
+  Void setVPS(TComVPS *p) { m_cVPS = *p; }
+  TComVPS *getVPS() { return &m_cVPS; }
+#if RECALCULATE_QP_ACCORDING_LAMBDA
+  Void      setUseRecalculateQPAccordingToLambda ( Bool b ) { m_recalculateQPAccordingToLambda = b;    }
+  Bool      getUseRecalculateQPAccordingToLambda ()         { return m_recalculateQPAccordingToLambda; }
+#endif
+#if ACTIVE_PARAMETER_SETS_SEI_MESSAGE 
+  Void      setActiveParameterSetsSEIEnabled ( Int b )  { m_activeParameterSetsSEIEnabled = b; }  
+  Int       getActiveParameterSetsSEIEnabled ()         { return m_activeParameterSetsSEIEnabled; }
+#endif 
+#if SUPPORT_FOR_VUI
+  Bool      getVuiParametersPresentFlag()                 { return m_vuiParametersPresentFlag; }
+  Void      setVuiParametersPresentFlag(Bool i)           { m_vuiParametersPresentFlag = i; }
+  Bool      getAspectRatioInfoPresentFlag()               { return m_aspectRatioInfoPresentFlag; }
+  Void      setAspectRatioInfoPresentFlag(Bool i)         { m_aspectRatioInfoPresentFlag = i; }
+  Int       getAspectRatioIdc()                           { return m_aspectRatioIdc; }
+  Void      setAspectRatioIdc(Int i)                      { m_aspectRatioIdc = i; }
+  Int       getSarWidth()                                 { return m_sarWidth; }
+  Void      setSarWidth(Int i)                            { m_sarWidth = i; }
+  Int       getSarHeight()                                { return m_sarHeight; }
+  Void      setSarHeight(Int i)                           { m_sarHeight = i; }
+  Bool      getOverscanInfoPresentFlag()                  { return m_overscanInfoPresentFlag; }
+  Void      setOverscanInfoPresentFlag(Bool i)            { m_overscanInfoPresentFlag = i; }
+  Bool      getOverscanAppropriateFlag()                  { return m_overscanAppropriateFlag; }
+  Void      setOverscanAppropriateFlag(Bool i)            { m_overscanAppropriateFlag = i; }
+  Bool      getVideoSignalTypePresentFlag()               { return m_videoSignalTypePresentFlag; }
+  Void      setVideoSignalTypePresentFlag(Bool i)         { m_videoSignalTypePresentFlag = i; }
+  Int       getVideoFormat()                              { return m_videoFormat; }
+  Void      setVideoFormat(Int i)                         { m_videoFormat = i; }
+  Bool      getVideoFullRangeFlag()                       { return m_videoFullRangeFlag; }
+  Void      setVideoFullRangeFlag(Bool i)                 { m_videoFullRangeFlag = i; }
+  Bool      getColourDescriptionPresentFlag()             { return m_colourDescriptionPresentFlag; }
+  Void      setColourDescriptionPresentFlag(Bool i)       { m_colourDescriptionPresentFlag = i; }
+  Int       getColourPrimaries()                          { return m_colourPrimaries; }
+  Void      setColourPrimaries(Int i)                     { m_colourPrimaries = i; }
+  Int       getTransferCharacteristics()                  { return m_transferCharacteristics; }
+  Void      setTransferCharacteristics(Int i)             { m_transferCharacteristics = i; }
+  Int       getMatrixCoefficients()                       { return m_matrixCoefficients; }
+  Void      setMatrixCoefficients(Int i)                  { m_matrixCoefficients = i; }
+  Bool      getChromaLocInfoPresentFlag()                 { return m_chromaLocInfoPresentFlag; }
+  Void      setChromaLocInfoPresentFlag(Bool i)           { m_chromaLocInfoPresentFlag = i; }
+  Int       getChromaSampleLocTypeTopField()              { return m_chromaSampleLocTypeTopField; }
+  Void      setChromaSampleLocTypeTopField(Int i)         { m_chromaSampleLocTypeTopField = i; }
+  Int       getChromaSampleLocTypeBottomField()           { return m_chromaSampleLocTypeBottomField; }
+  Void      setChromaSampleLocTypeBottomField(Int i)      { m_chromaSampleLocTypeBottomField = i; }
+  Bool      getNeutralChromaIndicationFlag()              { return m_neutralChromaIndicationFlag; }
+  Void      setNeutralChromaIndicationFlag(Bool i)        { m_neutralChromaIndicationFlag = i; }
+  Bool      getBitstreamRestrictionFlag()                 { return m_bitstreamRestrictionFlag; }
+  Void      setBitstreamRestrictionFlag(Bool i)           { m_bitstreamRestrictionFlag = i; }
+  Bool      getTilesFixedStructureFlag()                  { return m_tilesFixedStructureFlag; }
+  Void      setTilesFixedStructureFlag(Bool i)            { m_tilesFixedStructureFlag = i; }
+  Bool      getMotionVectorsOverPicBoundariesFlag()       { return m_motionVectorsOverPicBoundariesFlag; }
+  Void      setMotionVectorsOverPicBoundariesFlag(Bool i) { m_motionVectorsOverPicBoundariesFlag = i; }
+  Int       getMaxBytesPerPicDenom()                      { return m_maxBytesPerPicDenom; }
+  Void      setMaxBytesPerPicDenom(Int i)                 { m_maxBytesPerPicDenom = i; }
+  Int       getMaxBitsPerMinCuDenom()                     { return m_maxBitsPerMinCuDenom; }
+  Void      setMaxBitsPerMinCuDenom(Int i)                { m_maxBitsPerMinCuDenom = i; }
+  Int       getLog2MaxMvLengthHorizontal()                { return m_log2MaxMvLengthHorizontal; }
+  Void      setLog2MaxMvLengthHorizontal(Int i)           { m_log2MaxMvLengthHorizontal = i; }
+  Int       getLog2MaxMvLengthVertical()                  { return m_log2MaxMvLengthVertical; }
+  Void      setLog2MaxMvLengthVertical(Int i)             { m_log2MaxMvLengthVertical = i; }
+#endif
+
+#if SVC_EXTENSION
+  UInt      getLayerId            () { return m_layerId;              }
+  Void      setLayerId            (UInt layer) { m_layerId = layer; }
+  UInt      getNumLayer           () { return m_numLayer;             }  
+  Void      setNumLayer           (UInt uiNum)   { m_numLayer = uiNum;  }
+#endif
+#if REF_IDX_FRAMEWORK
+  Void      setElRapSliceTypeB(Int bEnabled) {m_elRapSliceBEnabled = bEnabled;}
+  Int       getElRapSliceTypeB()              {return m_elRapSliceBEnabled;}
+#endif
+
+};
+
+//! \}
+
+#endif // !defined(AFX_TENCCFG_H__6B99B797_F4DA_4E46_8E78_7656339A6C41__INCLUDED_)
Index: /trunk/source/Lib/TLibEncoder/TEncCu.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncCu.cpp	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/TEncCu.cpp	(revision 2)
@@ -0,0 +1,1941 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncCu.cpp
+    \brief    Coding Unit (CU) encoder class
+*/
+
+#include <stdio.h>
+#include "TEncTop.h"
+#include "TEncCu.h"
+#include "TEncAnalyze.h"
+
+#include <cmath>
+#include <algorithm>
+using namespace std;
+
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+/**
+ \param    uiTotalDepth  total number of allowable depth
+ \param    uiMaxWidth    largest CU width
+ \param    uiMaxHeight   largest CU height
+ */
+Void TEncCu::create(UChar uhTotalDepth, UInt uiMaxWidth, UInt uiMaxHeight)
+{
+  Int i;
+  
+  m_uhTotalDepth   = uhTotalDepth + 1;
+  m_ppcBestCU      = new TComDataCU*[m_uhTotalDepth-1];
+  m_ppcTempCU      = new TComDataCU*[m_uhTotalDepth-1];
+    
+  m_ppcPredYuvBest = new TComYuv*[m_uhTotalDepth-1];
+  m_ppcResiYuvBest = new TComYuv*[m_uhTotalDepth-1];
+  m_ppcRecoYuvBest = new TComYuv*[m_uhTotalDepth-1];
+  m_ppcPredYuvTemp = new TComYuv*[m_uhTotalDepth-1];
+  m_ppcResiYuvTemp = new TComYuv*[m_uhTotalDepth-1];
+  m_ppcRecoYuvTemp = new TComYuv*[m_uhTotalDepth-1];
+  m_ppcOrigYuv     = new TComYuv*[m_uhTotalDepth-1];
+  
+  UInt uiNumPartitions;
+  for( i=0 ; i<m_uhTotalDepth-1 ; i++)
+  {
+    uiNumPartitions = 1<<( ( m_uhTotalDepth - i - 1 )<<1 );
+    UInt uiWidth  = uiMaxWidth  >> i;
+    UInt uiHeight = uiMaxHeight >> i;
+    
+    m_ppcBestCU[i] = new TComDataCU; m_ppcBestCU[i]->create( uiNumPartitions, uiWidth, uiHeight, false, uiMaxWidth >> (m_uhTotalDepth - 1) );
+    m_ppcTempCU[i] = new TComDataCU; m_ppcTempCU[i]->create( uiNumPartitions, uiWidth, uiHeight, false, uiMaxWidth >> (m_uhTotalDepth - 1) );
+    
+    m_ppcPredYuvBest[i] = new TComYuv; m_ppcPredYuvBest[i]->create(uiWidth, uiHeight);
+    m_ppcResiYuvBest[i] = new TComYuv; m_ppcResiYuvBest[i]->create(uiWidth, uiHeight);
+    m_ppcRecoYuvBest[i] = new TComYuv; m_ppcRecoYuvBest[i]->create(uiWidth, uiHeight);
+    
+    m_ppcPredYuvTemp[i] = new TComYuv; m_ppcPredYuvTemp[i]->create(uiWidth, uiHeight);
+    m_ppcResiYuvTemp[i] = new TComYuv; m_ppcResiYuvTemp[i]->create(uiWidth, uiHeight);
+    m_ppcRecoYuvTemp[i] = new TComYuv; m_ppcRecoYuvTemp[i]->create(uiWidth, uiHeight);
+    
+    m_ppcOrigYuv    [i] = new TComYuv; m_ppcOrigYuv    [i]->create(uiWidth, uiHeight);
+  }
+  
+  m_bEncodeDQP = false;
+  m_checkBurstIPCMFlag = false;
+
+  // initialize partition order.
+  UInt* piTmp = &g_auiZscanToRaster[0];
+  initZscanToRaster( m_uhTotalDepth, 1, 0, piTmp);
+  initRasterToZscan( uiMaxWidth, uiMaxHeight, m_uhTotalDepth );
+  
+  // initialize conversion matrix from partition index to pel
+  initRasterToPelXY( uiMaxWidth, uiMaxHeight, m_uhTotalDepth );
+  initMotionReferIdx ( uiMaxWidth, uiMaxHeight, m_uhTotalDepth );
+}
+
+Void TEncCu::destroy()
+{
+  Int i;
+  
+  for( i=0 ; i<m_uhTotalDepth-1 ; i++)
+  {
+    if(m_ppcBestCU[i])
+    {
+      m_ppcBestCU[i]->destroy();      delete m_ppcBestCU[i];      m_ppcBestCU[i] = NULL;
+    }
+    if(m_ppcTempCU[i])
+    {
+      m_ppcTempCU[i]->destroy();      delete m_ppcTempCU[i];      m_ppcTempCU[i] = NULL;
+    }
+    if(m_ppcPredYuvBest[i])
+    {
+      m_ppcPredYuvBest[i]->destroy(); delete m_ppcPredYuvBest[i]; m_ppcPredYuvBest[i] = NULL;
+    }
+    if(m_ppcResiYuvBest[i])
+    {
+      m_ppcResiYuvBest[i]->destroy(); delete m_ppcResiYuvBest[i]; m_ppcResiYuvBest[i] = NULL;
+    }
+    if(m_ppcRecoYuvBest[i])
+    {
+      m_ppcRecoYuvBest[i]->destroy(); delete m_ppcRecoYuvBest[i]; m_ppcRecoYuvBest[i] = NULL;
+    }
+    if(m_ppcPredYuvTemp[i])
+    {
+      m_ppcPredYuvTemp[i]->destroy(); delete m_ppcPredYuvTemp[i]; m_ppcPredYuvTemp[i] = NULL;
+    }
+    if(m_ppcResiYuvTemp[i])
+    {
+      m_ppcResiYuvTemp[i]->destroy(); delete m_ppcResiYuvTemp[i]; m_ppcResiYuvTemp[i] = NULL;
+    }
+    if(m_ppcRecoYuvTemp[i])
+    {
+      m_ppcRecoYuvTemp[i]->destroy(); delete m_ppcRecoYuvTemp[i]; m_ppcRecoYuvTemp[i] = NULL;
+    }
+    if(m_ppcOrigYuv[i])
+    {
+      m_ppcOrigYuv[i]->destroy();     delete m_ppcOrigYuv[i];     m_ppcOrigYuv[i] = NULL;
+    }
+  }
+  if(m_ppcBestCU)
+  {
+    delete [] m_ppcBestCU;
+    m_ppcBestCU = NULL;
+  }
+  if(m_ppcTempCU)
+  {
+    delete [] m_ppcTempCU;
+    m_ppcTempCU = NULL;
+  }
+  
+  if(m_ppcPredYuvBest)
+  {
+    delete [] m_ppcPredYuvBest;
+    m_ppcPredYuvBest = NULL;
+  }
+  if(m_ppcResiYuvBest)
+  {
+    delete [] m_ppcResiYuvBest;
+    m_ppcResiYuvBest = NULL;
+  }
+  if(m_ppcRecoYuvBest)
+  {
+    delete [] m_ppcRecoYuvBest;
+    m_ppcRecoYuvBest = NULL;
+  }
+  if(m_ppcPredYuvTemp)
+  {
+    delete [] m_ppcPredYuvTemp;
+    m_ppcPredYuvTemp = NULL;
+  }
+  if(m_ppcResiYuvTemp)
+  {
+    delete [] m_ppcResiYuvTemp;
+    m_ppcResiYuvTemp = NULL;
+  }
+  if(m_ppcRecoYuvTemp)
+  {
+    delete [] m_ppcRecoYuvTemp;
+    m_ppcRecoYuvTemp = NULL;
+  }
+  if(m_ppcOrigYuv)
+  {
+    delete [] m_ppcOrigYuv;
+    m_ppcOrigYuv = NULL;
+  }
+}
+
+/** \param    pcEncTop      pointer of encoder class
+ */
+Void TEncCu::init( TEncTop* pcEncTop )
+{
+  m_pcEncCfg           = pcEncTop;
+  m_pcPredSearch       = pcEncTop->getPredSearch();
+  m_pcTrQuant          = pcEncTop->getTrQuant();
+  m_pcBitCounter       = pcEncTop->getBitCounter();
+  m_pcRdCost           = pcEncTop->getRdCost();
+
+#if SVC_EXTENSION
+  m_ppcTEncTop         = pcEncTop->getLayerEnc();
+  for(UInt i=0 ; i< m_uhTotalDepth-1 ; i++)
+  {    
+    m_ppcBestCU[i]->setLayerId(pcEncTop->getLayerId());
+    m_ppcTempCU[i]->setLayerId(pcEncTop->getLayerId());
+  }
+#endif
+  
+  m_pcEntropyCoder     = pcEncTop->getEntropyCoder();
+  m_pcCavlcCoder       = pcEncTop->getCavlcCoder();
+  m_pcSbacCoder       = pcEncTop->getSbacCoder();
+  m_pcBinCABAC         = pcEncTop->getBinCABAC();
+  
+  m_pppcRDSbacCoder   = pcEncTop->getRDSbacCoder();
+  m_pcRDGoOnSbacCoder = pcEncTop->getRDGoOnSbacCoder();
+  
+  m_bUseSBACRD        = pcEncTop->getUseSBACRD();
+  m_pcRateCtrl        = pcEncTop->getRateCtrl();
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/** \param  rpcCU pointer of CU data class
+ */
+Void TEncCu::compressCU( TComDataCU*& rpcCU )
+{
+  // initialize CU data
+  m_ppcBestCU[0]->initCU( rpcCU->getPic(), rpcCU->getAddr() );
+  m_ppcTempCU[0]->initCU( rpcCU->getPic(), rpcCU->getAddr() );
+
+  // analysis of CU
+  xCompressCU( m_ppcBestCU[0], m_ppcTempCU[0], 0 );
+
+#if ADAPTIVE_QP_SELECTION
+  if( m_pcEncCfg->getUseAdaptQpSelect() )
+  {
+    if(rpcCU->getSlice()->getSliceType()!=I_SLICE) //IIII
+    {
+      xLcuCollectARLStats( rpcCU);
+    }
+  }
+#endif
+}
+/** \param  pcCU  pointer of CU data class, bForceTerminate when set to true terminates slice (default is false).
+ */
+Void TEncCu::encodeCU ( TComDataCU* pcCU, Bool bForceTerminate )
+{
+  if ( pcCU->getSlice()->getPPS()->getUseDQP() )
+  {
+    setdQPFlag(true);
+  }
+
+  TComPic* pcPic = pcCU->getPic();
+  Bool checkBurstIPCMFlag = (pcPic->getSlice(0)->getSPS()->getUsePCM())? true : false;
+
+  setCheckBurstIPCMFlag( checkBurstIPCMFlag );
+
+  pcCU->setNumSucIPCM(0);
+  pcCU->setLastCUSucIPCMFlag(false);
+
+  // Encode CU data
+  xEncodeCU( pcCU, 0, 0 );
+  
+  bool bTerminateSlice = bForceTerminate;
+  UInt uiCUAddr = pcCU->getAddr();
+    /* If at the end of an LCU line but not at the end of a substream, perform CABAC flush */
+    if (!bTerminateSlice && pcCU->getSlice()->getPPS()->getNumSubstreams() > 1)
+    {
+      Int iNumSubstreams = pcCU->getSlice()->getPPS()->getNumSubstreams();
+      UInt uiWidthInLCUs = pcCU->getPic()->getPicSym()->getFrameWidthInCU();
+      UInt uiCol     = uiCUAddr % uiWidthInLCUs;
+      UInt uiLin     = uiCUAddr / uiWidthInLCUs;
+      UInt uiTileStartLCU = pcCU->getPic()->getPicSym()->getTComTile(pcCU->getPic()->getPicSym()->getTileIdxMap(uiCUAddr))->getFirstCUAddr();
+      UInt uiTileLCUX = uiTileStartLCU % uiWidthInLCUs;
+      UInt uiTileLCUY = uiTileStartLCU / uiWidthInLCUs;
+      UInt uiTileWidth = pcCU->getPic()->getPicSym()->getTComTile(pcCU->getPic()->getPicSym()->getTileIdxMap(uiCUAddr))->getTileWidth();
+      UInt uiTileHeight = pcCU->getPic()->getPicSym()->getTComTile(pcCU->getPic()->getPicSym()->getTileIdxMap(uiCUAddr))->getTileHeight();
+      Int iNumSubstreamsPerTile = iNumSubstreams;
+      if (pcCU->getSlice()->getPPS()->getNumSubstreams() > 1)
+      {
+        iNumSubstreamsPerTile /= pcCU->getPic()->getPicSym()->getNumTiles();
+      }
+      if ((uiCol == uiTileLCUX+uiTileWidth-1) && (uiLin+iNumSubstreamsPerTile < uiTileLCUY+uiTileHeight))
+      {
+        m_pcEntropyCoder->encodeFlush();
+      }
+    }
+}
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+/** Derive small set of test modes for AMP encoder speed-up
+ *\param   rpcBestCU
+ *\param   eParentPartSize
+ *\param   bTestAMP_Hor
+ *\param   bTestAMP_Ver
+ *\param   bTestMergeAMP_Hor
+ *\param   bTestMergeAMP_Ver
+ *\returns Void 
+*/
+#if AMP_ENC_SPEEDUP
+#if AMP_MRG
+Void TEncCu::deriveTestModeAMP (TComDataCU *&rpcBestCU, PartSize eParentPartSize, Bool &bTestAMP_Hor, Bool &bTestAMP_Ver, Bool &bTestMergeAMP_Hor, Bool &bTestMergeAMP_Ver)
+#else
+Void TEncCu::deriveTestModeAMP (TComDataCU *&rpcBestCU, PartSize eParentPartSize, Bool &bTestAMP_Hor, Bool &bTestAMP_Ver)
+#endif
+{
+  if ( rpcBestCU->getPartitionSize(0) == SIZE_2NxN )
+  {
+    bTestAMP_Hor = true;
+  }
+  else if ( rpcBestCU->getPartitionSize(0) == SIZE_Nx2N )
+  {
+    bTestAMP_Ver = true;
+  }
+  else if ( rpcBestCU->getPartitionSize(0) == SIZE_2Nx2N && rpcBestCU->getMergeFlag(0) == false && rpcBestCU->isSkipped(0) == false )
+  {
+    bTestAMP_Hor = true;          
+    bTestAMP_Ver = true;          
+  }
+
+#if AMP_MRG
+  //! Utilizing the partition size of parent PU    
+  if ( eParentPartSize >= SIZE_2NxnU && eParentPartSize <= SIZE_nRx2N )
+  { 
+    bTestMergeAMP_Hor = true;
+    bTestMergeAMP_Ver = true;
+  }
+
+  if ( eParentPartSize == SIZE_NONE ) //! if parent is intra
+  {
+    if ( rpcBestCU->getPartitionSize(0) == SIZE_2NxN )
+    {
+      bTestMergeAMP_Hor = true;
+    }
+    else if ( rpcBestCU->getPartitionSize(0) == SIZE_Nx2N )
+    {
+      bTestMergeAMP_Ver = true;
+    }
+  }
+
+  if ( rpcBestCU->getPartitionSize(0) == SIZE_2Nx2N && rpcBestCU->isSkipped(0) == false )
+  {
+    bTestMergeAMP_Hor = true;          
+    bTestMergeAMP_Ver = true;          
+  }
+
+  if ( rpcBestCU->getWidth(0) == 64 )
+  { 
+    bTestAMP_Hor = false;
+    bTestAMP_Ver = false;
+  }    
+#else
+  //! Utilizing the partition size of parent PU        
+  if ( eParentPartSize >= SIZE_2NxnU && eParentPartSize <= SIZE_nRx2N )
+  { 
+    bTestAMP_Hor = true;
+    bTestAMP_Ver = true;
+  }
+
+  if ( eParentPartSize == SIZE_2Nx2N )
+  { 
+    bTestAMP_Hor = false;
+    bTestAMP_Ver = false;
+  }      
+#endif
+}
+#endif
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+/** Compress a CU block recursively with enabling sub-LCU-level delta QP
+ *\param   rpcBestCU
+ *\param   rpcTempCU
+ *\param   uiDepth
+ *\returns Void
+ *
+ *- for loop of QP value to compress the current CU with all possible QP
+*/
+#if AMP_ENC_SPEEDUP
+Void TEncCu::xCompressCU( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UInt uiDepth, PartSize eParentPartSize )
+#else
+Void TEncCu::xCompressCU( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UInt uiDepth )
+#endif
+{
+  TComPic* pcPic = rpcBestCU->getPic();
+
+  // get Original YUV data from picture
+  m_ppcOrigYuv[uiDepth]->copyFromPicYuv( pcPic->getPicYuvOrg(), rpcBestCU->getAddr(), rpcBestCU->getZorderIdxInCU() );
+
+  // variables for fast encoder decision
+  Bool    bEarlySkip  = false;
+  Bool    bTrySplit    = true;
+  Double  fRD_Skip    = MAX_DOUBLE;
+
+  // variable for Early CU determination
+  Bool    bSubBranch = true;
+
+  // variable for Cbf fast mode PU decision
+  Bool    doNotBlockPu = true;
+  Bool earlyDetectionSkipMode = false;
+
+  Bool    bTrySplitDQP  = true;
+
+  static  Double  afCost[ MAX_CU_DEPTH ];
+  static  Int      aiNum [ MAX_CU_DEPTH ];
+
+  if ( rpcBestCU->getAddr() == 0 )
+  {
+    ::memset( afCost, 0, sizeof( afCost ) );
+    ::memset( aiNum,  0, sizeof( aiNum  ) );
+  }
+
+  Bool bBoundary = false;
+  UInt uiLPelX   = rpcBestCU->getCUPelX();
+  UInt uiRPelX   = uiLPelX + rpcBestCU->getWidth(0)  - 1;
+  UInt uiTPelY   = rpcBestCU->getCUPelY();
+  UInt uiBPelY   = uiTPelY + rpcBestCU->getHeight(0) - 1;
+
+  Int iBaseQP = xComputeQP( rpcBestCU, uiDepth );
+  Int iMinQP;
+  Int iMaxQP;
+  Bool isAddLowestQP = false;
+  Int lowestQP = -rpcTempCU->getSlice()->getSPS()->getQpBDOffsetY();
+
+  if( (g_uiMaxCUWidth>>uiDepth) >= rpcTempCU->getSlice()->getPPS()->getMinCuDQPSize() )
+  {
+    Int idQP = m_pcEncCfg->getMaxDeltaQP();
+    iMinQP = Clip3( -rpcTempCU->getSlice()->getSPS()->getQpBDOffsetY(), MAX_QP, iBaseQP-idQP );
+    iMaxQP = Clip3( -rpcTempCU->getSlice()->getSPS()->getQpBDOffsetY(), MAX_QP, iBaseQP+idQP );
+    if ( (rpcTempCU->getSlice()->getSPS()->getUseLossless()) && (lowestQP < iMinQP) && rpcTempCU->getSlice()->getPPS()->getUseDQP() )
+    {
+      isAddLowestQP = true; 
+      iMinQP = iMinQP - 1;
+       
+    }
+  }
+  else
+  {
+    iMinQP = rpcTempCU->getQP(0);
+    iMaxQP = rpcTempCU->getQP(0);
+  }
+
+  if(m_pcEncCfg->getUseRateCtrl())
+  {
+    Int qp = m_pcRateCtrl->getUnitQP();
+    iMinQP  = Clip3( MIN_QP, MAX_QP, qp);
+    iMaxQP  = Clip3( MIN_QP, MAX_QP, qp);
+  }
+
+  // If slice start or slice end is within this cu...
+  TComSlice * pcSlice = rpcTempCU->getPic()->getSlice(rpcTempCU->getPic()->getCurrSliceIdx());
+  Bool bSliceStart = pcSlice->getDependentSliceCurStartCUAddr()>rpcTempCU->getSCUAddr()&&pcSlice->getDependentSliceCurStartCUAddr()<rpcTempCU->getSCUAddr()+rpcTempCU->getTotalNumPart();
+  Bool bSliceEnd = (pcSlice->getDependentSliceCurEndCUAddr()>rpcTempCU->getSCUAddr()&&pcSlice->getDependentSliceCurEndCUAddr()<rpcTempCU->getSCUAddr()+rpcTempCU->getTotalNumPart());
+  Bool bInsidePicture = ( uiRPelX < rpcBestCU->getSlice()->getSPS()->getPicWidthInLumaSamples() ) && ( uiBPelY < rpcBestCU->getSlice()->getSPS()->getPicHeightInLumaSamples() );
+  // We need to split, so don't try these modes.
+  if(!bSliceEnd && !bSliceStart && bInsidePicture )
+  {
+    for (Int iQP=iMinQP; iQP<=iMaxQP; iQP++)
+    {
+      if (isAddLowestQP && (iQP == iMinQP))
+      {
+        iQP = lowestQP;
+      }
+      // variables for fast encoder decision
+      bEarlySkip  = false;
+      bTrySplit    = true;
+      fRD_Skip    = MAX_DOUBLE;
+
+      rpcTempCU->initEstData( uiDepth, iQP );
+
+      // do inter modes, SKIP and 2Nx2N
+      if( rpcBestCU->getSlice()->getSliceType() != I_SLICE )
+      {
+        // 2Nx2N
+        if(m_pcEncCfg->getUseEarlySkipDetection())
+        {
+          xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N );  rpcTempCU->initEstData( uiDepth, iQP );//by Competition for inter_2Nx2N
+        }
+        // SKIP
+        xCheckRDCostMerge2Nx2N( rpcBestCU, rpcTempCU, &earlyDetectionSkipMode );//by Merge for inter_2Nx2N
+        rpcTempCU->initEstData( uiDepth, iQP );
+
+        // fast encoder decision for early skip
+        if ( m_pcEncCfg->getUseFastEnc() )
+        {
+          Int iIdx = g_aucConvertToBit[ rpcBestCU->getWidth(0) ];
+          if ( aiNum [ iIdx ] > 5 && fRD_Skip < EARLY_SKIP_THRES*afCost[ iIdx ]/aiNum[ iIdx ] )
+          {
+            bEarlySkip = true;
+            bTrySplit  = false;
+          }
+        }
+
+    if(!m_pcEncCfg->getUseEarlySkipDetection())
+    {
+        // 2Nx2N, NxN
+        if ( !bEarlySkip )
+        {
+          xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N );  rpcTempCU->initEstData( uiDepth, iQP );
+          if(m_pcEncCfg->getUseCbfFastMode())
+          {
+            doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+          }
+        }
+    }
+
+      }
+
+      if( (g_uiMaxCUWidth>>uiDepth) >= rpcTempCU->getSlice()->getPPS()->getMinCuDQPSize() )
+      {
+        if(iQP == iBaseQP)
+        {
+          bTrySplitDQP = bTrySplit;
+        }
+      }
+      else
+      {
+        bTrySplitDQP = bTrySplit;
+      }
+      if (isAddLowestQP && (iQP == lowestQP))
+      {
+        iQP = iMinQP;
+      }
+    }
+
+  if(!earlyDetectionSkipMode)
+  {
+    for (Int iQP=iMinQP; iQP<=iMaxQP; iQP++)
+    {
+      if (isAddLowestQP && (iQP == iMinQP))
+      {
+        iQP = lowestQP;
+      }
+      rpcTempCU->initEstData( uiDepth, iQP );
+
+      // do inter modes, NxN, 2NxN, and Nx2N
+      if( rpcBestCU->getSlice()->getSliceType() != I_SLICE )
+      {
+        // 2Nx2N, NxN
+        if ( !bEarlySkip )
+        {
+          if(!( (rpcBestCU->getWidth(0)==8) && (rpcBestCU->getHeight(0)==8) ))
+        {
+          if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth && doNotBlockPu)
+          {
+            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_NxN   );
+            rpcTempCU->initEstData( uiDepth, iQP );
+          }
+        }
+        }
+
+        { // 2NxN, Nx2N
+          if(doNotBlockPu)
+          {
+            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_Nx2N  );
+            rpcTempCU->initEstData( uiDepth, iQP );
+            if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_Nx2N )
+            {
+              doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+            }
+          }
+          if(doNotBlockPu)
+          {
+            xCheckRDCostInter      ( rpcBestCU, rpcTempCU, SIZE_2NxN  );
+            rpcTempCU->initEstData( uiDepth, iQP );
+            if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxN)
+            {
+              doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+            }
+          }
+        }
+
+#if 1
+        //! Try AMP (SIZE_2NxnU, SIZE_2NxnD, SIZE_nLx2N, SIZE_nRx2N)
+        if( pcPic->getSlice(0)->getSPS()->getAMPAcc(uiDepth) )
+        {
+#if AMP_ENC_SPEEDUP        
+          Bool bTestAMP_Hor = false, bTestAMP_Ver = false;
+
+#if AMP_MRG
+          Bool bTestMergeAMP_Hor = false, bTestMergeAMP_Ver = false;
+
+          deriveTestModeAMP (rpcBestCU, eParentPartSize, bTestAMP_Hor, bTestAMP_Ver, bTestMergeAMP_Hor, bTestMergeAMP_Ver);
+#else
+          deriveTestModeAMP (rpcBestCU, eParentPartSize, bTestAMP_Hor, bTestAMP_Ver);
+#endif
+
+          //! Do horizontal AMP
+          if ( bTestAMP_Hor )
+          {
+            if(doNotBlockPu)
+            {
+              xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU );
+              rpcTempCU->initEstData( uiDepth, iQP );
+              if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxnU )
+              {
+                doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+              }
+            }
+            if(doNotBlockPu)
+            {
+              xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD );
+              rpcTempCU->initEstData( uiDepth, iQP );
+              if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxnD )
+              {
+                doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+              }
+            }
+          }
+#if AMP_MRG
+          else if ( bTestMergeAMP_Hor ) 
+          {
+            if(doNotBlockPu)
+            {
+              xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU, true );
+              rpcTempCU->initEstData( uiDepth, iQP );
+              if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxnU )
+              {
+                doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+              }
+            }
+            if(doNotBlockPu)
+            {
+              xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD, true );
+              rpcTempCU->initEstData( uiDepth, iQP );
+              if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxnD )
+              {
+                doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+              }
+            }
+          }
+#endif
+
+          //! Do horizontal AMP
+          if ( bTestAMP_Ver )
+          {
+            if(doNotBlockPu)
+            {
+              xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N );
+              rpcTempCU->initEstData( uiDepth, iQP );
+              if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_nLx2N )
+              {
+                doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+              }
+            }
+            if(doNotBlockPu)
+            {
+              xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N );
+              rpcTempCU->initEstData( uiDepth, iQP );
+            }
+          }
+#if AMP_MRG
+          else if ( bTestMergeAMP_Ver )
+          {
+            if(doNotBlockPu)
+            {
+              xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N, true );
+              rpcTempCU->initEstData( uiDepth, iQP );
+              if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_nLx2N )
+              {
+                doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+              }
+            }
+            if(doNotBlockPu)
+            {
+              xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N, true );
+              rpcTempCU->initEstData( uiDepth, iQP );
+            }
+          }
+#endif
+
+#else
+          xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU );
+          rpcTempCU->initEstData( uiDepth, iQP );
+          xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD );
+          rpcTempCU->initEstData( uiDepth, iQP );
+          xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N );
+          rpcTempCU->initEstData( uiDepth, iQP );
+
+          xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N );
+          rpcTempCU->initEstData( uiDepth, iQP );
+
+#endif
+        }    
+#endif
+      }
+
+      // initialize PCM flag
+      rpcTempCU->setIPCMFlag( 0, false);
+      rpcTempCU->setIPCMFlagSubParts ( false, 0, uiDepth); //SUB_LCU_DQP
+
+      // do normal intra modes
+      if ( !bEarlySkip )
+      {
+        // speedup for inter frames
+        if( rpcBestCU->getSlice()->getSliceType() == I_SLICE || 
+          rpcBestCU->getCbf( 0, TEXT_LUMA     ) != 0   ||
+          rpcBestCU->getCbf( 0, TEXT_CHROMA_U ) != 0   ||
+          rpcBestCU->getCbf( 0, TEXT_CHROMA_V ) != 0     ) // avoid very complex intra if it is unlikely
+        {
+          xCheckRDCostIntra( rpcBestCU, rpcTempCU, SIZE_2Nx2N );
+          rpcTempCU->initEstData( uiDepth, iQP );
+          if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+          {
+            if( rpcTempCU->getWidth(0) > ( 1 << rpcTempCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() ) )
+            {
+              xCheckRDCostIntra( rpcBestCU, rpcTempCU, SIZE_NxN   );
+              rpcTempCU->initEstData( uiDepth, iQP );
+            }
+          }
+        }
+      }
+
+      // test PCM
+      if(pcPic->getSlice(0)->getSPS()->getUsePCM()
+        && rpcTempCU->getWidth(0) <= (1<<pcPic->getSlice(0)->getSPS()->getPCMLog2MaxSize())
+        && rpcTempCU->getWidth(0) >= (1<<pcPic->getSlice(0)->getSPS()->getPCMLog2MinSize()) )
+      {
+        UInt uiRawBits = (g_uiBitDepth * rpcBestCU->getWidth(0) * rpcBestCU->getHeight(0) * 3 / 2);
+        UInt uiBestBits = rpcBestCU->getTotalBits();
+        if((uiBestBits > uiRawBits) || (rpcBestCU->getTotalCost() > m_pcRdCost->calcRdCost(uiRawBits, 0)))
+        {
+          xCheckIntraPCM (rpcBestCU, rpcTempCU);
+          rpcTempCU->initEstData( uiDepth, iQP );
+        }
+      }
+#if INTRA_BL
+      if(m_pcPicYuvRecBase)
+      {
+        xCheckRDCostIntraBL( rpcBestCU, rpcTempCU );
+        rpcTempCU->initEstData( uiDepth, iQP );
+      }
+#endif
+      if (isAddLowestQP && (iQP == lowestQP))
+      {
+        iQP = iMinQP;
+      }
+    }
+
+  }
+
+    m_pcEntropyCoder->resetBits();
+    m_pcEntropyCoder->encodeSplitFlag( rpcBestCU, 0, uiDepth, true );
+    rpcBestCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // split bits
+    if(m_pcEncCfg->getUseSBACRD())
+    {
+      rpcBestCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
+    }
+    rpcBestCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcBestCU->getTotalBits(), rpcBestCU->getTotalDistortion() );
+
+    // accumulate statistics for early skip
+    if ( m_pcEncCfg->getUseFastEnc() )
+    {
+      if ( rpcBestCU->isSkipped(0) )
+      {
+        Int iIdx = g_aucConvertToBit[ rpcBestCU->getWidth(0) ];
+        afCost[ iIdx ] += rpcBestCU->getTotalCost();
+        aiNum [ iIdx ] ++;
+      }
+    }
+
+    // Early CU determination
+    if( m_pcEncCfg->getUseEarlyCU() && rpcBestCU->isSkipped(0) )
+    {
+      bSubBranch = false;
+    }
+    else
+    {
+      bSubBranch = true;
+    }
+  }
+  else if(!(bSliceEnd && bInsidePicture))
+  {
+    bBoundary = true;
+  }
+
+  // copy orginal YUV samples to PCM buffer
+  if( rpcBestCU->isLosslessCoded(0) && (rpcBestCU->getIPCMFlag(0) == false))
+  {
+    xFillPCMBuffer(rpcBestCU, m_ppcOrigYuv[uiDepth]);
+  }
+  if( (g_uiMaxCUWidth>>uiDepth) == rpcTempCU->getSlice()->getPPS()->getMinCuDQPSize() )
+  {
+    Int idQP = m_pcEncCfg->getMaxDeltaQP();
+    iMinQP = Clip3( -rpcTempCU->getSlice()->getSPS()->getQpBDOffsetY(), MAX_QP, iBaseQP-idQP );
+    iMaxQP = Clip3( -rpcTempCU->getSlice()->getSPS()->getQpBDOffsetY(), MAX_QP, iBaseQP+idQP );
+    if ( (rpcTempCU->getSlice()->getSPS()->getUseLossless()) && (lowestQP < iMinQP) && rpcTempCU->getSlice()->getPPS()->getUseDQP() )
+    {
+      isAddLowestQP = true;
+      iMinQP = iMinQP - 1;      
+    }
+  }
+  else if( (g_uiMaxCUWidth>>uiDepth) > rpcTempCU->getSlice()->getPPS()->getMinCuDQPSize() )
+  {
+    iMinQP = iBaseQP;
+    iMaxQP = iBaseQP;
+  }
+  else
+  {
+    Int iStartQP;
+    if( pcPic->getCU( rpcTempCU->getAddr() )->getDependentSliceStartCU(rpcTempCU->getZorderIdxInCU()) == pcSlice->getDependentSliceCurStartCUAddr())
+    {
+      iStartQP = rpcTempCU->getQP(0);
+    }
+    else
+    {
+      UInt uiCurSliceStartPartIdx = pcSlice->getDependentSliceCurStartCUAddr() % pcPic->getNumPartInCU() - rpcTempCU->getZorderIdxInCU();
+      iStartQP = rpcTempCU->getQP(uiCurSliceStartPartIdx);
+    }
+    iMinQP = iStartQP;
+    iMaxQP = iStartQP;
+  }
+  if(m_pcEncCfg->getUseRateCtrl())
+  {
+    Int qp = m_pcRateCtrl->getUnitQP();
+    iMinQP  = Clip3( MIN_QP, MAX_QP, qp);
+    iMaxQP  = Clip3( MIN_QP, MAX_QP, qp);
+  }
+  for (Int iQP=iMinQP; iQP<=iMaxQP; iQP++)
+  {
+      if (isAddLowestQP && (iQP == iMinQP))
+      {
+        iQP = lowestQP;
+      }
+    rpcTempCU->initEstData( uiDepth, iQP );
+
+    // further split
+    if( bSubBranch && bTrySplitDQP && uiDepth < g_uiMaxCUDepth - g_uiAddCUDepth )
+    {
+      UChar       uhNextDepth         = uiDepth+1;
+      TComDataCU* pcSubBestPartCU     = m_ppcBestCU[uhNextDepth];
+      TComDataCU* pcSubTempPartCU     = m_ppcTempCU[uhNextDepth];
+
+      for ( UInt uiPartUnitIdx = 0; uiPartUnitIdx < 4; uiPartUnitIdx++ )
+      {
+        pcSubBestPartCU->initSubCU( rpcTempCU, uiPartUnitIdx, uhNextDepth, iQP );           // clear sub partition datas or init.
+        pcSubTempPartCU->initSubCU( rpcTempCU, uiPartUnitIdx, uhNextDepth, iQP );           // clear sub partition datas or init.
+
+        Bool bInSlice = pcSubBestPartCU->getSCUAddr()+pcSubBestPartCU->getTotalNumPart()>pcSlice->getDependentSliceCurStartCUAddr()&&pcSubBestPartCU->getSCUAddr()<pcSlice->getDependentSliceCurEndCUAddr();
+        if(bInSlice && ( pcSubBestPartCU->getCUPelX() < pcSlice->getSPS()->getPicWidthInLumaSamples() ) && ( pcSubBestPartCU->getCUPelY() < pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+        {
+          if( m_bUseSBACRD )
+          {
+            if ( 0 == uiPartUnitIdx) //initialize RD with previous depth buffer
+            {
+              m_pppcRDSbacCoder[uhNextDepth][CI_CURR_BEST]->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
+            }
+            else
+            {
+              m_pppcRDSbacCoder[uhNextDepth][CI_CURR_BEST]->load(m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]);
+            }
+          }
+
+#if AMP_ENC_SPEEDUP
+          if ( rpcBestCU->isIntra(0) )
+          {
+            xCompressCU( pcSubBestPartCU, pcSubTempPartCU, uhNextDepth, SIZE_NONE );
+          }
+          else
+          {
+            xCompressCU( pcSubBestPartCU, pcSubTempPartCU, uhNextDepth, rpcBestCU->getPartitionSize(0) );
+          }
+#else
+          xCompressCU( pcSubBestPartCU, pcSubTempPartCU, uhNextDepth );
+#endif
+
+          rpcTempCU->copyPartFrom( pcSubBestPartCU, uiPartUnitIdx, uhNextDepth );         // Keep best part data to current temporary data.
+          xCopyYuv2Tmp( pcSubBestPartCU->getTotalNumPart()*uiPartUnitIdx, uhNextDepth );
+        }
+        else if (bInSlice)
+        {
+          pcSubBestPartCU->copyToPic( uhNextDepth );
+          rpcTempCU->copyPartFrom( pcSubBestPartCU, uiPartUnitIdx, uhNextDepth );
+        }
+      }
+
+      if( !bBoundary )
+      {
+        m_pcEntropyCoder->resetBits();
+        m_pcEntropyCoder->encodeSplitFlag( rpcTempCU, 0, uiDepth, true );
+
+        rpcTempCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // split bits
+        if(m_pcEncCfg->getUseSBACRD())
+        {
+          rpcTempCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
+        }
+      }
+      rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+
+      if( (g_uiMaxCUWidth>>uiDepth) == rpcTempCU->getSlice()->getPPS()->getMinCuDQPSize() && rpcTempCU->getSlice()->getPPS()->getUseDQP())
+      {
+        Bool hasResidual = false;
+        for( UInt uiBlkIdx = 0; uiBlkIdx < rpcTempCU->getTotalNumPart(); uiBlkIdx ++)
+        {
+          if( ( pcPic->getCU( rpcTempCU->getAddr() )->getDependentSliceStartCU(uiBlkIdx+rpcTempCU->getZorderIdxInCU()) == rpcTempCU->getSlice()->getDependentSliceCurStartCUAddr() ) && 
+              ( rpcTempCU->getCbf( uiBlkIdx, TEXT_LUMA ) || rpcTempCU->getCbf( uiBlkIdx, TEXT_CHROMA_U ) || rpcTempCU->getCbf( uiBlkIdx, TEXT_CHROMA_V ) ) )
+          {
+            hasResidual = true;
+            break;
+          }
+        }
+
+        UInt uiTargetPartIdx;
+        if ( pcPic->getCU( rpcTempCU->getAddr() )->getDependentSliceStartCU(rpcTempCU->getZorderIdxInCU()) != pcSlice->getDependentSliceCurStartCUAddr() )
+        {
+          uiTargetPartIdx = pcSlice->getDependentSliceCurStartCUAddr() % pcPic->getNumPartInCU() - rpcTempCU->getZorderIdxInCU();
+        }
+        else
+        {
+          uiTargetPartIdx = 0;
+        }
+        if ( hasResidual )
+        {
+#if !RDO_WITHOUT_DQP_BITS
+          m_pcEntropyCoder->resetBits();
+          m_pcEntropyCoder->encodeQP( rpcTempCU, uiTargetPartIdx, false );
+          rpcTempCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // dQP bits
+          if(m_pcEncCfg->getUseSBACRD())
+          {
+            rpcTempCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
+          }
+          rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+#endif
+
+          Bool foundNonZeroCbf = false;
+          rpcTempCU->setQPSubCUs( rpcTempCU->getRefQP( uiTargetPartIdx ), rpcTempCU, 0, uiDepth, foundNonZeroCbf );
+          assert( foundNonZeroCbf );
+        }
+        else
+        {
+          rpcTempCU->setQPSubParts( rpcTempCU->getRefQP( uiTargetPartIdx ), 0, uiDepth ); // set QP to default QP
+        }
+      }
+
+      if( m_bUseSBACRD )
+      {
+        m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
+      }
+      Bool bEntropyLimit=false;
+      Bool bSliceLimit=false;
+      bSliceLimit=rpcBestCU->getSlice()->getSliceMode()==AD_HOC_SLICES_FIXED_NUMBER_OF_BYTES_IN_SLICE&&(rpcBestCU->getTotalBits()>rpcBestCU->getSlice()->getSliceArgument()<<3);
+      if(rpcBestCU->getSlice()->getDependentSliceMode()==SHARP_MULTIPLE_CONSTRAINT_BASED_DEPENDENT_SLICE&&m_pcEncCfg->getUseSBACRD())
+      {
+        if(rpcBestCU->getTotalBins()>rpcBestCU->getSlice()->getDependentSliceArgument())
+        {
+          bEntropyLimit=true;
+        }
+      }
+      else if(rpcBestCU->getSlice()->getDependentSliceMode()==SHARP_MULTIPLE_CONSTRAINT_BASED_DEPENDENT_SLICE)
+      {
+        if(rpcBestCU->getTotalBits()>rpcBestCU->getSlice()->getDependentSliceArgument())
+        {
+          bEntropyLimit=true;
+        }
+      }
+#if !REMOVE_FGS
+      if(rpcBestCU->getDepth(0)>=rpcBestCU->getSlice()->getPPS()->getSliceGranularity())
+#endif
+      {
+        bSliceLimit=false;
+        bEntropyLimit=false;
+      }
+      if(bSliceLimit||bEntropyLimit)
+      {
+        rpcBestCU->getTotalCost()=rpcTempCU->getTotalCost()+1;
+      }
+      xCheckBestMode( rpcBestCU, rpcTempCU, uiDepth);                                  // RD compare current larger prediction
+    }                                                                                  // with sub partitioned prediction.
+      if (isAddLowestQP && (iQP == lowestQP))
+      {
+        iQP = iMinQP;
+      }
+  }
+
+  rpcBestCU->copyToPic(uiDepth);                                                     // Copy Best data to Picture for next partition prediction.
+
+  xCopyYuv2Pic( rpcBestCU->getPic(), rpcBestCU->getAddr(), rpcBestCU->getZorderIdxInCU(), uiDepth, uiDepth, rpcBestCU, uiLPelX, uiTPelY );   // Copy Yuv data to picture Yuv
+  if( bBoundary ||(bSliceEnd && bInsidePicture))
+  {
+    return;
+  }
+
+  // Assert if Best prediction mode is NONE
+  // Selected mode's RD-cost must be not MAX_DOUBLE.
+  assert( rpcBestCU->getPartitionSize ( 0 ) != SIZE_NONE  );
+  assert( rpcBestCU->getPredictionMode( 0 ) != MODE_NONE  );
+  assert( rpcBestCU->getTotalCost     (   ) != MAX_DOUBLE );
+}
+
+/** finish encoding a cu and handle end-of-slice conditions
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param uiDepth 
+ * \returns Void
+ */
+Void TEncCu::finishCU( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  TComPic* pcPic = pcCU->getPic();
+  TComSlice * pcSlice = pcCU->getPic()->getSlice(pcCU->getPic()->getCurrSliceIdx());
+
+  //Calculate end address
+  UInt uiCUAddr = pcCU->getSCUAddr()+uiAbsPartIdx;
+
+  UInt uiInternalAddress = pcPic->getPicSym()->getPicSCUAddr(pcSlice->getDependentSliceCurEndCUAddr()-1) % pcPic->getNumPartInCU();
+  UInt uiExternalAddress = pcPic->getPicSym()->getPicSCUAddr(pcSlice->getDependentSliceCurEndCUAddr()-1) / pcPic->getNumPartInCU();
+  UInt uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
+  UInt uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
+  UInt uiWidth = pcSlice->getSPS()->getPicWidthInLumaSamples();
+  UInt uiHeight = pcSlice->getSPS()->getPicHeightInLumaSamples();
+  while(uiPosX>=uiWidth||uiPosY>=uiHeight)
+  {
+    uiInternalAddress--;
+    uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
+    uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
+  }
+  uiInternalAddress++;
+  if(uiInternalAddress==pcCU->getPic()->getNumPartInCU())
+  {
+    uiInternalAddress = 0;
+    uiExternalAddress = pcPic->getPicSym()->getCUOrderMap(pcPic->getPicSym()->getInverseCUOrderMap(uiExternalAddress)+1);
+  }
+  UInt uiRealEndAddress = pcPic->getPicSym()->getPicSCUEncOrder(uiExternalAddress*pcPic->getNumPartInCU()+uiInternalAddress);
+
+  // Encode slice finish
+  Bool bTerminateSlice = false;
+  if (uiCUAddr+(pcCU->getPic()->getNumPartInCU()>>(uiDepth<<1)) == uiRealEndAddress)
+  {
+    bTerminateSlice = true;
+  }
+#if REMOVE_FGS
+  UInt uiGranularityWidth = g_uiMaxCUWidth;
+#else
+  UInt uiGranularityWidth = g_uiMaxCUWidth>>(pcSlice->getPPS()->getSliceGranularity());
+#endif
+  uiPosX = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
+  uiPosY = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
+  Bool granularityBoundary=((uiPosX+pcCU->getWidth(uiAbsPartIdx))%uiGranularityWidth==0||(uiPosX+pcCU->getWidth(uiAbsPartIdx)==uiWidth))
+    &&((uiPosY+pcCU->getHeight(uiAbsPartIdx))%uiGranularityWidth==0||(uiPosY+pcCU->getHeight(uiAbsPartIdx)==uiHeight));
+  
+  if(granularityBoundary && (!(pcCU->getIPCMFlag(uiAbsPartIdx) && ( pcCU->getNumSucIPCM() > 1 ))))
+  {
+    // The 1-terminating bit is added to all streams, so don't add it here when it's 1.
+    if (!bTerminateSlice)
+      m_pcEntropyCoder->encodeTerminatingBit( bTerminateSlice ? 1 : 0 );
+  }
+  
+  Int numberOfWrittenBits = 0;
+  if (m_pcBitCounter)
+  {
+    numberOfWrittenBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+  }
+  
+  // Calculate slice end IF this CU puts us over slice bit size.
+#if REMOVE_FGS
+  unsigned iGranularitySize = pcCU->getPic()->getNumPartInCU();
+#else
+  unsigned iGranularitySize = pcCU->getPic()->getNumPartInCU()>>(pcSlice->getPPS()->getSliceGranularity()<<1);
+#endif
+  int iGranularityEnd = ((pcCU->getSCUAddr()+uiAbsPartIdx)/iGranularitySize)*iGranularitySize;
+  if(iGranularityEnd<=pcSlice->getDependentSliceCurStartCUAddr()) 
+  {
+    iGranularityEnd+=max(iGranularitySize,(pcCU->getPic()->getNumPartInCU()>>(uiDepth<<1)));
+  }
+  // Set slice end parameter
+  if(pcSlice->getSliceMode()==AD_HOC_SLICES_FIXED_NUMBER_OF_BYTES_IN_SLICE&&!pcSlice->getFinalized()&&pcSlice->getSliceBits()+numberOfWrittenBits>pcSlice->getSliceArgument()<<3) 
+  {
+    pcSlice->setDependentSliceCurEndCUAddr(iGranularityEnd);
+    pcSlice->setSliceCurEndCUAddr(iGranularityEnd);
+    return;
+  }
+  // Set dependent slice end parameter
+  if(m_pcEncCfg->getUseSBACRD()) 
+  {
+    TEncBinCABAC *pppcRDSbacCoder = (TEncBinCABAC *) m_pppcRDSbacCoder[0][CI_CURR_BEST]->getEncBinIf();
+    UInt uiBinsCoded = pppcRDSbacCoder->getBinsCoded();
+    if(pcSlice->getDependentSliceMode()==SHARP_MULTIPLE_CONSTRAINT_BASED_DEPENDENT_SLICE&&!pcSlice->getFinalized()&&pcSlice->getDependentSliceCounter()+uiBinsCoded>pcSlice->getDependentSliceArgument())
+    {
+      pcSlice->setDependentSliceCurEndCUAddr(iGranularityEnd);
+      return;
+    }
+  }
+  else
+  {
+    if(pcSlice->getDependentSliceMode()==SHARP_MULTIPLE_CONSTRAINT_BASED_DEPENDENT_SLICE&&!pcSlice->getFinalized()&&pcSlice->getDependentSliceCounter()+numberOfWrittenBits>pcSlice->getDependentSliceArgument()) 
+    {
+      pcSlice->setDependentSliceCurEndCUAddr(iGranularityEnd);
+      return;
+    }
+  }
+  if(granularityBoundary)
+  {
+    pcSlice->setSliceBits( (UInt)(pcSlice->getSliceBits() + numberOfWrittenBits) );
+    if(m_pcEncCfg->getUseSBACRD()) 
+    {
+      TEncBinCABAC *pppcRDSbacCoder = (TEncBinCABAC *) m_pppcRDSbacCoder[0][CI_CURR_BEST]->getEncBinIf();
+      pcSlice->setDependentSliceCounter(pcSlice->getDependentSliceCounter()+pppcRDSbacCoder->getBinsCoded());
+      pppcRDSbacCoder->setBinsCoded( 0 );
+    }
+    else 
+    {
+      pcSlice->setDependentSliceCounter(pcSlice->getDependentSliceCounter()+numberOfWrittenBits);
+    }
+    if (m_pcBitCounter)
+    {
+      m_pcEntropyCoder->resetBits();      
+    }
+  }
+}
+
+/** Compute QP for each CU
+ * \param pcCU Target CU
+ * \param uiDepth CU depth
+ * \returns quantization parameter
+ */
+Int TEncCu::xComputeQP( TComDataCU* pcCU, UInt uiDepth )
+{
+  Int iBaseQp = pcCU->getSlice()->getSliceQp();
+  Int iQpOffset = 0;
+  if ( m_pcEncCfg->getUseAdaptiveQP() )
+  {
+    TEncPic* pcEPic = dynamic_cast<TEncPic*>( pcCU->getPic() );
+    UInt uiAQDepth = min( uiDepth, pcEPic->getMaxAQDepth()-1 );
+    TEncPicQPAdaptationLayer* pcAQLayer = pcEPic->getAQLayer( uiAQDepth );
+    UInt uiAQUPosX = pcCU->getCUPelX() / pcAQLayer->getAQPartWidth();
+    UInt uiAQUPosY = pcCU->getCUPelY() / pcAQLayer->getAQPartHeight();
+    UInt uiAQUStride = pcAQLayer->getAQPartStride();
+    TEncQPAdaptationUnit* acAQU = pcAQLayer->getQPAdaptationUnit();
+
+    Double dMaxQScale = pow(2.0, m_pcEncCfg->getQPAdaptationRange()/6.0);
+    Double dAvgAct = pcAQLayer->getAvgActivity();
+    Double dCUAct = acAQU[uiAQUPosY * uiAQUStride + uiAQUPosX].getActivity();
+    Double dNormAct = (dMaxQScale*dCUAct + dAvgAct) / (dCUAct + dMaxQScale*dAvgAct);
+    Double dQpOffset = log(dNormAct) / log(2.0) * 6.0;
+    iQpOffset = Int(floor( dQpOffset + 0.49999 ));
+  }
+  return Clip3(-pcCU->getSlice()->getSPS()->getQpBDOffsetY(), MAX_QP, iBaseQp+iQpOffset );
+}
+
+/** encode a CU block recursively
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param uiDepth 
+ * \returns Void
+ */
+Void TEncCu::xEncodeCU( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  TComPic* pcPic = pcCU->getPic();
+  
+  Bool bBoundary = false;
+  UInt uiLPelX   = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
+  UInt uiRPelX   = uiLPelX + (g_uiMaxCUWidth>>uiDepth)  - 1;
+  UInt uiTPelY   = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
+  UInt uiBPelY   = uiTPelY + (g_uiMaxCUHeight>>uiDepth) - 1;
+  
+  if( getCheckBurstIPCMFlag() )
+  {
+    pcCU->setLastCUSucIPCMFlag( checkLastCUSucIPCM( pcCU, uiAbsPartIdx ));
+    pcCU->setNumSucIPCM( countNumSucIPCM ( pcCU, uiAbsPartIdx ) );
+  }
+
+  TComSlice * pcSlice = pcCU->getPic()->getSlice(pcCU->getPic()->getCurrSliceIdx());
+  // If slice start is within this cu...
+  Bool bSliceStart = pcSlice->getDependentSliceCurStartCUAddr() > pcPic->getPicSym()->getInverseCUOrderMap(pcCU->getAddr())*pcCU->getPic()->getNumPartInCU()+uiAbsPartIdx && 
+    pcSlice->getDependentSliceCurStartCUAddr() < pcPic->getPicSym()->getInverseCUOrderMap(pcCU->getAddr())*pcCU->getPic()->getNumPartInCU()+uiAbsPartIdx+( pcPic->getNumPartInCU() >> (uiDepth<<1) );
+  // We need to split, so don't try these modes.
+  if(!bSliceStart&&( uiRPelX < pcSlice->getSPS()->getPicWidthInLumaSamples() ) && ( uiBPelY < pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+  {
+    m_pcEntropyCoder->encodeSplitFlag( pcCU, uiAbsPartIdx, uiDepth );
+  }
+  else
+  {
+    bBoundary = true;
+  }
+  
+  if( ( ( uiDepth < pcCU->getDepth( uiAbsPartIdx ) ) && ( uiDepth < (g_uiMaxCUDepth-g_uiAddCUDepth) ) ) || bBoundary )
+  {
+    UInt uiQNumParts = ( pcPic->getNumPartInCU() >> (uiDepth<<1) )>>2;
+    if( (g_uiMaxCUWidth>>uiDepth) == pcCU->getSlice()->getPPS()->getMinCuDQPSize() && pcCU->getSlice()->getPPS()->getUseDQP())
+    {
+      setdQPFlag(true);
+    }
+    pcCU->setNumSucIPCM(0);
+    pcCU->setLastCUSucIPCMFlag(false);
+    for ( UInt uiPartUnitIdx = 0; uiPartUnitIdx < 4; uiPartUnitIdx++, uiAbsPartIdx+=uiQNumParts )
+    {
+      uiLPelX   = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
+      uiTPelY   = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
+      Bool bInSlice = pcCU->getSCUAddr()+uiAbsPartIdx+uiQNumParts>pcSlice->getDependentSliceCurStartCUAddr()&&pcCU->getSCUAddr()+uiAbsPartIdx<pcSlice->getDependentSliceCurEndCUAddr();
+      if(bInSlice&&( uiLPelX < pcSlice->getSPS()->getPicWidthInLumaSamples() ) && ( uiTPelY < pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+      {
+        xEncodeCU( pcCU, uiAbsPartIdx, uiDepth+1 );
+      }
+    }
+    return;
+  }
+  
+  if( (g_uiMaxCUWidth>>uiDepth) >= pcCU->getSlice()->getPPS()->getMinCuDQPSize() && pcCU->getSlice()->getPPS()->getUseDQP())
+  {
+    setdQPFlag(true);
+  }
+  if (pcCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
+  {
+    m_pcEntropyCoder->encodeCUTransquantBypassFlag( pcCU, uiAbsPartIdx );
+  }
+  if( !pcCU->getSlice()->isIntra() )
+  {
+    m_pcEntropyCoder->encodeSkipFlag( pcCU, uiAbsPartIdx );
+  }
+  
+  if( pcCU->isSkipped( uiAbsPartIdx ) )
+  {
+    m_pcEntropyCoder->encodeMergeIndex( pcCU, uiAbsPartIdx, 0 );
+    finishCU(pcCU,uiAbsPartIdx,uiDepth);
+    return;
+  }
+#if INTRA_BL
+  m_pcEntropyCoder->encodeIntraBLFlag( pcCU, uiAbsPartIdx );
+  if ( !pcCU->isIntraBL( uiAbsPartIdx ) )
+  {
+#endif
+  m_pcEntropyCoder->encodePredMode( pcCU, uiAbsPartIdx );
+  
+  m_pcEntropyCoder->encodePartSize( pcCU, uiAbsPartIdx, uiDepth );
+  
+  if (pcCU->isIntra( uiAbsPartIdx ) && pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_2Nx2N )
+  {
+    m_pcEntropyCoder->encodeIPCMInfo( pcCU, uiAbsPartIdx );
+
+    if(pcCU->getIPCMFlag(uiAbsPartIdx))
+    {
+      // Encode slice finish
+      finishCU(pcCU,uiAbsPartIdx,uiDepth);
+      return;
+    }
+  }
+
+  // prediction Info ( Intra : direction mode, Inter : Mv, reference idx )
+  m_pcEntropyCoder->encodePredInfo( pcCU, uiAbsPartIdx );
+#if INTRA_BL
+  }
+#endif
+  
+  // Encode Coefficients
+  Bool bCodeDQP = getdQPFlag();
+  m_pcEntropyCoder->encodeCoeff( pcCU, uiAbsPartIdx, uiDepth, pcCU->getWidth (uiAbsPartIdx), pcCU->getHeight(uiAbsPartIdx), bCodeDQP );
+  setdQPFlag( bCodeDQP );
+
+  // --- write terminating bit ---
+  finishCU(pcCU,uiAbsPartIdx,uiDepth);
+}
+
+/** check RD costs for a CU block encoded with merge
+ * \param rpcBestCU
+ * \param rpcTempCU
+ * \returns Void
+ */
+Void TEncCu::xCheckRDCostMerge2Nx2N( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, Bool *earlyDetectionSkipMode )
+{
+  assert( rpcTempCU->getSlice()->getSliceType() != I_SLICE );
+  TComMvField  cMvFieldNeighbours[MRG_MAX_NUM_CANDS << 1]; // double length for mv of both lists
+  UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS];
+  Int numValidMergeCand = 0;
+
+  for( UInt ui = 0; ui < rpcTempCU->getSlice()->getMaxNumMergeCand(); ++ui )
+  {
+    uhInterDirNeighbours[ui] = 0;
+  }
+  UChar uhDepth = rpcTempCU->getDepth( 0 );
+  rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uhDepth ); // interprets depth relative to LCU level
+  rpcTempCU->setCUTransquantBypassSubParts( m_pcEncCfg->getCUTransquantBypassFlagValue(), 0, uhDepth );
+  rpcTempCU->getInterMergeCandidates( 0, 0, uhDepth, cMvFieldNeighbours,uhInterDirNeighbours, numValidMergeCand );
+
+  Int mergeCandBuffer[MRG_MAX_NUM_CANDS];
+  for( UInt ui = 0; ui < rpcTempCU->getSlice()->getMaxNumMergeCand(); ++ui )
+  {
+    mergeCandBuffer[ui] = 0;
+  }
+
+  Bool bestIsSkip = false;
+
+  UInt iteration;
+  if ( rpcTempCU->isLosslessCoded(0))
+  {
+    iteration = 1;
+  }
+  else 
+  {
+    iteration = 2;
+  }
+
+  for( UInt uiNoResidual = 0; uiNoResidual < iteration; ++uiNoResidual )
+  {
+    for( UInt uiMergeCand = 0; uiMergeCand < numValidMergeCand; ++uiMergeCand )
+    {
+      {
+        if(!(uiNoResidual==1 && mergeCandBuffer[uiMergeCand]==1))
+        {
+
+        if( !(bestIsSkip && uiNoResidual == 0) )
+        {
+          // set MC parameters
+          rpcTempCU->setPredModeSubParts( MODE_INTER, 0, uhDepth ); // interprets depth relative to LCU level
+          rpcTempCU->setCUTransquantBypassSubParts( m_pcEncCfg->getCUTransquantBypassFlagValue(),     0, uhDepth );
+          rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uhDepth ); // interprets depth relative to LCU level
+          rpcTempCU->setMergeFlagSubParts( true, 0, 0, uhDepth ); // interprets depth relative to LCU level
+          rpcTempCU->setMergeIndexSubParts( uiMergeCand, 0, 0, uhDepth ); // interprets depth relative to LCU level
+          rpcTempCU->setInterDirSubParts( uhInterDirNeighbours[uiMergeCand], 0, 0, uhDepth ); // interprets depth relative to LCU level
+          rpcTempCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( cMvFieldNeighbours[0 + 2*uiMergeCand], SIZE_2Nx2N, 0, 0 ); // interprets depth relative to rpcTempCU level
+          rpcTempCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMvFieldNeighbours[1 + 2*uiMergeCand], SIZE_2Nx2N, 0, 0 ); // interprets depth relative to rpcTempCU level
+
+       // do MC
+       m_pcPredSearch->motionCompensation ( rpcTempCU, m_ppcPredYuvTemp[uhDepth] );
+       // estimate residual and encode everything
+       m_pcPredSearch->encodeResAndCalcRdInterCU( rpcTempCU,
+         m_ppcOrigYuv    [uhDepth],
+         m_ppcPredYuvTemp[uhDepth],
+         m_ppcResiYuvTemp[uhDepth],
+         m_ppcResiYuvBest[uhDepth],
+         m_ppcRecoYuvTemp[uhDepth],
+         (uiNoResidual? true:false));
+
+
+       if(uiNoResidual==0)
+       {
+         if(rpcTempCU->getQtRootCbf(0) == 0)
+         {
+           mergeCandBuffer[uiMergeCand] = 1;
+         }
+       }
+
+#if SKIP_FLAG
+       rpcTempCU->setSkipFlagSubParts( rpcTempCU->getQtRootCbf(0) == 0, 0, uhDepth );
+#endif
+          Int orgQP = rpcTempCU->getQP( 0 );
+          xCheckDQP( rpcTempCU );
+          xCheckBestMode(rpcBestCU, rpcTempCU, uhDepth);
+          rpcTempCU->initEstData( uhDepth, orgQP );
+
+
+      if( m_pcEncCfg->getUseFastDecisionForMerge() && !bestIsSkip )
+      {
+        bestIsSkip = rpcBestCU->getQtRootCbf(0) == 0;
+      }
+
+    }
+    }
+   }
+  }
+
+  if(uiNoResidual == 0 && m_pcEncCfg->getUseEarlySkipDetection())
+  {
+    if(rpcBestCU->getQtRootCbf( 0 ) == 0)
+    {
+      if( rpcBestCU->getMergeFlag( 0 ))
+      {
+        *earlyDetectionSkipMode = true;
+      }
+      else
+      {
+        Int absoulte_MV=0;
+        for ( UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )
+        {
+          if ( rpcBestCU->getSlice()->getNumRefIdx( RefPicList( uiRefListIdx ) ) > 0 )
+          {
+            TComCUMvField* pcCUMvField = rpcBestCU->getCUMvField(RefPicList( uiRefListIdx ));
+            Int iHor = pcCUMvField->getMvd( 0 ).getAbsHor();
+            Int iVer = pcCUMvField->getMvd( 0 ).getAbsVer();
+            absoulte_MV+=iHor+iVer;
+          }
+        }
+
+        if(absoulte_MV == 0)
+        {
+          *earlyDetectionSkipMode = true;
+        }
+      }
+    }
+  }
+ }
+}
+
+
+#if AMP_MRG
+Void TEncCu::xCheckRDCostInter( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize, Bool bUseMRG)
+#else
+Void TEncCu::xCheckRDCostInter( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize )
+#endif
+{
+  UChar uhDepth = rpcTempCU->getDepth( 0 );
+  
+  rpcTempCU->setDepthSubParts( uhDepth, 0 );
+  
+#if SKIP_FLAG
+  rpcTempCU->setSkipFlagSubParts( false, 0, uhDepth );
+#endif
+
+  rpcTempCU->setPartSizeSubParts  ( ePartSize,  0, uhDepth );
+  rpcTempCU->setPredModeSubParts  ( MODE_INTER, 0, uhDepth );
+  rpcTempCU->setCUTransquantBypassSubParts  ( m_pcEncCfg->getCUTransquantBypassFlagValue(),      0, uhDepth );
+  
+#if AMP_MRG
+  rpcTempCU->setMergeAMP (true);
+  m_pcPredSearch->predInterSearch ( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcRecoYuvTemp[uhDepth], false, bUseMRG );
+#else  
+  m_pcPredSearch->predInterSearch ( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcRecoYuvTemp[uhDepth] );
+#endif
+
+#if AMP_MRG
+  if ( !rpcTempCU->getMergeAMP() )
+  {
+    return;
+  }
+#endif
+
+  m_pcPredSearch->encodeResAndCalcRdInterCU( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcResiYuvBest[uhDepth], m_ppcRecoYuvTemp[uhDepth], false );
+  rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+
+  xCheckDQP( rpcTempCU );
+  xCheckBestMode(rpcBestCU, rpcTempCU, uhDepth);
+}
+
+Void TEncCu::xCheckRDCostIntra( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize eSize )
+{
+  UInt uiDepth = rpcTempCU->getDepth( 0 );
+  
+#if SKIP_FLAG
+  rpcTempCU->setSkipFlagSubParts( false, 0, uiDepth );
+#endif
+
+  rpcTempCU->setPartSizeSubParts( eSize, 0, uiDepth );
+  rpcTempCU->setPredModeSubParts( MODE_INTRA, 0, uiDepth );
+  rpcTempCU->setCUTransquantBypassSubParts( m_pcEncCfg->getCUTransquantBypassFlagValue(), 0, uiDepth );
+  
+  Bool bSeparateLumaChroma = true; // choose estimation mode
+  UInt uiPreCalcDistC      = 0;
+  if( !bSeparateLumaChroma )
+  {
+    m_pcPredSearch->preestChromaPredMode( rpcTempCU, m_ppcOrigYuv[uiDepth], m_ppcPredYuvTemp[uiDepth] );
+  }
+  m_pcPredSearch  ->estIntraPredQT      ( rpcTempCU, m_ppcOrigYuv[uiDepth], m_ppcPredYuvTemp[uiDepth], m_ppcResiYuvTemp[uiDepth], m_ppcRecoYuvTemp[uiDepth], uiPreCalcDistC, bSeparateLumaChroma );
+
+  m_ppcRecoYuvTemp[uiDepth]->copyToPicLuma(rpcTempCU->getPic()->getPicYuvRec(), rpcTempCU->getAddr(), rpcTempCU->getZorderIdxInCU() );
+  
+  m_pcPredSearch  ->estIntraPredChromaQT( rpcTempCU, m_ppcOrigYuv[uiDepth], m_ppcPredYuvTemp[uiDepth], m_ppcResiYuvTemp[uiDepth], m_ppcRecoYuvTemp[uiDepth], uiPreCalcDistC );
+  
+  m_pcEntropyCoder->resetBits();
+#if INTRA_BL
+  m_pcEntropyCoder->encodeIntraBLFlag ( rpcTempCU, 0,       true );
+#endif
+  if ( rpcTempCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
+  {
+    m_pcEntropyCoder->encodeCUTransquantBypassFlag( rpcTempCU, 0,          true );
+  }
+  m_pcEntropyCoder->encodeSkipFlag ( rpcTempCU, 0,          true );
+  m_pcEntropyCoder->encodePredMode( rpcTempCU, 0,          true );
+  m_pcEntropyCoder->encodePartSize( rpcTempCU, 0, uiDepth, true );
+  m_pcEntropyCoder->encodePredInfo( rpcTempCU, 0,          true );
+  m_pcEntropyCoder->encodeIPCMInfo(rpcTempCU, 0, true );
+
+  // Encode Coefficients
+  Bool bCodeDQP = getdQPFlag();
+  m_pcEntropyCoder->encodeCoeff( rpcTempCU, 0, uiDepth, rpcTempCU->getWidth (0), rpcTempCU->getHeight(0), bCodeDQP );
+  setdQPFlag( bCodeDQP );
+  
+  if( m_bUseSBACRD ) m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
+  
+  rpcTempCU->getTotalBits() = m_pcEntropyCoder->getNumberOfWrittenBits();
+  if(m_pcEncCfg->getUseSBACRD())
+  {
+    rpcTempCU->getTotalBins() = ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
+  }
+  rpcTempCU->getTotalCost() = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+  
+  xCheckDQP( rpcTempCU );
+  xCheckBestMode(rpcBestCU, rpcTempCU, uiDepth);
+}
+#if INTRA_BL
+Void TEncCu::xCheckRDCostIntraBL( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU )
+{
+  UInt uiDepth = rpcTempCU->getDepth( 0 );
+#if SKIP_FLAG
+  rpcTempCU->setSkipFlagSubParts( false, 0, uiDepth );
+#endif
+  
+  rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uiDepth );
+  rpcTempCU->setPredModeSubParts( MODE_INTRA_BL, 0, uiDepth );  
+  rpcTempCU->setCUTransquantBypassSubParts( m_pcEncCfg->getCUTransquantBypassFlagValue(), 0, uiDepth );
+
+  m_pcPredSearch->setBaseRecPic( m_pcPicYuvRecBase ); 
+  m_pcPredSearch->estIntraBLPredQT( rpcTempCU, m_ppcOrigYuv[uiDepth], m_ppcPredYuvTemp[uiDepth], m_ppcResiYuvTemp[uiDepth], m_ppcRecoYuvTemp[uiDepth] );
+
+  m_pcEntropyCoder->resetBits();
+  m_pcEntropyCoder->encodeIntraBLFlag ( rpcTempCU, 0,       true );
+  m_pcEntropyCoder->encodeSkipFlag( rpcTempCU, 0,       true );
+  if ( rpcTempCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
+  {
+    m_pcEntropyCoder->encodeCUTransquantBypassFlag( rpcTempCU, 0,          true );
+  }
+
+  // Encode Coefficients
+  Bool bCodeDQP = getdQPFlag();
+  m_pcEntropyCoder->encodeCoeff( rpcTempCU, 0, uiDepth, rpcTempCU->getWidth (0), rpcTempCU->getHeight(0), bCodeDQP );
+  setdQPFlag( bCodeDQP );
+  
+  if( m_bUseSBACRD ) m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
+  
+  rpcTempCU->getTotalBits() = m_pcEntropyCoder->getNumberOfWrittenBits();
+  if(m_pcEncCfg->getUseSBACRD())
+  {
+    rpcTempCU->getTotalBins() = ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
+  }
+  rpcTempCU->getTotalCost() = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+  
+  xCheckDQP( rpcTempCU );
+  xCheckBestMode(rpcBestCU, rpcTempCU, uiDepth);
+}
+#endif
+
+
+/** Check R-D costs for a CU with PCM mode. 
+ * \param rpcBestCU pointer to best mode CU data structure
+ * \param rpcTempCU pointer to testing mode CU data structure
+ * \returns Void
+ * 
+ * \note Current PCM implementation encodes sample values in a lossless way. The distortion of PCM mode CUs are zero. PCM mode is selected if the best mode yields bits greater than that of PCM mode.
+ */
+Void TEncCu::xCheckIntraPCM( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU )
+{
+  UInt uiDepth = rpcTempCU->getDepth( 0 );
+
+  rpcTempCU->setCUTransquantBypassSubParts(false, 0, uiDepth);
+
+#if SKIP_FLAG
+  rpcTempCU->setSkipFlagSubParts( false, 0, uiDepth );
+#endif
+
+  rpcTempCU->setIPCMFlag(0, true);
+  rpcTempCU->setIPCMFlagSubParts (true, 0, rpcTempCU->getDepth(0));
+  rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uiDepth );
+  rpcTempCU->setPredModeSubParts( MODE_INTRA, 0, uiDepth );
+  rpcTempCU->setTrIdxSubParts ( 0, 0, uiDepth );
+  rpcTempCU->setCUTransquantBypassSubParts( m_pcEncCfg->getCUTransquantBypassFlagValue(), 0, uiDepth );
+
+  m_pcPredSearch->IPCMSearch( rpcTempCU, m_ppcOrigYuv[uiDepth], m_ppcPredYuvTemp[uiDepth], m_ppcResiYuvTemp[uiDepth], m_ppcRecoYuvTemp[uiDepth]);
+
+  if( m_bUseSBACRD ) m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
+
+  m_pcEntropyCoder->resetBits();
+#if INTRA_BL
+  m_pcEntropyCoder->encodeIntraBLFlag ( rpcTempCU, 0,       true );
+#endif
+  if ( rpcTempCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
+  {
+    m_pcEntropyCoder->encodeCUTransquantBypassFlag( rpcTempCU, 0,          true );
+  }
+  m_pcEntropyCoder->encodeSkipFlag ( rpcTempCU, 0,          true );
+  m_pcEntropyCoder->encodePredMode ( rpcTempCU, 0,          true );
+  m_pcEntropyCoder->encodePartSize ( rpcTempCU, 0, uiDepth, true );
+  m_pcEntropyCoder->encodeIPCMInfo ( rpcTempCU, 0, true );
+
+  if( m_bUseSBACRD ) m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
+
+  rpcTempCU->getTotalBits() = m_pcEntropyCoder->getNumberOfWrittenBits();
+  if(m_pcEncCfg->getUseSBACRD())
+  {
+    rpcTempCU->getTotalBins() = ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
+  }
+  rpcTempCU->getTotalCost() = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+
+  xCheckDQP( rpcTempCU );
+  xCheckBestMode( rpcBestCU, rpcTempCU, uiDepth );
+}
+
+// check whether current try is the best
+Void TEncCu::xCheckBestMode( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU )
+{
+  if( rpcTempCU->getTotalCost() < rpcBestCU->getTotalCost() )
+  {
+    TComYuv* pcYuv;
+    UChar uhDepth = rpcBestCU->getDepth(0);
+
+    // Change Information data
+    TComDataCU* pcCU = rpcBestCU;
+    rpcBestCU = rpcTempCU;
+    rpcTempCU = pcCU;
+    
+    // Change Prediction data
+    pcYuv = m_ppcPredYuvBest[uhDepth];
+    m_ppcPredYuvBest[uhDepth] = m_ppcPredYuvTemp[uhDepth];
+    m_ppcPredYuvTemp[uhDepth] = pcYuv;
+    
+    // Change Reconstruction data
+    pcYuv = m_ppcRecoYuvBest[uhDepth];
+    m_ppcRecoYuvBest[uhDepth] = m_ppcRecoYuvTemp[uhDepth];
+    m_ppcRecoYuvTemp[uhDepth] = pcYuv;
+    
+    pcYuv = NULL;
+    pcCU  = NULL;
+    
+    if( m_bUseSBACRD )  // store temp best CI for next CU coding
+      m_pppcRDSbacCoder[uhDepth][CI_TEMP_BEST]->store(m_pppcRDSbacCoder[uhDepth][CI_NEXT_BEST]);
+  }
+}
+
+/** check whether current try is the best with identifying the depth of current try
+ * \param rpcBestCU
+ * \param rpcTempCU
+ * \returns Void
+ */
+Void TEncCu::xCheckBestMode( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UInt uiDepth )
+{
+  if( rpcTempCU->getTotalCost() < rpcBestCU->getTotalCost() )
+  {
+    TComYuv* pcYuv;
+    // Change Information data
+    TComDataCU* pcCU = rpcBestCU;
+    rpcBestCU = rpcTempCU;
+    rpcTempCU = pcCU;
+
+    // Change Prediction data
+    pcYuv = m_ppcPredYuvBest[uiDepth];
+    m_ppcPredYuvBest[uiDepth] = m_ppcPredYuvTemp[uiDepth];
+    m_ppcPredYuvTemp[uiDepth] = pcYuv;
+
+    // Change Reconstruction data
+    pcYuv = m_ppcRecoYuvBest[uiDepth];
+    m_ppcRecoYuvBest[uiDepth] = m_ppcRecoYuvTemp[uiDepth];
+    m_ppcRecoYuvTemp[uiDepth] = pcYuv;
+
+    pcYuv = NULL;
+    pcCU  = NULL;
+
+    if( m_bUseSBACRD )  // store temp best CI for next CU coding
+      m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]->store(m_pppcRDSbacCoder[uiDepth][CI_NEXT_BEST]);
+  }
+}
+
+Void TEncCu::xCheckDQP( TComDataCU* pcCU )
+{
+  UInt uiDepth = pcCU->getDepth( 0 );
+
+  if( pcCU->getSlice()->getPPS()->getUseDQP() && (g_uiMaxCUWidth>>uiDepth) >= pcCU->getSlice()->getPPS()->getMinCuDQPSize() )
+  {
+    if ( pcCU->getCbf( 0, TEXT_LUMA, 0 ) || pcCU->getCbf( 0, TEXT_CHROMA_U, 0 ) || pcCU->getCbf( 0, TEXT_CHROMA_V, 0 ) )
+    {
+#if !RDO_WITHOUT_DQP_BITS
+      m_pcEntropyCoder->resetBits();
+      m_pcEntropyCoder->encodeQP( pcCU, 0, false );
+      pcCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // dQP bits
+      if(m_pcEncCfg->getUseSBACRD())
+      {
+        pcCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
+      }
+      pcCU->getTotalCost() = m_pcRdCost->calcRdCost( pcCU->getTotalBits(), pcCU->getTotalDistortion() );
+#endif
+    }
+    else
+    {
+      pcCU->setQPSubParts( pcCU->getRefQP( 0 ), 0, uiDepth ); // set QP to default QP
+    }
+  }
+}
+
+/** Check whether the last CU shares the same root as the current CU and is IPCM or not.  
+ * \param pcCU
+ * \param uiCurAbsPartIdx
+ * \returns Bool
+ */
+Bool TEncCu::checkLastCUSucIPCM( TComDataCU* pcCU, UInt uiCurAbsPartIdx )
+{
+  Bool lastCUSucIPCMFlag = false;
+
+  UInt curDepth = pcCU->getDepth(uiCurAbsPartIdx);
+  UInt shift = ((pcCU->getPic()->getSlice(pcCU->getPic()->getCurrSliceIdx())->getSPS()->getMaxCUDepth() - curDepth)<<1);
+  UInt startPartUnitIdx = ((uiCurAbsPartIdx&(0x03<<shift))>>shift);
+
+  TComSlice * pcSlice = pcCU->getPic()->getSlice(pcCU->getPic()->getCurrSliceIdx());
+  if( pcSlice->getDependentSliceCurStartCUAddr() == ( pcCU->getSCUAddr() + uiCurAbsPartIdx ) )
+  {
+    return false;
+  }
+
+  if(curDepth > 0 && startPartUnitIdx > 0)
+  {
+    Int lastValidPartIdx = pcCU->getLastValidPartIdx((Int) uiCurAbsPartIdx );
+
+    if( lastValidPartIdx >= 0 )
+    {
+      if(( pcCU->getSliceStartCU( uiCurAbsPartIdx ) == pcCU->getSliceStartCU( (UInt) lastValidPartIdx ))
+        && 
+        ( pcCU->getDepth( uiCurAbsPartIdx ) == pcCU->getDepth( (UInt) lastValidPartIdx )) 
+        && 
+        pcCU->getIPCMFlag( (UInt) lastValidPartIdx ) )
+      {
+        lastCUSucIPCMFlag = true;
+      }
+    }
+  }
+
+  return  lastCUSucIPCMFlag;
+}
+
+/** Count the number of successive IPCM CUs sharing the same root.
+ * \param pcCU
+ * \param uiCurAbsPartIdx
+ * \returns Int
+ */
+Int TEncCu::countNumSucIPCM ( TComDataCU* pcCU, UInt uiCurAbsPartIdx )
+{
+  Int numSucIPCM = 0;
+  UInt CurDepth = pcCU->getDepth(uiCurAbsPartIdx);
+
+  if( pcCU->getIPCMFlag(uiCurAbsPartIdx) )
+  {
+    if(CurDepth == 0)
+    {
+       numSucIPCM = 1;
+    }
+    else 
+    {
+      TComPic* pcPic = pcCU->getPic();
+      TComSlice * pcSlice = pcCU->getPic()->getSlice(pcCU->getPic()->getCurrSliceIdx());
+      UInt qNumParts = ( pcPic->getNumPartInCU() >> ((CurDepth-1)<<1) )>>2;
+
+      Bool continueFlag = true;
+      UInt absPartIdx = uiCurAbsPartIdx;
+      UInt shift = ((pcSlice->getSPS()->getMaxCUDepth() - CurDepth)<<1);
+      UInt startPartUnitIdx = ((uiCurAbsPartIdx&(0x03<<shift))>>shift);
+
+      for ( UInt partUnitIdx = startPartUnitIdx; partUnitIdx < 4 && continueFlag; partUnitIdx++, absPartIdx+=qNumParts )
+      {
+        UInt lPelX = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[absPartIdx] ];
+        UInt tPelY = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[absPartIdx] ];
+        Bool inSliceFlag = ( pcCU->getSCUAddr()+absPartIdx+qNumParts>pcSlice->getDependentSliceCurStartCUAddr() ) && ( pcCU->getSCUAddr()+absPartIdx < pcSlice->getDependentSliceCurEndCUAddr());
+
+        if( inSliceFlag && ( lPelX < pcSlice->getSPS()->getPicWidthInLumaSamples() ) && ( tPelY < pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+        {
+          UInt uiDepth = pcCU->getDepth(absPartIdx);
+
+          if( ( CurDepth == uiDepth) && pcCU->getIPCMFlag( absPartIdx ) )
+          {
+            numSucIPCM++;
+          }
+          else
+          {
+            continueFlag = false;
+          }
+        }
+      }
+    }
+  }
+
+  return numSucIPCM;
+}
+
+Void TEncCu::xCopyAMVPInfo (AMVPInfo* pSrc, AMVPInfo* pDst)
+{
+  pDst->iN = pSrc->iN;
+  for (Int i = 0; i < pSrc->iN; i++)
+  {
+    pDst->m_acMvCand[i] = pSrc->m_acMvCand[i];
+  }
+}
+Void TEncCu::xCopyYuv2Pic(TComPic* rpcPic, UInt uiCUAddr, UInt uiAbsPartIdx, UInt uiDepth, UInt uiSrcDepth, TComDataCU* pcCU, UInt uiLPelX, UInt uiTPelY )
+{
+  UInt uiRPelX   = uiLPelX + (g_uiMaxCUWidth>>uiDepth)  - 1;
+  UInt uiBPelY   = uiTPelY + (g_uiMaxCUHeight>>uiDepth) - 1;
+  TComSlice * pcSlice = pcCU->getPic()->getSlice(pcCU->getPic()->getCurrSliceIdx());
+  Bool bSliceStart = pcSlice->getDependentSliceCurStartCUAddr() > rpcPic->getPicSym()->getInverseCUOrderMap(pcCU->getAddr())*pcCU->getPic()->getNumPartInCU()+uiAbsPartIdx && 
+    pcSlice->getDependentSliceCurStartCUAddr() < rpcPic->getPicSym()->getInverseCUOrderMap(pcCU->getAddr())*pcCU->getPic()->getNumPartInCU()+uiAbsPartIdx+( pcCU->getPic()->getNumPartInCU() >> (uiDepth<<1) );
+  Bool bSliceEnd   = pcSlice->getDependentSliceCurEndCUAddr() > rpcPic->getPicSym()->getInverseCUOrderMap(pcCU->getAddr())*pcCU->getPic()->getNumPartInCU()+uiAbsPartIdx && 
+    pcSlice->getDependentSliceCurEndCUAddr() < rpcPic->getPicSym()->getInverseCUOrderMap(pcCU->getAddr())*pcCU->getPic()->getNumPartInCU()+uiAbsPartIdx+( pcCU->getPic()->getNumPartInCU() >> (uiDepth<<1) );
+  if(!bSliceEnd && !bSliceStart && ( uiRPelX < pcSlice->getSPS()->getPicWidthInLumaSamples() ) && ( uiBPelY < pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+  {
+    UInt uiAbsPartIdxInRaster = g_auiZscanToRaster[uiAbsPartIdx];
+    UInt uiSrcBlkWidth = rpcPic->getNumPartInWidth() >> (uiSrcDepth);
+    UInt uiBlkWidth    = rpcPic->getNumPartInWidth() >> (uiDepth);
+    UInt uiPartIdxX = ( ( uiAbsPartIdxInRaster % rpcPic->getNumPartInWidth() ) % uiSrcBlkWidth) / uiBlkWidth;
+    UInt uiPartIdxY = ( ( uiAbsPartIdxInRaster / rpcPic->getNumPartInWidth() ) % uiSrcBlkWidth) / uiBlkWidth;
+    UInt uiPartIdx = uiPartIdxY * ( uiSrcBlkWidth / uiBlkWidth ) + uiPartIdxX;
+    m_ppcRecoYuvBest[uiSrcDepth]->copyToPicYuv( rpcPic->getPicYuvRec (), uiCUAddr, uiAbsPartIdx, uiDepth - uiSrcDepth, uiPartIdx);
+  }
+  else
+  {
+    UInt uiQNumParts = ( pcCU->getPic()->getNumPartInCU() >> (uiDepth<<1) )>>2;
+
+    for ( UInt uiPartUnitIdx = 0; uiPartUnitIdx < 4; uiPartUnitIdx++, uiAbsPartIdx+=uiQNumParts )
+    {
+      UInt uiSubCULPelX   = uiLPelX + ( g_uiMaxCUWidth >>(uiDepth+1) )*( uiPartUnitIdx &  1 );
+      UInt uiSubCUTPelY   = uiTPelY + ( g_uiMaxCUHeight>>(uiDepth+1) )*( uiPartUnitIdx >> 1 );
+
+      Bool bInSlice = rpcPic->getPicSym()->getInverseCUOrderMap(pcCU->getAddr())*pcCU->getPic()->getNumPartInCU()+uiAbsPartIdx+uiQNumParts > pcSlice->getDependentSliceCurStartCUAddr() && 
+        rpcPic->getPicSym()->getInverseCUOrderMap(pcCU->getAddr())*pcCU->getPic()->getNumPartInCU()+uiAbsPartIdx < pcSlice->getDependentSliceCurEndCUAddr();
+      if(bInSlice&&( uiSubCULPelX < pcSlice->getSPS()->getPicWidthInLumaSamples() ) && ( uiSubCUTPelY < pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+      {
+        xCopyYuv2Pic( rpcPic, uiCUAddr, uiAbsPartIdx, uiDepth+1, uiSrcDepth, pcCU, uiSubCULPelX, uiSubCUTPelY );   // Copy Yuv data to picture Yuv
+      }
+    }
+  }
+}
+
+Void TEncCu::xCopyYuv2Tmp( UInt uiPartUnitIdx, UInt uiNextDepth )
+{
+  UInt uiCurrDepth = uiNextDepth - 1;
+  m_ppcRecoYuvBest[uiNextDepth]->copyToPartYuv( m_ppcRecoYuvTemp[uiCurrDepth], uiPartUnitIdx );
+}
+
+/** Function for filling the PCM buffer of a CU using its original sample array 
+ * \param pcCU pointer to current CU
+ * \param pcOrgYuv pointer to original sample array
+ * \returns Void
+ */
+Void TEncCu::xFillPCMBuffer     ( TComDataCU*& pCU, TComYuv* pOrgYuv )
+{
+
+  UInt   width        = pCU->getWidth(0);
+  UInt   height       = pCU->getHeight(0);
+
+  Pel*   pSrcY = pOrgYuv->getLumaAddr(0, width); 
+  Pel*   pDstY = pCU->getPCMSampleY();
+  UInt   srcStride = pOrgYuv->getStride();
+
+  for(Int y = 0; y < height; y++ )
+  {
+    for(Int x = 0; x < width; x++ )
+    {
+      pDstY[x] = pSrcY[x];
+    }
+    pDstY += width;
+    pSrcY += srcStride;
+  }
+
+  Pel* pSrcCb       = pOrgYuv->getCbAddr();
+  Pel* pSrcCr       = pOrgYuv->getCrAddr();;
+
+  Pel* pDstCb       = pCU->getPCMSampleCb();
+  Pel* pDstCr       = pCU->getPCMSampleCr();;
+
+  UInt srcStrideC = pOrgYuv->getCStride();
+  UInt heightC   = height >> 1;
+  UInt widthC    = width  >> 1;
+
+  for(Int y = 0; y < heightC; y++ )
+  {
+    for(Int x = 0; x < widthC; x++ )
+    {
+      pDstCb[x] = pSrcCb[x];
+      pDstCr[x] = pSrcCr[x];
+    }
+    pDstCb += widthC;
+    pDstCr += widthC;
+    pSrcCb += srcStrideC;
+    pSrcCr += srcStrideC;
+  }
+}
+
+#if ADAPTIVE_QP_SELECTION
+/** Collect ARL statistics from one block
+  */
+Int TEncCu::xTuCollectARLStats(TCoeff* rpcCoeff, Int* rpcArlCoeff, Int NumCoeffInCU, Double* cSum, UInt* numSamples )
+{
+  for( Int n = 0; n < NumCoeffInCU; n++ )
+  {
+    Int u = abs( rpcCoeff[ n ] );
+    Int absc = rpcArlCoeff[ n ];
+
+    if( u != 0 )
+    {
+      if( u < LEVEL_RANGE )
+      {
+        cSum[ u ] += ( Double )absc;
+        numSamples[ u ]++;
+      }
+      else 
+      {
+        cSum[ LEVEL_RANGE ] += ( Double )absc - ( Double )( u << ARL_C_PRECISION );
+        numSamples[ LEVEL_RANGE ]++;
+      }
+    }
+  }
+
+  return 0;
+}
+
+/** Collect ARL statistics from one LCU
+ * \param pcCU
+ */
+Void TEncCu::xLcuCollectARLStats(TComDataCU* rpcCU )
+{
+  Double cSum[ LEVEL_RANGE + 1 ];     //: the sum of DCT coefficients corresponding to datatype and quantization output
+  UInt numSamples[ LEVEL_RANGE + 1 ]; //: the number of coefficients corresponding to datatype and quantization output
+
+  TCoeff* pCoeffY = rpcCU->getCoeffY();
+  Int* pArlCoeffY = rpcCU->getArlCoeffY();
+
+  UInt uiMinCUWidth = g_uiMaxCUWidth >> g_uiMaxCUDepth;
+  UInt uiMinNumCoeffInCU = 1 << uiMinCUWidth;
+
+  memset( cSum, 0, sizeof( Double )*(LEVEL_RANGE+1) );
+  memset( numSamples, 0, sizeof( UInt )*(LEVEL_RANGE+1) );
+
+  // Collect stats to cSum[][] and numSamples[][]
+  for(Int i = 0; i < rpcCU->getTotalNumPart(); i ++ )
+  {
+    UInt uiTrIdx = rpcCU->getTransformIdx(i);
+
+    if(rpcCU->getPredictionMode(i) == MODE_INTER)
+    if( rpcCU->getCbf( i, TEXT_LUMA, uiTrIdx ) )
+    {
+      xTuCollectARLStats(pCoeffY, pArlCoeffY, uiMinNumCoeffInCU, cSum, numSamples);
+    }//Note that only InterY is processed. QP rounding is based on InterY data only.
+   
+    pCoeffY  += uiMinNumCoeffInCU;
+    pArlCoeffY  += uiMinNumCoeffInCU;
+  }
+
+  for(Int u=1; u<LEVEL_RANGE;u++)
+  {
+    m_pcTrQuant->getSliceSumC()[u] += cSum[ u ] ;
+    m_pcTrQuant->getSliceNSamples()[u] += numSamples[ u ] ;
+  }
+  m_pcTrQuant->getSliceSumC()[LEVEL_RANGE] += cSum[ LEVEL_RANGE ] ;
+  m_pcTrQuant->getSliceNSamples()[LEVEL_RANGE] += numSamples[ LEVEL_RANGE ] ;
+}
+#endif
+//! \}
Index: /trunk/source/Lib/TLibEncoder/TEncCu.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncCu.h	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/TEncCu.h	(revision 2)
@@ -0,0 +1,193 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncCu.h
+    \brief    Coding Unit (CU) encoder class (header)
+*/
+
+#ifndef __TENCCU__
+#define __TENCCU__
+
+// Include files
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComYuv.h"
+#include "TLibCommon/TComPrediction.h"
+#include "TLibCommon/TComTrQuant.h"
+#include "TLibCommon/TComBitCounter.h"
+#include "TLibCommon/TComDataCU.h"
+
+#include "TEncEntropy.h"
+#include "TEncSearch.h"
+#include "TEncRateCtrl.h"
+//! \ingroup TLibEncoder
+//! \{
+
+class TEncTop;
+class TEncSbac;
+class TEncCavlc;
+class TEncSlice;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// CU encoder class
+class TEncCu
+{
+private:
+  
+  TComDataCU**            m_ppcBestCU;      ///< Best CUs in each depth
+  TComDataCU**            m_ppcTempCU;      ///< Temporary CUs in each depth
+  UChar                   m_uhTotalDepth;
+  
+  TComYuv**               m_ppcPredYuvBest; ///< Best Prediction Yuv for each depth
+  TComYuv**               m_ppcResiYuvBest; ///< Best Residual Yuv for each depth
+  TComYuv**               m_ppcRecoYuvBest; ///< Best Reconstruction Yuv for each depth
+  TComYuv**               m_ppcPredYuvTemp; ///< Temporary Prediction Yuv for each depth
+  TComYuv**               m_ppcResiYuvTemp; ///< Temporary Residual Yuv for each depth
+  TComYuv**               m_ppcRecoYuvTemp; ///< Temporary Reconstruction Yuv for each depth
+  TComYuv**               m_ppcOrigYuv;     ///< Original Yuv for each depth
+  
+  //  Data : encoder control
+  Bool                    m_bEncodeDQP;
+  Bool                    m_checkBurstIPCMFlag;
+
+  //  Access channel
+  TEncCfg*                m_pcEncCfg;
+#if INTRA_BL
+  TComPicYuv*             m_pcPicYuvRecBase;       ///< reconstructed base layer
+#endif 
+  TEncSearch*             m_pcPredSearch;
+  TComTrQuant*            m_pcTrQuant;
+  TComBitCounter*         m_pcBitCounter;
+  TComRdCost*             m_pcRdCost;
+  
+#if SVC_EXTENSION
+  TEncTop**               m_ppcTEncTop;
+#endif
+  
+  TEncEntropy*            m_pcEntropyCoder;
+  TEncCavlc*              m_pcCavlcCoder;
+  TEncSbac*               m_pcSbacCoder;
+  TEncBinCABAC*           m_pcBinCABAC;
+  
+  // SBAC RD
+  TEncSbac***             m_pppcRDSbacCoder;
+  TEncSbac*               m_pcRDGoOnSbacCoder;
+  Bool                    m_bUseSBACRD;
+  TEncRateCtrl*           m_pcRateCtrl;
+public:
+  /// copy parameters from encoder class
+  Void  init                ( TEncTop* pcEncTop );
+  
+  /// create internal buffers
+  Void  create              ( UChar uhTotalDepth, UInt iMaxWidth, UInt iMaxHeight );
+  
+  /// destroy internal buffers
+  Void  destroy             ();
+  
+  /// CU analysis function
+  Void  compressCU          ( TComDataCU*&  rpcCU );
+  
+  /// CU encoding function
+  Void  encodeCU            ( TComDataCU*    pcCU, Bool bForceTerminate = false  );
+  
+  Void setBitCounter        ( TComBitCounter* pcBitCounter ) { m_pcBitCounter = pcBitCounter; }
+#if INTRA_BL 
+  Void  setBaseRecPic       ( TComPicYuv* p ) { m_pcPicYuvRecBase = p; }   
+#endif
+protected:
+  Void  finishCU            ( TComDataCU*  pcCU, UInt uiAbsPartIdx,           UInt uiDepth        );
+#if AMP_ENC_SPEEDUP
+  Void  xCompressCU         ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UInt uiDepth, PartSize eParentPartSize = SIZE_NONE );
+#else
+  Void  xCompressCU         ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UInt uiDepth        );
+#endif
+  Void  xEncodeCU           ( TComDataCU*  pcCU, UInt uiAbsPartIdx,           UInt uiDepth        );
+  
+  Int   xComputeQP          ( TComDataCU* pcCU, UInt uiDepth );
+  Void  xCheckBestMode      ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UInt uiDepth        );
+  
+  Void  xCheckRDCostMerge2Nx2N( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, Bool *earlyDetectionSkipMode);
+
+#if AMP_MRG
+  Void  xCheckRDCostInter   ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize, Bool bUseMRG = false  );
+#else
+  Void  xCheckRDCostInter   ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize  );
+#endif
+  Void  xCheckRDCostIntra   ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize  );
+#if INTRA_BL
+  Void  xCheckRDCostIntraBL ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU  );
+#endif
+
+  Void  xCheckBestMode      ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU                      );
+  Void  xCheckDQP           ( TComDataCU*  pcCU );
+  
+  Void  xCheckIntraPCM      ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU                      );
+  Void  xCopyAMVPInfo       ( AMVPInfo* pSrc, AMVPInfo* pDst );
+  Void  xCopyYuv2Pic        (TComPic* rpcPic, UInt uiCUAddr, UInt uiAbsPartIdx, UInt uiDepth, UInt uiSrcDepth, TComDataCU* pcCU, UInt uiLPelX, UInt uiTPelY );
+  Void  xCopyYuv2Tmp        ( UInt uhPartUnitIdx, UInt uiDepth );
+
+  Bool getdQPFlag           ()                        { return m_bEncodeDQP;        }
+  Void setdQPFlag           ( Bool b )                { m_bEncodeDQP = b;           }
+
+  Bool getCheckBurstIPCMFlag()                        { return m_checkBurstIPCMFlag;   }
+  Void setCheckBurstIPCMFlag( Bool b )                { m_checkBurstIPCMFlag = b;      }
+
+  Bool checkLastCUSucIPCM   ( TComDataCU* pcCU, UInt uiCurAbsPartIdx );
+  Int  countNumSucIPCM      ( TComDataCU* pcCU, UInt uiCurAbsPartIdx );
+
+#if ADAPTIVE_QP_SELECTION
+  // Adaptive reconstruction level (ARL) statistics collection functions
+  Void xLcuCollectARLStats(TComDataCU* rpcCU);
+  Int  xTuCollectARLStats(TCoeff* rpcCoeff, Int* rpcArlCoeff, Int NumCoeffInCU, Double* cSum, UInt* numSamples );
+#endif
+
+#if AMP_ENC_SPEEDUP 
+#if AMP_MRG
+  Void deriveTestModeAMP (TComDataCU *&rpcBestCU, PartSize eParentPartSize, Bool &bTestAMP_Hor, Bool &bTestAMP_Ver, Bool &bTestMergeAMP_Hor, Bool &bTestMergeAMP_Ver);
+#else
+  Void deriveTestModeAMP (TComDataCU *&rpcBestCU, PartSize eParentPartSize, Bool &bTestAMP_Hor, Bool &bTestAMP_Ver);
+#endif
+#endif
+
+#if SVC_EXTENSION
+  TEncTop*   getLayerEnc(UInt LayerId)  {return m_ppcTEncTop[LayerId]; }
+#endif 
+
+  Void  xFillPCMBuffer     ( TComDataCU*& pCU, TComYuv* pOrgYuv ); 
+};
+
+//! \}
+
+#endif // __TENCMB__
Index: /trunk/source/Lib/TLibEncoder/TEncEntropy.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncEntropy.cpp	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/TEncEntropy.cpp	(revision 2)
@@ -0,0 +1,943 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncEntropy.cpp
+    \brief    entropy encoder class
+*/
+
+#include "TEncEntropy.h"
+#include "TLibCommon/TypeDef.h"
+#include "TLibCommon/TComAdaptiveLoopFilter.h"
+#include "TLibCommon/TComSampleAdaptiveOffset.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+Void TEncEntropy::setEntropyCoder ( TEncEntropyIf* e, TComSlice* pcSlice )
+{
+  m_pcEntropyCoderIf = e;
+  m_pcEntropyCoderIf->setSlice ( pcSlice );
+}
+
+Void TEncEntropy::encodeSliceHeader ( TComSlice* pcSlice )
+{
+  if (pcSlice->getSPS()->getUseSAO())
+  {
+#if REMOVE_APS
+    SAOParam *saoParam = pcSlice->getPic()->getPicSym()->getSaoParam();
+#else
+    SAOParam *saoParam = pcSlice->getAPS()->getSaoParam();
+#endif
+    pcSlice->setSaoEnabledFlag     (saoParam->bSaoFlag[0]);
+#if !SAO_LUM_CHROMA_ONOFF_FLAGS
+    if (pcSlice->getSaoEnabledFlag())
+#endif
+    {
+#if SAO_TYPE_SHARING
+      pcSlice->setSaoEnabledFlagChroma   (saoParam->bSaoFlag[1]);
+#else
+      pcSlice->setSaoEnabledFlagCb   (saoParam->bSaoFlag[1]);
+      pcSlice->setSaoEnabledFlagCr   (saoParam->bSaoFlag[2]);
+#endif
+    }
+#if !SAO_LUM_CHROMA_ONOFF_FLAGS
+    else
+    {
+#if SAO_TYPE_SHARING
+      pcSlice->setSaoEnabledFlagChroma (0);
+#else
+      pcSlice->setSaoEnabledFlagCb   (0);
+      pcSlice->setSaoEnabledFlagCr   (0);
+#endif
+    }
+#endif
+  }
+
+  m_pcEntropyCoderIf->codeSliceHeader( pcSlice );
+  return;
+}
+
+Void  TEncEntropy::encodeTilesWPPEntryPoint( TComSlice* pSlice )
+{
+  m_pcEntropyCoderIf->codeTilesWPPEntryPoint( pSlice );
+}
+
+Void TEncEntropy::encodeTerminatingBit      ( UInt uiIsLast )
+{
+  m_pcEntropyCoderIf->codeTerminatingBit( uiIsLast );
+  
+  return;
+}
+
+Void TEncEntropy::encodeSliceFinish()
+{
+  m_pcEntropyCoderIf->codeSliceFinish();
+}
+
+Void TEncEntropy::encodeFlush()
+{
+  m_pcEntropyCoderIf->codeFlush();
+}
+
+Void TEncEntropy::encodeStart()
+{
+  m_pcEntropyCoderIf->encodeStart();
+}
+
+Void TEncEntropy::encodePPS( TComPPS* pcPPS )
+{
+  m_pcEntropyCoderIf->codePPS( pcPPS );
+  return;
+}
+
+Void TEncEntropy::encodeSPS( TComSPS* pcSPS )
+{
+  m_pcEntropyCoderIf->codeSPS( pcSPS );
+  return;
+}
+
+Void TEncEntropy::encodeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
+{
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+  if( !bRD )
+  {
+    if( pcCU->getLastCUSucIPCMFlag() && pcCU->getIPCMFlag(uiAbsPartIdx) )
+    {
+      return;
+    }
+  }
+  m_pcEntropyCoderIf->codeCUTransquantBypassFlag( pcCU, uiAbsPartIdx );
+}
+
+Void TEncEntropy::encodeVPS( TComVPS* pcVPS )
+{
+  m_pcEntropyCoderIf->codeVPS( pcVPS );
+  return;
+}
+
+Void TEncEntropy::encodeSkipFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
+{
+  if ( pcCU->getSlice()->isIntra() )
+  {
+    return;
+  }
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+  if( !bRD )
+  {
+    if( pcCU->getLastCUSucIPCMFlag() && pcCU->getIPCMFlag(uiAbsPartIdx) )
+    {
+      return;
+    }
+  }
+  m_pcEntropyCoderIf->codeSkipFlag( pcCU, uiAbsPartIdx );
+}
+#if INTRA_BL
+Void TEncEntropy::encodeIntraBLFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
+{
+  if( pcCU->getLayerId() == 0 )
+  {
+    return;
+  }
+
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+  m_pcEntropyCoderIf->codeIntraBLFlag( pcCU, uiAbsPartIdx );
+}
+#endif
+/** encode merge flag
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param uiPUIdx
+ * \returns Void
+ */
+Void TEncEntropy::encodeMergeFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiPUIdx )
+{ 
+  // at least one merge candidate exists
+  m_pcEntropyCoderIf->codeMergeFlag( pcCU, uiAbsPartIdx );
+}
+
+/** encode merge index
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param uiPUIdx
+ * \param bRD
+ * \returns Void
+ */
+Void TEncEntropy::encodeMergeIndex( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiPUIdx, Bool bRD )
+{
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+    assert( pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_2Nx2N );
+  }
+  m_pcEntropyCoderIf->codeMergeIndex( pcCU, uiAbsPartIdx );
+}
+
+/** encode prediction mode
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param bRD
+ * \returns Void
+ */
+Void TEncEntropy::encodePredMode( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
+{
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+  if( !bRD )
+  {
+    if( pcCU->getLastCUSucIPCMFlag() && pcCU->getIPCMFlag(uiAbsPartIdx) )
+    {
+      return;
+    }
+  }
+
+  if ( pcCU->getSlice()->isIntra() )
+  {
+    return;
+  }
+
+  m_pcEntropyCoderIf->codePredMode( pcCU, uiAbsPartIdx );
+}
+
+// Split mode
+Void TEncEntropy::encodeSplitFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, Bool bRD )
+{
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+  if( !bRD )
+  {
+    if( pcCU->getLastCUSucIPCMFlag() && pcCU->getIPCMFlag(uiAbsPartIdx) )
+    {
+      return;
+    }
+  }
+
+  m_pcEntropyCoderIf->codeSplitFlag( pcCU, uiAbsPartIdx, uiDepth );
+}
+
+/** encode partition size
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param uiDepth
+ * \param bRD
+ * \returns Void
+ */
+Void TEncEntropy::encodePartSize( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, Bool bRD )
+{
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+  if( !bRD )
+  {
+    if( pcCU->getLastCUSucIPCMFlag() && pcCU->getIPCMFlag(uiAbsPartIdx) )
+    {
+      return;
+    }
+  }
+  m_pcEntropyCoderIf->codePartSize( pcCU, uiAbsPartIdx, uiDepth );
+}
+
+/** Encode I_PCM information. 
+ * \param pcCU pointer to CU 
+ * \param uiAbsPartIdx CU index
+ * \param bRD flag indicating estimation or encoding
+ * \returns Void
+ */
+Void TEncEntropy::encodeIPCMInfo( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
+{
+  if(!pcCU->getSlice()->getSPS()->getUsePCM()
+    || pcCU->getWidth(uiAbsPartIdx) > (1<<pcCU->getSlice()->getSPS()->getPCMLog2MaxSize())
+    || pcCU->getWidth(uiAbsPartIdx) < (1<<pcCU->getSlice()->getSPS()->getPCMLog2MinSize()))
+  {
+    return;
+  }
+  
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+  
+  Int numIPCM = 0;
+  Bool firstIPCMFlag = false;
+
+  if( pcCU->getIPCMFlag(uiAbsPartIdx) )
+  {
+    numIPCM = 1;
+    firstIPCMFlag = true;
+
+    if( !bRD )
+    {
+      numIPCM = pcCU->getNumSucIPCM();
+      firstIPCMFlag = !pcCU->getLastCUSucIPCMFlag();
+    }
+  }
+  m_pcEntropyCoderIf->codeIPCMInfo ( pcCU, uiAbsPartIdx, numIPCM, firstIPCMFlag);
+
+}
+
+Void TEncEntropy::xEncodeTransform( TComDataCU* pcCU,UInt offsetLuma, UInt offsetChroma, UInt uiAbsPartIdx, UInt absTUPartIdx, UInt uiDepth, UInt width, UInt height, UInt uiTrIdx, UInt uiInnerQuadIdx, Bool& bCodeDQP )
+{
+  const UInt uiSubdiv = pcCU->getTransformIdx( uiAbsPartIdx ) + pcCU->getDepth( uiAbsPartIdx ) > uiDepth;
+  const UInt uiLog2TrafoSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth()]+2 - uiDepth;
+  UInt cbfY = pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA    , uiTrIdx );
+  UInt cbfU = pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrIdx );
+  UInt cbfV = pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrIdx );
+
+  if(uiTrIdx==0)
+  {
+    m_bakAbsPartIdxCU = uiAbsPartIdx;
+  }
+  if( uiLog2TrafoSize == 2 )
+  {
+    UInt partNum = pcCU->getPic()->getNumPartInCU() >> ( ( uiDepth - 1 ) << 1 );
+    if( ( uiAbsPartIdx % partNum ) == 0 )
+    {
+      m_uiBakAbsPartIdx   = uiAbsPartIdx;
+      m_uiBakChromaOffset = offsetChroma;
+    }
+    else if( ( uiAbsPartIdx % partNum ) == (partNum - 1) )
+    {
+      cbfU = pcCU->getCbf( m_uiBakAbsPartIdx, TEXT_CHROMA_U, uiTrIdx );
+      cbfV = pcCU->getCbf( m_uiBakAbsPartIdx, TEXT_CHROMA_V, uiTrIdx );
+    }
+  }
+#if INTRA_BL
+    if( pcCU->isIntra(uiAbsPartIdx) && pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_NxN && uiDepth == pcCU->getDepth(uiAbsPartIdx) )
+#else
+  
+  if( pcCU->getPredictionMode(uiAbsPartIdx) == MODE_INTRA && pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_NxN && uiDepth == pcCU->getDepth(uiAbsPartIdx) )
+#endif
+  {
+    assert( uiSubdiv );
+  }
+  else if( pcCU->getPredictionMode(uiAbsPartIdx) == MODE_INTER && (pcCU->getPartitionSize(uiAbsPartIdx) != SIZE_2Nx2N) && uiDepth == pcCU->getDepth(uiAbsPartIdx) &&  (pcCU->getSlice()->getSPS()->getQuadtreeTUMaxDepthInter() == 1) )
+  {
+    if ( uiLog2TrafoSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
+    {
+      assert( uiSubdiv );
+    }
+    else
+    {
+      assert(!uiSubdiv );
+    }
+  }
+  else if( uiLog2TrafoSize > pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() )
+  {
+    assert( uiSubdiv );
+  }
+  else if( uiLog2TrafoSize == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+  {
+    assert( !uiSubdiv );
+  }
+  else if( uiLog2TrafoSize == pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
+  {
+    assert( !uiSubdiv );
+  }
+  else
+  {
+    assert( uiLog2TrafoSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) );
+#if TRANS_SPLIT_FLAG_CTX_REDUCTION
+    m_pcEntropyCoderIf->codeTransformSubdivFlag( uiSubdiv, 5 - uiLog2TrafoSize );
+#else
+    m_pcEntropyCoderIf->codeTransformSubdivFlag( uiSubdiv, uiDepth );
+#endif
+  }
+
+  const UInt uiTrDepthCurr = uiDepth - pcCU->getDepth( uiAbsPartIdx );
+  const Bool bFirstCbfOfCU = uiTrDepthCurr == 0;
+  if( bFirstCbfOfCU || uiLog2TrafoSize > 2 )
+  {
+    if( bFirstCbfOfCU || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepthCurr - 1 ) )
+    {
+      m_pcEntropyCoderIf->codeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepthCurr );
+    }
+    if( bFirstCbfOfCU || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepthCurr - 1 ) )
+    {
+      m_pcEntropyCoderIf->codeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepthCurr );
+    }
+  }
+  else if( uiLog2TrafoSize == 2 )
+  {
+    assert( pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepthCurr ) == pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepthCurr - 1 ) );
+    assert( pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepthCurr ) == pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepthCurr - 1 ) );
+  }
+  
+  if( uiSubdiv )
+  {
+    UInt size;
+    width  >>= 1;
+    height >>= 1;
+    size = width*height;
+    uiTrIdx++;
+    ++uiDepth;
+    const UInt partNum = pcCU->getPic()->getNumPartInCU() >> (uiDepth << 1);
+    
+#if REMOVE_NSQT
+    UInt nsAddr = uiAbsPartIdx;
+#else
+    UInt nsAddr = 0;
+    nsAddr = pcCU->getNSAbsPartIdx( uiLog2TrafoSize-1, uiAbsPartIdx, absTUPartIdx, 0, uiDepth - pcCU->getDepth( uiAbsPartIdx ) );
+#endif
+    xEncodeTransform( pcCU, offsetLuma, offsetChroma, uiAbsPartIdx, nsAddr, uiDepth, width, height, uiTrIdx, 0, bCodeDQP );
+
+    uiAbsPartIdx += partNum;  offsetLuma += size;  offsetChroma += (size>>2);
+#if REMOVE_NSQT
+    nsAddr = uiAbsPartIdx;
+#else
+    nsAddr = pcCU->getNSAbsPartIdx( uiLog2TrafoSize-1, uiAbsPartIdx, absTUPartIdx, 1, uiDepth - pcCU->getDepth( uiAbsPartIdx ) );
+#endif
+    xEncodeTransform( pcCU, offsetLuma, offsetChroma, uiAbsPartIdx, nsAddr, uiDepth, width, height, uiTrIdx, 1, bCodeDQP );
+
+    uiAbsPartIdx += partNum;  offsetLuma += size;  offsetChroma += (size>>2);
+#if REMOVE_NSQT
+    nsAddr = uiAbsPartIdx;
+#else
+    nsAddr = pcCU->getNSAbsPartIdx( uiLog2TrafoSize-1, uiAbsPartIdx, absTUPartIdx, 2, uiDepth - pcCU->getDepth( uiAbsPartIdx ) );
+#endif
+    xEncodeTransform( pcCU, offsetLuma, offsetChroma, uiAbsPartIdx, nsAddr, uiDepth, width, height, uiTrIdx, 2, bCodeDQP );
+
+    uiAbsPartIdx += partNum;  offsetLuma += size;  offsetChroma += (size>>2);
+#if REMOVE_NSQT
+    nsAddr = uiAbsPartIdx;
+#else
+    nsAddr = pcCU->getNSAbsPartIdx( uiLog2TrafoSize-1, uiAbsPartIdx, absTUPartIdx, 3, uiDepth - pcCU->getDepth( uiAbsPartIdx ) );
+#endif
+    xEncodeTransform( pcCU, offsetLuma, offsetChroma, uiAbsPartIdx, nsAddr, uiDepth, width, height, uiTrIdx, 3, bCodeDQP );
+  }
+  else
+  {
+    {
+      DTRACE_CABAC_VL( g_nSymbolCounter++ );
+      DTRACE_CABAC_T( "\tTrIdx: abspart=" );
+      DTRACE_CABAC_V( uiAbsPartIdx );
+      DTRACE_CABAC_T( "\tdepth=" );
+      DTRACE_CABAC_V( uiDepth );
+      DTRACE_CABAC_T( "\ttrdepth=" );
+      DTRACE_CABAC_V( pcCU->getTransformIdx( uiAbsPartIdx ) );
+      DTRACE_CABAC_T( "\n" );
+    }
+    UInt uiLumaTrMode, uiChromaTrMode;
+    pcCU->convertTransIdx( uiAbsPartIdx, pcCU->getTransformIdx( uiAbsPartIdx ), uiLumaTrMode, uiChromaTrMode );
+#if !REMOVE_NSQT
+    if(pcCU->getPredictionMode( uiAbsPartIdx ) == MODE_INTER && pcCU->useNonSquarePU( uiAbsPartIdx ) )
+    {
+      pcCU->setNSQTIdxSubParts( uiLog2TrafoSize, uiAbsPartIdx, absTUPartIdx, uiLumaTrMode );
+    }
+#endif
+#if INTRA_BL
+    if( ( !pcCU->isIntra( uiAbsPartIdx ) ) && uiDepth == pcCU->getDepth( uiAbsPartIdx ) && !pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, 0 ) && !pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, 0 ) )
+#else   
+    if( pcCU->getPredictionMode(uiAbsPartIdx) != MODE_INTRA && uiDepth == pcCU->getDepth( uiAbsPartIdx ) && !pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, 0 ) && !pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, 0 ) )
+#endif
+    {
+      assert( pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA, 0 ) );
+      //      printf( "saved one bin! " );
+    }
+    else
+    {
+      m_pcEntropyCoderIf->codeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA, uiLumaTrMode );
+    }
+
+
+    if ( cbfY || cbfU || cbfV )
+    {
+      // dQP: only for LCU once
+      if ( pcCU->getSlice()->getPPS()->getUseDQP() )
+      {
+        if ( bCodeDQP )
+        {
+          encodeQP( pcCU, m_bakAbsPartIdxCU );
+          bCodeDQP = false;
+        }
+      }
+    }
+    if( cbfY )
+    {
+      Int trWidth = width;
+      Int trHeight = height;
+#if !REMOVE_NSQT
+      pcCU->getNSQTSize( uiTrIdx, uiAbsPartIdx, trWidth, trHeight );
+#endif
+      m_pcEntropyCoderIf->codeCoeffNxN( pcCU, (pcCU->getCoeffY()+offsetLuma), uiAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_LUMA );
+    }
+    if( uiLog2TrafoSize > 2 )
+    {
+      Int trWidth = width >> 1;
+      Int trHeight = height >> 1;
+#if !REMOVE_NSQT
+      pcCU->getNSQTSize( uiTrIdx, uiAbsPartIdx, trWidth, trHeight );
+#endif
+      if( cbfU )
+      {
+        m_pcEntropyCoderIf->codeCoeffNxN( pcCU, (pcCU->getCoeffCb()+offsetChroma), uiAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_CHROMA_U );
+      }
+      if( cbfV )
+      {
+        m_pcEntropyCoderIf->codeCoeffNxN( pcCU, (pcCU->getCoeffCr()+offsetChroma), uiAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_CHROMA_V );
+      }
+    }
+    else
+    {
+      UInt partNum = pcCU->getPic()->getNumPartInCU() >> ( ( uiDepth - 1 ) << 1 );
+      if( ( uiAbsPartIdx % partNum ) == (partNum - 1) )
+      {
+        Int trWidth = width;
+        Int trHeight = height;
+#if !REMOVE_NSQT
+        pcCU->getNSQTSize( uiTrIdx - 1, uiAbsPartIdx, trWidth, trHeight );
+#endif
+        if( cbfU )
+        {
+          m_pcEntropyCoderIf->codeCoeffNxN( pcCU, (pcCU->getCoeffCb()+m_uiBakChromaOffset), m_uiBakAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_CHROMA_U );
+        }
+        if( cbfV )
+        {
+          m_pcEntropyCoderIf->codeCoeffNxN( pcCU, (pcCU->getCoeffCr()+m_uiBakChromaOffset), m_uiBakAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_CHROMA_V );
+        }
+      }
+    }
+  }
+}
+
+// Intra direction for Luma
+Void TEncEntropy::encodeIntraDirModeLuma  ( TComDataCU* pcCU, UInt absPartIdx, Bool isMultiplePU )
+{
+  m_pcEntropyCoderIf->codeIntraDirLumaAng( pcCU, absPartIdx , isMultiplePU);
+}
+
+// Intra direction for Chroma
+Void TEncEntropy::encodeIntraDirModeChroma( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
+{
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+  
+  m_pcEntropyCoderIf->codeIntraDirChroma( pcCU, uiAbsPartIdx );
+}
+
+Void TEncEntropy::encodePredInfo( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
+{
+#if INTRA_BL
+  assert ( !pcCU->isIntraBL( uiAbsPartIdx ) );
+#endif
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+  if( pcCU->isIntra( uiAbsPartIdx ) )                                 // If it is Intra mode, encode intra prediction mode.
+  {
+    encodeIntraDirModeLuma  ( pcCU, uiAbsPartIdx,true );
+    encodeIntraDirModeChroma( pcCU, uiAbsPartIdx, bRD );
+  }
+  else                                                                // if it is Inter mode, encode motion vector and reference index
+  {
+    encodePUWise( pcCU, uiAbsPartIdx, bRD );
+  }
+}
+
+/** encode motion information for every PU block
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param bRD
+ * \returns Void
+ */
+Void TEncEntropy::encodePUWise( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
+{
+  if ( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+  
+  PartSize ePartSize = pcCU->getPartitionSize( uiAbsPartIdx );
+  UInt uiNumPU = ( ePartSize == SIZE_2Nx2N ? 1 : ( ePartSize == SIZE_NxN ? 4 : 2 ) );
+  UInt uiDepth = pcCU->getDepth( uiAbsPartIdx );
+  UInt uiPUOffset = ( g_auiPUOffset[UInt( ePartSize )] << ( ( pcCU->getSlice()->getSPS()->getMaxCUDepth() - uiDepth ) << 1 ) ) >> 4;
+
+  for ( UInt uiPartIdx = 0, uiSubPartIdx = uiAbsPartIdx; uiPartIdx < uiNumPU; uiPartIdx++, uiSubPartIdx += uiPUOffset )
+  {
+    encodeMergeFlag( pcCU, uiSubPartIdx, uiPartIdx );
+    if ( pcCU->getMergeFlag( uiSubPartIdx ) )
+    {
+      encodeMergeIndex( pcCU, uiSubPartIdx, uiPartIdx );
+    }
+    else
+    {
+      encodeInterDirPU( pcCU, uiSubPartIdx );
+      for ( UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )
+      {
+        if ( pcCU->getSlice()->getNumRefIdx( RefPicList( uiRefListIdx ) ) > 0 )
+        {
+          encodeRefFrmIdxPU ( pcCU, uiSubPartIdx, RefPicList( uiRefListIdx ) );
+          encodeMvdPU       ( pcCU, uiSubPartIdx, RefPicList( uiRefListIdx ) );
+          encodeMVPIdxPU    ( pcCU, uiSubPartIdx, RefPicList( uiRefListIdx ) );
+        }
+      }
+    }
+  }
+
+  return;
+}
+
+Void TEncEntropy::encodeInterDirPU( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  if ( !pcCU->getSlice()->isInterB() )
+  {
+    return;
+  }
+
+  m_pcEntropyCoderIf->codeInterDir( pcCU, uiAbsPartIdx );
+  return;
+}
+
+/** encode reference frame index for a PU block
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param eRefList
+ * \returns Void
+ */
+Void TEncEntropy::encodeRefFrmIdxPU( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
+{
+  assert( !pcCU->isIntra( uiAbsPartIdx ) );
+  {
+    if ( ( pcCU->getSlice()->getNumRefIdx( eRefList ) == 1 ) )
+    {
+      return;
+    }
+
+    if ( pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList ) )
+    {
+      m_pcEntropyCoderIf->codeRefFrmIdx( pcCU, uiAbsPartIdx, eRefList );
+    }
+  }
+
+  return;
+}
+
+/** encode motion vector difference for a PU block
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param eRefList
+ * \returns Void
+ */
+Void TEncEntropy::encodeMvdPU( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
+{
+  assert( !pcCU->isIntra( uiAbsPartIdx ) );
+
+  if ( pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList ) )
+  {
+    m_pcEntropyCoderIf->codeMvd( pcCU, uiAbsPartIdx, eRefList );
+  }
+  return;
+}
+
+Void TEncEntropy::encodeMVPIdxPU( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
+{
+#if !SPS_AMVP_CLEANUP
+  if ( (pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList )) && (pcCU->getAMVPMode(uiAbsPartIdx) == AM_EXPL) )
+#else
+  if ( (pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList )) )
+#endif
+  {
+    m_pcEntropyCoderIf->codeMVPIdx( pcCU, uiAbsPartIdx, eRefList );
+  }
+
+  return;
+}
+
+Void TEncEntropy::encodeQtCbf( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth )
+{
+  m_pcEntropyCoderIf->codeQtCbf( pcCU, uiAbsPartIdx, eType, uiTrDepth );
+}
+
+Void TEncEntropy::encodeTransformSubdivFlag( UInt uiSymbol, UInt uiCtx )
+{
+  m_pcEntropyCoderIf->codeTransformSubdivFlag( uiSymbol, uiCtx );
+}
+
+Void TEncEntropy::encodeQtRootCbf( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  m_pcEntropyCoderIf->codeQtRootCbf( pcCU, uiAbsPartIdx );
+}
+
+#if TU_ZERO_CBF_RDO
+Void TEncEntropy::encodeQtCbfZero( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth )
+{
+  m_pcEntropyCoderIf->codeQtCbfZero( pcCU, uiAbsPartIdx, eType, uiTrDepth );
+}
+Void TEncEntropy::encodeQtRootCbfZero( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  m_pcEntropyCoderIf->codeQtRootCbfZero( pcCU, uiAbsPartIdx );
+}
+#endif
+
+// dQP
+Void TEncEntropy::encodeQP( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
+{
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+  
+  if ( pcCU->getSlice()->getPPS()->getUseDQP() )
+  {
+    m_pcEntropyCoderIf->codeDeltaQP( pcCU, uiAbsPartIdx );
+  }
+}
+
+
+// texture
+/** encode coefficients
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param uiDepth
+ * \param uiWidth
+ * \param uiHeight
+ */
+Void TEncEntropy::encodeCoeff( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiWidth, UInt uiHeight, Bool& bCodeDQP )
+{
+  UInt uiMinCoeffSize = pcCU->getPic()->getMinCUWidth()*pcCU->getPic()->getMinCUHeight();
+  UInt uiLumaOffset   = uiMinCoeffSize*uiAbsPartIdx;
+  UInt uiChromaOffset = uiLumaOffset>>2;
+  
+  UInt uiLumaTrMode, uiChromaTrMode;
+  pcCU->convertTransIdx( uiAbsPartIdx, pcCU->getTransformIdx(uiAbsPartIdx), uiLumaTrMode, uiChromaTrMode );
+  
+  if( pcCU->isIntra(uiAbsPartIdx) )
+  {
+    DTRACE_CABAC_VL( g_nSymbolCounter++ )
+    DTRACE_CABAC_T( "\tdecodeTransformIdx()\tCUDepth=" )
+    DTRACE_CABAC_V( uiDepth )
+    DTRACE_CABAC_T( "\n" )
+  }
+  else
+  {
+    if( !(pcCU->getMergeFlag( uiAbsPartIdx ) && pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_2Nx2N ) )
+    {
+      m_pcEntropyCoderIf->codeQtRootCbf( pcCU, uiAbsPartIdx );
+    }
+    if ( !pcCU->getQtRootCbf( uiAbsPartIdx ) )
+    {
+#if !REMOVE_NSQT
+      pcCU->setNSQTIdxSubParts( uiAbsPartIdx, uiDepth );
+#endif
+      return;
+    }
+  }
+  
+  xEncodeTransform( pcCU, uiLumaOffset, uiChromaOffset, uiAbsPartIdx, uiAbsPartIdx, uiDepth, uiWidth, uiHeight, 0, 0, bCodeDQP);
+}
+
+Void TEncEntropy::encodeCoeffNxN( TComDataCU* pcCU, TCoeff* pcCoeff, UInt uiAbsPartIdx, UInt uiTrWidth, UInt uiTrHeight, UInt uiDepth, TextType eType )
+{
+  // This is for Transform unit processing. This may be used at mode selection stage for Inter.
+  m_pcEntropyCoderIf->codeCoeffNxN( pcCU, pcCoeff, uiAbsPartIdx, uiTrWidth, uiTrHeight, uiDepth, eType );
+}
+
+Void TEncEntropy::estimateBit (estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType)
+{  
+  eTType = eTType == TEXT_LUMA ? TEXT_LUMA : TEXT_CHROMA;
+  
+  m_pcEntropyCoderIf->estBit ( pcEstBitsSbac, width, height, eTType );
+}
+
+/** Encode SAO Offset
+ * \param  saoLcuParam SAO LCU paramters
+ */
+#if SAO_TYPE_SHARING 
+Void TEncEntropy::encodeSaoOffset(SaoLcuParam* saoLcuParam, UInt compIdx)
+#else
+Void TEncEntropy::encodeSaoOffset(SaoLcuParam* saoLcuParam)
+#endif
+{
+  UInt uiSymbol;
+  Int i;
+
+  uiSymbol = saoLcuParam->typeIdx + 1;
+#if SAO_TYPE_SHARING
+  if (compIdx!=2)
+  {
+    m_pcEntropyCoderIf->codeSaoTypeIdx(uiSymbol);
+  }
+#else
+  m_pcEntropyCoderIf->codeSaoTypeIdx(uiSymbol);
+#endif
+  if (uiSymbol)
+  {
+#if SAO_TYPE_CODING
+#if SAO_TYPE_SHARING
+    if (saoLcuParam->typeIdx < 4 && compIdx != 2)
+#else
+    if (saoLcuParam->typeIdx < 4)
+#endif
+    {
+      saoLcuParam->subTypeIdx = saoLcuParam->typeIdx;
+    }
+#endif
+#if FULL_NBIT
+    Int offsetTh = 1 << ( min((Int)(g_uiBitDepth + (g_uiBitDepth-8)-5),5) );
+#else
+    Int offsetTh = 1 << ( min((Int)(g_uiBitDepth + g_uiBitIncrement-5),5) );
+#endif
+    if( saoLcuParam->typeIdx == SAO_BO )
+    {
+#if !SAO_TYPE_CODING
+      // Code Left Band Index
+      uiSymbol = (UInt) (saoLcuParam->bandPosition);
+      m_pcEntropyCoderIf->codeSaoUflc(uiSymbol);
+#endif
+      for( i=0; i< saoLcuParam->length; i++)
+      {
+        UInt absOffset = ( (saoLcuParam->offset[i] < 0) ? -saoLcuParam->offset[i] : saoLcuParam->offset[i]);
+        m_pcEntropyCoderIf->codeSaoMaxUvlc(absOffset, offsetTh-1);
+      }  
+      for( i=0; i< saoLcuParam->length; i++)
+      {
+        if (saoLcuParam->offset[i] != 0)
+        {
+          UInt sign = (saoLcuParam->offset[i] < 0) ? 1 : 0 ;
+          m_pcEntropyCoderIf->codeSAOSign(sign);
+        }
+      }
+#if SAO_TYPE_CODING
+      uiSymbol = (UInt) (saoLcuParam->subTypeIdx);
+      m_pcEntropyCoderIf->codeSaoUflc(5, uiSymbol);
+#endif
+    }
+    else if( saoLcuParam->typeIdx < 4 )
+    {
+      m_pcEntropyCoderIf->codeSaoMaxUvlc( saoLcuParam->offset[0], offsetTh-1);
+      m_pcEntropyCoderIf->codeSaoMaxUvlc( saoLcuParam->offset[1], offsetTh-1);
+      m_pcEntropyCoderIf->codeSaoMaxUvlc(-saoLcuParam->offset[2], offsetTh-1);
+      m_pcEntropyCoderIf->codeSaoMaxUvlc(-saoLcuParam->offset[3], offsetTh-1);
+#if SAO_TYPE_CODING
+#if SAO_TYPE_SHARING
+      if (compIdx!=2)
+      {
+        uiSymbol = (UInt) (saoLcuParam->subTypeIdx);
+        m_pcEntropyCoderIf->codeSaoUflc(2, uiSymbol);
+      }
+#else
+     uiSymbol = (UInt) (saoLcuParam->subTypeIdx);
+     m_pcEntropyCoderIf->codeSaoUflc(2, uiSymbol);
+#endif
+#endif
+    }
+  }
+}
+
+/** Encode SAO unit interleaving
+* \param  rx
+* \param  ry
+* \param  pSaoParam
+* \param  pcCU
+* \param  iCUAddrInSlice
+* \param  iCUAddrUpInSlice
+* \param  bLFCrossSliceBoundaryFlag
+ */
+Void TEncEntropy::encodeSaoUnitInterleaving(Int compIdx, Bool saoFlag, Int rx, Int ry, SaoLcuParam* saoLcuParam, Int cuAddrInSlice, Int cuAddrUpInSlice, Int allowMergeLeft, Int allowMergeUp)
+{
+  if (saoFlag)
+  {
+    if (rx>0 && cuAddrInSlice!=0 && allowMergeLeft)
+    {
+#if SAO_MERGE_ONE_CTX
+      m_pcEntropyCoderIf->codeSaoMerge(saoLcuParam->mergeLeftFlag);
+#else
+      m_pcEntropyCoderIf->codeSaoMergeLeft(saoLcuParam->mergeLeftFlag,compIdx);
+#endif
+    }
+    else
+    {
+      saoLcuParam->mergeLeftFlag = 0;
+    }
+    if (saoLcuParam->mergeLeftFlag == 0)
+    {
+      if ( (ry > 0) && (cuAddrUpInSlice>=0) && allowMergeUp )
+      {
+#if SAO_MERGE_ONE_CTX
+        m_pcEntropyCoderIf->codeSaoMerge(saoLcuParam->mergeUpFlag);
+#else
+        m_pcEntropyCoderIf->codeSaoMergeUp(saoLcuParam->mergeUpFlag);
+#endif
+      }
+      else
+      {
+        saoLcuParam->mergeUpFlag = 0;
+      }
+      if (!saoLcuParam->mergeUpFlag)
+      {
+#if SAO_TYPE_SHARING 
+        encodeSaoOffset(saoLcuParam, compIdx);
+#else
+        encodeSaoOffset(saoLcuParam);
+#endif
+      }
+    }
+  }
+}
+
+Int TEncEntropy::countNonZeroCoeffs( TCoeff* pcCoef, UInt uiSize )
+{
+  Int count = 0;
+  
+  for ( Int i = 0; i < uiSize; i++ )
+  {
+    count += pcCoef[i] != 0;
+  }
+  
+  return count;
+}
+
+/** encode quantization matrix
+ * \param scalingList quantization matrix information
+ */
+Void TEncEntropy::encodeScalingList( TComScalingList* scalingList )
+{
+  m_pcEntropyCoderIf->codeScalingList( scalingList );
+}
+
+//! \}
Index: /trunk/source/Lib/TLibEncoder/TEncEntropy.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncEntropy.h	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/TEncEntropy.h	(revision 2)
@@ -0,0 +1,264 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncEntropy.h
+    \brief    entropy encoder class (header)
+*/
+
+#ifndef __TENCENTROPY__
+#define __TENCENTROPY__
+
+#include "TLibCommon/TComSlice.h"
+#include "TLibCommon/TComDataCU.h"
+#include "TLibCommon/TComBitStream.h"
+#include "TLibCommon/ContextModel.h"
+#include "TLibCommon/TComPic.h"
+#include "TLibCommon/TComTrQuant.h"
+#include "TLibCommon/TComAdaptiveLoopFilter.h"
+#include "TLibCommon/TComSampleAdaptiveOffset.h"
+
+class TEncSbac;
+class TEncCavlc;
+class SEI;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// entropy encoder pure class
+class TEncEntropyIf
+{
+public:
+  virtual Void  resetEntropy          ()                = 0;
+  virtual Void  determineCabacInitIdx ()                = 0;
+  virtual Void  setBitstream          ( TComBitIf* p )  = 0;
+  virtual Void  setSlice              ( TComSlice* p )  = 0;
+  virtual Void  resetBits             ()                = 0;
+  virtual Void  resetCoeffCost        ()                = 0;
+  virtual UInt  getNumberOfWrittenBits()                = 0;
+  virtual UInt  getCoeffCost          ()                = 0;
+
+  virtual Void  codeVPS                 ( TComVPS* pcVPS )                                      = 0;
+  virtual Void  codeSPS                 ( TComSPS* pcSPS )                                      = 0;
+  virtual Void  codePPS                 ( TComPPS* pcPPS )                                      = 0;
+  virtual Void  codeSliceHeader         ( TComSlice* pcSlice )                                  = 0;
+
+  virtual Void  codeTilesWPPEntryPoint  ( TComSlice* pSlice )     = 0;
+  virtual Void  codeTerminatingBit      ( UInt uilsLast )                                       = 0;
+  virtual Void  codeSliceFinish         ()                                                      = 0;
+  virtual Void  codeFlush               ()                                                      = 0;
+  virtual Void  encodeStart             ()                                                      = 0;
+  virtual Void codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList ) = 0;
+  virtual Void codeScalingList   ( TComScalingList* scalingList )      = 0;
+  
+public:
+#if !REMOVE_ALF
+  virtual Void codeAlfCtrlFlag   ( Int compIdx, UInt code ) = 0;
+#endif
+  virtual Void codeApsExtensionFlag () = 0;
+  
+  virtual Void codeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+  virtual Void codeSkipFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+  virtual Void codeMergeFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+  virtual Void codeMergeIndex    ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+  virtual Void codeSplitFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+  
+#if INTRA_BL
+  virtual Void codeIntraBLFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+#endif
+  virtual Void codePartSize      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+  virtual Void codePredMode      ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+  
+  virtual Void codeIPCMInfo      ( TComDataCU* pcCU, UInt uiAbsPartIdx, Int numIPCM, Bool firstIPCMFlag) = 0;
+
+  virtual Void codeTransformSubdivFlag( UInt uiSymbol, UInt uiCtx ) = 0;
+  virtual Void codeQtCbf         ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth ) = 0;
+  virtual Void codeQtRootCbf     ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+#if TU_ZERO_CBF_RDO
+  virtual Void codeQtCbfZero     ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth ) = 0;
+  virtual Void codeQtRootCbfZero ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+#endif
+  virtual Void codeIntraDirLumaAng( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool isMultiplePU ) = 0;
+  
+  virtual Void codeIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+  virtual Void codeInterDir      ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+  virtual Void codeRefFrmIdx     ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )      = 0;
+  virtual Void codeMvd           ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )      = 0;
+  virtual Void codeDeltaQP       ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+  virtual Void codeCoeffNxN      ( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType ) = 0;
+  virtual Void codeTransformSkipFlags ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, UInt uiDepth, TextType eTType ) = 0;
+#if !REMOVE_ALF
+  virtual Void codeAlfParam      (ALFParam* alfParam) = 0;
+#endif
+#if !REMOVE_FGS
+  /// set slice granularity
+  virtual Void setSliceGranularity(Int iSliceGranularity) = 0;
+
+  /// get slice granularity
+  virtual Int  getSliceGranularity()                      = 0;
+#endif
+  virtual Void codeSAOSign          ( UInt code   ) = 0;
+  virtual Void codeSaoMaxUvlc       ( UInt code, UInt maxSymbol ) = 0;
+#if SAO_MERGE_ONE_CTX
+  virtual Void codeSaoMerge    ( UInt   uiCode  ) = 0;
+#else
+  virtual Void codeSaoMergeLeft    ( UInt   uiCode, UInt uiCompIdx  ) = 0;
+  virtual Void codeSaoMergeUp      ( UInt   uiCode) = 0;
+#endif
+  virtual Void codeSaoTypeIdx      ( UInt   uiCode) = 0;
+#if SAO_TYPE_CODING
+  virtual Void codeSaoUflc         ( UInt uiLength, UInt   uiCode ) = 0;
+#else
+  virtual Void codeSaoUflc         ( UInt   uiCode) = 0;
+#endif
+  virtual Void estBit               (estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType) = 0;
+  
+  virtual Void updateContextTables ( SliceType eSliceType, Int iQp, Bool bExecuteFinish )   = 0;
+  virtual Void updateContextTables ( SliceType eSliceType, Int iQp )   = 0;
+
+#if !REMOVE_APS
+  virtual Void codeAPSInitInfo  (TComAPS* pcAPS)= 0;
+#endif
+  virtual Void codeFinish       (Bool bEnd)= 0;
+
+  virtual Void codeDFFlag (UInt uiCode, const Char *pSymbolName) = 0;
+  virtual Void codeDFSvlc (Int iCode, const Char *pSymbolName)   = 0;
+
+  virtual ~TEncEntropyIf() {}
+
+};
+
+/// entropy encoder class
+class TEncEntropy
+{
+private:
+  UInt    m_uiBakAbsPartIdx;
+  UInt    m_uiBakChromaOffset;
+  UInt    m_bakAbsPartIdxCU;
+
+public:
+  Void    setEntropyCoder           ( TEncEntropyIf* e, TComSlice* pcSlice );
+  Void    setBitstream              ( TComBitIf* p )          { m_pcEntropyCoderIf->setBitstream(p);  }
+  Void    resetBits                 ()                        { m_pcEntropyCoderIf->resetBits();      }
+  Void    resetCoeffCost            ()                        { m_pcEntropyCoderIf->resetCoeffCost(); }
+  UInt    getNumberOfWrittenBits    ()                        { return m_pcEntropyCoderIf->getNumberOfWrittenBits(); }
+  UInt    getCoeffCost              ()                        { return  m_pcEntropyCoderIf->getCoeffCost(); }
+  Void    resetEntropy              ()                        { m_pcEntropyCoderIf->resetEntropy();  }
+  Void    determineCabacInitIdx     ()                        { m_pcEntropyCoderIf->determineCabacInitIdx(); }
+  
+  Void    encodeSliceHeader         ( TComSlice* pcSlice );
+  Void    encodeTilesWPPEntryPoint( TComSlice* pSlice );
+  Void    encodeTerminatingBit      ( UInt uiIsLast );
+  Void    encodeSliceFinish         ();
+  Void    encodeFlush               ();
+  Void    encodeStart               ();
+#if !REMOVE_ALF
+  Void encodeAlfParam(ALFParam* alfParam) {m_pcEntropyCoderIf->codeAlfParam(alfParam);}
+#endif
+  TEncEntropyIf*      m_pcEntropyCoderIf;
+  
+public:
+  Void encodeVPS               ( TComVPS* pcVPS);
+  // SPS
+  Void encodeSPS               ( TComSPS* pcSPS );
+  Void encodePPS               ( TComPPS* pcPPS );
+  Void encodeSplitFlag         ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, Bool bRD = false );
+  Void encodeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
+  Void encodeSkipFlag          ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
+  Void encodePUWise       ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
+  Void encodeInterDirPU   ( TComDataCU* pcSubCU, UInt uiAbsPartIdx  );
+  Void encodeRefFrmIdxPU  ( TComDataCU* pcSubCU, UInt uiAbsPartIdx, RefPicList eRefList );
+  Void encodeMvdPU        ( TComDataCU* pcSubCU, UInt uiAbsPartIdx, RefPicList eRefList );
+  Void encodeMVPIdxPU     ( TComDataCU* pcSubCU, UInt uiAbsPartIdx, RefPicList eRefList );
+  Void encodeMergeFlag    ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiPUIdx );
+  Void encodeMergeIndex   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiPUIdx, Bool bRD = false );
+
+#if INTRA_BL
+  Void encodeIntraBLFlag  ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
+#endif
+#if !REMOVE_FGS
+  /// set slice granularity
+  Void setSliceGranularity (Int iSliceGranularity) {m_pcEntropyCoderIf->setSliceGranularity(iSliceGranularity);}
+#endif
+#if !REMOVE_ALF
+  /// encode ALF LCU control flag
+  Void encodeAlfCtrlFlag( Int compIdx, UInt code ) {m_pcEntropyCoderIf->codeAlfCtrlFlag(compIdx, code);}
+#endif
+  Void encodeApsExtensionFlag() {m_pcEntropyCoderIf->codeApsExtensionFlag();};
+  Void encodePredMode          ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
+  Void encodePartSize          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, Bool bRD = false );
+  Void encodeIPCMInfo          ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
+  Void encodePredInfo          ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
+  Void encodeIntraDirModeLuma  ( TComDataCU* pcCU, UInt absPartIdx, Bool isMultiplePU = false );
+  
+  Void encodeIntraDirModeChroma( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
+  
+  Void encodeTransformSubdivFlag( UInt uiSymbol, UInt uiCtx );
+  Void encodeQtCbf             ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth );
+#if TU_ZERO_CBF_RDO
+  Void encodeQtCbfZero         ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth );
+  Void encodeQtRootCbfZero     ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#endif
+  Void encodeQtRootCbf         ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void encodeQP                ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
+  Void updateContextTables     ( SliceType eSliceType, Int iQp, Bool bExecuteFinish )   { m_pcEntropyCoderIf->updateContextTables( eSliceType, iQp, bExecuteFinish );     }
+  Void updateContextTables     ( SliceType eSliceType, Int iQp )                        { m_pcEntropyCoderIf->updateContextTables( eSliceType, iQp, true );               }
+
+#if !REMOVE_APS
+  Void encodeAPSInitInfo          (TComAPS* pcAPS) {m_pcEntropyCoderIf->codeAPSInitInfo(pcAPS);}
+#endif
+  Void encodeFinish               (Bool bEnd) {m_pcEntropyCoderIf->codeFinish(bEnd);}
+  Void encodeScalingList       ( TComScalingList* scalingList );
+
+private:
+  Void xEncodeTransform        ( TComDataCU* pcCU,UInt offsetLumaOffset, UInt offsetChroma, UInt uiAbsPartIdx, UInt absTUPartIdx, UInt uiDepth, UInt width, UInt height, UInt uiTrIdx, UInt uiInnerQuadIdx,Bool& bCodeDQP );
+public:
+  Void encodeCoeff             ( TComDataCU* pcCU,                 UInt uiAbsPartIdx, UInt uiDepth, UInt uiWidth, UInt uiHeight, Bool& bCodeDQP );
+  
+  Void encodeCoeffNxN         ( TComDataCU* pcCU, TCoeff* pcCoeff, UInt uiAbsPartIdx, UInt uiTrWidth, UInt uiTrHeight, UInt uiDepth, TextType eType );
+  
+  Void estimateBit             ( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType);
+#if SAO_TYPE_SHARING 
+  Void    encodeSaoOffset(SaoLcuParam* saoLcuParam, UInt compIdx);
+#else
+  Void    encodeSaoOffset(SaoLcuParam* saoLcuParam);
+#endif
+  Void    encodeSaoUnitInterleaving(Int compIdx, Bool saoFlag, Int rx, Int ry, SaoLcuParam* saoLcuParam, Int cuAddrInSlice, Int cuAddrUpInSlice, Int allowMergeLeft, Int allowMergeUp);
+  static Int countNonZeroCoeffs( TCoeff* pcCoef, UInt uiSize );
+
+};// END CLASS DEFINITION TEncEntropy
+
+//! \}
+
+#endif // __TENCENTROPY__
+
Index: /trunk/source/Lib/TLibEncoder/TEncGOP.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 2)
@@ -0,0 +1,2470 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncGOP.cpp
+    \brief    GOP encoder class
+*/
+
+#include <list>
+#include <algorithm>
+#include <functional>
+
+#include "TEncTop.h"
+#include "TEncGOP.h"
+#include "TEncAnalyze.h"
+#include "libmd5/MD5.h"
+#include "TLibCommon/SEI.h"
+#include "TLibCommon/NAL.h"
+#include "NALwrite.h"
+#include <time.h>
+#include <math.h>
+
+using namespace std;
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+Int getLSB(Int poc, Int maxLSB)
+{
+  if (poc >= 0)
+  {
+    return poc % maxLSB;
+  }
+  else
+  {
+    return (maxLSB - ((-poc) % maxLSB)) % maxLSB;
+  }
+}
+
+TEncGOP::TEncGOP()
+{
+  m_iLastIDR            = 0;
+  m_iGopSize            = 0;
+  m_iNumPicCoded        = 0; //Niko
+  m_bFirst              = true;
+  
+  m_pcCfg               = NULL;
+  m_pcSliceEncoder      = NULL;
+  m_pcListPic           = NULL;
+  
+  m_pcEntropyCoder      = NULL;
+  m_pcCavlcCoder        = NULL;
+  m_pcSbacCoder         = NULL;
+  m_pcBinCABAC          = NULL;
+  
+  m_bSeqFirst           = true;
+  
+  m_bRefreshPending     = 0;
+  m_pocCRA            = 0;
+#if LTRP_IN_SPS
+  m_numLongTermRefPicSPS = 0;
+  ::memset(m_ltRefPicPocLsbSps, 0, sizeof(m_ltRefPicPocLsbSps));
+  ::memset(m_ltRefPicUsedByCurrPicFlag, 0, sizeof(m_ltRefPicUsedByCurrPicFlag));
+#endif
+#if BUFFERING_PERIOD_AND_TIMING_SEI
+  m_cpbRemovalDelay   = 0;
+  m_lastBPSEI         = 0;
+#endif
+
+#if SVC_UPSAMPLING
+  m_pcPredSearch        = NULL;
+#endif
+  return;
+}
+
+TEncGOP::~TEncGOP()
+{
+}
+
+/** Create list to contain pointers to LCU start addresses of slice.
+ * \param iWidth, iHeight are picture width, height. iMaxCUWidth, iMaxCUHeight are LCU width, height.
+ */
+#if SVC_EXTENSION
+Void  TEncGOP::create( Int iWidth, Int iHeight, UInt iMaxCUWidth, UInt iMaxCUHeight, UInt layerId )
+#else
+Void  TEncGOP::create( Int iWidth, Int iHeight, UInt iMaxCUWidth, UInt iMaxCUHeight )
+#endif
+{
+  m_bLongtermTestPictureHasBeenCoded = 0;
+  m_bLongtermTestPictureHasBeenCoded2 = 0;
+
+#if SVC_EXTENSION
+  m_layerId = layerId;
+#endif
+}
+
+Void  TEncGOP::destroy()
+{
+}
+
+Void TEncGOP::init ( TEncTop* pcTEncTop )
+{
+  m_pcEncTop     = pcTEncTop;
+  m_pcCfg                = pcTEncTop;
+  m_pcSliceEncoder       = pcTEncTop->getSliceEncoder();
+  m_pcListPic            = pcTEncTop->getListPic();
+
+#if SVC_EXTENSION
+  m_ppcTEncTop           = pcTEncTop->getLayerEnc();
+#endif
+  
+  m_pcEntropyCoder       = pcTEncTop->getEntropyCoder();
+  m_pcCavlcCoder         = pcTEncTop->getCavlcCoder();
+  m_pcSbacCoder          = pcTEncTop->getSbacCoder();
+  m_pcBinCABAC           = pcTEncTop->getBinCABAC();
+  m_pcLoopFilter         = pcTEncTop->getLoopFilter();
+  m_pcBitCounter         = pcTEncTop->getBitCounter();
+  
+#if !REMOVE_ALF
+  // Adaptive Loop filter
+  m_pcAdaptiveLoopFilter = pcTEncTop->getAdaptiveLoopFilter();
+#endif
+  //--Adaptive Loop filter
+  m_pcSAO                = pcTEncTop->getSAO();
+  m_pcRateCtrl           = pcTEncTop->getRateCtrl();
+#if BUFFERING_PERIOD_AND_TIMING_SEI
+  m_lastBPSEI          = 0;
+  m_totalCoded         = 0;
+#endif
+
+#if SVC_UPSAMPLING
+  m_pcPredSearch         = pcTEncTop->getPredSearch();                       ///< encoder search class
+#endif
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+#if SVC_EXTENSION
+Void TEncGOP::compressGOP( Int iPicIdInGOP, Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP)
+#else
+Void TEncGOP::compressGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP)
+#endif
+{
+  TComPic*        pcPic;
+  TComPicYuv*     pcPicYuvRecOut;
+  TComSlice*      pcSlice;
+  TComOutputBitstream  *pcBitstreamRedirect;
+  pcBitstreamRedirect = new TComOutputBitstream;
+  AccessUnit::iterator  itLocationToPushSliceHeaderNALU; // used to store location where NALU containing slice header is to be inserted
+  UInt                  uiOneBitstreamPerSliceLength = 0;
+  TEncSbac* pcSbacCoders = NULL;
+  TComOutputBitstream* pcSubstreamsOut = NULL;
+
+  xInitGOP( iPOCLast, iNumPicRcvd, rcListPic, rcListPicYuvRecOut );
+
+  m_iNumPicCoded = 0;
+#if BUFFERING_PERIOD_AND_TIMING_SEI
+  SEIPictureTiming pictureTimingSEI;
+  UInt *accumBitsDU = NULL;
+  UInt *accumNalsDU = NULL;
+#endif
+#if SVC_EXTENSION
+  for ( Int iGOPid=iPicIdInGOP; iGOPid < iPicIdInGOP+1; iGOPid++ )
+#else
+  for ( Int iGOPid=0; iGOPid < m_iGopSize; iGOPid++ )
+#endif
+  {
+    UInt uiColDir = 1;
+    //-- For time output for each slice
+    long iBeforeTime = clock();
+
+    //select uiColDir
+    Int iCloseLeft=1, iCloseRight=-1;
+    for(Int i = 0; i<m_pcCfg->getGOPEntry(iGOPid).m_numRefPics; i++) 
+    {
+      Int iRef = m_pcCfg->getGOPEntry(iGOPid).m_referencePics[i];
+      if(iRef>0&&(iRef<iCloseRight||iCloseRight==-1))
+      {
+        iCloseRight=iRef;
+      }
+      else if(iRef<0&&(iRef>iCloseLeft||iCloseLeft==1))
+      {
+        iCloseLeft=iRef;
+      }
+    }
+    if(iCloseRight>-1)
+    {
+      iCloseRight=iCloseRight+m_pcCfg->getGOPEntry(iGOPid).m_POC-1;
+    }
+    if(iCloseLeft<1) 
+    {
+      iCloseLeft=iCloseLeft+m_pcCfg->getGOPEntry(iGOPid).m_POC-1;
+      while(iCloseLeft<0)
+      {
+        iCloseLeft+=m_iGopSize;
+      }
+    }
+    Int iLeftQP=0, iRightQP=0;
+    for(Int i=0; i<m_iGopSize; i++)
+    {
+      if(m_pcCfg->getGOPEntry(i).m_POC==(iCloseLeft%m_iGopSize)+1)
+      {
+        iLeftQP= m_pcCfg->getGOPEntry(i).m_QPOffset;
+      }
+      if (m_pcCfg->getGOPEntry(i).m_POC==(iCloseRight%m_iGopSize)+1)
+      {
+        iRightQP=m_pcCfg->getGOPEntry(i).m_QPOffset;
+      }
+    }
+    if(iCloseRight>-1&&iRightQP<iLeftQP)
+    {
+      uiColDir=0;
+    }
+
+    /////////////////////////////////////////////////////////////////////////////////////////////////// Initial to start encoding
+    UInt uiPOCCurr = iPOCLast -iNumPicRcvd+ m_pcCfg->getGOPEntry(iGOPid).m_POC;
+    Int iTimeOffset = m_pcCfg->getGOPEntry(iGOPid).m_POC;
+    if(iPOCLast == 0)
+    {
+      uiPOCCurr=0;
+      iTimeOffset = 1;
+    }
+    if(uiPOCCurr>=m_pcCfg->getFrameToBeEncoded())
+    {
+      continue;
+    }
+
+#if SUPPORT_FOR_RAP_N_LP
+    if( getNalUnitType(uiPOCCurr) == NAL_UNIT_CODED_SLICE_IDR || getNalUnitType(uiPOCCurr) == NAL_UNIT_CODED_SLICE_IDR_N_LP )
+#else
+    if(getNalUnitType(uiPOCCurr) == NAL_UNIT_CODED_SLICE_IDR)
+#endif
+    {
+      m_iLastIDR = uiPOCCurr;
+    }        
+    // start a new access unit: create an entry in the list of output access units
+    accessUnitsInGOP.push_back(AccessUnit());
+    AccessUnit& accessUnit = accessUnitsInGOP.back();
+    xGetBuffer( rcListPic, rcListPicYuvRecOut, iNumPicRcvd, iTimeOffset, pcPic, pcPicYuvRecOut, uiPOCCurr );
+
+    //  Slice data initialization
+    pcPic->clearSliceBuffer();
+    assert(pcPic->getNumAllocatedSlice() == 1);
+    m_pcSliceEncoder->setSliceIdx(0);
+    pcPic->setCurrSliceIdx(0);
+#if SVC_EXTENSION
+      pcPic->setLayerId( m_layerId );
+#endif
+
+#if !REMOVE_APS
+    std::vector<TComAPS>& vAPS = m_pcEncTop->getAPS();
+#endif
+    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, uiPOCCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getSPS(), m_pcEncTop->getPPS() );
+    pcSlice->setLastIDR(m_iLastIDR);
+    pcSlice->setSliceIdx(0);
+    //set default slice level flag to the same as SPS level flag
+#if MOVE_LOOP_FILTER_SLICES_FLAG
+    pcSlice->setLFCrossSliceBoundaryFlag(  pcSlice->getPPS()->getLoopFilterAcrossSlicesEnabledFlag()  );
+#else
+    pcSlice->setLFCrossSliceBoundaryFlag(  pcSlice->getSPS()->getLFCrossSliceBoundaryFlag()  );
+#endif
+    pcSlice->setScalingList ( m_pcEncTop->getScalingList()  );
+#if TS_FLAT_QUANTIZATION_MATRIX
+    pcSlice->getScalingList()->setUseTransformSkip(m_pcEncTop->getPPS()->getUseTransformSkip());
+#endif
+    if(m_pcEncTop->getUseScalingListId() == SCALING_LIST_OFF)
+    {
+      m_pcEncTop->getTrQuant()->setFlatScalingList();
+      m_pcEncTop->getTrQuant()->setUseScalingList(false);
+      m_pcEncTop->getSPS()->setScalingListPresentFlag(false);
+      m_pcEncTop->getPPS()->setScalingListPresentFlag(false);
+    }
+    else if(m_pcEncTop->getUseScalingListId() == SCALING_LIST_DEFAULT)
+    {
+      pcSlice->setDefaultScalingList ();
+      m_pcEncTop->getSPS()->setScalingListPresentFlag(false);
+      m_pcEncTop->getPPS()->setScalingListPresentFlag(false);
+      m_pcEncTop->getTrQuant()->setScalingList(pcSlice->getScalingList());
+      m_pcEncTop->getTrQuant()->setUseScalingList(true);
+    }
+    else if(m_pcEncTop->getUseScalingListId() == SCALING_LIST_FILE_READ)
+    {
+      if(pcSlice->getScalingList()->xParseScalingList(m_pcCfg->getScalingListFile()))
+      {
+        pcSlice->setDefaultScalingList ();
+      }
+      pcSlice->getScalingList()->checkDcOfMatrix();
+      m_pcEncTop->getSPS()->setScalingListPresentFlag(pcSlice->checkDefaultScalingList());
+      m_pcEncTop->getPPS()->setScalingListPresentFlag(false);
+      m_pcEncTop->getTrQuant()->setScalingList(pcSlice->getScalingList());
+      m_pcEncTop->getTrQuant()->setUseScalingList(true);
+    }
+    else
+    {
+      printf("error : ScalingList == %d no support\n",m_pcEncTop->getUseScalingListId());
+      assert(0);
+    }
+
+    if(pcSlice->getSliceType()==B_SLICE&&m_pcCfg->getGOPEntry(iGOPid).m_sliceType=='P')
+    {
+      pcSlice->setSliceType(P_SLICE);
+    }
+
+    // Set the nal unit type
+    pcSlice->setNalUnitType(getNalUnitType(uiPOCCurr));
+#if REF_IDX_FRAMEWORK
+    if (m_layerId > 0 && (uiPOCCurr % m_pcCfg->getIntraPeriod() == 0))
+      pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_CRA);
+    if( m_layerId > 0 && !m_pcEncTop->getElRapSliceTypeB() )
+    {
+      if( (pcSlice->getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA) &&
+          (pcSlice->getNalUnitType() <= NAL_UNIT_CODED_SLICE_CRA) &&
+           pcSlice->getSliceType() == B_SLICE ) 
+        pcSlice->setSliceType(P_SLICE);
+    }
+#endif
+#if TEMPORAL_LAYER_NON_REFERENCE
+    if(pcSlice->getNalUnitType()==NAL_UNIT_CODED_SLICE_TRAIL_R)
+    {
+      if(pcSlice->getTemporalLayerNonReferenceFlag())
+      {
+        pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TRAIL_N);
+      }
+    }
+#endif
+
+    // Do decoding refresh marking if any 
+    pcSlice->decodingRefreshMarking(m_pocCRA, m_bRefreshPending, rcListPic);
+    m_pcEncTop->selectReferencePictureSet(pcSlice, uiPOCCurr, iGOPid,rcListPic);
+    pcSlice->getRPS()->setNumberOfLongtermPictures(0);
+
+    if(pcSlice->checkThatAllRefPicsAreAvailable(rcListPic, pcSlice->getRPS(), false) != 0)
+    {
+      pcSlice->createExplicitReferencePictureSetFromReference(rcListPic, pcSlice->getRPS());
+    }
+    pcSlice->applyReferencePictureSet(rcListPic, pcSlice->getRPS());
+
+    if(pcSlice->getTLayer() > 0)
+    {
+      if(pcSlice->isTemporalLayerSwitchingPoint(rcListPic, pcSlice->getRPS()) || pcSlice->getSPS()->getTemporalIdNestingFlag())
+      {
+#if TEMPORAL_LAYER_NON_REFERENCE
+        if(pcSlice->getTemporalLayerNonReferenceFlag())
+        {
+          pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TSA_N);
+        }
+        else
+        {
+          pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TLA);
+        }
+#else
+        pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TLA);
+#endif
+      }
+#if STSA
+      else if(pcSlice->isStepwiseTemporalLayerSwitchingPointCandidate(rcListPic, pcSlice->getRPS()))
+      {
+          Bool isSTSA=true;
+          for(Int ii=iGOPid+1;(ii<m_pcCfg->getGOPSize() && isSTSA==true);ii++)
+          {
+              Int lTid= m_pcCfg->getGOPEntry(ii).m_temporalId;
+              if(lTid==pcSlice->getTLayer()) 
+              {
+                  TComReferencePictureSet* nRPS = pcSlice->getSPS()->getRPSList()->getReferencePictureSet(ii);
+                  for(Int jj=0;jj<nRPS->getNumberOfPictures();jj++)
+                  {
+                      if(nRPS->getUsed(jj)) {
+                          Int tPoc=m_pcCfg->getGOPEntry(ii).m_POC+nRPS->getDeltaPOC(jj);
+                          Int kk=0;
+                          for(kk=0;kk<m_pcCfg->getGOPSize();kk++)
+                          {
+                              if(m_pcCfg->getGOPEntry(kk).m_POC==tPoc)
+                                  break;
+                          }
+                          Int tTid=m_pcCfg->getGOPEntry(kk).m_temporalId;
+                          if(tTid >= pcSlice->getTLayer())
+                          {
+                              isSTSA=false;
+                              break;
+                          }
+                          
+                      }
+                  }
+              }
+          }
+          if(isSTSA==true)
+          {    
+#if TEMPORAL_LAYER_NON_REFERENCE
+            if(pcSlice->getTemporalLayerNonReferenceFlag())
+            {
+              pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_STSA_N);
+            }
+            else
+            {
+              pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_STSA_R);
+            }
+#else
+            pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_STSA_R);
+#endif
+          }
+      }
+#endif
+
+    }
+    arrangeLongtermPicturesInRPS(pcSlice, rcListPic);
+    TComRefPicListModification* refPicListModification = pcSlice->getRefPicListModification();
+    refPicListModification->setRefPicListModificationFlagL0(0);
+    refPicListModification->setRefPicListModificationFlagL1(0);
+    pcSlice->setNumRefIdx(REF_PIC_LIST_0,min(m_pcCfg->getGOPEntry(iGOPid).m_numRefPicsActive,pcSlice->getRPS()->getNumberOfPictures()));
+    pcSlice->setNumRefIdx(REF_PIC_LIST_1,min(m_pcCfg->getGOPEntry(iGOPid).m_numRefPicsActive,pcSlice->getRPS()->getNumberOfPictures()));
+
+#if ADAPTIVE_QP_SELECTION
+    pcSlice->setTrQuant( m_pcEncTop->getTrQuant() );
+#endif      
+
+#if SVC_EXTENSION      
+      if(m_layerId > 0)
+      {
+        TComList<TComPic*> *cListPic = m_ppcTEncTop[m_layerId-1]->getListPic();
+        pcSlice->setBaseColPic (*cListPic, m_layerId );
+#if SVC_UPSAMPLING
+        if ( pcPic->isSpatialEnhLayer())
+        {    
+          m_pcPredSearch->upsampleBasePic( pcPic->getFullPelBaseRec(), pcSlice->getBaseColPic()->getPicYuvRec(), pcPic->getPicYuvRec() );
+        }
+        else
+        {
+        pcPic->setFullPelBaseRec( pcSlice->getBaseColPic()->getPicYuvRec() );
+        }
+        pcSlice->setFullPelBaseRec ( pcPic->getFullPelBaseRec() );
+#endif
+      }
+#endif 
+
+    //  Set reference list
+    pcSlice->setRefPicList ( rcListPic );
+#if REF_IDX_FRAMEWORK
+    if(m_layerId > 0)
+    {
+      m_pcEncTop->setILRPic(pcPic);
+      pcSlice->addRefPicList ( m_pcEncTop->getIlpList(), 1);
+    }
+#endif
+
+    //  Slice info. refinement
+    if ( (pcSlice->getSliceType() == B_SLICE) && (pcSlice->getNumRefIdx(REF_PIC_LIST_1) == 0) )
+    {
+      pcSlice->setSliceType ( P_SLICE );
+    }
+
+    if (pcSlice->getSliceType() != B_SLICE || !pcSlice->getSPS()->getUseLComb())
+    {
+      pcSlice->setNumRefIdx(REF_PIC_LIST_C, 0);
+      pcSlice->setRefPicListCombinationFlag(false);
+      pcSlice->setRefPicListModificationFlagLC(false);
+    }
+    else
+    {
+      pcSlice->setRefPicListCombinationFlag(pcSlice->getSPS()->getUseLComb());
+      pcSlice->setNumRefIdx(REF_PIC_LIST_C, pcSlice->getNumRefIdx(REF_PIC_LIST_0));
+    }
+
+    if (pcSlice->getSliceType() == B_SLICE)
+    {
+      pcSlice->setColFromL0Flag(1-uiColDir);
+      Bool bLowDelay = true;
+      Int  iCurrPOC  = pcSlice->getPOC();
+      Int iRefIdx = 0;
+
+      for (iRefIdx = 0; iRefIdx < pcSlice->getNumRefIdx(REF_PIC_LIST_0) && bLowDelay; iRefIdx++)
+      {
+        if ( pcSlice->getRefPic(REF_PIC_LIST_0, iRefIdx)->getPOC() > iCurrPOC )
+        {
+          bLowDelay = false;
+        }
+      }
+      for (iRefIdx = 0; iRefIdx < pcSlice->getNumRefIdx(REF_PIC_LIST_1) && bLowDelay; iRefIdx++)
+      {
+        if ( pcSlice->getRefPic(REF_PIC_LIST_1, iRefIdx)->getPOC() > iCurrPOC )
+        {
+          bLowDelay = false;
+        }
+      }
+
+      pcSlice->setCheckLDC(bLowDelay);  
+    }
+
+    uiColDir = 1-uiColDir;
+
+    //-------------------------------------------------------------
+    pcSlice->setRefPOCList();
+
+    pcSlice->setNoBackPredFlag( false );
+    if ( pcSlice->getSliceType() == B_SLICE && !pcSlice->getRefPicListCombinationFlag())
+    {
+      if ( pcSlice->getNumRefIdx(RefPicList( 0 ) ) == pcSlice->getNumRefIdx(RefPicList( 1 ) ) )
+      {
+        pcSlice->setNoBackPredFlag( true );
+        int i;
+        for ( i=0; i < pcSlice->getNumRefIdx(RefPicList( 1 ) ); i++ )
+        {
+          if ( pcSlice->getRefPOC(RefPicList(1), i) != pcSlice->getRefPOC(RefPicList(0), i) ) 
+          {
+            pcSlice->setNoBackPredFlag( false );
+            break;
+          }
+        }
+      }
+    }
+
+    if(pcSlice->getNoBackPredFlag())
+    {
+      pcSlice->setNumRefIdx(REF_PIC_LIST_C, 0);
+    }
+    pcSlice->generateCombinedList();
+
+    if (m_pcEncTop->getTMVPModeId() == 2)
+    {
+      if (iGOPid == 0) // first picture in SOP (i.e. forward B)
+      {
+        pcSlice->setEnableTMVPFlag(0);
+      }
+      else
+      {
+        // Note: pcSlice->getColFromL0Flag() is assumed to be always 0 and getcolRefIdx() is always 0.
+        pcSlice->setEnableTMVPFlag(1);
+      }
+      pcSlice->getSPS()->setTMVPFlagsPresent(1);
+    }
+    else if (m_pcEncTop->getTMVPModeId() == 1)
+    {
+      pcSlice->getSPS()->setTMVPFlagsPresent(1);
+      pcSlice->setEnableTMVPFlag(1);
+    }
+    else
+    {
+      pcSlice->getSPS()->setTMVPFlagsPresent(0);
+      pcSlice->setEnableTMVPFlag(0);
+    }
+    /////////////////////////////////////////////////////////////////////////////////////////////////// Compress a slice
+    //  Slice compression
+    if (m_pcCfg->getUseASR())
+    {
+      m_pcSliceEncoder->setSearchRange(pcSlice);
+    }
+
+    Bool bGPBcheck=false;
+    if ( pcSlice->getSliceType() == B_SLICE)
+    {
+      if ( pcSlice->getNumRefIdx(RefPicList( 0 ) ) == pcSlice->getNumRefIdx(RefPicList( 1 ) ) )
+      {
+        bGPBcheck=true;
+        int i;
+        for ( i=0; i < pcSlice->getNumRefIdx(RefPicList( 1 ) ); i++ )
+        {
+          if ( pcSlice->getRefPOC(RefPicList(1), i) != pcSlice->getRefPOC(RefPicList(0), i) ) 
+          {
+            bGPBcheck=false;
+            break;
+          }
+        }
+      }
+    }
+    if(bGPBcheck)
+    {
+      pcSlice->setMvdL1ZeroFlag(true);
+    }
+    else
+    {
+      pcSlice->setMvdL1ZeroFlag(false);
+    }
+    pcPic->getSlice(pcSlice->getSliceIdx())->setMvdL1ZeroFlag(pcSlice->getMvdL1ZeroFlag());
+
+    UInt uiNumSlices = 1;
+
+    UInt uiInternalAddress = pcPic->getNumPartInCU()-4;
+    UInt uiExternalAddress = pcPic->getPicSym()->getNumberOfCUsInFrame()-1;
+    UInt uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
+    UInt uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
+    UInt uiWidth = pcSlice->getSPS()->getPicWidthInLumaSamples();
+    UInt uiHeight = pcSlice->getSPS()->getPicHeightInLumaSamples();
+    while(uiPosX>=uiWidth||uiPosY>=uiHeight) 
+    {
+      uiInternalAddress--;
+      uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
+      uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
+    }
+    uiInternalAddress++;
+    if(uiInternalAddress==pcPic->getNumPartInCU()) 
+    {
+      uiInternalAddress = 0;
+      uiExternalAddress++;
+    }
+    UInt uiRealEndAddress = uiExternalAddress*pcPic->getNumPartInCU()+uiInternalAddress;
+
+    UInt uiCummulativeTileWidth;
+    UInt uiCummulativeTileHeight;
+    Int  p, j;
+    UInt uiEncCUAddr;
+
+    //set NumColumnsMinus1 and NumRowsMinus1
+    pcPic->getPicSym()->setNumColumnsMinus1( pcSlice->getPPS()->getNumColumnsMinus1() );
+    pcPic->getPicSym()->setNumRowsMinus1( pcSlice->getPPS()->getNumRowsMinus1() );
+
+    //create the TComTileArray
+    pcPic->getPicSym()->xCreateTComTileArray();
+
+    if( pcSlice->getPPS()->getUniformSpacingFlag() == 1 )
+    {
+      //set the width for each tile
+      for(j=0; j < pcPic->getPicSym()->getNumRowsMinus1()+1; j++)
+      {
+        for(p=0; p < pcPic->getPicSym()->getNumColumnsMinus1()+1; p++)
+        {
+          pcPic->getPicSym()->getTComTile( j * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + p )->
+            setTileWidth( (p+1)*pcPic->getPicSym()->getFrameWidthInCU()/(pcPic->getPicSym()->getNumColumnsMinus1()+1) 
+            - (p*pcPic->getPicSym()->getFrameWidthInCU())/(pcPic->getPicSym()->getNumColumnsMinus1()+1) );
+        }
+      }
+
+      //set the height for each tile
+      for(j=0; j < pcPic->getPicSym()->getNumColumnsMinus1()+1; j++)
+      {
+        for(p=0; p < pcPic->getPicSym()->getNumRowsMinus1()+1; p++)
+        {
+          pcPic->getPicSym()->getTComTile( p * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + j )->
+            setTileHeight( (p+1)*pcPic->getPicSym()->getFrameHeightInCU()/(pcPic->getPicSym()->getNumRowsMinus1()+1) 
+            - (p*pcPic->getPicSym()->getFrameHeightInCU())/(pcPic->getPicSym()->getNumRowsMinus1()+1) );   
+        }
+      }
+    }
+    else
+    {
+      //set the width for each tile
+      for(j=0; j < pcPic->getPicSym()->getNumRowsMinus1()+1; j++)
+      {
+        uiCummulativeTileWidth = 0;
+        for(p=0; p < pcPic->getPicSym()->getNumColumnsMinus1(); p++)
+        {
+          pcPic->getPicSym()->getTComTile( j * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + p )->setTileWidth( pcSlice->getPPS()->getColumnWidth(p) );
+          uiCummulativeTileWidth += pcSlice->getPPS()->getColumnWidth(p);
+        }
+        pcPic->getPicSym()->getTComTile(j * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + p)->setTileWidth( pcPic->getPicSym()->getFrameWidthInCU()-uiCummulativeTileWidth );
+      }
+
+      //set the height for each tile
+      for(j=0; j < pcPic->getPicSym()->getNumColumnsMinus1()+1; j++)
+      {
+        uiCummulativeTileHeight = 0;
+        for(p=0; p < pcPic->getPicSym()->getNumRowsMinus1(); p++)
+        {
+          pcPic->getPicSym()->getTComTile( p * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + j )->setTileHeight( pcSlice->getPPS()->getRowHeight(p) );
+          uiCummulativeTileHeight += pcSlice->getPPS()->getRowHeight(p);
+        }
+        pcPic->getPicSym()->getTComTile(p * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + j)->setTileHeight( pcPic->getPicSym()->getFrameHeightInCU()-uiCummulativeTileHeight );
+      }
+    }
+    //intialize each tile of the current picture
+    pcPic->getPicSym()->xInitTiles();
+
+    // Allocate some coders, now we know how many tiles there are.
+    Int iNumSubstreams = pcSlice->getPPS()->getNumSubstreams();
+
+    //generate the Coding Order Map and Inverse Coding Order Map
+    for(p=0, uiEncCUAddr=0; p<pcPic->getPicSym()->getNumberOfCUsInFrame(); p++, uiEncCUAddr = pcPic->getPicSym()->xCalculateNxtCUAddr(uiEncCUAddr))
+    {
+      pcPic->getPicSym()->setCUOrderMap(p, uiEncCUAddr);
+      pcPic->getPicSym()->setInverseCUOrderMap(uiEncCUAddr, p);
+    }
+    pcPic->getPicSym()->setCUOrderMap(pcPic->getPicSym()->getNumberOfCUsInFrame(), pcPic->getPicSym()->getNumberOfCUsInFrame());    
+    pcPic->getPicSym()->setInverseCUOrderMap(pcPic->getPicSym()->getNumberOfCUsInFrame(), pcPic->getPicSym()->getNumberOfCUsInFrame());
+
+    // Allocate some coders, now we know how many tiles there are.
+    m_pcEncTop->createWPPCoders(iNumSubstreams);
+    pcSbacCoders = m_pcEncTop->getSbacCoders();
+    pcSubstreamsOut = new TComOutputBitstream[iNumSubstreams];
+
+    UInt uiStartCUAddrSliceIdx = 0; // used to index "m_uiStoredStartCUAddrForEncodingSlice" containing locations of slice boundaries
+    UInt uiStartCUAddrSlice    = 0; // used to keep track of current slice's starting CU addr.
+    pcSlice->setSliceCurStartCUAddr( uiStartCUAddrSlice ); // Setting "start CU addr" for current slice
+    m_storedStartCUAddrForEncodingSlice.clear();
+
+    UInt uiStartCUAddrDependentSliceIdx = 0; // used to index "m_uiStoredStartCUAddrForEntropyEncodingSlice" containing locations of slice boundaries
+    UInt uiStartCUAddrDependentSlice    = 0; // used to keep track of current Dependent slice's starting CU addr.
+    pcSlice->setDependentSliceCurStartCUAddr( uiStartCUAddrDependentSlice ); // Setting "start CU addr" for current Dependent slice
+
+    m_storedStartCUAddrForEncodingDependentSlice.clear();
+    UInt uiNextCUAddr = 0;
+    m_storedStartCUAddrForEncodingSlice.push_back (uiNextCUAddr);
+    uiStartCUAddrSliceIdx++;
+    m_storedStartCUAddrForEncodingDependentSlice.push_back(uiNextCUAddr);
+    uiStartCUAddrDependentSliceIdx++;
+
+#if AVC_BASE
+    if( m_layerId == 0 )
+    {
+      pcPic->getPicYuvOrg()->copyToPic( pcPic->getPicYuvRec() );
+      return;
+    }
+#endif
+
+    while(uiNextCUAddr<uiRealEndAddress) // determine slice boundaries
+    {
+      pcSlice->setNextSlice       ( false );
+      pcSlice->setNextDependentSlice( false );
+      assert(pcPic->getNumAllocatedSlice() == uiStartCUAddrSliceIdx);
+      m_pcSliceEncoder->precompressSlice( pcPic );
+      m_pcSliceEncoder->compressSlice   ( pcPic );
+
+      Bool bNoBinBitConstraintViolated = (!pcSlice->isNextSlice() && !pcSlice->isNextDependentSlice());
+      if (pcSlice->isNextSlice() || (bNoBinBitConstraintViolated && m_pcCfg->getSliceMode()==AD_HOC_SLICES_FIXED_NUMBER_OF_LCU_IN_SLICE))
+      {
+        uiStartCUAddrSlice = pcSlice->getSliceCurEndCUAddr();
+        // Reconstruction slice
+        m_storedStartCUAddrForEncodingSlice.push_back(uiStartCUAddrSlice);
+        uiStartCUAddrSliceIdx++;
+        // Dependent slice
+        if (uiStartCUAddrDependentSliceIdx>0 && m_storedStartCUAddrForEncodingDependentSlice[uiStartCUAddrDependentSliceIdx-1] != uiStartCUAddrSlice)
+        {
+          m_storedStartCUAddrForEncodingDependentSlice.push_back(uiStartCUAddrSlice);
+          uiStartCUAddrDependentSliceIdx++;
+        }
+
+        if (uiStartCUAddrSlice < uiRealEndAddress)
+        {
+          pcPic->allocateNewSlice();          
+          pcPic->setCurrSliceIdx                  ( uiStartCUAddrSliceIdx-1 );
+          m_pcSliceEncoder->setSliceIdx           ( uiStartCUAddrSliceIdx-1 );
+          pcSlice = pcPic->getSlice               ( uiStartCUAddrSliceIdx-1 );
+          pcSlice->copySliceInfo                  ( pcPic->getSlice(0)      );
+          pcSlice->setSliceIdx                    ( uiStartCUAddrSliceIdx-1 );
+          pcSlice->setSliceCurStartCUAddr         ( uiStartCUAddrSlice      );
+          pcSlice->setDependentSliceCurStartCUAddr  ( uiStartCUAddrSlice      );
+          pcSlice->setSliceBits(0);
+          uiNumSlices ++;
+        }
+      }
+      else if (pcSlice->isNextDependentSlice() || (bNoBinBitConstraintViolated && m_pcCfg->getDependentSliceMode()==SHARP_FIXED_NUMBER_OF_LCU_IN_DEPENDENT_SLICE))
+      {
+        uiStartCUAddrDependentSlice                                                     = pcSlice->getDependentSliceCurEndCUAddr();
+        m_storedStartCUAddrForEncodingDependentSlice.push_back(uiStartCUAddrDependentSlice);
+        uiStartCUAddrDependentSliceIdx++;
+        pcSlice->setDependentSliceCurStartCUAddr( uiStartCUAddrDependentSlice );
+      }
+      else
+      {
+        uiStartCUAddrSlice                                                            = pcSlice->getSliceCurEndCUAddr();
+        uiStartCUAddrDependentSlice                                                     = pcSlice->getDependentSliceCurEndCUAddr();
+      }        
+
+      uiNextCUAddr = (uiStartCUAddrSlice > uiStartCUAddrDependentSlice) ? uiStartCUAddrSlice : uiStartCUAddrDependentSlice;
+    }
+    m_storedStartCUAddrForEncodingSlice.push_back( pcSlice->getSliceCurEndCUAddr());
+    uiStartCUAddrSliceIdx++;
+    m_storedStartCUAddrForEncodingDependentSlice.push_back(pcSlice->getSliceCurEndCUAddr());
+    uiStartCUAddrDependentSliceIdx++;
+
+    pcSlice = pcPic->getSlice(0);
+
+#if SAO_LCU_BOUNDARY
+    // SAO parameter estimation using non-deblocked pixels for LCU bottom and right boundary areas
+    if( m_pcCfg->getSaoLcuBasedOptimization() && m_pcCfg->getSaoLcuBoundary() )
+    {
+      m_pcSAO->resetStats();
+      m_pcSAO->calcSaoStatsCu_BeforeDblk( pcPic );
+    }
+#endif
+
+    //-- Loop filter
+    Bool bLFCrossTileBoundary = pcSlice->getPPS()->getLoopFilterAcrossTilesEnabledFlag();
+    m_pcLoopFilter->setCfg(pcSlice->getPPS()->getDeblockingFilterControlPresentFlag(), pcSlice->getDeblockingFilterDisable(), pcSlice->getDeblockingFilterBetaOffsetDiv2(), pcSlice->getDeblockingFilterTcOffsetDiv2(), bLFCrossTileBoundary);
+    m_pcLoopFilter->loopFilterPic( pcPic );
+
+    pcSlice = pcPic->getSlice(0);
+#if REMOVE_ALF
+    if(pcSlice->getSPS()->getUseSAO())
+#else
+    if(pcSlice->getSPS()->getUseSAO() || pcSlice->getSPS()->getUseALF())
+#endif
+    {
+#if !REMOVE_FGS
+      Int sliceGranularity = pcSlice->getPPS()->getSliceGranularity();
+#endif
+      std::vector<Bool> LFCrossSliceBoundaryFlag;
+      for(Int s=0; s< uiNumSlices; s++)
+      {
+        LFCrossSliceBoundaryFlag.push_back(  ((uiNumSlices==1)?true:pcPic->getSlice(s)->getLFCrossSliceBoundaryFlag()) );
+      }
+      m_storedStartCUAddrForEncodingSlice.resize(uiNumSlices+1);
+#if REMOVE_FGS
+      pcPic->createNonDBFilterInfo(m_storedStartCUAddrForEncodingSlice, 0, &LFCrossSliceBoundaryFlag ,pcPic->getPicSym()->getNumTiles() ,bLFCrossTileBoundary);
+#else
+      pcPic->createNonDBFilterInfo(m_storedStartCUAddrForEncodingSlice, sliceGranularity, &LFCrossSliceBoundaryFlag ,pcPic->getPicSym()->getNumTiles() ,bLFCrossTileBoundary);
+#endif
+    }
+
+
+    pcSlice = pcPic->getSlice(0);
+
+    if(pcSlice->getSPS()->getUseSAO())
+    {
+      m_pcSAO->createPicSaoInfo(pcPic, uiNumSlices);
+    }
+
+#if !REMOVE_ALF
+    pcSlice = pcPic->getSlice(0);
+
+    if(pcSlice->getSPS()->getUseALF())
+    {
+      m_pcAdaptiveLoopFilter->createPicAlfInfo(pcPic, uiNumSlices);
+    }
+#endif
+    /////////////////////////////////////////////////////////////////////////////////////////////////// File writing
+    // Set entropy coder
+    m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder, pcSlice );
+
+    /* write various header sets. */
+    if ( m_bSeqFirst )
+    {
+#if SVC_EXTENSION
+#if REMOVE_NAL_REF_FLAG
+      OutputNALUnit nalu(NAL_UNIT_VPS, 0, m_layerId);
+#else
+      OutputNALUnit nalu(NAL_UNIT_VPS, true, 0, m_layerId);
+#endif
+#else
+#if REMOVE_NAL_REF_FLAG
+      OutputNALUnit nalu(NAL_UNIT_VPS);
+#else
+      OutputNALUnit nalu(NAL_UNIT_VPS, true);
+#endif
+#endif
+      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+      m_pcEntropyCoder->encodeVPS(m_pcEncTop->getVPS());
+      writeRBSPTrailingBits(nalu.m_Bitstream);
+      accessUnit.push_back(new NALUnitEBSP(nalu));
+
+#if SVC_EXTENSION
+#if REMOVE_NAL_REF_FLAG
+      nalu = NALUnit(NAL_UNIT_SPS, 0, m_layerId);
+#else
+      nalu = NALUnit(NAL_UNIT_SPS, true, 0, m_layerId);
+#endif
+#else
+#if REMOVE_NAL_REF_FLAG
+      nalu = NALUnit(NAL_UNIT_SPS);
+#else
+      nalu = NALUnit(NAL_UNIT_SPS, true);
+#endif
+#endif
+      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+#if LTRP_IN_SPS
+      if (m_bSeqFirst)
+      {
+        pcSlice->getSPS()->setNumLongTermRefPicSPS(m_numLongTermRefPicSPS);
+        for (Int k = 0; k < m_numLongTermRefPicSPS; k++)
+        {
+          pcSlice->getSPS()->setLtRefPicPocLsbSps(k, m_ltRefPicPocLsbSps[k]);
+          pcSlice->getSPS()->setUsedByCurrPicLtSPSFlag(k, m_ltRefPicUsedByCurrPicFlag[k]);
+        }
+      }
+#endif
+#if BUFFERING_PERIOD_AND_TIMING_SEI
+      if( m_pcCfg->getPictureTimingSEIEnabled() )
+      {
+        UInt maxCU = m_pcCfg->getSliceArgument() >> ( pcSlice->getSPS()->getMaxCUDepth() << 1);
+        UInt numDU = ( m_pcCfg->getSliceMode() == 1 ) ? ( pcPic->getNumCUsInFrame() / maxCU ) : ( 0 );
+        if( pcPic->getNumCUsInFrame() % maxCU != 0 )
+        {
+          numDU ++;
+        }
+        pcSlice->getSPS()->getVuiParameters()->setNumDU( numDU );
+        pcSlice->getSPS()->setHrdParameters( m_pcCfg->getFrameRate(), numDU, m_pcCfg->getTargetBitrate(), ( m_pcCfg->getIntraPeriod() > 0 ) );
+      }
+      if( m_pcCfg->getBufferingPeriodSEIEnabled() || m_pcCfg->getPictureTimingSEIEnabled() )
+      {
+        pcSlice->getSPS()->getVuiParameters()->setHrdParametersPresentFlag( true );
+      }
+#endif
+      m_pcEntropyCoder->encodeSPS(pcSlice->getSPS());
+      writeRBSPTrailingBits(nalu.m_Bitstream);
+      accessUnit.push_back(new NALUnitEBSP(nalu));
+
+#if SVC_EXTENSION
+#if REMOVE_NAL_REF_FLAG
+      nalu = NALUnit(NAL_UNIT_PPS, 0, m_layerId);
+#else
+      nalu = NALUnit(NAL_UNIT_PPS, true, 0, m_layerId);
+#endif
+#else
+#if REMOVE_NAL_REF_FLAG
+      nalu = NALUnit(NAL_UNIT_PPS);
+#else
+      nalu = NALUnit(NAL_UNIT_PPS, true);
+#endif
+#endif
+      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+      m_pcEntropyCoder->encodePPS(pcSlice->getPPS());
+      writeRBSPTrailingBits(nalu.m_Bitstream);
+      accessUnit.push_back(new NALUnitEBSP(nalu));
+
+#if ACTIVE_PARAMETER_SETS_SEI_MESSAGE  
+      if(m_pcCfg->getActiveParameterSetsSEIEnabled())
+      {
+        SEIActiveParameterSets sei_active_parameter_sets; 
+        sei_active_parameter_sets.activeVPSId = m_pcCfg->getVPS()->getVPSId(); 
+        sei_active_parameter_sets.activeSPSIdPresentFlag = m_pcCfg->getActiveParameterSetsSEIEnabled()==2 ? 1 : 0;
+        if(sei_active_parameter_sets.activeSPSIdPresentFlag) 
+        {
+          sei_active_parameter_sets.activeSeqParamSetId = pcSlice->getSPS()->getSPSId(); 
+        }
+        sei_active_parameter_sets.activeParamSetSEIExtensionFlag = 0;
+
+        nalu = NALUnit(NAL_UNIT_SEI); 
+        m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+        m_seiWriter.writeSEImessage(nalu.m_Bitstream, sei_active_parameter_sets); 
+        writeRBSPTrailingBits(nalu.m_Bitstream);
+        accessUnit.push_back(new NALUnitEBSP(nalu));
+      }
+#endif 
+
+      m_bSeqFirst = false;
+    }
+
+#if BUFFERING_PERIOD_AND_TIMING_SEI
+    if( ( m_pcCfg->getPictureTimingSEIEnabled() ) &&
+        ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) && 
+        ( ( pcSlice->getSPS()->getVuiParameters()->getNalHrdParametersPresentFlag() ) || ( pcSlice->getSPS()->getVuiParameters()->getVclHrdParametersPresentFlag() ) ) )
+    {
+      if( pcSlice->getSPS()->getVuiParameters()->getSubPicCpbParamsPresentFlag() )
+      {
+        UInt numDU = pcSlice->getSPS()->getVuiParameters()->getNumDU();
+        pictureTimingSEI.m_numDecodingUnitsMinus1     = ( numDU - 1 );
+        pictureTimingSEI.m_duCommonCpbRemovalDelayFlag = 0;
+
+        if( pictureTimingSEI.m_numNalusInDuMinus1 == NULL )
+        {
+          pictureTimingSEI.m_numNalusInDuMinus1       = new UInt[ numDU ];
+        }
+        if( pictureTimingSEI.m_duCpbRemovalDelayMinus1  == NULL )
+        {
+          pictureTimingSEI.m_duCpbRemovalDelayMinus1  = new UInt[ numDU ];
+        }
+        if( accumBitsDU == NULL )
+        {
+          accumBitsDU                                  = new UInt[ numDU ];
+        }
+        if( accumNalsDU == NULL )
+        {
+          accumNalsDU                                  = new UInt[ numDU ];
+        }
+      }
+      pictureTimingSEI.m_auCpbRemovalDelay = m_totalCoded - m_lastBPSEI;
+      pictureTimingSEI.m_picDpbOutputDelay = pcSlice->getSPS()->getNumReorderPics(0) + pcSlice->getPOC() - m_totalCoded;
+    }
+    if( ( m_pcCfg->getBufferingPeriodSEIEnabled() ) && ( pcSlice->getSliceType() == I_SLICE ) &&
+        ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) && 
+        ( ( pcSlice->getSPS()->getVuiParameters()->getNalHrdParametersPresentFlag() ) || ( pcSlice->getSPS()->getVuiParameters()->getVclHrdParametersPresentFlag() ) ) )
+    {
+      OutputNALUnit nalu(NAL_UNIT_SEI);
+      m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
+      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+
+      SEIBufferingPeriod sei_buffering_period;
+      
+      UInt uiInitialCpbRemovalDelay = (90000/2);                      // 0.5 sec
+      sei_buffering_period.m_initialCpbRemovalDelay      [0][0]     = uiInitialCpbRemovalDelay;
+      sei_buffering_period.m_initialCpbRemovalDelayOffset[0][0]     = uiInitialCpbRemovalDelay;
+      sei_buffering_period.m_initialCpbRemovalDelay      [0][1]     = uiInitialCpbRemovalDelay;
+      sei_buffering_period.m_initialCpbRemovalDelayOffset[0][1]     = uiInitialCpbRemovalDelay;
+
+      Double dTmp = (Double)pcSlice->getSPS()->getVuiParameters()->getNumUnitsInTick() / (Double)pcSlice->getSPS()->getVuiParameters()->getTimeScale();
+
+      UInt uiTmp = (UInt)( dTmp * 90000.0 ); 
+      uiInitialCpbRemovalDelay -= uiTmp;
+      uiInitialCpbRemovalDelay -= uiTmp / ( pcSlice->getSPS()->getVuiParameters()->getTickDivisorMinus2() + 2 );
+      sei_buffering_period.m_initialAltCpbRemovalDelay      [0][0]  = uiInitialCpbRemovalDelay;
+      sei_buffering_period.m_initialAltCpbRemovalDelayOffset[0][0]  = uiInitialCpbRemovalDelay;
+      sei_buffering_period.m_initialAltCpbRemovalDelay      [0][1]  = uiInitialCpbRemovalDelay;
+      sei_buffering_period.m_initialAltCpbRemovalDelayOffset[0][1]  = uiInitialCpbRemovalDelay;
+
+      sei_buffering_period.m_altCpbParamsPresentFlag              = 0;
+      sei_buffering_period.m_sps                                  = pcSlice->getSPS();
+
+      m_seiWriter.writeSEImessage( nalu.m_Bitstream, sei_buffering_period );
+      writeRBSPTrailingBits(nalu.m_Bitstream);
+      accessUnit.push_back(new NALUnitEBSP(nalu));
+
+      m_lastBPSEI = m_totalCoded;
+      m_cpbRemovalDelay = 0;
+    }
+    m_cpbRemovalDelay ++;
+#endif
+#if RECOVERY_POINT_SEI
+    if( ( m_pcEncTop->getRecoveryPointSEIEnabled() ) && ( pcSlice->getSliceType() == I_SLICE ) )
+    {
+      // Recovery point SEI
+      OutputNALUnit nalu(NAL_UNIT_SEI);
+      m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
+      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+
+      SEIRecoveryPoint sei_recovery_point;
+      sei_recovery_point.m_recoveryPocCnt    = 0;
+      sei_recovery_point.m_exactMatchingFlag = ( pcSlice->getPOC() == 0 ) ? (true) : (false);
+      sei_recovery_point.m_brokenLinkFlag    = false;
+
+      m_seiWriter.writeSEImessage( nalu.m_Bitstream, sei_recovery_point );
+      writeRBSPTrailingBits(nalu.m_Bitstream);
+      accessUnit.push_back(new NALUnitEBSP(nalu));
+    }
+#endif
+    /* use the main bitstream buffer for storing the marshalled picture */
+    m_pcEntropyCoder->setBitstream(NULL);
+
+    uiStartCUAddrSliceIdx = 0;
+    uiStartCUAddrSlice    = 0; 
+
+    uiStartCUAddrDependentSliceIdx = 0;
+    uiStartCUAddrDependentSlice    = 0; 
+    uiNextCUAddr                 = 0;
+    pcSlice = pcPic->getSlice(uiStartCUAddrSliceIdx);
+
+#if REMOVE_ALF
+    Int processingState = (pcSlice->getSPS()->getUseSAO())?(EXECUTE_INLOOPFILTER):(ENCODE_SLICE);
+#else
+    Int processingState = (pcSlice->getSPS()->getUseALF() || pcSlice->getSPS()->getUseSAO())?(EXECUTE_INLOOPFILTER):(ENCODE_SLICE);
+#endif
+#if !REMOVE_APS
+    static Int iCurrAPSIdx = 0;
+    Int iCodedAPSIdx = 0;
+    TComSlice* pcSliceForAPS = NULL;
+#endif
+    bool skippedSlice=false;
+    while (uiNextCUAddr < uiRealEndAddress) // Iterate over all slices
+    {
+      switch(processingState)
+      {
+      case ENCODE_SLICE:
+        {
+          pcSlice->setNextSlice       ( false );
+          pcSlice->setNextDependentSlice( false );
+          if (uiNextCUAddr == m_storedStartCUAddrForEncodingSlice[uiStartCUAddrSliceIdx])
+          {
+            pcSlice = pcPic->getSlice(uiStartCUAddrSliceIdx);
+            if(uiStartCUAddrSliceIdx > 0 && pcSlice->getSliceType()!= I_SLICE)
+            {
+              pcSlice->checkColRefIdx(uiStartCUAddrSliceIdx, pcPic);
+            }
+            pcPic->setCurrSliceIdx(uiStartCUAddrSliceIdx);
+            m_pcSliceEncoder->setSliceIdx(uiStartCUAddrSliceIdx);
+            assert(uiStartCUAddrSliceIdx == pcSlice->getSliceIdx());
+            // Reconstruction slice
+            pcSlice->setSliceCurStartCUAddr( uiNextCUAddr );  // to be used in encodeSlice() + context restriction
+            pcSlice->setSliceCurEndCUAddr  ( m_storedStartCUAddrForEncodingSlice[uiStartCUAddrSliceIdx+1 ] );
+            // Dependent slice
+            pcSlice->setDependentSliceCurStartCUAddr( uiNextCUAddr );  // to be used in encodeSlice() + context restriction
+            pcSlice->setDependentSliceCurEndCUAddr  ( m_storedStartCUAddrForEncodingDependentSlice[uiStartCUAddrDependentSliceIdx+1 ] );
+
+            pcSlice->setNextSlice       ( true );
+
+            uiStartCUAddrSliceIdx++;
+            uiStartCUAddrDependentSliceIdx++;
+          } 
+          else if (uiNextCUAddr == m_storedStartCUAddrForEncodingDependentSlice[uiStartCUAddrDependentSliceIdx])
+          {
+            // Dependent slice
+            pcSlice->setDependentSliceCurStartCUAddr( uiNextCUAddr );  // to be used in encodeSlice() + context restriction
+            pcSlice->setDependentSliceCurEndCUAddr  ( m_storedStartCUAddrForEncodingDependentSlice[uiStartCUAddrDependentSliceIdx+1 ] );
+
+            pcSlice->setNextDependentSlice( true );
+
+            uiStartCUAddrDependentSliceIdx++;
+          }
+
+          pcSlice->setRPS(pcPic->getSlice(0)->getRPS());
+          pcSlice->setRPSidx(pcPic->getSlice(0)->getRPSidx());
+          UInt uiDummyStartCUAddr;
+          UInt uiDummyBoundingCUAddr;
+          m_pcSliceEncoder->xDetermineStartAndBoundingCUAddr(uiDummyStartCUAddr,uiDummyBoundingCUAddr,pcPic,true);
+
+          uiInternalAddress = pcPic->getPicSym()->getPicSCUAddr(pcSlice->getDependentSliceCurEndCUAddr()-1) % pcPic->getNumPartInCU();
+          uiExternalAddress = pcPic->getPicSym()->getPicSCUAddr(pcSlice->getDependentSliceCurEndCUAddr()-1) / pcPic->getNumPartInCU();
+          uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
+          uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
+          uiWidth = pcSlice->getSPS()->getPicWidthInLumaSamples();
+          uiHeight = pcSlice->getSPS()->getPicHeightInLumaSamples();
+          while(uiPosX>=uiWidth||uiPosY>=uiHeight)
+          {
+            uiInternalAddress--;
+            uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
+            uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
+          }
+          uiInternalAddress++;
+          if(uiInternalAddress==pcPic->getNumPartInCU())
+          {
+            uiInternalAddress = 0;
+            uiExternalAddress = pcPic->getPicSym()->getCUOrderMap(pcPic->getPicSym()->getInverseCUOrderMap(uiExternalAddress)+1);
+          }
+          UInt uiEndAddress = pcPic->getPicSym()->getPicSCUEncOrder(uiExternalAddress*pcPic->getNumPartInCU()+uiInternalAddress);
+          if(uiEndAddress<=pcSlice->getDependentSliceCurStartCUAddr()) {
+            UInt uiBoundingAddrSlice, uiBoundingAddrDependentSlice;
+            uiBoundingAddrSlice          = m_storedStartCUAddrForEncodingSlice[uiStartCUAddrSliceIdx];          
+            uiBoundingAddrDependentSlice = m_storedStartCUAddrForEncodingDependentSlice[uiStartCUAddrDependentSliceIdx];          
+            uiNextCUAddr               = min(uiBoundingAddrSlice, uiBoundingAddrDependentSlice);
+            if(pcSlice->isNextSlice())
+            {
+              skippedSlice=true;
+            }
+            continue;
+          }
+          if(skippedSlice) 
+          {
+            pcSlice->setNextSlice       ( true );
+            pcSlice->setNextDependentSlice( false );
+          }
+          skippedSlice=false;
+          pcSlice->allocSubstreamSizes( iNumSubstreams );
+          for ( UInt ui = 0 ; ui < iNumSubstreams; ui++ )
+          {
+            pcSubstreamsOut[ui].clear();
+          }
+
+          m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder, pcSlice );
+          m_pcEntropyCoder->resetEntropy      ();
+          /* start slice NALunit */
+#if SVC_EXTENSION
+#if REMOVE_NAL_REF_FLAG
+          OutputNALUnit nalu( pcSlice->getNalUnitType(), pcSlice->getTLayer(), m_layerId );
+#else
+          OutputNALUnit nalu( pcSlice->getNalUnitType(), pcSlice->isReferenced(), pcSlice->getTLayer(), m_layerId );
+#endif
+#else
+#if REMOVE_NAL_REF_FLAG
+          OutputNALUnit nalu( pcSlice->getNalUnitType(), pcSlice->getTLayer() );
+#else
+          OutputNALUnit nalu( pcSlice->getNalUnitType(), pcSlice->isReferenced(), pcSlice->getTLayer() );
+#endif
+#endif
+          Bool bDependentSlice = (!pcSlice->isNextSlice());
+          if (!bDependentSlice)
+          {
+            uiOneBitstreamPerSliceLength = 0; // start of a new slice
+          }
+          m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+          m_pcEntropyCoder->encodeSliceHeader(pcSlice);
+
+          // is it needed?
+          {
+            if (!bDependentSlice)
+            {
+              pcBitstreamRedirect->writeAlignOne();
+            }
+            else
+            {
+              // We've not completed our slice header info yet, do the alignment later.
+            }
+            m_pcSbacCoder->init( (TEncBinIf*)m_pcBinCABAC );
+            m_pcEntropyCoder->setEntropyCoder ( m_pcSbacCoder, pcSlice );
+            m_pcEntropyCoder->resetEntropy    ();
+            for ( UInt ui = 0 ; ui < pcSlice->getPPS()->getNumSubstreams() ; ui++ )
+            {
+              m_pcEntropyCoder->setEntropyCoder ( &pcSbacCoders[ui], pcSlice );
+              m_pcEntropyCoder->resetEntropy    ();
+            }
+          }
+
+          if(pcSlice->isNextSlice())
+          {
+            // set entropy coder for writing
+            m_pcSbacCoder->init( (TEncBinIf*)m_pcBinCABAC );
+            {
+              for ( UInt ui = 0 ; ui < pcSlice->getPPS()->getNumSubstreams() ; ui++ )
+              {
+                m_pcEntropyCoder->setEntropyCoder ( &pcSbacCoders[ui], pcSlice );
+                m_pcEntropyCoder->resetEntropy    ();
+              }
+              pcSbacCoders[0].load(m_pcSbacCoder);
+              m_pcEntropyCoder->setEntropyCoder ( &pcSbacCoders[0], pcSlice );  //ALF is written in substream #0 with CABAC coder #0 (see ALF param encoding below)
+            }
+            m_pcEntropyCoder->resetEntropy    ();
+            // File writing
+            if (!bDependentSlice)
+            {
+              m_pcEntropyCoder->setBitstream(pcBitstreamRedirect);
+            }
+            else
+            {
+              m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+            }
+            // for now, override the TILES_DECODER setting in order to write substreams.
+            m_pcEntropyCoder->setBitstream    ( &pcSubstreamsOut[0] );
+
+          }
+          pcSlice->setFinalized(true);
+
+          m_pcSbacCoder->load( &pcSbacCoders[0] );
+
+          pcSlice->setTileOffstForMultES( uiOneBitstreamPerSliceLength );
+          if (!bDependentSlice)
+          {
+            pcSlice->setTileLocationCount ( 0 );
+            m_pcSliceEncoder->encodeSlice(pcPic, pcBitstreamRedirect, pcSubstreamsOut); // redirect is only used for CAVLC tile position info.
+          }
+          else
+          {
+            m_pcSliceEncoder->encodeSlice(pcPic, &nalu.m_Bitstream, pcSubstreamsOut); // nalu.m_Bitstream is only used for CAVLC tile position info.
+          }
+
+          {
+            // Construct the final bitstream by flushing and concatenating substreams.
+            // The final bitstream is either nalu.m_Bitstream or pcBitstreamRedirect;
+            UInt* puiSubstreamSizes = pcSlice->getSubstreamSizes();
+            UInt uiTotalCodedSize = 0; // for padding calcs.
+            UInt uiNumSubstreamsPerTile = iNumSubstreams;
+            if (iNumSubstreams > 1)
+            {
+              uiNumSubstreamsPerTile /= pcPic->getPicSym()->getNumTiles();
+            }
+            for ( UInt ui = 0 ; ui < iNumSubstreams; ui++ )
+            {
+              // Flush all substreams -- this includes empty ones.
+              // Terminating bit and flush.
+              m_pcEntropyCoder->setEntropyCoder   ( &pcSbacCoders[ui], pcSlice );
+              m_pcEntropyCoder->setBitstream      (  &pcSubstreamsOut[ui] );
+              m_pcEntropyCoder->encodeTerminatingBit( 1 );
+              m_pcEntropyCoder->encodeSliceFinish();
+
+#if BYTE_ALIGNMENT  
+              pcSubstreamsOut[ui].writeByteAlignment();   // Byte-alignment in slice_data() at end of sub-stream
+#else
+              //!KS: The following writes trailing_bits. Should use proper function call to writeRBSPTrailingBits()
+              pcSubstreamsOut[ui].write( 1, 1 ); // stop bit.
+              pcSubstreamsOut[ui].writeAlignZero();
+#endif
+              // Byte alignment is necessary between tiles when tiles are independent.
+              uiTotalCodedSize += pcSubstreamsOut[ui].getNumberOfWrittenBits();
+
+              {
+                Bool bNextSubstreamInNewTile = ((ui+1) < iNumSubstreams)
+                  && ((ui+1)%uiNumSubstreamsPerTile == 0);
+                if (bNextSubstreamInNewTile)
+                {
+                  // byte align.
+                  while (uiTotalCodedSize&0x7)
+                  {
+                    pcSubstreamsOut[ui].write(0, 1);
+                    uiTotalCodedSize++;
+                  }
+                }
+                Bool bRecordOffsetNext = bNextSubstreamInNewTile;
+                if (bRecordOffsetNext)
+                  pcSlice->setTileLocation(ui/uiNumSubstreamsPerTile, pcSlice->getTileOffstForMultES()+(uiTotalCodedSize>>3));
+              }
+              if (ui+1 < pcSlice->getPPS()->getNumSubstreams())
+                puiSubstreamSizes[ui] = pcSubstreamsOut[ui].getNumberOfWrittenBits();
+            }
+
+            // Complete the slice header info.
+            m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder, pcSlice );
+            m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+            m_pcEntropyCoder->encodeTilesWPPEntryPoint( pcSlice );
+
+            // Substreams...
+            TComOutputBitstream *pcOut = pcBitstreamRedirect;
+#if !BYTE_ALIGNMENT
+            // xWriteTileLocation will perform byte-alignment...
+            {
+              if (bDependentSlice)
+              {
+                // In these cases, padding is necessary here.
+                pcOut = &nalu.m_Bitstream;
+                pcOut->writeAlignOne();
+              }
+            }
+#endif
+          Int offs = 0;
+          Int nss = pcSlice->getPPS()->getNumSubstreams();
+#if TILES_WPP_ENTROPYSLICES_FLAGS
+          if (pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag())
+#else
+          if (pcSlice->getPPS()->getTilesOrEntropyCodingSyncIdc() == 2)
+#endif
+          {
+            // 1st line present for WPP.
+#if DEPENDENT_SLICES
+            offs = pcSlice->getDependentSliceCurStartCUAddr()/pcSlice->getPic()->getNumPartInCU()/pcSlice->getPic()->getFrameWidthInCU();
+#else
+            offs = pcSlice->getSliceCurStartCUAddr()/pcSlice->getPic()->getNumPartInCU()/pcSlice->getPic()->getFrameWidthInCU();
+#endif
+            nss  = pcSlice->getNumEntryPointOffsets()+1;
+          }
+          for ( UInt ui = 0 ; ui < nss; ui++ )
+          {
+            pcOut->addSubstream(&pcSubstreamsOut[ui+offs]);
+            }
+          }
+
+          UInt uiBoundingAddrSlice, uiBoundingAddrDependentSlice;
+          uiBoundingAddrSlice          = m_storedStartCUAddrForEncodingSlice[uiStartCUAddrSliceIdx];          
+          uiBoundingAddrDependentSlice = m_storedStartCUAddrForEncodingDependentSlice[uiStartCUAddrDependentSliceIdx];          
+          uiNextCUAddr               = min(uiBoundingAddrSlice, uiBoundingAddrDependentSlice);
+          // If current NALU is the first NALU of slice (containing slice header) and more NALUs exist (due to multiple dependent slices) then buffer it.
+          // If current NALU is the last NALU of slice and a NALU was buffered, then (a) Write current NALU (b) Update an write buffered NALU at approproate location in NALU list.
+          Bool bNALUAlignedWrittenToList    = false; // used to ensure current NALU is not written more than once to the NALU list.
+          xWriteTileLocationToSliceHeader(nalu, pcBitstreamRedirect, pcSlice);
+          accessUnit.push_back(new NALUnitEBSP(nalu));
+          bNALUAlignedWrittenToList = true; 
+          uiOneBitstreamPerSliceLength += nalu.m_Bitstream.getNumberOfWrittenBits(); // length of bitstream after byte-alignment
+
+          if (!bNALUAlignedWrittenToList)
+          {
+            {
+              nalu.m_Bitstream.writeAlignZero();
+            }
+            accessUnit.push_back(new NALUnitEBSP(nalu));
+            uiOneBitstreamPerSliceLength += nalu.m_Bitstream.getNumberOfWrittenBits() + 24; // length of bitstream after byte-alignment + 3 byte startcode 0x000001
+          }
+
+#if BUFFERING_PERIOD_AND_TIMING_SEI
+          if( ( m_pcCfg->getPictureTimingSEIEnabled() ) &&
+              ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) && 
+              ( ( pcSlice->getSPS()->getVuiParameters()->getNalHrdParametersPresentFlag() ) || ( pcSlice->getSPS()->getVuiParameters()->getVclHrdParametersPresentFlag() ) ) &&
+              ( pcSlice->getSPS()->getVuiParameters()->getSubPicCpbParamsPresentFlag() ) )
+          {
+            UInt numRBSPBytes = 0;
+            for (AccessUnit::const_iterator it = accessUnit.begin(); it != accessUnit.end(); it++)
+            {
+              UInt numRBSPBytes_nal = UInt((*it)->m_nalUnitData.str().size());
+              if ((*it)->m_nalUnitType != NAL_UNIT_SEI)
+              {
+                numRBSPBytes += numRBSPBytes_nal;
+              }
+            }
+            accumBitsDU[ pcSlice->getSliceIdx() ] = ( numRBSPBytes << 3 );
+            accumNalsDU[ pcSlice->getSliceIdx() ] = (UInt)accessUnit.size();
+          }
+#endif
+          processingState = ENCODE_SLICE;
+          }
+          break;
+        case EXECUTE_INLOOPFILTER:
+          {
+#if !REMOVE_APS
+            TComAPS cAPS;
+            allocAPS(&cAPS, pcSlice->getSPS());
+#endif
+            // set entropy coder for RD
+            m_pcEntropyCoder->setEntropyCoder ( m_pcSbacCoder, pcSlice );
+            if ( pcSlice->getSPS()->getUseSAO() )
+            {
+              m_pcEntropyCoder->resetEntropy();
+              m_pcEntropyCoder->setBitstream( m_pcBitCounter );
+              m_pcSAO->startSaoEnc(pcPic, m_pcEntropyCoder, m_pcEncTop->getRDSbacCoder(), m_pcEncTop->getRDGoOnSbacCoder());
+#if REMOVE_APS
+              SAOParam& cSaoParam = *pcSlice->getPic()->getPicSym()->getSaoParam();
+#else
+              SAOParam& cSaoParam = *(cAPS.getSaoParam());
+#endif
+
+#if SAO_CHROMA_LAMBDA
+#if SAO_ENCODING_CHOICE
+              m_pcSAO->SAOProcess(&cSaoParam, pcPic->getSlice(0)->getLambdaLuma(), pcPic->getSlice(0)->getLambdaChroma(), pcPic->getSlice(0)->getDepth());
+#else
+              m_pcSAO->SAOProcess(&cSaoParam, pcPic->getSlice(0)->getLambdaLuma(), pcPic->getSlice(0)->getLambdaChroma());
+#endif
+#else
+#if ALF_CHROMA_LAMBDA
+              m_pcSAO->SAOProcess(&cSaoParam, pcPic->getSlice(0)->getLambdaLuma());
+#else
+              m_pcSAO->SAOProcess(&cSaoParam, pcPic->getSlice(0)->getLambda());
+#endif
+#endif
+              m_pcSAO->endSaoEnc();
+#if !REMOVE_ALF
+              m_pcAdaptiveLoopFilter->PCMLFDisableProcess(pcPic);
+#else
+              m_pcSAO->PCMLFDisableProcess(pcPic);
+#endif
+            }
+#if SAO_RDO
+            m_pcEntropyCoder->setEntropyCoder ( m_pcCavlcCoder, pcSlice );
+#endif
+            // adaptive loop filter
+#if !REMOVE_ALF
+            if ( pcSlice->getSPS()->getUseALF())
+            {
+#if ALF_CHROMA_LAMBDA 
+              m_pcAdaptiveLoopFilter->ALFProcess(cAPS.getAlfParam(), pcPic->getSlice(0)->getLambdaLuma(), pcPic->getSlice(0)->getLambdaChroma() );
+#else
+#if SAO_CHROMA_LAMBDA
+              m_pcAdaptiveLoopFilter->ALFProcess(cAPS.getAlfParam(), pcPic->getSlice(0)->getLambdaLuma());
+#else
+              m_pcAdaptiveLoopFilter->ALFProcess(cAPS.getAlfParam(), pcPic->getSlice(0)->getLambda());
+#endif
+#endif
+              m_pcAdaptiveLoopFilter->PCMLFDisableProcess(pcPic);
+            }
+#endif
+#if !REMOVE_APS
+            iCodedAPSIdx = iCurrAPSIdx;
+            pcSliceForAPS = pcSlice;
+
+            assignNewAPS(cAPS, iCodedAPSIdx, vAPS, pcSliceForAPS);
+            iCurrAPSIdx = (iCurrAPSIdx +1)%MAX_NUM_SUPPORTED_APS;
+#endif
+            processingState = ENCODE_APS;
+
+            //set APS link to the slices
+            for(Int s=0; s< uiNumSlices; s++)
+            {
+#if !REMOVE_ALF
+              if (pcSlice->getSPS()->getUseALF())
+              {
+                for(Int compIdx =0; compIdx< 3; compIdx++)
+                {
+                  pcPic->getSlice(s)->setAlfEnabledFlag( cAPS.getAlfEnabled(compIdx), compIdx);
+                }
+              }
+#endif
+              if (pcSlice->getSPS()->getUseSAO())
+              {
+#if REMOVE_APS
+                pcPic->getSlice(s)->setSaoEnabledFlag((pcSlice->getPic()->getPicSym()->getSaoParam()->bSaoFlag[0]==1)?true:false);
+#else
+                pcPic->getSlice(s)->setSaoEnabledFlag((cAPS.getSaoParam()->bSaoFlag[0]==1)?true:false);
+#endif
+              }
+#if !REMOVE_APS
+              pcPic->getSlice(s)->setAPS(&(vAPS[iCodedAPSIdx]));
+              pcPic->getSlice(s)->setAPSId(iCodedAPSIdx);
+#endif
+            }
+
+            /* The destructor of cAPS that is about to be called will free
+             * the resource held by cAPS, which will cause problems since it
+             * has been aliased elsewhere.
+             *   Hint: never ever write an assignment operator that copies
+             *         pointers without the use of smart pointers.
+             * The following will clear the saved state before the destructor.
+             */
+#if !REMOVE_APS
+            cAPS = TComAPS();
+#endif
+          }
+          break;
+        case ENCODE_APS:
+          {
+#if !REMOVE_APS
+            OutputNALUnit nalu(NAL_UNIT_APS, true);
+            encodeAPS(&(vAPS[iCodedAPSIdx]), nalu.m_Bitstream, pcSliceForAPS);
+            accessUnit.push_back(new NALUnitEBSP(nalu));
+#endif
+            processingState = ENCODE_SLICE;
+          }
+          break;
+        default:
+          {
+            printf("Not a supported encoding state\n");
+            assert(0);
+            exit(-1);
+          }
+        }
+      } // end iteration over slices
+
+#if REMOVE_ALF
+      if(pcSlice->getSPS()->getUseSAO())
+#else
+      if(pcSlice->getSPS()->getUseSAO() || pcSlice->getSPS()->getUseALF())
+#endif
+      {
+        if(pcSlice->getSPS()->getUseSAO())
+        {
+          m_pcSAO->destroyPicSaoInfo();
+        }
+#if !REMOVE_ALF
+        if(pcSlice->getSPS()->getUseALF())
+        {
+          m_pcAdaptiveLoopFilter->destroyPicAlfInfo();
+        }
+#endif
+        pcPic->destroyNonDBFilterInfo();
+      }
+
+      pcPic->compressMotion(); 
+      
+      //-- For time output for each slice
+      Double dEncTime = (double)(clock()-iBeforeTime) / CLOCKS_PER_SEC;
+
+      const char* digestStr = NULL;
+      if (m_pcCfg->getDecodedPictureHashSEIEnabled())
+      {
+        /* calculate MD5sum for entire reconstructed picture */
+        SEIDecodedPictureHash sei_recon_picture_digest;
+        if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 1)
+        {
+          sei_recon_picture_digest.method = SEIDecodedPictureHash::MD5;
+          calcMD5(*pcPic->getPicYuvRec(), sei_recon_picture_digest.digest);
+          digestStr = digestToString(sei_recon_picture_digest.digest, 16);
+        }
+        else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 2)
+        {
+          sei_recon_picture_digest.method = SEIDecodedPictureHash::CRC;
+          calcCRC(*pcPic->getPicYuvRec(), sei_recon_picture_digest.digest);
+          digestStr = digestToString(sei_recon_picture_digest.digest, 2);
+        }
+        else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 3)
+        {
+          sei_recon_picture_digest.method = SEIDecodedPictureHash::CHECKSUM;
+          calcChecksum(*pcPic->getPicYuvRec(), sei_recon_picture_digest.digest);
+          digestStr = digestToString(sei_recon_picture_digest.digest, 4);
+        }
+#if SVC_EXTENSION
+#if REMOVE_NAL_REF_FLAG
+        OutputNALUnit nalu(NAL_UNIT_SEI, pcSlice->getTLayer(), m_layerId);
+#else
+        OutputNALUnit nalu(NAL_UNIT_SEI, false, pcSlice->getTLayer(), m_layerId);
+#endif
+#else
+#if REMOVE_NAL_REF_FLAG
+        OutputNALUnit nalu(NAL_UNIT_SEI, pcSlice->getTLayer());
+#else
+        OutputNALUnit nalu(NAL_UNIT_SEI, false, pcSlice->getTLayer());
+#endif
+#endif
+
+        /* write the SEI messages */
+        m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
+        m_seiWriter.writeSEImessage(nalu.m_Bitstream, sei_recon_picture_digest);
+        writeRBSPTrailingBits(nalu.m_Bitstream);
+
+        /* insert the SEI message NALUnit before any Slice NALUnits */
+        AccessUnit::iterator it = find_if(accessUnit.begin(), accessUnit.end(), mem_fun(&NALUnit::isSlice));
+        accessUnit.insert(it, new NALUnitEBSP(nalu));
+      }
+
+      xCalculateAddPSNR( pcPic, pcPic->getPicYuvRec(), accessUnit, dEncTime );
+
+      if (digestStr)
+      {
+        if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 1)
+        {
+          printf(" [MD5:%s]", digestStr);
+        }
+        else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 2)
+        {
+          printf(" [CRC:%s]", digestStr);
+        }
+        else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 3)
+        {
+          printf(" [Checksum:%s]", digestStr);
+        }
+      }
+      if(m_pcCfg->getUseRateCtrl())
+      {
+        unsigned  frameBits = m_vRVM_RP[m_vRVM_RP.size()-1];
+        m_pcRateCtrl->updataRCFrameStatus((Int)frameBits, pcSlice->getSliceType());
+      }
+#if BUFFERING_PERIOD_AND_TIMING_SEI
+      if( ( m_pcCfg->getPictureTimingSEIEnabled() ) &&
+          ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) && 
+          ( ( pcSlice->getSPS()->getVuiParameters()->getNalHrdParametersPresentFlag() ) || ( pcSlice->getSPS()->getVuiParameters()->getVclHrdParametersPresentFlag() ) ) )
+      {
+        OutputNALUnit nalu(NAL_UNIT_SEI, pcSlice->getTLayer());
+        TComVUI *vui = pcSlice->getSPS()->getVuiParameters();
+
+        if( vui->getSubPicCpbParamsPresentFlag() )
+        {
+          Int i;
+          UInt64 ui64Tmp;
+          UInt uiTmp, uiPrev, uiCurr;
+
+          uiPrev = 0;
+          for( i = 0; i < ( pictureTimingSEI.m_numDecodingUnitsMinus1 + 1 ); i ++ )
+          {
+            pictureTimingSEI.m_numNalusInDuMinus1[ i ]       = ( i == 0 ) ? ( accumNalsDU[ i ] ) : ( accumNalsDU[ i ] - accumNalsDU[ i - 1] - 1 );
+            ui64Tmp = ( ( ( accumBitsDU[ pictureTimingSEI.m_numDecodingUnitsMinus1 ] - accumBitsDU[ i ] ) * ( vui->getTimeScale() / vui->getNumUnitsInTick() ) * ( vui->getTickDivisorMinus2() + 2 ) ) 
+                        / ( m_pcCfg->getTargetBitrate() << 10 ) );
+
+            uiTmp = (UInt)ui64Tmp;
+            if( uiTmp >= ( vui->getTickDivisorMinus2() + 2 ) )      uiCurr = 0;
+            else                                                     uiCurr = ( vui->getTickDivisorMinus2() + 2 ) - uiTmp;
+
+            if( i == pictureTimingSEI.m_numDecodingUnitsMinus1 ) uiCurr = vui->getTickDivisorMinus2() + 2;
+            if( uiCurr <= uiPrev )                                   uiCurr = uiPrev + 1;
+
+            pictureTimingSEI.m_duCpbRemovalDelayMinus1[ i ]              = (uiCurr - uiPrev) - 1;
+            uiPrev = uiCurr;
+          }
+        }
+        m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
+        pictureTimingSEI.m_sps = pcSlice->getSPS();
+        m_seiWriter.writeSEImessage(nalu.m_Bitstream, pictureTimingSEI);
+        writeRBSPTrailingBits(nalu.m_Bitstream);
+
+        AccessUnit::iterator it = find_if(accessUnit.begin(), accessUnit.end(), mem_fun(&NALUnit::isSlice));
+        accessUnit.insert(it, new NALUnitEBSP(nalu));
+      }
+#endif
+#if FIXED_ROUNDING_FRAME_MEMORY
+      /* TODO: this should happen after copyToPic(pcPicYuvRecOut) */
+      pcPic->getPicYuvRec()->xFixedRoundingPic();
+#endif
+      pcPic->getPicYuvRec()->copyToPic(pcPicYuvRecOut);
+
+      pcPic->setReconMark   ( true );
+      m_bFirst = false;
+      m_iNumPicCoded++;
+#if BUFFERING_PERIOD_AND_TIMING_SEI
+      m_totalCoded ++;
+#endif
+      /* logging: insert a newline at end of picture period */
+      printf("\n");
+      fflush(stdout);
+
+      delete[] pcSubstreamsOut;
+  }
+  if(m_pcCfg->getUseRateCtrl())
+  {
+    m_pcRateCtrl->updateRCGOPStatus();
+  }
+  delete pcBitstreamRedirect;
+
+#if BUFFERING_PERIOD_AND_TIMING_SEI
+  if( accumBitsDU != NULL) delete accumBitsDU;
+  if( accumNalsDU != NULL) delete accumNalsDU;
+#endif
+
+#if SVC_EXTENSION
+  assert ( m_iNumPicCoded <= 1 );
+#else
+  assert ( m_iNumPicCoded == iNumPicRcvd );
+#endif
+}
+
+#if !REMOVE_APS
+/** Memory allocation for APS
+  * \param [out] pAPS APS pointer
+  * \param [in] pSPS SPS pointer
+  */
+Void TEncGOP::allocAPS (TComAPS* pAPS, TComSPS* pSPS)
+{
+  if(pSPS->getUseSAO())
+  {
+    pAPS->createSaoParam();
+    m_pcSAO->allocSaoParam(pAPS->getSaoParam());
+  }
+#if !REMOVE_ALF
+  pAPS->createAlfParam();
+#endif
+}
+
+/** Memory deallocation for APS
+  * \param [out] pAPS APS pointer
+  * \param [in] pSPS SPS pointer
+  */
+Void TEncGOP::freeAPS (TComAPS* pAPS, TComSPS* pSPS)
+{
+  if(pSPS->getUseSAO())
+  {
+    if(pAPS->getSaoParam() != NULL)
+    {
+      m_pcSAO->freeSaoParam(pAPS->getSaoParam());
+      pAPS->destroySaoParam();
+
+    }
+  }
+#if !REMOVE_ALF
+  pAPS->destroyAlfParam();
+#endif
+}
+
+/** Assign APS object into APS container according to APS ID
+  * \param [in] cAPS APS object
+  * \param [in] apsID APS ID
+  * \param [in,out] vAPS APS container
+  * \param [in] pcSlice pointer to slice
+  */
+Void TEncGOP::assignNewAPS(TComAPS& cAPS, Int apsID, std::vector<TComAPS>& vAPS, TComSlice* pcSlice)
+{
+
+  cAPS.setAPSID(apsID);
+
+  //assign new APS into APS container
+  Int apsBufSize= (Int)vAPS.size();
+
+  if(apsID >= apsBufSize)
+  {
+    vAPS.resize(apsID +1);
+  }
+
+  freeAPS(&(vAPS[apsID]), pcSlice->getSPS());
+  vAPS[apsID] = cAPS;
+}
+
+/** encode APS syntax elements
+  * \param [in] pcAPS APS pointer
+  * \param [in, out] APSbs bitstream
+  * \param [in] pointer to slice (just used for entropy coder initialization)
+  */
+Void TEncGOP::encodeAPS(TComAPS* pcAPS, TComOutputBitstream& APSbs, TComSlice* pcSlice)
+{
+  m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder, pcSlice);
+  m_pcEntropyCoder->resetEntropy      ();
+  m_pcEntropyCoder->setBitstream(&APSbs);
+
+  m_pcEntropyCoder->encodeAPSInitInfo(pcAPS);
+#if !REMOVE_ALF
+  for(Int compIdx=0; compIdx < 3; compIdx++)
+  {
+    m_pcEntropyCoder->encodeAlfParam( (pcAPS->getAlfParam())[compIdx]);
+  }
+#endif
+  m_pcEntropyCoder->encodeApsExtensionFlag();
+  //neither SAO and ALF is enabled
+  writeRBSPTrailingBits(APSbs);
+}
+#endif
+
+#if !SVC_EXTENSION
+Void TEncGOP::printOutSummary(UInt uiNumAllPicCoded)
+{
+  assert (uiNumAllPicCoded == m_gcAnalyzeAll.getNumPic());
+  
+    
+  //--CFG_KDY
+  m_gcAnalyzeAll.setFrmRate( m_pcCfg->getFrameRate() );
+  m_gcAnalyzeI.setFrmRate( m_pcCfg->getFrameRate() );
+  m_gcAnalyzeP.setFrmRate( m_pcCfg->getFrameRate() );
+  m_gcAnalyzeB.setFrmRate( m_pcCfg->getFrameRate() );
+  
+  //-- all
+  printf( "\n\nSUMMARY --------------------------------------------------------\n" );
+  m_gcAnalyzeAll.printOut('a');
+  
+  printf( "\n\nI Slices--------------------------------------------------------\n" );
+  m_gcAnalyzeI.printOut('i');
+  
+  printf( "\n\nP Slices--------------------------------------------------------\n" );
+  m_gcAnalyzeP.printOut('p');
+  
+  printf( "\n\nB Slices--------------------------------------------------------\n" );
+  m_gcAnalyzeB.printOut('b');
+  
+#if _SUMMARY_OUT_
+  m_gcAnalyzeAll.printSummaryOut();
+#endif
+#if _SUMMARY_PIC_
+  m_gcAnalyzeI.printSummary('I');
+  m_gcAnalyzeP.printSummary('P');
+  m_gcAnalyzeB.printSummary('B');
+#endif
+
+  printf("\nRVM: %.3lf\n" , xCalculateRVM());
+}
+#endif
+
+Void TEncGOP::preLoopFilterPicAll( TComPic* pcPic, UInt64& ruiDist, UInt64& ruiBits )
+{
+  TComSlice* pcSlice = pcPic->getSlice(pcPic->getCurrSliceIdx());
+  Bool bCalcDist = false;
+  m_pcLoopFilter->setCfg(pcSlice->getPPS()->getDeblockingFilterControlPresentFlag(), pcSlice->getDeblockingFilterDisable(), m_pcCfg->getLoopFilterBetaOffset(), m_pcCfg->getLoopFilterTcOffset(), m_pcCfg->getLFCrossTileBoundaryFlag());
+  m_pcLoopFilter->loopFilterPic( pcPic );
+  
+  m_pcEntropyCoder->setEntropyCoder ( m_pcEncTop->getRDGoOnSbacCoder(), pcSlice );
+  m_pcEntropyCoder->resetEntropy    ();
+  m_pcEntropyCoder->setBitstream    ( m_pcBitCounter );
+  pcSlice = pcPic->getSlice(0);
+#if REMOVE_ALF
+  if(pcSlice->getSPS()->getUseSAO())
+#else
+  if(pcSlice->getSPS()->getUseSAO() || pcSlice->getSPS()->getUseALF())
+#endif
+  {
+    std::vector<Bool> LFCrossSliceBoundaryFlag(1, true);
+    std::vector<Int>  sliceStartAddress;
+    sliceStartAddress.push_back(0);
+    sliceStartAddress.push_back(pcPic->getNumCUsInFrame()* pcPic->getNumPartInCU());
+    pcPic->createNonDBFilterInfo(sliceStartAddress, 0, &LFCrossSliceBoundaryFlag);
+  }
+  
+#if !REMOVE_ALF
+  // Adaptive Loop filter
+  if( pcSlice->getSPS()->getUseALF() )
+  {
+    m_pcAdaptiveLoopFilter->createPicAlfInfo(pcPic);
+
+    ALFParam* alfPicParam[3];
+    for(Int compIdx=0; compIdx < 3; compIdx++)
+    {
+      alfPicParam[compIdx] = new ALFParam(compIdx);
+    }
+
+#if ALF_CHROMA_LAMBDA 
+    m_pcAdaptiveLoopFilter->ALFProcess(alfPicParam, pcPic->getSlice(0)->getLambdaLuma(), pcPic->getSlice(0)->getLambdaChroma() );
+#else
+#if SAO_CHROMA_LAMBDA
+    m_pcAdaptiveLoopFilter->ALFProcess(alfPicParam, pcPic->getSlice(0)->getLambdaLuma());
+#else
+    m_pcAdaptiveLoopFilter->ALFProcess(alfPicParam, pcPic->getSlice(0)->getLambda());
+#endif
+#endif
+    for(Int compIdx=0; compIdx < 3; compIdx++)
+    {
+      delete alfPicParam[compIdx]; alfPicParam[compIdx] = NULL;
+    }
+    m_pcAdaptiveLoopFilter->PCMLFDisableProcess(pcPic);
+    m_pcAdaptiveLoopFilter->destroyPicAlfInfo();
+  }
+#endif
+#if REMOVE_ALF
+  if( pcSlice->getSPS()->getUseSAO())
+#else
+  if( pcSlice->getSPS()->getUseSAO() || pcSlice->getSPS()->getUseALF())
+#endif
+  {
+    pcPic->destroyNonDBFilterInfo();
+  }
+  
+  m_pcEntropyCoder->resetEntropy    ();
+  ruiBits += m_pcEntropyCoder->getNumberOfWrittenBits();
+  
+  if (!bCalcDist)
+    ruiDist = xFindDistortionFrame(pcPic->getPicYuvOrg(), pcPic->getPicYuvRec());
+}
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+Void TEncGOP::xInitGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut )
+{
+  assert( iNumPicRcvd > 0 );
+  //  Exception for the first frame
+  if ( iPOCLast == 0 )
+  {
+    m_iGopSize    = 1;
+  }
+  else
+    m_iGopSize    = m_pcCfg->getGOPSize();
+  
+  assert (m_iGopSize > 0); 
+
+  return;
+}
+
+Void TEncGOP::xGetBuffer( TComList<TComPic*>&       rcListPic,
+                         TComList<TComPicYuv*>&    rcListPicYuvRecOut,
+                         Int                       iNumPicRcvd,
+                         Int                       iTimeOffset,
+                         TComPic*&                 rpcPic,
+                         TComPicYuv*&              rpcPicYuvRecOut,
+                         UInt                      uiPOCCurr )
+{
+  Int i;
+  //  Rec. output
+  TComList<TComPicYuv*>::iterator     iterPicYuvRec = rcListPicYuvRecOut.end();
+  for ( i = 0; i < iNumPicRcvd - iTimeOffset + 1; i++ )
+  {
+    iterPicYuvRec--;
+  }
+  
+  rpcPicYuvRecOut = *(iterPicYuvRec);
+  
+  //  Current pic.
+  TComList<TComPic*>::iterator        iterPic       = rcListPic.begin();
+  while (iterPic != rcListPic.end())
+  {
+    rpcPic = *(iterPic);
+    rpcPic->setCurrSliceIdx(0);
+    if (rpcPic->getPOC() == (Int)uiPOCCurr)
+    {
+      break;
+    }
+    iterPic++;
+  }
+  
+  assert (rpcPic->getPOC() == (Int)uiPOCCurr);
+  
+  return;
+}
+
+UInt64 TEncGOP::xFindDistortionFrame (TComPicYuv* pcPic0, TComPicYuv* pcPic1)
+{
+  Int     x, y;
+  Pel*  pSrc0   = pcPic0 ->getLumaAddr();
+  Pel*  pSrc1   = pcPic1 ->getLumaAddr();
+#if IBDI_DISTORTION
+  Int  iShift = g_uiBitIncrement;
+  Int  iOffset = 1<<(g_uiBitIncrement-1);
+#else
+  UInt  uiShift = g_uiBitIncrement<<1;
+#endif
+  Int   iTemp;
+  
+  Int   iStride = pcPic0->getStride();
+  Int   iWidth  = pcPic0->getWidth();
+  Int   iHeight = pcPic0->getHeight();
+  
+  UInt64  uiTotalDiff = 0;
+  
+  for( y = 0; y < iHeight; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+#if IBDI_DISTORTION
+      iTemp = ((pSrc0[x]+iOffset)>>iShift) - ((pSrc1[x]+iOffset)>>iShift); uiTotalDiff += iTemp * iTemp;
+#else
+      iTemp = pSrc0[x] - pSrc1[x]; uiTotalDiff += (iTemp*iTemp) >> uiShift;
+#endif
+    }
+    pSrc0 += iStride;
+    pSrc1 += iStride;
+  }
+  
+  iHeight >>= 1;
+  iWidth  >>= 1;
+  iStride >>= 1;
+  
+  pSrc0  = pcPic0->getCbAddr();
+  pSrc1  = pcPic1->getCbAddr();
+  
+  for( y = 0; y < iHeight; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+#if IBDI_DISTORTION
+      iTemp = ((pSrc0[x]+iOffset)>>iShift) - ((pSrc1[x]+iOffset)>>iShift); uiTotalDiff += iTemp * iTemp;
+#else
+      iTemp = pSrc0[x] - pSrc1[x]; uiTotalDiff += (iTemp*iTemp) >> uiShift;
+#endif
+    }
+    pSrc0 += iStride;
+    pSrc1 += iStride;
+  }
+  
+  pSrc0  = pcPic0->getCrAddr();
+  pSrc1  = pcPic1->getCrAddr();
+  
+  for( y = 0; y < iHeight; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+#if IBDI_DISTORTION
+      iTemp = ((pSrc0[x]+iOffset)>>iShift) - ((pSrc1[x]+iOffset)>>iShift); uiTotalDiff += iTemp * iTemp;
+#else
+      iTemp = pSrc0[x] - pSrc1[x]; uiTotalDiff += (iTemp*iTemp) >> uiShift;
+#endif
+    }
+    pSrc0 += iStride;
+    pSrc1 += iStride;
+  }
+  
+  return uiTotalDiff;
+}
+
+#if VERBOSE_RATE
+static const char* nalUnitTypeToString(NalUnitType type)
+{
+  switch (type)
+  {
+#if NAL_UNIT_TYPES_J1003_D7
+    case NAL_UNIT_CODED_SLICE_TRAIL_R: return "TRAIL_R";
+    case NAL_UNIT_CODED_SLICE_TRAIL_N: return "TRAIL_N";
+    case NAL_UNIT_CODED_SLICE_TLA: return "TLA";
+    case NAL_UNIT_CODED_SLICE_TSA_N: return "TSA_N";
+    case NAL_UNIT_CODED_SLICE_STSA_R: return "STSA_R";
+    case NAL_UNIT_CODED_SLICE_STSA_N: return "STSA_N";
+    case NAL_UNIT_CODED_SLICE_BLA: return "BLA";
+    case NAL_UNIT_CODED_SLICE_BLANT: return "BLANT";
+    case NAL_UNIT_CODED_SLICE_BLA_N_LP: return "BLA_N_LP";
+    case NAL_UNIT_CODED_SLICE_IDR: return "IDR";
+    case NAL_UNIT_CODED_SLICE_IDR_N_LP: return "IDR_N_LP";
+    case NAL_UNIT_CODED_SLICE_CRA: return "CRA";
+    case NAL_UNIT_CODED_SLICE_DLP: return "DLP";
+    case NAL_UNIT_CODED_SLICE_TFD: return "TFD";
+#else
+    case NAL_UNIT_CODED_SLICE: return "SLICE";
+    case NAL_UNIT_CODED_SLICE_TFD: return "TFD";
+    case NAL_UNIT_CODED_SLICE_TLA: return "TLA";
+    case NAL_UNIT_CODED_SLICE_CRA: return "CRA";
+    case NAL_UNIT_CODED_SLICE_CRANT: return "CRANT";
+    case NAL_UNIT_CODED_SLICE_BLA: return "BLA";
+    case NAL_UNIT_CODED_SLICE_BLANT: return "BLANT";
+    case NAL_UNIT_CODED_SLICE_IDR: return "IDR";
+#endif
+    case NAL_UNIT_VPS: return "VPS";
+    case NAL_UNIT_SPS: return "SPS";
+    case NAL_UNIT_PPS: return "PPS";
+#if NAL_UNIT_TYPES_J1003_D7
+    case NAL_UNIT_ACCESS_UNIT_DELIMITER: return "AUD";
+    case NAL_UNIT_EOS: return "EOS";
+    case NAL_UNIT_EOB: return "EOB";
+    case NAL_UNIT_FILLER_DATA: return "FILLER";
+    case NAL_UNIT_SEI: return "SEI";
+#else
+    case NAL_UNIT_APS: return "APS";
+    case NAL_UNIT_ACCESS_UNIT_DELIMITER: return "AUD";
+    case NAL_UNIT_FILLER_DATA: return "FILLER";
+    case NAL_UNIT_SEI: return "SEI";
+#endif
+    default: return "UNK";
+  }
+}
+#endif
+
+Void TEncGOP::xCalculateAddPSNR( TComPic* pcPic, TComPicYuv* pcPicD, const AccessUnit& accessUnit, Double dEncTime )
+{
+  Int     x, y;
+  UInt64 uiSSDY  = 0;
+  UInt64 uiSSDU  = 0;
+  UInt64 uiSSDV  = 0;
+  
+  Double  dYPSNR  = 0.0;
+  Double  dUPSNR  = 0.0;
+  Double  dVPSNR  = 0.0;
+  
+  //===== calculate PSNR =====
+  Pel*  pOrg    = pcPic ->getPicYuvOrg()->getLumaAddr();
+  Pel*  pRec    = pcPicD->getLumaAddr();
+  Int   iStride = pcPicD->getStride();
+  
+  Int   iWidth;
+  Int   iHeight;
+  
+  iWidth  = pcPicD->getWidth () - m_pcEncTop->getPad(0);
+  iHeight = pcPicD->getHeight() - m_pcEncTop->getPad(1);
+  
+  Int   iSize   = iWidth*iHeight;
+  
+  for( y = 0; y < iHeight; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+      Int iDiff = (Int)( pOrg[x] - pRec[x] );
+      uiSSDY   += iDiff * iDiff;
+    }
+    pOrg += iStride;
+    pRec += iStride;
+  }
+  
+  iHeight >>= 1;
+  iWidth  >>= 1;
+  iStride >>= 1;
+  pOrg  = pcPic ->getPicYuvOrg()->getCbAddr();
+  pRec  = pcPicD->getCbAddr();
+  
+  for( y = 0; y < iHeight; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+      Int iDiff = (Int)( pOrg[x] - pRec[x] );
+      uiSSDU   += iDiff * iDiff;
+    }
+    pOrg += iStride;
+    pRec += iStride;
+  }
+  
+  pOrg  = pcPic ->getPicYuvOrg()->getCrAddr();
+  pRec  = pcPicD->getCrAddr();
+  
+  for( y = 0; y < iHeight; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+      Int iDiff = (Int)( pOrg[x] - pRec[x] );
+      uiSSDV   += iDiff * iDiff;
+    }
+    pOrg += iStride;
+    pRec += iStride;
+  }
+  
+  unsigned int maxval = 255 * (1<<(g_uiBitDepth + g_uiBitIncrement -8));
+  Double fRefValueY = (double) maxval * maxval * iSize;
+  Double fRefValueC = fRefValueY / 4.0;
+  dYPSNR            = ( uiSSDY ? 10.0 * log10( fRefValueY / (Double)uiSSDY ) : 99.99 );
+  dUPSNR            = ( uiSSDU ? 10.0 * log10( fRefValueC / (Double)uiSSDU ) : 99.99 );
+  dVPSNR            = ( uiSSDV ? 10.0 * log10( fRefValueC / (Double)uiSSDV ) : 99.99 );
+
+  /* calculate the size of the access unit, excluding:
+   *  - any AnnexB contributions (start_code_prefix, zero_byte, etc.,)
+   *  - SEI NAL units
+   */
+  unsigned numRBSPBytes = 0;
+  for (AccessUnit::const_iterator it = accessUnit.begin(); it != accessUnit.end(); it++)
+  {
+    unsigned numRBSPBytes_nal = unsigned((*it)->m_nalUnitData.str().size());
+#if VERBOSE_RATE
+    printf("*** %6s numBytesInNALunit: %u\n", nalUnitTypeToString((*it)->m_nalUnitType), numRBSPBytes_nal);
+#endif
+    if ((*it)->m_nalUnitType != NAL_UNIT_SEI)
+      numRBSPBytes += numRBSPBytes_nal;
+  }
+
+  unsigned uibits = numRBSPBytes * 8;
+  m_vRVM_RP.push_back( uibits );
+
+  //===== add PSNR =====
+#if SVC_EXTENSION
+  m_gcAnalyzeAll[m_layerId].addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
+  TComSlice*  pcSlice = pcPic->getSlice(0);
+  if (pcSlice->isIntra())
+  {
+    m_gcAnalyzeI[m_layerId].addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
+  }
+  if (pcSlice->isInterP())
+  {
+    m_gcAnalyzeP[m_layerId].addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
+  }
+  if (pcSlice->isInterB())
+  {
+    m_gcAnalyzeB[m_layerId].addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
+  }
+#else
+  m_gcAnalyzeAll.addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
+  TComSlice*  pcSlice = pcPic->getSlice(0);
+  if (pcSlice->isIntra())
+  {
+    m_gcAnalyzeI.addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
+  }
+  if (pcSlice->isInterP())
+  {
+    m_gcAnalyzeP.addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
+  }
+  if (pcSlice->isInterB())
+  {
+    m_gcAnalyzeB.addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
+  }
+#endif
+
+  Char c = (pcSlice->isIntra() ? 'I' : pcSlice->isInterP() ? 'P' : 'B');
+  if (!pcSlice->isReferenced()) c += 32;
+
+#if SVC_EXTENSION
+#if ADAPTIVE_QP_SELECTION
+  printf("POC %4d LId: %1d TId: %1d ( %c-SLICE, nQP %d QP %d ) %10d bits",
+         pcSlice->getPOC(),
+         pcSlice->getLayerId(),
+         pcSlice->getTLayer(),
+         c,
+         pcSlice->getSliceQpBase(),
+         pcSlice->getSliceQp(),
+         uibits );
+#else
+  printf("POC %4d LId: %1d TId: %1d ( %c-SLICE, QP %d ) %10d bits",
+         pcSlice->getPOC()-pcSlice->getLastIDR(),
+         pcSlice->getLayerId(),
+         pcSlice->getTLayer(),
+         c,
+         pcSlice->getSliceQp(),
+         uibits );
+#endif
+#else
+#if ADAPTIVE_QP_SELECTION
+  printf("POC %4d TId: %1d ( %c-SLICE, nQP %d QP %d ) %10d bits",
+         pcSlice->getPOC(),
+         pcSlice->getTLayer(),
+         c,
+         pcSlice->getSliceQpBase(),
+         pcSlice->getSliceQp(),
+         uibits );
+#else
+  printf("POC %4d TId: %1d ( %c-SLICE, QP %d ) %10d bits",
+         pcSlice->getPOC()-pcSlice->getLastIDR(),
+         pcSlice->getTLayer(),
+         c,
+         pcSlice->getSliceQp(),
+         uibits );
+#endif
+#endif
+
+  printf(" [Y %6.4lf dB    U %6.4lf dB    V %6.4lf dB]", dYPSNR, dUPSNR, dVPSNR );
+  printf(" [ET %5.0f ]", dEncTime );
+  
+  for (Int iRefList = 0; iRefList < 2; iRefList++)
+  {
+    printf(" [L%d ", iRefList);
+    for (Int iRefIndex = 0; iRefIndex < pcSlice->getNumRefIdx(RefPicList(iRefList)); iRefIndex++)
+    {
+      printf ("%d ", pcSlice->getRefPOC(RefPicList(iRefList), iRefIndex)-pcSlice->getLastIDR());
+    }
+    printf("]");
+  }
+}
+
+/** Function for deciding the nal_unit_type.
+ * \param uiPOCCurr POC of the current picture
+ * \returns the nal_unit type of the picture
+ * This function checks the configuration and returns the appropriate nal_unit_type for the picture.
+ */
+NalUnitType TEncGOP::getNalUnitType(UInt uiPOCCurr)
+{
+  if (uiPOCCurr == 0)
+  {
+    return NAL_UNIT_CODED_SLICE_IDR;
+  }
+  if (uiPOCCurr % m_pcCfg->getIntraPeriod() == 0)
+  {
+    if (m_pcCfg->getDecodingRefreshType() == 1)
+    {
+      return NAL_UNIT_CODED_SLICE_CRA;
+    }
+    else if (m_pcCfg->getDecodingRefreshType() == 2)
+    {
+      return NAL_UNIT_CODED_SLICE_IDR;
+    }
+  }
+  if(m_pocCRA>0)
+  {
+    if(uiPOCCurr<m_pocCRA)
+    {
+      // All leading pictures are being marked as TFD pictures here since current encoder uses all 
+      // reference pictures while encoding leading pictures. An encoder can ensure that a leading 
+      // picture can be still decodable when random accessing to a CRA/CRANT/BLA/BLANT picture by 
+      // controlling the reference pictures used for encoding that leading picture. Such a leading 
+      // picture need not be marked as a TFD picture.
+      return NAL_UNIT_CODED_SLICE_TFD;
+    }
+  }
+#if NAL_UNIT_TYPES_J1003_D7
+  return NAL_UNIT_CODED_SLICE_TRAIL_R;
+#else
+  return NAL_UNIT_CODED_SLICE;
+#endif
+}
+
+Double TEncGOP::xCalculateRVM()
+{
+  Double dRVM = 0;
+  
+  if( m_pcCfg->getGOPSize() == 1 && m_pcCfg->getIntraPeriod() != 1 && m_pcCfg->getFrameToBeEncoded() > RVM_VCEGAM10_M * 2 )
+  {
+    // calculate RVM only for lowdelay configurations
+    std::vector<Double> vRL , vB;
+    size_t N = m_vRVM_RP.size();
+    vRL.resize( N );
+    vB.resize( N );
+    
+    Int i;
+    Double dRavg = 0 , dBavg = 0;
+    vB[RVM_VCEGAM10_M] = 0;
+    for( i = RVM_VCEGAM10_M + 1 ; i < N - RVM_VCEGAM10_M + 1 ; i++ )
+    {
+      vRL[i] = 0;
+      for( Int j = i - RVM_VCEGAM10_M ; j <= i + RVM_VCEGAM10_M - 1 ; j++ )
+        vRL[i] += m_vRVM_RP[j];
+      vRL[i] /= ( 2 * RVM_VCEGAM10_M );
+      vB[i] = vB[i-1] + m_vRVM_RP[i] - vRL[i];
+      dRavg += m_vRVM_RP[i];
+      dBavg += vB[i];
+    }
+    
+    dRavg /= ( N - 2 * RVM_VCEGAM10_M );
+    dBavg /= ( N - 2 * RVM_VCEGAM10_M );
+    
+    double dSigamB = 0;
+    for( i = RVM_VCEGAM10_M + 1 ; i < N - RVM_VCEGAM10_M + 1 ; i++ )
+    {
+      Double tmp = vB[i] - dBavg;
+      dSigamB += tmp * tmp;
+    }
+    dSigamB = sqrt( dSigamB / ( N - 2 * RVM_VCEGAM10_M ) );
+    
+    double f = sqrt( 12.0 * ( RVM_VCEGAM10_M - 1 ) / ( RVM_VCEGAM10_M + 1 ) );
+    
+    dRVM = dSigamB / dRavg * f;
+  }
+  
+  return( dRVM );
+}
+
+/** Determine the difference between consecutive tile sizes (in bytes) and writes it to  bistream rNalu [slice header]
+ * \param rpcBitstreamRedirect contains the bitstream to be concatenated to rNalu. rpcBitstreamRedirect contains slice payload. rpcSlice contains tile location information.
+ * \returns Updates rNalu to contain concatenated bitstream. rpcBitstreamRedirect is cleared at the end of this function call.
+ */
+Void TEncGOP::xWriteTileLocationToSliceHeader (OutputNALUnit& rNalu, TComOutputBitstream*& rpcBitstreamRedirect, TComSlice*& rpcSlice)
+{
+  // Byte-align
+#if BYTE_ALIGNMENT
+  rNalu.m_Bitstream.writeByteAlignment();   // Slice header byte-alignment
+#else
+  rNalu.m_Bitstream.writeAlignOne();
+#endif
+
+  // Perform bitstream concatenation
+  if (rpcBitstreamRedirect->getNumberOfWrittenBits() > 0)
+  {
+    UInt uiBitCount  = rpcBitstreamRedirect->getNumberOfWrittenBits();
+    if (rpcBitstreamRedirect->getByteStreamLength()>0)
+    {
+      UChar *pucStart  =  reinterpret_cast<UChar*>(rpcBitstreamRedirect->getByteStream());
+      UInt uiWriteByteCount = 0;
+      while (uiWriteByteCount < (uiBitCount >> 3) )
+      {
+        UInt uiBits = (*pucStart);
+        rNalu.m_Bitstream.write(uiBits, 8);
+        pucStart++;
+        uiWriteByteCount++;
+      }
+    }
+    UInt uiBitsHeld = (uiBitCount & 0x07);
+    for (UInt uiIdx=0; uiIdx < uiBitsHeld; uiIdx++)
+    {
+      rNalu.m_Bitstream.write((rpcBitstreamRedirect->getHeldBits() & (1 << (7-uiIdx))) >> (7-uiIdx), 1);
+    }          
+  }
+
+  m_pcEntropyCoder->setBitstream(&rNalu.m_Bitstream);
+
+  delete rpcBitstreamRedirect;
+  rpcBitstreamRedirect = new TComOutputBitstream;
+}
+
+// Function will arrange the long-term pictures in the decreasing order of poc_lsb_lt, 
+// and among the pictures with the same lsb, it arranges them in increasing delta_poc_msb_cycle_lt value
+Void TEncGOP::arrangeLongtermPicturesInRPS(TComSlice *pcSlice, TComList<TComPic*>& rcListPic)
+{
+  TComReferencePictureSet *rps = pcSlice->getRPS();
+  if(!rps->getNumberOfLongtermPictures())
+  {
+    return;
+  }
+
+  // Arrange long-term reference pictures in the correct order of LSB and MSB,
+  // and assign values for pocLSBLT and MSB present flag
+  Int longtermPicsPoc[MAX_NUM_REF_PICS], longtermPicsLSB[MAX_NUM_REF_PICS], indices[MAX_NUM_REF_PICS];
+  Bool mSBPresentFlag[MAX_NUM_REF_PICS];
+  ::memset(longtermPicsPoc, 0, sizeof(longtermPicsPoc));    // Store POC values of LTRP
+  ::memset(longtermPicsLSB, 0, sizeof(longtermPicsLSB));    // Store POC LSB values of LTRP
+  ::memset(indices        , 0, sizeof(indices));            // Indices to aid in tracking sorted LTRPs
+  ::memset(mSBPresentFlag , 0, sizeof(mSBPresentFlag));     // Indicate if MSB needs to be present
+
+  // Get the long-term reference pictures 
+  Int offset = rps->getNumberOfNegativePictures() + rps->getNumberOfPositivePictures();
+  Int i, ctr = 0;
+  Int maxPicOrderCntLSB = 1 << pcSlice->getSPS()->getBitsForPOC();
+  for(i = rps->getNumberOfPictures() - 1; i >= offset; i--, ctr++)
+  {
+    longtermPicsPoc[ctr] = rps->getPOC(i);                                  // LTRP POC
+    longtermPicsLSB[ctr] = getLSB(longtermPicsPoc[ctr], maxPicOrderCntLSB); // LTRP POC LSB
+    indices[ctr]      = i; 
+  }
+  Int numLongPics = rps->getNumberOfLongtermPictures();
+  assert(ctr == numLongPics);
+
+  // Arrange LTR pictures in decreasing order of LSB
+  for(i = 0; i < numLongPics; i++)
+  {
+    for(Int j = 0; j < numLongPics - 1; j++)
+    {
+      if(longtermPicsLSB[j] < longtermPicsLSB[j+1])
+      {
+        std::swap(longtermPicsPoc[j], longtermPicsPoc[j+1]);
+        std::swap(longtermPicsLSB[j], longtermPicsLSB[j+1]);
+        std::swap(indices[j]        , indices[j+1]        );
+      }
+    }
+  }
+  // Now for those pictures that have the same LSB, arrange them 
+  // in increasing MSB cycle, or equivalently decreasing MSB
+  for(i = 0; i < numLongPics;)    // i incremented using j
+  {
+    Int j = i + 1;
+    Int pocLSB = longtermPicsLSB[i];
+    for(; j < numLongPics; j++)
+    {
+      if(pocLSB != longtermPicsLSB[j])
+      {
+        break;
+      }
+    }
+    // Last index upto which lsb equals pocLSB is j - 1 
+    // Now sort based on the MSB values
+    Int sta, end;
+    for(sta = i; sta < j; sta++)
+    {
+      for(end = i; end < j - 1; end++)
+      {
+      // longtermPicsMSB = longtermPicsPoc - longtermPicsLSB
+        if(longtermPicsPoc[end] - longtermPicsLSB[end] < longtermPicsPoc[end+1] - longtermPicsLSB[end+1])
+        {
+          std::swap(longtermPicsPoc[end], longtermPicsPoc[end+1]);
+          std::swap(longtermPicsLSB[end], longtermPicsLSB[end+1]);
+          std::swap(indices[end]        , indices[end+1]        );
+        }
+      }
+    }
+    i = j;
+  }
+  for(i = 0; i < numLongPics; i++)
+  {
+    // Check if MSB present flag should be enabled.
+    // Check if the buffer contains any pictures that have the same LSB.
+    TComList<TComPic*>::iterator  iterPic = rcListPic.begin();  
+    TComPic*                      pcPic;
+    while ( iterPic != rcListPic.end() )
+    {
+      pcPic = *iterPic;
+      if( (getLSB(pcPic->getPOC(), maxPicOrderCntLSB) == longtermPicsLSB[i])   &&     // Same LSB
+#if REFERENCE_PICTURE_DEFN
+                                      (pcPic->getSlice(0)->isReferenced())     &&    // Reference picture
+#else
+                                      (pcPic->getSlice(0)->getNalRefFlag())     &&    // Reference picture
+#endif
+                                        (pcPic->getPOC() != longtermPicsPoc[i])    )  // Not the LTRP itself
+      {
+        mSBPresentFlag[i] = true;
+        break;
+      }
+      iterPic++;      
+    }
+  }
+
+  // tempArray for usedByCurr flag
+  Bool tempArray[MAX_NUM_REF_PICS]; ::memset(tempArray, 0, sizeof(tempArray));
+  for(i = 0; i < numLongPics; i++)
+  {
+    tempArray[i] = rps->getUsed(indices[i]);
+  }
+  // Now write the final values;
+  ctr = 0;
+  Int currMSB = 0, currLSB = 0;
+  // currPicPoc = currMSB + currLSB
+  currLSB = getLSB(pcSlice->getPOC(), maxPicOrderCntLSB);  
+  currMSB = pcSlice->getPOC() - currLSB;
+
+  for(i = rps->getNumberOfPictures() - 1; i >= offset; i--, ctr++)
+  {
+    rps->setPOC                   (i, longtermPicsPoc[ctr]);
+    rps->setDeltaPOC              (i, - pcSlice->getPOC() + longtermPicsPoc[ctr]);
+    rps->setUsed                  (i, tempArray[ctr]);
+    rps->setPocLSBLT              (i, longtermPicsLSB[ctr]);
+    rps->setDeltaPocMSBCycleLT    (i, (currMSB - (longtermPicsPoc[ctr] - longtermPicsLSB[ctr])) / maxPicOrderCntLSB);
+    rps->setDeltaPocMSBPresentFlag(i, mSBPresentFlag[ctr]);     
+
+    assert(rps->getDeltaPocMSBCycleLT(i) >= 0);   // Non-negative value
+  }
+}
+//! \}
Index: /trunk/source/Lib/TLibEncoder/TEncGOP.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncGOP.h	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/TEncGOP.h	(revision 2)
@@ -0,0 +1,208 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncGOP.h
+    \brief    GOP encoder class (header)
+*/
+
+#ifndef __TENCGOP__
+#define __TENCGOP__
+
+#include <list>
+
+#include <stdlib.h>
+
+#include "TLibCommon/TComList.h"
+#include "TLibCommon/TComPic.h"
+#include "TLibCommon/TComBitCounter.h"
+#include "TLibCommon/TComLoopFilter.h"
+#include "TLibCommon/AccessUnit.h"
+#include "TEncAdaptiveLoopFilter.h"
+#include "TEncSampleAdaptiveOffset.h"
+#include "TEncSlice.h"
+#include "TEncEntropy.h"
+#include "TEncCavlc.h"
+#include "TEncSbac.h"
+#include "SEIwrite.h"
+
+#include "TEncAnalyze.h"
+#include "TEncRateCtrl.h"
+#include <vector>
+
+//! \ingroup TLibEncoder
+//! \{
+
+class TEncTop;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// GOP encoder class
+class TEncGOP
+{
+private:
+  //  Data
+  Bool                    m_bLongtermTestPictureHasBeenCoded;
+  Bool                    m_bLongtermTestPictureHasBeenCoded2;
+#if LTRP_IN_SPS
+  UInt            m_numLongTermRefPicSPS;
+  UInt            m_ltRefPicPocLsbSps[33];
+  Bool            m_ltRefPicUsedByCurrPicFlag[33];
+#endif
+  Int                     m_iLastIDR;
+  Int                     m_iGopSize;
+  Int                     m_iNumPicCoded;
+  Bool                    m_bFirst;
+  
+#if SVC_EXTENSION
+  UInt                    m_layerId;      
+#endif
+
+  //  Access channel
+  TEncTop*                m_pcEncTop;
+  TEncCfg*                m_pcCfg;
+  TEncSlice*              m_pcSliceEncoder;
+  TComList<TComPic*>*     m_pcListPic;
+
+#if SVC_EXTENSION
+  TEncTop**               m_ppcTEncTop;
+#if SVC_UPSAMPLING
+  TEncSearch*             m_pcPredSearch;                       ///< encoder search class
+#endif  
+#endif
+  
+  TEncEntropy*            m_pcEntropyCoder;
+  TEncCavlc*              m_pcCavlcCoder;
+  TEncSbac*               m_pcSbacCoder;
+  TEncBinCABAC*           m_pcBinCABAC;
+  TComLoopFilter*         m_pcLoopFilter;
+
+  SEIWriter               m_seiWriter;
+  
+#if !REMOVE_ALF
+  // Adaptive Loop filter
+  TEncAdaptiveLoopFilter* m_pcAdaptiveLoopFilter;
+#endif
+  //--Adaptive Loop filter
+  TEncSampleAdaptiveOffset*  m_pcSAO;
+  TComBitCounter*         m_pcBitCounter;
+  TEncRateCtrl*           m_pcRateCtrl;
+  // indicate sequence first
+  Bool                    m_bSeqFirst;
+  
+  // clean decoding refresh
+  Bool                    m_bRefreshPending;
+  Int                     m_pocCRA;
+  std::vector<Int>        m_storedStartCUAddrForEncodingSlice;
+  std::vector<Int>        m_storedStartCUAddrForEncodingDependentSlice;
+
+  std::vector<Int> m_vRVM_RP;
+#if BUFFERING_PERIOD_AND_TIMING_SEI
+  UInt                    m_lastBPSEI;
+  UInt                    m_totalCoded;
+  UInt                    m_cpbRemovalDelay;
+#endif
+public:
+  TEncGOP();
+  virtual ~TEncGOP();
+  
+#if SVC_EXTENSION
+  Void  create      ( Int iWidth, Int iHeight, UInt iMaxCUWidth, UInt iMaxCUHeight, UInt layerId );
+#else
+  Void  create      ( Int iWidth, Int iHeight, UInt iMaxCUWidth, UInt iMaxCUHeight );
+#endif
+  Void  destroy     ();
+  
+  Void  init        ( TEncTop* pcTEncTop );
+#if SVC_EXTENSION
+  Void  compressGOP ( Int iPicIdInGOP, Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRec, std::list<AccessUnit>& accessUnitsInGOP );
+#else
+  Void  compressGOP ( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRec, std::list<AccessUnit>& accessUnitsInGOP );
+#endif
+  Void xWriteTileLocationToSliceHeader (OutputNALUnit& rNalu, TComOutputBitstream*& rpcBitstreamRedirect, TComSlice*& rpcSlice);
+
+  
+  Int   getGOPSize()          { return  m_iGopSize;  }
+  
+  TComList<TComPic*>*   getListPic()      { return m_pcListPic; }
+  
+  Void  printOutSummary      ( UInt uiNumAllPicCoded );
+  Void  preLoopFilterPicAll  ( TComPic* pcPic, UInt64& ruiDist, UInt64& ruiBits );
+  
+  TEncSlice*  getSliceEncoder()   { return m_pcSliceEncoder; }
+  NalUnitType getNalUnitType( UInt uiPOCCurr );
+#if !REMOVE_APS
+  Void freeAPS     (TComAPS* pAPS, TComSPS* pSPS);
+  Void allocAPS    (TComAPS* pAPS, TComSPS* pSPS);
+#endif
+  Void arrangeLongtermPicturesInRPS(TComSlice *, TComList<TComPic*>& );
+protected:
+#if !REMOVE_APS
+  Void encodeAPS   (TComAPS* pcAPS, TComOutputBitstream& APSbs, TComSlice* pcSlice);            //!< encode APS syntax elements
+  Void assignNewAPS(TComAPS& cAPS, Int apsID, std::vector<TComAPS>& vAPS, TComSlice* pcSlice);  //!< Assign APS object into APS container
+#endif
+  TEncRateCtrl* getRateCtrl()       { return m_pcRateCtrl;  }
+
+protected:
+  Void  xInitGOP          ( Int iPOC, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut );
+  Void  xGetBuffer        ( TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, Int iNumPicRcvd, Int iTimeOffset, TComPic*& rpcPic, TComPicYuv*& rpcPicYuvRecOut, UInt uiPOCCurr );
+  
+  Void  xCalculateAddPSNR ( TComPic* pcPic, TComPicYuv* pcPicD, const AccessUnit&, Double dEncTime );
+  
+  UInt64 xFindDistortionFrame (TComPicYuv* pcPic0, TComPicYuv* pcPic1);
+
+  Double xCalculateRVM();
+};// END CLASS DEFINITION TEncGOP
+
+// ====================================================================================================================
+// Enumeration
+// ====================================================================================================================
+enum PROCESSING_STATE
+{
+  EXECUTE_INLOOPFILTER,
+  ENCODE_APS,
+  ENCODE_SLICE
+};
+
+enum SCALING_LIST_PARAMETER
+{
+  SCALING_LIST_OFF,
+  SCALING_LIST_DEFAULT,
+  SCALING_LIST_FILE_READ
+};
+
+//! \}
+
+#endif // __TENCGOP__
+
Index: /trunk/source/Lib/TLibEncoder/TEncPic.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncPic.cpp	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/TEncPic.cpp	(revision 2)
@@ -0,0 +1,163 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncPic.cpp
+    \brief    class of picture which includes side information for encoder
+*/
+
+#include "TEncPic.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+/** Constructor
+ */
+TEncQPAdaptationUnit::TEncQPAdaptationUnit()
+: m_dActivity(0.0)
+{
+}
+
+/** Destructor
+ */
+TEncQPAdaptationUnit::~TEncQPAdaptationUnit()
+{
+}
+
+/** Constructor
+ */
+TEncPicQPAdaptationLayer::TEncPicQPAdaptationLayer()
+: m_uiAQPartWidth(0)
+, m_uiAQPartHeight(0)
+, m_uiNumAQPartInWidth(0)
+, m_uiNumAQPartInHeight(0)
+, m_acTEncAQU(NULL)
+, m_dAvgActivity(0.0)
+{
+}
+
+/** Destructor
+ */
+TEncPicQPAdaptationLayer::~TEncPicQPAdaptationLayer()
+{
+  destroy();
+}
+
+/** Initialize member variables
+ * \param iWidth Picture width
+ * \param iHeight Picture height
+ * \param uiAQPartWidth Width of unit block for analyzing local image characteristics
+ * \param uiAQPartHeight Height of unit block for analyzing local image characteristics
+ * \return Void
+ */
+Void TEncPicQPAdaptationLayer::create( Int iWidth, Int iHeight, UInt uiAQPartWidth, UInt uiAQPartHeight )
+{
+  m_uiAQPartWidth = uiAQPartWidth;
+  m_uiAQPartHeight = uiAQPartHeight;
+  m_uiNumAQPartInWidth = (iWidth + m_uiAQPartWidth-1) / m_uiAQPartWidth;
+  m_uiNumAQPartInHeight = (iHeight + m_uiAQPartHeight-1) / m_uiAQPartHeight;
+  m_acTEncAQU = new TEncQPAdaptationUnit[ m_uiNumAQPartInWidth * m_uiNumAQPartInHeight ];
+}
+
+/** Clean up
+ * \return Void
+ */
+Void TEncPicQPAdaptationLayer::destroy()
+{
+  if (m_acTEncAQU)
+  {
+    delete[] m_acTEncAQU;
+    m_acTEncAQU = NULL;
+  }
+}
+
+/** Constructor
+ */
+TEncPic::TEncPic()
+: m_acAQLayer(NULL)
+, m_uiMaxAQDepth(0)
+{
+}
+
+/** Destructor
+ */
+TEncPic::~TEncPic()
+{
+  destroy();
+}
+
+/** Initialize member variables
+ * \param iWidth Picture width
+ * \param iHeight Picture height
+ * \param uiMaxWidth Maximum CU width
+ * \param uiMaxHeight Maximum CU height
+ * \param uiMaxDepth Maximum CU depth
+ * \param uiMaxAQDepth Maximum depth of unit block for assigning QP adaptive to local image characteristics
+ * \param bIsVirtual
+ * \return Void
+ */
+#if SVC_UPSAMPLING
+Void TEncPic::create( Int iWidth, Int iHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth, UInt uiMaxAQDepth, TComSPS* pcSps, Bool bIsVirtual )
+#else
+Void TEncPic::create( Int iWidth, Int iHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth, UInt uiMaxAQDepth, Bool bIsVirtual )
+#endif
+{
+#if SVC_UPSAMPLING
+  TComPic::create( iWidth, iHeight, uiMaxWidth, uiMaxHeight, uiMaxDepth, pcSps, bIsVirtual );
+#else
+  TComPic::create( iWidth, iHeight, uiMaxWidth, uiMaxHeight, uiMaxDepth, bIsVirtual );
+#endif
+  m_uiMaxAQDepth = uiMaxAQDepth;
+  if ( uiMaxAQDepth > 0 )
+  {
+    m_acAQLayer = new TEncPicQPAdaptationLayer[ m_uiMaxAQDepth ]; 
+    for (UInt d = 0; d < m_uiMaxAQDepth; d++)
+    {
+      m_acAQLayer[d].create( iWidth, iHeight, uiMaxWidth>>d, uiMaxHeight>>d );
+    }
+  }
+}
+
+/** Clean up
+ * \return Void
+ */
+Void TEncPic::destroy()
+{
+  if (m_acAQLayer)
+  {
+    delete[] m_acAQLayer;
+    m_acAQLayer = NULL;
+  }
+  TComPic::destroy();
+}
+//! \}
+
Index: /trunk/source/Lib/TLibEncoder/TEncPic.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncPic.h	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/TEncPic.h	(revision 2)
@@ -0,0 +1,120 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncPic.h
+    \brief    class of picture which includes side information for encoder (header)
+*/
+
+#ifndef __TENCPIC__
+#define __TENCPIC__
+
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComPic.h"
+#if SVC_UPSAMPLING
+#include "TLibCommon/TComSlice.h"
+#endif
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// Unit block for storing image characteristics
+class TEncQPAdaptationUnit
+{
+private:
+  Double m_dActivity;
+
+public:
+  TEncQPAdaptationUnit();
+  ~TEncQPAdaptationUnit();
+
+  Void   setActivity( Double d ) { m_dActivity = d; }
+  Double getActivity()           { return m_dActivity; }
+};
+
+/// Local image characteristics for CUs on a specific depth
+class TEncPicQPAdaptationLayer
+{
+private:
+  UInt                  m_uiAQPartWidth;
+  UInt                  m_uiAQPartHeight;
+  UInt                  m_uiNumAQPartInWidth;
+  UInt                  m_uiNumAQPartInHeight;
+  TEncQPAdaptationUnit* m_acTEncAQU;
+  Double                m_dAvgActivity;
+
+public:
+  TEncPicQPAdaptationLayer();
+  virtual ~TEncPicQPAdaptationLayer();
+
+  Void  create( Int iWidth, Int iHeight, UInt uiAQPartWidth, UInt uiAQPartHeight );
+  Void  destroy();
+
+  UInt                   getAQPartWidth()        { return m_uiAQPartWidth;       }
+  UInt                   getAQPartHeight()       { return m_uiAQPartHeight;      }
+  UInt                   getNumAQPartInWidth()   { return m_uiNumAQPartInWidth;  }
+  UInt                   getNumAQPartInHeight()  { return m_uiNumAQPartInHeight; }
+  UInt                   getAQPartStride()       { return m_uiNumAQPartInWidth;  }
+  TEncQPAdaptationUnit*  getQPAdaptationUnit()   { return m_acTEncAQU;           }
+  Double                 getAvgActivity()        { return m_dAvgActivity;        }
+
+  Void                   setAvgActivity( Double d )  { m_dAvgActivity = d; }
+};
+
+/// Picture class including local image characteristics information for QP adaptation
+class TEncPic : public TComPic
+{
+private:
+  TEncPicQPAdaptationLayer* m_acAQLayer;
+  UInt                      m_uiMaxAQDepth;
+
+public:
+  TEncPic();
+  virtual ~TEncPic();
+
+#if SVC_UPSAMPLING
+  Void          create( Int iWidth, Int iHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth, UInt uiMaxAQDepth, TComSPS* pcSps, Bool bIsVirtual = false );
+#else
+  Void          create( Int iWidth, Int iHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth, UInt uiMaxAQDepth, Bool bIsVirtual = false );
+#endif
+  virtual Void  destroy();
+
+  TEncPicQPAdaptationLayer* getAQLayer( UInt uiDepth )  { return &m_acAQLayer[uiDepth]; }
+  UInt                      getMaxAQDepth()             { return m_uiMaxAQDepth;        }
+};
+
+//! \}
+
+#endif // __TENCPIC__
Index: /trunk/source/Lib/TLibEncoder/TEncPreanalyzer.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncPreanalyzer.cpp	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/TEncPreanalyzer.cpp	(revision 2)
@@ -0,0 +1,141 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncPreanalyzer.cpp
+    \brief    source picture analyzer class
+*/
+
+#include <cfloat>
+#include <algorithm>
+
+#include "TEncPreanalyzer.h"
+
+using namespace std;
+
+//! \ingroup TLibEncoder
+//! \{
+
+/** Constructor
+ */
+TEncPreanalyzer::TEncPreanalyzer()
+{
+}
+
+/** Destructor
+ */
+TEncPreanalyzer::~TEncPreanalyzer()
+{
+}
+
+/** Analyze source picture and compute local image characteristics used for QP adaptation
+ * \param pcEPic Picture object to be analyzed
+ * \return Void
+ */
+Void TEncPreanalyzer::xPreanalyze( TEncPic* pcEPic )
+{
+  TComPicYuv* pcPicYuv = pcEPic->getPicYuvOrg();
+  const Int iWidth = pcPicYuv->getWidth();
+  const Int iHeight = pcPicYuv->getHeight();
+  const Int iStride = pcPicYuv->getStride();
+
+  for ( UInt d = 0; d < pcEPic->getMaxAQDepth(); d++ )
+  {
+    const Pel* pLineY = pcPicYuv->getLumaAddr();
+    TEncPicQPAdaptationLayer* pcAQLayer = pcEPic->getAQLayer(d);
+    const UInt uiAQPartWidth = pcAQLayer->getAQPartWidth();
+    const UInt uiAQPartHeight = pcAQLayer->getAQPartHeight();
+    TEncQPAdaptationUnit* pcAQU = pcAQLayer->getQPAdaptationUnit();
+
+    Double dSumAct = 0.0;
+    for ( UInt y = 0; y < iHeight; y += uiAQPartHeight )
+    {
+      const UInt uiCurrAQPartHeight = min(uiAQPartHeight, iHeight-y);
+      for ( UInt x = 0; x < iWidth; x += uiAQPartWidth, pcAQU++ )
+      {
+        const UInt uiCurrAQPartWidth = min(uiAQPartWidth, iWidth-x);
+        const Pel* pBlkY = &pLineY[x];
+        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++ )
+          {
+            uiSum  [0] += pBlkY[bx];
+            uiSumSq[0] += pBlkY[bx] * pBlkY[bx];
+          }
+          for ( ; bx < uiCurrAQPartWidth; bx++, uiNumPixInAQPart++ )
+          {
+            uiSum  [1] += pBlkY[bx];
+            uiSumSq[1] += pBlkY[bx] * pBlkY[bx];
+          }
+          pBlkY += iStride;
+        }
+        for ( ; by < uiCurrAQPartHeight; by++ )
+        {
+          UInt bx = 0;
+          for ( ; bx < uiCurrAQPartWidth>>1; bx++, uiNumPixInAQPart++ )
+          {
+            uiSum  [2] += pBlkY[bx];
+            uiSumSq[2] += pBlkY[bx] * pBlkY[bx];
+          }
+          for ( ; bx < uiCurrAQPartWidth; bx++, uiNumPixInAQPart++ )
+          {
+            uiSum  [3] += pBlkY[bx];
+            uiSumSq[3] += pBlkY[bx] * pBlkY[bx];
+          }
+          pBlkY += iStride;
+        }
+
+        Double dMinVar = DBL_MAX;
+        for ( Int i=0; i<4; i++)
+        {
+          const Double dAverage = Double(uiSum[i]) / uiNumPixInAQPart;
+          const Double dVariance = Double(uiSumSq[i]) / uiNumPixInAQPart - dAverage * dAverage;
+          dMinVar = min(dMinVar, dVariance);
+        }
+        const Double dActivity = 1.0 + dMinVar;
+        pcAQU->setActivity( dActivity );
+        dSumAct += dActivity;
+      }
+      pLineY += iStride * uiCurrAQPartHeight;
+    }
+
+    const Double dAvgAct = dSumAct / (pcAQLayer->getNumAQPartInWidth() * pcAQLayer->getNumAQPartInHeight());
+    pcAQLayer->setAvgActivity( dAvgAct );
+  }
+}
+//! \}
+
Index: /trunk/source/Lib/TLibEncoder/TEncPreanalyzer.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncPreanalyzer.h	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/TEncPreanalyzer.h	(revision 2)
@@ -0,0 +1,62 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncPreanalyzer.h
+    \brief    source picture analyzer class (header)
+*/
+
+#ifndef __TENCPREANALYZER__
+#define __TENCPREANALYZER__
+
+#include "TEncPic.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// Source picture analyzer class
+class TEncPreanalyzer
+{
+public:
+  TEncPreanalyzer();
+  virtual ~TEncPreanalyzer();
+
+  Void xPreanalyze( TEncPic* pcPic );
+};
+
+//! \}
+
+#endif // __TENCPREANALYZER__
Index: /trunk/source/Lib/TLibEncoder/TEncRateCtrl.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncRateCtrl.cpp	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/TEncRateCtrl.cpp	(revision 2)
@@ -0,0 +1,646 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncRateCtrl.cpp
+    \brief    Rate control manager class
+*/
+#include "TEncRateCtrl.h"
+#include "../TLibCommon/TComPic.h"
+
+#include <cmath>
+
+using namespace std;
+
+#define ADJUSTMENT_FACTOR       0.60
+#define HIGH_QSTEP_THRESHOLD    9.5238
+#define HIGH_QSTEP_ALPHA        4.9371
+#define HIGH_QSTEP_BETA         0.0922
+#define LOW_QSTEP_ALPHA         16.7429
+#define LOW_QSTEP_BETA          -1.1494
+
+#define MAD_PRED_Y1             1.0
+#define MAD_PRED_Y2             0.0
+
+enum MAD_HISOTRY {
+  MAD_PPPrevious = 0,
+  MAD_PPrevious  = 1,
+  MAD_Previous   = 2
+};
+
+Void    MADLinearModel::initMADLinearModel()
+{
+  m_activeOn = false;
+  m_paramY1  = 1.0;
+  m_paramY2  = 0.0;
+  m_costMADs[0] = m_costMADs[1] = m_costMADs[2] = 0.0;
+}
+
+Double  MADLinearModel::getMAD()
+{
+  Double costPredMAD = m_paramY1 * m_costMADs[MAD_Previous] + m_paramY2;
+
+  if(costPredMAD < 0)
+  {
+    costPredMAD = m_costMADs[MAD_Previous];
+    m_paramY1   = MAD_PRED_Y1;
+    m_paramY2   = MAD_PRED_Y2;
+  } 
+  return costPredMAD;
+}
+
+Void    MADLinearModel::updateMADLiearModel()
+{
+  Double dNewY1 = ((m_costMADs[MAD_Previous] - m_costMADs[MAD_PPrevious]) / (m_costMADs[MAD_PPrevious] - m_costMADs[MAD_PPPrevious]));
+  Double dNewY2 =  (m_costMADs[MAD_Previous] - (dNewY1*m_costMADs[MAD_PPrevious]));
+  
+  m_paramY1 = 0.70+0.20*m_paramY1+ 0.10*dNewY1;
+  m_paramY2 =      0.20*m_paramY2+ 0.10*dNewY2;
+}
+
+Void    MADLinearModel::updateMADHistory(Double dMAD)
+{
+  m_costMADs[MAD_PPPrevious] = m_costMADs[MAD_PPrevious];
+  m_costMADs[MAD_PPrevious ] = m_costMADs[MAD_Previous ];
+  m_costMADs[MAD_Previous  ] = dMAD;
+  m_activeOn = (m_costMADs[MAD_Previous  ] && m_costMADs[MAD_PPrevious ] && m_costMADs[MAD_PPPrevious]);
+}
+
+
+Void    PixelBaseURQQuadraticModel::initPixelBaseQuadraticModel()
+{
+  m_paramHighX1 = HIGH_QSTEP_ALPHA;
+  m_paramHighX2 = HIGH_QSTEP_BETA;
+  m_paramLowX1  = LOW_QSTEP_ALPHA;
+  m_paramLowX2  = LOW_QSTEP_BETA;
+}
+
+Int     PixelBaseURQQuadraticModel::getQP(Int qp, Int targetBits, Int numberOfPixels, Double costPredMAD)
+{
+  Double qStep;
+  Double bppPerMAD = (Double)(targetBits/(numberOfPixels*costPredMAD));
+  
+  if(xConvertQP2QStep(qp) >= HIGH_QSTEP_THRESHOLD)
+  {
+#if J0260
+    qStep = 1/( sqrt((bppPerMAD/m_paramHighX1)+((m_paramHighX2*m_paramHighX2)/(4*m_paramHighX1*m_paramHighX1))) - (m_paramHighX2/(2*m_paramHighX1)));
+#else
+    qStep = 1/( sqrt((bppPerMAD/m_paramHighX1)+((m_paramHighX2*m_paramHighX2)/(4*m_paramHighX1*m_paramHighX1*m_paramHighX1))) - (m_paramHighX2/(2*m_paramHighX1)));
+#endif
+  }
+  else
+  {
+#if J0260
+    qStep = 1/( sqrt((bppPerMAD/m_paramLowX1)+((m_paramLowX2*m_paramLowX2)/(4*m_paramLowX1*m_paramLowX1))) - (m_paramLowX2/(2*m_paramLowX1)));
+#else
+    qStep = 1/( sqrt((bppPerMAD/m_paramLowX1)+((m_paramLowX2*m_paramLowX2)/(4*m_paramLowX1*m_paramLowX1*m_paramLowX1))) - (m_paramLowX2/(2*m_paramLowX1)));
+#endif
+  }
+  
+  return xConvertQStep2QP(qStep);
+}
+
+Void    PixelBaseURQQuadraticModel::updatePixelBasedURQQuadraticModel (Int qp, Int bits, Int numberOfPixels, Double costMAD)
+{
+  Double qStep     = xConvertQP2QStep(qp);
+  Double invqStep = (1/qStep);
+  Double paramNewX1, paramNewX2;
+  
+  if(qStep >= HIGH_QSTEP_THRESHOLD)
+  {
+    paramNewX2    = (((bits/(numberOfPixels*costMAD))-(23.3772*invqStep*invqStep))/((1-200*invqStep)*invqStep));
+    paramNewX1    = (23.3772-200*paramNewX2);
+    m_paramHighX1 = 0.70*HIGH_QSTEP_ALPHA + 0.20 * m_paramHighX1 + 0.10 * paramNewX1;
+    m_paramHighX2 = 0.70*HIGH_QSTEP_BETA  + 0.20 * m_paramHighX2 + 0.10 * paramNewX2;
+  }
+  else
+  {
+    paramNewX2   = (((bits/(numberOfPixels*costMAD))-(5.8091*invqStep*invqStep))/((1-9.5455*invqStep)*invqStep));
+    paramNewX1   = (5.8091-9.5455*paramNewX2);
+    m_paramLowX1 = 0.90*LOW_QSTEP_ALPHA + 0.09 * m_paramLowX1 + 0.01 * paramNewX1;
+    m_paramLowX2 = 0.90*LOW_QSTEP_BETA  + 0.09 * m_paramLowX2 + 0.01 * paramNewX2;
+  }
+}
+
+Bool    PixelBaseURQQuadraticModel::checkUpdateAvailable(Int qpReference )
+{ 
+  Double qStep = xConvertQP2QStep(qpReference);
+
+  if (qStep > xConvertQP2QStep(MAX_QP) 
+    ||qStep < xConvertQP2QStep(MIN_QP) )
+  {
+    return false;
+  }
+
+  return true;
+}
+
+Double  PixelBaseURQQuadraticModel::xConvertQP2QStep(Int qp )
+{
+  Int i;
+  Double qStep;
+  static const Double mapQP2QSTEP[6] = { 0.625, 0.703, 0.797, 0.891, 1.000, 1.125 };
+
+  qStep = mapQP2QSTEP[qp % 6];
+  for( i=0; i<(qp/6); i++)
+  {
+    qStep *= 2;
+  }
+
+  return qStep;
+}
+
+Int     PixelBaseURQQuadraticModel::xConvertQStep2QP(Double qStep )
+{
+  Int per = 0, rem = 0;
+
+  if( qStep < xConvertQP2QStep(MIN_QP))
+  {
+    return MIN_QP;
+  }
+  else if (qStep > xConvertQP2QStep(MAX_QP) )
+  {
+    return MAX_QP;
+  }
+
+  while( qStep > xConvertQP2QStep(5) )
+  {
+    qStep /= 2.0;
+    per++;
+  }
+
+  if (qStep <= 0.625)
+  {
+    rem = 0;
+  }
+  else if (qStep <= 0.703)
+  {
+    rem = 1;
+  }
+  else if (qStep <= 0.797)
+  {
+    rem = 2;
+  }
+  else if (qStep <= 0.891)
+  {
+    rem = 3;
+  }
+  else if (qStep <= 1.000)
+  {
+    rem = 4;
+  }
+  else
+  {
+    rem = 5;
+  }
+  return (per * 6 + rem);
+}
+
+
+Void  TEncRateCtrl::create(Int sizeIntraPeriod, Int sizeGOP, Int frameRate, Int targetKbps, Int qp, Int numLCUInBasicUnit, Int sourceWidth, Int sourceHeight, Int maxCUWidth, Int maxCUHeight)
+{
+  Int leftInHeight, leftInWidth;
+
+  m_sourceWidthInLCU         = (sourceWidth  / maxCUWidth  ) + (( sourceWidth  %  maxCUWidth ) ? 1 : 0);
+  m_sourceHeightInLCU        = (sourceHeight / maxCUHeight) + (( sourceHeight %  maxCUHeight) ? 1 : 0);  
+  m_isLowdelay               = (sizeIntraPeriod == -1) ? true : false;
+#if !BUFFERING_PERIOD_AND_TIMING_SEI
+  m_prevBitrate              = targetKbps*1000;
+  m_currBitrate              = targetKbps*1000;
+#else
+  m_prevBitrate              = ( targetKbps << 10 );  // in units of 1,024 bps
+  m_currBitrate              = ( targetKbps << 10 );
+#endif
+  m_frameRate                = frameRate;
+  m_refFrameNum              = m_isLowdelay ? (sizeGOP) : (sizeGOP>>1);
+  m_nonRefFrameNum           = sizeGOP-m_refFrameNum;
+  m_sizeGOP                  = sizeGOP;
+  m_numOfPixels              = ((sourceWidth*sourceHeight*3)>>1);
+  m_indexGOP                 = 0;
+  m_indexFrame               = 0;
+  m_indexLCU                 = 0;
+  m_indexUnit                = 0;
+  m_indexRefFrame            = 0;
+  m_indexNonRefFrame         = 0;
+  m_occupancyVB              = 0;
+  m_initialOVB               = 0;
+  m_targetBufLevel           = 0;
+  m_initialTBL               = 0;
+  m_occupancyVBInFrame       = 0;
+  m_remainingBitsInGOP       = (m_currBitrate*sizeGOP/m_frameRate);
+  m_remainingBitsInFrame     = 0;
+  m_numUnitInFrame           = m_sourceWidthInLCU*m_sourceHeightInLCU;
+  m_cMADLinearModel.        initMADLinearModel();
+  m_cPixelURQQuadraticModel.initPixelBaseQuadraticModel();
+
+  m_costRefAvgWeighting      = 0.0;
+  m_costNonRefAvgWeighting   = 0.0;
+  m_costAvgbpp               = 0.0;  
+  m_activeUnitLevelOn        = false;
+
+  m_pcFrameData              = new FrameData   [sizeGOP+1];         initFrameData(qp);
+  m_pcLCUData                = new LCUData     [m_numUnitInFrame];  initUnitData (qp);
+
+  for(Int i = 0, addressUnit = 0; i < m_sourceHeightInLCU*maxCUHeight; i += maxCUHeight)  
+  {
+    leftInHeight = sourceHeight - i;
+    leftInHeight = min(leftInHeight, maxCUHeight);
+    for(Int j = 0; j < m_sourceWidthInLCU*maxCUWidth; j += maxCUWidth, addressUnit++)
+    {
+      leftInWidth = sourceWidth - j;
+      leftInWidth = min(leftInWidth, maxCUWidth);
+      m_pcLCUData[addressUnit].m_widthInPixel = leftInWidth;
+      m_pcLCUData[addressUnit].m_heightInPixel= leftInHeight;
+      m_pcLCUData[addressUnit].m_pixels       = ((leftInHeight*leftInWidth*3)>>1);
+    }
+  }
+}
+
+Void  TEncRateCtrl::destroy()
+{
+  if(m_pcFrameData)
+  {
+    delete [] m_pcFrameData;
+    m_pcFrameData = NULL;
+  }
+  if(m_pcLCUData)
+  {
+    delete [] m_pcLCUData;
+    m_pcLCUData = NULL;
+  }
+}
+
+Void  TEncRateCtrl::initFrameData   (Int qp)
+{
+  for(Int i = 0 ; i <= m_sizeGOP; i++)
+  {
+    m_pcFrameData[i].m_isReferenced = false;
+    m_pcFrameData[i].m_costMAD      = 0.0;
+    m_pcFrameData[i].m_bits         = 0;
+    m_pcFrameData[i].m_qp           = qp;
+  }
+}
+
+Void  TEncRateCtrl::initUnitData    (Int qp)
+{
+  for(Int i = 1 ; i < m_numUnitInFrame; i++)
+  {
+    m_pcLCUData[i].m_qp            = qp;
+    m_pcLCUData[i].m_bits          = 0;
+    m_pcLCUData[i].m_pixels        = 0;
+    m_pcLCUData[i].m_widthInPixel  = 0;
+    m_pcLCUData[i].m_heightInPixel = 0;
+    m_pcLCUData[i].m_costMAD       = 0.0;
+  }
+}
+
+Int  TEncRateCtrl::getFrameQP(Bool isReferenced, Int POC)
+{
+  Int numofReferenced = 0;
+  Int finalQP = 0;
+  FrameData* pcFrameData;
+
+  m_indexPOCInGOP = (POC%m_sizeGOP) == 0 ? m_sizeGOP : (POC%m_sizeGOP);
+  pcFrameData     = &m_pcFrameData[m_indexPOCInGOP];
+    
+  if(m_indexFrame != 0)
+  {
+    if(isReferenced)
+    {
+      Double gamma = m_isLowdelay ? 0.5 : 0.25;
+      Double beta  = m_isLowdelay ? 0.9 : 0.6;
+      Int    numRemainingRefFrames  = m_refFrameNum    - m_indexRefFrame;
+      Int    numRemainingNRefFrames = m_nonRefFrameNum - m_indexNonRefFrame;
+      
+      Double targetBitsOccupancy  = (m_currBitrate/(Double)m_frameRate) + gamma*(m_targetBufLevel-m_occupancyVB - (m_initialOVB/(Double)m_frameRate));
+      Double targetBitsLeftBudget = ((m_costRefAvgWeighting*m_remainingBitsInGOP)/((m_costRefAvgWeighting*numRemainingRefFrames)+(m_costNonRefAvgWeighting*numRemainingNRefFrames)));
+
+      m_targetBits = (Int)(beta * targetBitsLeftBudget + (1-beta) * targetBitsOccupancy);
+  
+      if(m_targetBits <= 0 || m_remainingBitsInGOP <= 0)
+      {
+        finalQP = m_pcFrameData[m_indexPrevPOCInGOP].m_qp + 2;
+      }
+      else
+      {
+        Double costPredMAD   = m_cMADLinearModel.getMAD();
+        Int    qpLowerBound = m_pcFrameData[m_indexPrevPOCInGOP].m_qp-2;
+        Int    qpUpperBound = m_pcFrameData[m_indexPrevPOCInGOP].m_qp+2;
+        finalQP = m_cPixelURQQuadraticModel.getQP(m_pcFrameData[m_indexPrevPOCInGOP].m_qp, m_targetBits, m_numOfPixels, costPredMAD);
+        finalQP = max(qpLowerBound, min(qpUpperBound, finalQP));
+        m_activeUnitLevelOn    = true;
+        m_remainingBitsInFrame = m_targetBits;
+        m_costAvgbpp           = (m_targetBits/(Double)m_numOfPixels);
+      }
+
+      m_indexRefFrame++;
+    }
+    else
+    {
+      Int bwdQP = m_pcFrameData[m_indexPOCInGOP-1].m_qp;
+      Int fwdQP = m_pcFrameData[m_indexPOCInGOP+1].m_qp;
+       
+      if( (fwdQP+bwdQP) == m_pcFrameData[m_indexPOCInGOP-1].m_qp
+        ||(fwdQP+bwdQP) == m_pcFrameData[m_indexPOCInGOP+1].m_qp)
+      {
+        finalQP = (fwdQP+bwdQP);
+      }
+      else if(bwdQP != fwdQP)
+      {
+        finalQP = ((bwdQP+fwdQP+2)>>1);
+      }
+      else
+      {
+        finalQP = bwdQP+2;
+      }
+      m_indexNonRefFrame++;
+    }
+  }
+  else
+  {
+    Int lastQPminus2 = m_pcFrameData[0].m_qp - 2;
+    Int lastQPplus2  = m_pcFrameData[0].m_qp + 2;
+
+    for(Int idx = 1; idx <= m_sizeGOP; idx++)
+    {
+      if(m_pcFrameData[idx].m_isReferenced)
+      {
+        finalQP += m_pcFrameData[idx].m_qp;
+        numofReferenced++;
+      }
+    }
+    
+    finalQP = (numofReferenced == 0) ? m_pcFrameData[0].m_qp : ((finalQP + (1<<(numofReferenced>>1)))/numofReferenced);
+    finalQP = max( lastQPminus2, min( lastQPplus2, finalQP));
+
+    Double costAvgFrameBits = m_remainingBitsInGOP/(Double)m_sizeGOP;
+    Int    bufLevel  = m_occupancyVB + m_initialOVB;
+
+    if(abs(bufLevel) > costAvgFrameBits)
+    {
+      if(bufLevel < 0)
+      {
+        finalQP -= 2;
+      }
+      else
+      {
+        finalQP += 2;
+      }
+    }
+    m_indexRefFrame++;
+  }
+  finalQP = max(MIN_QP, min(MAX_QP, finalQP));
+
+  for(Int indexLCU = 0 ; indexLCU < m_numUnitInFrame; indexLCU++)
+  {
+    m_pcLCUData[indexLCU].m_qp = finalQP;
+  }
+
+  pcFrameData->m_isReferenced = isReferenced;
+  pcFrameData->m_qp           = finalQP;
+
+  return finalQP;
+}
+
+Bool  TEncRateCtrl::calculateUnitQP ()
+{
+  if(!m_activeUnitLevelOn || m_indexLCU == 0)
+  {
+    return false;
+  }
+  Int upperQPBound, lowerQPBound, finalQP;
+  Int    colQP        = m_pcLCUData[m_indexLCU].m_qp;
+  Double colMAD       = m_pcLCUData[m_indexLCU].m_costMAD;
+  Double budgetInUnit = m_pcLCUData[m_indexLCU].m_pixels*m_costAvgbpp;
+
+
+  Int targetBitsOccupancy = (Int)(budgetInUnit - (m_occupancyVBInFrame/(m_numUnitInFrame-m_indexUnit)));
+  Int targetBitsLeftBudget= (Int)((m_remainingBitsInFrame*m_pcLCUData[m_indexLCU].m_pixels)/(Double)(m_numOfPixels-m_codedPixels));
+  Int targetBits = (targetBitsLeftBudget>>1) + (targetBitsOccupancy>>1);
+  
+
+  if( m_indexLCU >= m_sourceWidthInLCU)
+  {
+    upperQPBound = ( (m_pcLCUData[m_indexLCU-1].m_qp + m_pcLCUData[m_indexLCU - m_sourceWidthInLCU].m_qp)>>1) + MAX_DELTA_QP;
+    lowerQPBound = ( (m_pcLCUData[m_indexLCU-1].m_qp + m_pcLCUData[m_indexLCU - m_sourceWidthInLCU].m_qp)>>1) - MAX_DELTA_QP;
+  }
+  else
+  {
+    upperQPBound = m_pcLCUData[m_indexLCU-1].m_qp + MAX_DELTA_QP;
+    lowerQPBound = m_pcLCUData[m_indexLCU-1].m_qp - MAX_DELTA_QP;
+  }
+
+  if(targetBits < 0)
+  {
+    finalQP = m_pcLCUData[m_indexLCU-1].m_qp + 1;
+  }
+  else
+  {
+    finalQP = m_cPixelURQQuadraticModel.getQP(colQP, targetBits, m_pcLCUData[m_indexLCU].m_pixels, colMAD);
+  }
+  
+  finalQP = max(lowerQPBound, min(upperQPBound, finalQP));
+  m_pcLCUData[m_indexLCU].m_qp = max(MIN_QP, min(MAX_QP, finalQP));
+  
+  return true;
+}
+
+Void  TEncRateCtrl::updateRCGOPStatus()
+{
+  m_remainingBitsInGOP = ((m_currBitrate/m_frameRate)*m_sizeGOP) - m_occupancyVB;
+  
+  FrameData cFrameData = m_pcFrameData[m_sizeGOP];
+  initFrameData();
+
+  m_pcFrameData[0]   = cFrameData;
+  m_indexGOP++;
+  m_indexFrame       = 0;
+  m_indexRefFrame    = 0;
+  m_indexNonRefFrame = 0;
+}
+
+Void  TEncRateCtrl::updataRCFrameStatus(Int frameBits, SliceType eSliceType)
+{
+  FrameData* pcFrameData = &m_pcFrameData[m_indexPOCInGOP];
+  Int occupancyBits;
+  Double adjustmentBits;
+
+  m_remainingBitsInGOP = m_remainingBitsInGOP + ( ((m_currBitrate-m_prevBitrate)/m_frameRate)*(m_sizeGOP-m_indexFrame) ) - frameBits;
+  occupancyBits        = (Int)((Double)frameBits - (m_currBitrate/(Double)m_frameRate));
+  
+  if( (occupancyBits < 0) && (m_initialOVB > 0) )
+  {
+    adjustmentBits = xAdjustmentBits(occupancyBits, m_initialOVB );
+
+    if(m_initialOVB < 0)
+    {
+      adjustmentBits = m_initialOVB;
+      occupancyBits += (Int)adjustmentBits;
+      m_initialOVB   =  0;
+    }
+  }
+  else if( (occupancyBits > 0) && (m_initialOVB < 0) )
+  {
+    adjustmentBits = xAdjustmentBits(m_initialOVB, occupancyBits );
+    
+    if(occupancyBits < 0)
+    {
+      adjustmentBits = occupancyBits;
+      m_initialOVB  += (Int)adjustmentBits;
+      occupancyBits  =  0;
+    }
+  }
+
+  if(m_indexGOP == 0)
+  {
+    m_initialOVB = occupancyBits;
+  }
+  else
+  {
+    m_occupancyVB= m_occupancyVB + occupancyBits;
+  }
+
+  if(pcFrameData->m_isReferenced)
+  {
+    m_costRefAvgWeighting  = ((pcFrameData->m_bits*pcFrameData->m_qp)/8.0) + (7.0*(m_costRefAvgWeighting)/8.0);
+
+    if(m_indexFrame == 0)
+    {
+      m_initialTBL = m_targetBufLevel  = (frameBits - (m_currBitrate/m_frameRate));
+    }
+    else
+    {
+      Int distance = (m_costNonRefAvgWeighting == 0) ? 0 : 1;
+      m_targetBufLevel =  m_targetBufLevel 
+                            - (m_initialTBL/(m_refFrameNum-1)) 
+                            + (Int)((m_costRefAvgWeighting*(distance+1)*m_currBitrate)/(m_frameRate*(m_costRefAvgWeighting+(m_costNonRefAvgWeighting*distance)))) 
+                            - (m_currBitrate/m_frameRate);
+    }
+
+    if(m_cMADLinearModel.IsUpdateAvailable())
+    {
+      m_cMADLinearModel.updateMADLiearModel();
+    }
+
+    if(eSliceType != I_SLICE &&
+       m_cPixelURQQuadraticModel.checkUpdateAvailable(pcFrameData->m_qp))
+    {
+      m_cPixelURQQuadraticModel.updatePixelBasedURQQuadraticModel(pcFrameData->m_qp, pcFrameData->m_bits, m_numOfPixels, pcFrameData->m_costMAD);
+    }
+  }
+  else
+  {
+    m_costNonRefAvgWeighting = ((pcFrameData->m_bits*pcFrameData->m_qp)/8.0) + (7.0*(m_costNonRefAvgWeighting)/8.0);
+  }
+
+  m_indexFrame++;
+  m_indexLCU             = 0;
+  m_indexUnit            = 0;
+  m_occupancyVBInFrame   = 0;
+  m_remainingBitsInFrame = 0;
+  m_codedPixels          = 0;
+  m_activeUnitLevelOn    = false;
+  m_costAvgbpp           = 0.0;
+}
+Void  TEncRateCtrl::updataRCUnitStatus ()
+{
+  if(!m_activeUnitLevelOn || m_indexLCU == 0)
+  {
+    return;
+  }
+
+  m_codedPixels  += m_pcLCUData[m_indexLCU-1].m_pixels;
+  m_remainingBitsInFrame = m_remainingBitsInFrame - m_pcLCUData[m_indexLCU-1].m_bits;
+  m_occupancyVBInFrame   = (Int)(m_occupancyVBInFrame + m_pcLCUData[m_indexLCU-1].m_bits - m_pcLCUData[m_indexLCU-1].m_pixels*m_costAvgbpp);
+
+  if( m_cPixelURQQuadraticModel.checkUpdateAvailable(m_pcLCUData[m_indexLCU-1].m_qp) )
+  {
+    m_cPixelURQQuadraticModel.updatePixelBasedURQQuadraticModel(m_pcLCUData[m_indexLCU-1].m_qp, m_pcLCUData[m_indexLCU-1].m_bits, m_pcLCUData[m_indexLCU-1].m_pixels, m_pcLCUData[m_indexLCU-1].m_costMAD);
+  }
+
+  m_indexUnit++;
+}
+
+Void  TEncRateCtrl::updateFrameData(UInt64 actualFrameBits)
+{
+  Double costMAD = 0.0;
+  
+  for(Int i = 0; i < m_numUnitInFrame; i++)
+  {
+    costMAD    += m_pcLCUData[i].m_costMAD;
+  }
+  
+  m_pcFrameData[m_indexPOCInGOP].m_costMAD = (costMAD/(Double)m_numUnitInFrame);
+  m_pcFrameData[m_indexPOCInGOP].m_bits    = (Int)actualFrameBits;
+  
+  if(m_pcFrameData[m_indexPOCInGOP].m_isReferenced)
+  {
+    m_indexPrevPOCInGOP = m_indexPOCInGOP;
+    m_cMADLinearModel.updateMADHistory(m_pcFrameData[m_indexPOCInGOP].m_costMAD);
+  }
+}
+
+Void  TEncRateCtrl::updateLCUData(TComDataCU* pcCU, UInt64 actualLCUBits, Int qp)
+{
+  Int     x, y;
+  double  costMAD = 0.0;
+
+  Pel*  pOrg   = pcCU->getPic()->getPicYuvOrg()->getLumaAddr(pcCU->getAddr(), 0);
+  Pel*  pRec   = pcCU->getPic()->getPicYuvRec()->getLumaAddr(pcCU->getAddr(), 0);
+  Int   stride = pcCU->getPic()->getStride();
+
+  Int   width  = m_pcLCUData[m_indexLCU].m_widthInPixel;
+  Int   height = m_pcLCUData[m_indexLCU].m_heightInPixel;
+
+  for( y = 0; y < height; y++ )
+  {
+    for( x = 0; x < width; x++ )
+    {
+      costMAD += abs( pOrg[x] - pRec[x] );
+    }
+    pOrg += stride;
+    pRec += stride;
+  }
+  m_pcLCUData[m_indexLCU  ].m_qp      = qp;
+  m_pcLCUData[m_indexLCU  ].m_costMAD = (costMAD /(Double)(width*height));
+  m_pcLCUData[m_indexLCU++].m_bits    = (Int)actualLCUBits;
+}
+
+Double TEncRateCtrl::xAdjustmentBits(Int& reductionBits, Int& compensationBits)
+{
+  Double adjustment  = ADJUSTMENT_FACTOR*reductionBits;
+  reductionBits     -= (Int)adjustment;
+  compensationBits  += (Int)adjustment;
+
+  return adjustment;
+}
+
Index: /trunk/source/Lib/TLibEncoder/TEncRateCtrl.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncRateCtrl.h	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/TEncRateCtrl.h	(revision 2)
@@ -0,0 +1,183 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncRateCtrl.h
+    \brief    Rate control manager class
+*/
+
+#ifndef _HM_TENCRATECTRL_H_
+#define _HM_TENCRATECTRL_H_
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+
+#include "../TLibCommon/CommonDef.h"
+#include "../TLibCommon/TComDataCU.h"
+
+#include <vector>
+#include <algorithm>
+
+using namespace std;
+
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+#define MAX_DELTA_QP    2
+#define MAX_CUDQP_DEPTH 0 
+
+typedef struct FrameData
+{
+  Bool       m_isReferenced;
+  Int        m_qp;
+  Int        m_bits;
+  Double     m_costMAD;
+}FrameData;
+
+typedef struct LCUData
+{
+  Int     m_qp;                ///<  coded QP
+  Int     m_bits;              ///<  actually generated bits
+  Int     m_pixels;            ///<  number of pixels for a unit
+  Int     m_widthInPixel;      ///<  number of pixels for width
+  Int     m_heightInPixel;     ///<  number of pixels for height
+  Double  m_costMAD;           ///<  texture complexity for a unit
+}LCUData;
+
+class MADLinearModel
+{
+private:
+  Bool   m_activeOn;
+  Double m_paramY1;
+  Double m_paramY2;
+  Double m_costMADs[3];
+
+public:
+  MADLinearModel ()   {};
+  ~MADLinearModel()   {};
+  
+  Void    initMADLinearModel      ();
+  Double  getMAD                  ();
+  Void    updateMADLiearModel     ();
+  Void    updateMADHistory        (Double costMAD);
+  Bool    IsUpdateAvailable       ()              { return m_activeOn; }
+};
+
+class PixelBaseURQQuadraticModel
+{
+private:
+  Double m_paramHighX1;
+  Double m_paramHighX2;
+  Double m_paramLowX1;
+  Double m_paramLowX2;
+public:
+  PixelBaseURQQuadraticModel () {};
+  ~PixelBaseURQQuadraticModel() {};
+
+  Void    initPixelBaseQuadraticModel       ();
+  Int     getQP                             (Int qp, Int targetBits, Int numberOfPixels, Double costPredMAD);
+  Void    updatePixelBasedURQQuadraticModel (Int qp, Int bits, Int numberOfPixels, Double costMAD);
+  Bool    checkUpdateAvailable              (Int qpReference );
+  Double  xConvertQP2QStep                  (Int qp );
+  Int     xConvertQStep2QP                  (Double qStep );
+};
+
+class TEncRateCtrl
+{
+private:
+  Bool            m_isLowdelay;
+  Int             m_prevBitrate;
+  Int             m_currBitrate;
+  Int             m_frameRate;
+  Int             m_refFrameNum;
+  Int             m_nonRefFrameNum;
+  Int             m_numOfPixels;
+  Int             m_sourceWidthInLCU;
+  Int             m_sourceHeightInLCU;      
+  Int             m_sizeGOP;
+  Int             m_indexGOP;
+  Int             m_indexFrame;
+  Int             m_indexLCU;
+  Int             m_indexUnit;
+  Int             m_indexRefFrame;
+  Int             m_indexNonRefFrame;
+  Int             m_indexPOCInGOP;
+  Int             m_indexPrevPOCInGOP;
+  Int             m_occupancyVB;
+  Int             m_initialOVB;
+  Int             m_targetBufLevel;
+  Int             m_initialTBL;
+  Int             m_remainingBitsInGOP;
+  Int             m_remainingBitsInFrame;
+  Int             m_occupancyVBInFrame;
+  Int             m_targetBits;
+  Int             m_numUnitInFrame;
+  Int             m_codedPixels;
+  Bool            m_activeUnitLevelOn;
+  Double          m_costNonRefAvgWeighting;
+  Double          m_costRefAvgWeighting;
+  Double          m_costAvgbpp;         
+  
+  FrameData*      m_pcFrameData;
+  LCUData*        m_pcLCUData;
+
+  MADLinearModel              m_cMADLinearModel;
+  PixelBaseURQQuadraticModel  m_cPixelURQQuadraticModel;
+  
+public:
+  TEncRateCtrl         () {};
+  virtual ~TEncRateCtrl() {};
+
+  Void          create                (Int sizeIntraPeriod, Int sizeGOP, Int frameRate, Int targetKbps, Int qp, Int numLCUInBasicUnit, Int sourceWidth, Int sourceHeight, Int maxCUWidth, Int maxCUHeight);
+  Void          destroy               ();
+
+  Void          initFrameData         (Int qp = 0);
+  Void          initUnitData          (Int qp = 0);
+  Int           getFrameQP            (Bool isReferenced, Int POC);
+  Bool          calculateUnitQP       ();
+  Int           getUnitQP             ()                                          { return m_pcLCUData[m_indexLCU].m_qp;  }
+  Void          updateRCGOPStatus     ();
+  Void          updataRCFrameStatus   (Int frameBits, SliceType eSliceType);
+  Void          updataRCUnitStatus    ();
+  Void          updateLCUData         (TComDataCU* pcCU, UInt64 actualLCUBits, Int qp);
+  Void          updateFrameData       (UInt64 actualFrameBits);
+  Double        xAdjustmentBits       (Int& reductionBits, Int& compensationBits);
+  Int           getGOPId              ()                                          { return m_indexFrame; }
+};
+#endif
+
+
Index: /trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp	(revision 2)
@@ -0,0 +1,3027 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncSampleAdaptiveOffset.cpp
+ \brief       estimation part of sample adaptive offset class
+ */
+#include "TEncSampleAdaptiveOffset.h"
+#include <string.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <math.h>
+
+//! \ingroup TLibEncoder
+//! \{
+
+TEncSampleAdaptiveOffset::TEncSampleAdaptiveOffset()
+{
+  m_pcEntropyCoder = NULL;
+  m_pppcRDSbacCoder = NULL;
+  m_pcRDGoOnSbacCoder = NULL;
+  m_pppcBinCoderCABAC = NULL;            
+  m_iCount = NULL;     
+  m_iOffset = NULL;      
+  m_iOffsetOrg = NULL;  
+  m_iRate = NULL;       
+  m_iDist = NULL;        
+  m_dCost = NULL;        
+  m_dCostPartBest = NULL; 
+  m_iDistOrg = NULL;      
+  m_iTypePartBest = NULL; 
+#if SAO_ENCODING_CHOICE_CHROMA
+  m_depthSaoRate[0][0] = 0;
+  m_depthSaoRate[0][1] = 0;
+  m_depthSaoRate[0][2] = 0;
+  m_depthSaoRate[0][3] = 0;
+  m_depthSaoRate[1][0] = 0;
+  m_depthSaoRate[1][1] = 0;
+  m_depthSaoRate[1][2] = 0;
+  m_depthSaoRate[1][3] = 0;
+#endif
+}
+TEncSampleAdaptiveOffset::~TEncSampleAdaptiveOffset()
+{
+
+}
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+
+// ====================================================================================================================
+// Tables
+// ====================================================================================================================
+
+inline Double xRoundIbdi2(Double x)
+{
+#if FULL_NBIT
+  Int bitDepthMinus8 = g_uiBitDepth - 8;
+  return ((x)>0) ? (Int)(((Int)(x)+(1<<(bitDepthMinus8-1)))/(1<<bitDepthMinus8)) : ((Int)(((Int)(x)-(1<<(bitDepthMinus8-1)))/(1<<bitDepthMinus8)));
+#else
+  return ((x)>0) ? (Int)(((Int)(x)+(1<<(g_uiBitIncrement-1)))/(1<<g_uiBitIncrement)) : ((Int)(((Int)(x)-(1<<(g_uiBitIncrement-1)))/(1<<g_uiBitIncrement)));
+#endif
+}
+
+/** rounding with IBDI
+ * \param  x
+ */
+inline Double xRoundIbdi(Double x)
+{
+#if FULL_NBIT
+  return (g_uiBitDepth > 8 ? xRoundIbdi2((x)) : ((x)>=0 ? ((Int)((x)+0.5)) : ((Int)((x)-0.5)))) ;
+#else
+  return (g_uiBitIncrement >0 ? xRoundIbdi2((x)) : ((x)>=0 ? ((Int)((x)+0.5)) : ((Int)((x)-0.5)))) ;
+#endif
+}
+
+
+
+/** process SAO for one partition
+ * \param  *psQTPart, iPartIdx, dLambda
+ */
+#if PICTURE_SAO_RDO_FIX
+Void TEncSampleAdaptiveOffset::rdoSaoOnePart(SAOQTPart *psQTPart, Int iPartIdx, Double dLambda, Int yCbCr)
+#else
+Void TEncSampleAdaptiveOffset::rdoSaoOnePart(SAOQTPart *psQTPart, Int iPartIdx, Double dLambda)
+#endif
+{
+  Int iTypeIdx;
+  Int iNumTotalType = MAX_NUM_SAO_TYPE;
+  SAOQTPart*  pOnePart = &(psQTPart[iPartIdx]);
+
+  Int64 iEstDist;
+  Int iClassIdx;
+  Int uiShift = g_uiBitIncrement << 1;
+  UInt uiDepth = pOnePart->PartLevel;
+
+  m_iDistOrg [iPartIdx] =  0;
+
+  Double  bestRDCostTableBo = MAX_DOUBLE;
+  Int     bestClassTableBo    = 0;
+  Int     currentDistortionTableBo[MAX_NUM_SAO_CLASS];
+  Double  currentRdCostTableBo[MAX_NUM_SAO_CLASS];
+
+#if PICTURE_SAO_RDO_FIX
+  Int addr;
+  Int allowMergeLeft;
+  Int allowMergeUp;
+  Int frameWidthInCU = m_pcPic->getFrameWidthInCU();
+  SaoLcuParam  saoLcuParamRdo;
+#endif
+
+  for (iTypeIdx=-1; iTypeIdx<iNumTotalType; iTypeIdx++)
+  {
+    if( m_bUseSBACRD )
+    {
+      m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
+      m_pcRDGoOnSbacCoder->resetBits();
+    }
+    else
+    {
+      m_pcEntropyCoder->resetEntropy();
+      m_pcEntropyCoder->resetBits();
+    }
+
+    iEstDist = 0;
+
+#if PICTURE_SAO_RDO_FIX
+    if (iTypeIdx == -1)
+    {      
+      for (Int ry = pOnePart->StartCUY; ry<= pOnePart->EndCUY; ry++)
+      {
+        for (Int rx = pOnePart->StartCUX; rx <= pOnePart->EndCUX; rx++)
+        {
+          addr = ry * frameWidthInCU + rx;          
+
+          // get bits for iTypeIdx = -1
+          allowMergeLeft = 1;
+          allowMergeUp   = 1;
+          if (rx != 0)
+          { 
+            // check tile id and slice id 
+            if ( (m_pcPic->getPicSym()->getTileIdxMap(addr-1) != m_pcPic->getPicSym()->getTileIdxMap(addr)) || (m_pcPic->getCU(addr-1)->getSlice()->getSliceIdx() != m_pcPic->getCU(addr)->getSlice()->getSliceIdx()))
+            {
+              allowMergeLeft = 0;
+            }
+          }
+          if (ry!=0)
+          {
+            if ( (m_pcPic->getPicSym()->getTileIdxMap(addr-m_iNumCuInWidth) != m_pcPic->getPicSym()->getTileIdxMap(addr)) || (m_pcPic->getCU(addr-m_iNumCuInWidth)->getSlice()->getSliceIdx() != m_pcPic->getCU(addr)->getSlice()->getSliceIdx()))
+            {
+              allowMergeUp = 0;
+            }
+          }
+
+          // reset
+          resetSaoUnit(&saoLcuParamRdo);
+
+          // set merge flag
+          saoLcuParamRdo.mergeUpFlag   = 1;
+          saoLcuParamRdo.mergeLeftFlag = 1;
+
+          if (ry == pOnePart->StartCUY) 
+          {
+            saoLcuParamRdo.mergeUpFlag = 0;
+          } 
+          
+          if (rx == pOnePart->StartCUX) 
+          {
+            saoLcuParamRdo.mergeLeftFlag = 0;
+          }
+
+          m_pcEntropyCoder->encodeSaoUnitInterleaving(yCbCr, 1, rx, ry,  &saoLcuParamRdo, 1,  1,  allowMergeLeft, allowMergeUp);
+
+        }
+      }
+    }
+#else
+    m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoTypeIdx(iTypeIdx+1);
+#endif
+
+    if (iTypeIdx>=0)
+    {
+      iEstDist = estSaoTypeDist(iPartIdx, iTypeIdx, uiShift, dLambda, currentDistortionTableBo, currentRdCostTableBo);
+      if( iTypeIdx == SAO_BO )
+      {
+        // Estimate Best Position
+        Double currentRDCost = 0.0;
+
+        for(Int i=0; i< SAO_MAX_BO_CLASSES -SAO_BO_LEN +1; i++)
+        {
+          currentRDCost = 0.0;
+          for(UInt uj = i; uj < i+SAO_BO_LEN; uj++)
+          {
+            currentRDCost += currentRdCostTableBo[uj];
+          }
+
+          if( currentRDCost < bestRDCostTableBo)
+          {
+            bestRDCostTableBo = currentRDCost;
+            bestClassTableBo  = i;
+          }
+        }
+
+        // Re code all Offsets
+        // Code Center
+        for(iClassIdx = bestClassTableBo; iClassIdx < bestClassTableBo+SAO_BO_LEN; iClassIdx++)
+        {
+          iEstDist += currentDistortionTableBo[iClassIdx];
+        }
+      }
+
+#if PICTURE_SAO_RDO_FIX      
+      for (Int ry = pOnePart->StartCUY; ry<= pOnePart->EndCUY; ry++)
+      {
+        for (Int rx = pOnePart->StartCUX; rx <= pOnePart->EndCUX; rx++)
+        {
+          addr = ry * frameWidthInCU + rx;          
+
+          // get bits for iTypeIdx = -1
+          allowMergeLeft = 1;
+          allowMergeUp   = 1;
+          if (rx != 0)
+          { 
+            // check tile id and slice id 
+            if ( (m_pcPic->getPicSym()->getTileIdxMap(addr-1) != m_pcPic->getPicSym()->getTileIdxMap(addr)) || (m_pcPic->getCU(addr-1)->getSlice()->getSliceIdx() != m_pcPic->getCU(addr)->getSlice()->getSliceIdx()))
+            {
+              allowMergeLeft = 0;
+            }
+          }
+          if (ry!=0)
+          {
+            if ( (m_pcPic->getPicSym()->getTileIdxMap(addr-m_iNumCuInWidth) != m_pcPic->getPicSym()->getTileIdxMap(addr)) || (m_pcPic->getCU(addr-m_iNumCuInWidth)->getSlice()->getSliceIdx() != m_pcPic->getCU(addr)->getSlice()->getSliceIdx()))
+            {
+              allowMergeUp = 0;
+            }
+          }
+
+          // reset
+          resetSaoUnit(&saoLcuParamRdo);
+          
+          // set merge flag
+          saoLcuParamRdo.mergeUpFlag   = 1;
+          saoLcuParamRdo.mergeLeftFlag = 1;
+
+          if (ry == pOnePart->StartCUY) 
+          {
+            saoLcuParamRdo.mergeUpFlag = 0;
+          } 
+          
+          if (rx == pOnePart->StartCUX) 
+          {
+            saoLcuParamRdo.mergeLeftFlag = 0;
+          }
+
+          // set type and offsets
+          saoLcuParamRdo.typeIdx = iTypeIdx;
+#if SAO_TYPE_CODING
+          saoLcuParamRdo.subTypeIdx = (iTypeIdx==SAO_BO)?bestClassTableBo:0;
+#else
+          saoLcuParamRdo.bandPosition = (iTypeIdx==SAO_BO)?bestClassTableBo:0;
+#endif        
+          saoLcuParamRdo.length = m_iNumClass[iTypeIdx];
+          for (iClassIdx = 0; iClassIdx < saoLcuParamRdo.length; iClassIdx++)
+          {
+#if SAO_TYPE_CODING
+            saoLcuParamRdo.offset[iClassIdx] = (Int)m_iOffset[iPartIdx][iTypeIdx][iClassIdx+saoLcuParamRdo.subTypeIdx+1];
+#else
+            saoLcuParamRdo.offset[iClassIdx] = (Int)m_iOffset[iPartIdx][iTypeIdx][iClassIdx+saoLcuParamRdo.bandPosition+1];
+#endif            
+          }
+
+          m_pcEntropyCoder->encodeSaoUnitInterleaving(yCbCr, 1, rx, ry,  &saoLcuParamRdo, 1,  1,  allowMergeLeft, allowMergeUp);
+
+        }
+      }
+#else // #if PICTURE_SAO_RDO_FIX 
+
+      SaoLcuParam  saoLcuParamRdo;   
+      resetSaoUnit(&saoLcuParamRdo);
+      saoLcuParamRdo.typeIdx = iTypeIdx;
+#if SAO_TYPE_CODING
+      saoLcuParamRdo.subTypeIdx = (iTypeIdx==SAO_BO)?bestClassTableBo:0;
+#else
+      saoLcuParamRdo.bandPosition = (iTypeIdx==SAO_BO)?bestClassTableBo:0;
+#endif
+      saoLcuParamRdo.length = m_iNumClass[iTypeIdx];
+      for (iClassIdx = 0; iClassIdx < saoLcuParamRdo.length; iClassIdx++)
+      {
+#if SAO_TYPE_CODING
+        saoLcuParamRdo.offset[iClassIdx] = (Int)m_iOffset[iPartIdx][iTypeIdx][iClassIdx+saoLcuParamRdo.subTypeIdx+1];
+#else
+        saoLcuParamRdo.offset[iClassIdx] = (Int)m_iOffset[iPartIdx][iTypeIdx][iClassIdx+saoLcuParamRdo.bandPosition+1];
+#endif
+      }
+      m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
+      m_pcRDGoOnSbacCoder->resetBits();
+#if SAO_TYPE_SHARING
+      m_pcEntropyCoder->encodeSaoOffset(&saoLcuParamRdo, iPartIdx);
+#else
+      m_pcEntropyCoder->encodeSaoOffset(&saoLcuParamRdo);
+#endif
+#endif // #if PICTURE_SAO_RDO_FIX 
+
+      m_iDist[iPartIdx][iTypeIdx] = iEstDist;
+      m_iRate[iPartIdx][iTypeIdx] = m_pcEntropyCoder->getNumberOfWrittenBits();
+
+      m_dCost[iPartIdx][iTypeIdx] = (Double)((Double)m_iDist[iPartIdx][iTypeIdx] + dLambda * (Double) m_iRate[iPartIdx][iTypeIdx]);
+
+      if(m_dCost[iPartIdx][iTypeIdx] < m_dCostPartBest[iPartIdx])
+      {
+        m_iDistOrg [iPartIdx] = 0;
+        m_dCostPartBest[iPartIdx] = m_dCost[iPartIdx][iTypeIdx];
+        m_iTypePartBest[iPartIdx] = iTypeIdx;
+        if( m_bUseSBACRD )
+          m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[pOnePart->PartLevel][CI_TEMP_BEST] );
+      }
+    }
+    else
+    {
+      if(m_iDistOrg[iPartIdx] < m_dCostPartBest[iPartIdx] )
+      {
+        m_dCostPartBest[iPartIdx] = (Double) m_iDistOrg[iPartIdx] + m_pcEntropyCoder->getNumberOfWrittenBits()*dLambda ; 
+        m_iTypePartBest[iPartIdx] = -1;
+        if( m_bUseSBACRD )
+          m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[pOnePart->PartLevel][CI_TEMP_BEST] );
+      }
+    }
+  }
+
+  pOnePart->bProcessed = true;
+  pOnePart->bSplit     = false;
+  pOnePart->iMinDist   =        m_iTypePartBest[iPartIdx] >= 0 ? m_iDist[iPartIdx][m_iTypePartBest[iPartIdx]] : m_iDistOrg[iPartIdx];
+  pOnePart->iMinRate   = (Int) (m_iTypePartBest[iPartIdx] >= 0 ? m_iRate[iPartIdx][m_iTypePartBest[iPartIdx]] : 0);
+  pOnePart->dMinCost   = pOnePart->iMinDist + dLambda * pOnePart->iMinRate;
+  pOnePart->iBestType  = m_iTypePartBest[iPartIdx];
+  if (pOnePart->iBestType != -1)
+  {
+    //     pOnePart->bEnableFlag =  1;
+    pOnePart->iLength = m_iNumClass[pOnePart->iBestType];
+    Int minIndex = 0;
+    if( pOnePart->iBestType == SAO_BO )
+    {
+#if SAO_TYPE_CODING
+      pOnePart->subTypeIdx = bestClassTableBo;
+      minIndex = pOnePart->subTypeIdx;
+#else
+      pOnePart->bandPosition = bestClassTableBo;
+      minIndex = pOnePart->bandPosition;
+#endif
+    }
+    for (Int i=0; i< pOnePart->iLength ; i++)
+    {
+      pOnePart->iOffset[i] = (Int) m_iOffset[iPartIdx][pOnePart->iBestType][minIndex+i+1];
+    }
+
+  }
+  else
+  {
+    //     pOnePart->bEnableFlag = 0;
+    pOnePart->iLength     = 0;
+  }
+}
+
+/** Run partition tree disable
+ */
+Void TEncSampleAdaptiveOffset::disablePartTree(SAOQTPart *psQTPart, Int iPartIdx)
+{
+  SAOQTPart*  pOnePart= &(psQTPart[iPartIdx]);
+  pOnePart->bSplit      = false;
+  pOnePart->iLength     =  0;
+  pOnePart->iBestType   = -1;
+
+  if (pOnePart->PartLevel < m_uiMaxSplitLevel)
+  {
+    for (Int i=0; i<NUM_DOWN_PART; i++)
+    {
+      disablePartTree(psQTPart, pOnePart->DownPartsIdx[i]);
+    }
+  }
+}
+
+/** Run quadtree decision function
+ * \param  iPartIdx, pcPicOrg, pcPicDec, pcPicRest, &dCostFinal
+ */
+#if PICTURE_SAO_RDO_FIX
+Void TEncSampleAdaptiveOffset::runQuadTreeDecision(SAOQTPart *psQTPart, Int iPartIdx, Double &dCostFinal, Int iMaxLevel, Double dLambda, Int yCbCr)
+#else
+Void TEncSampleAdaptiveOffset::runQuadTreeDecision(SAOQTPart *psQTPart, Int iPartIdx, Double &dCostFinal, Int iMaxLevel, Double dLambda)
+#endif
+{
+  SAOQTPart*  pOnePart = &(psQTPart[iPartIdx]);
+
+  UInt uiDepth = pOnePart->PartLevel;
+  UInt uhNextDepth = uiDepth+1;
+
+  if (iPartIdx == 0)
+  {
+    dCostFinal = 0;
+  }
+
+  //SAO for this part
+  if(!pOnePart->bProcessed)
+  {
+#if PICTURE_SAO_RDO_FIX
+    rdoSaoOnePart (psQTPart, iPartIdx, dLambda, yCbCr);
+#else
+    rdoSaoOnePart (psQTPart, iPartIdx, dLambda);
+#endif
+  }
+
+  //SAO for sub 4 parts
+  if (pOnePart->PartLevel < iMaxLevel)
+  {
+    Double      dCostNotSplit = dLambda + pOnePart->dMinCost;
+    Double      dCostSplit    = dLambda;
+
+    for (Int i=0; i< NUM_DOWN_PART ;i++)
+    {
+      if( m_bUseSBACRD )  
+      {
+        if ( 0 == i) //initialize RD with previous depth buffer
+        {
+          m_pppcRDSbacCoder[uhNextDepth][CI_CURR_BEST]->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
+        }
+        else
+        {
+          m_pppcRDSbacCoder[uhNextDepth][CI_CURR_BEST]->load(m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]);
+        }
+      }  
+#if PICTURE_SAO_RDO_FIX
+      runQuadTreeDecision(psQTPart, pOnePart->DownPartsIdx[i], dCostFinal, iMaxLevel, dLambda, yCbCr);
+#else
+      runQuadTreeDecision(psQTPart, pOnePart->DownPartsIdx[i], dCostFinal, iMaxLevel, dLambda);
+#endif
+      dCostSplit += dCostFinal;
+      if( m_bUseSBACRD )
+      {
+        m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]->load(m_pppcRDSbacCoder[uhNextDepth][CI_TEMP_BEST]);
+      }
+    }
+
+    if(dCostSplit < dCostNotSplit)
+    {
+      dCostFinal = dCostSplit;
+      pOnePart->bSplit      = true;
+      pOnePart->iLength     =  0;
+      pOnePart->iBestType   = -1;
+      if( m_bUseSBACRD )
+      {
+        m_pppcRDSbacCoder[uiDepth][CI_NEXT_BEST]->load(m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]);
+      }
+    }
+    else
+    {
+      dCostFinal = dCostNotSplit;
+      pOnePart->bSplit = false;
+      for (Int i=0; i<NUM_DOWN_PART; i++)
+      {
+        disablePartTree(psQTPart, pOnePart->DownPartsIdx[i]);
+      }
+      if( m_bUseSBACRD )
+      {
+        m_pppcRDSbacCoder[uiDepth][CI_NEXT_BEST]->load(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
+      }
+    }
+  }
+  else
+  {
+    dCostFinal = pOnePart->dMinCost;
+  }
+}
+
+/** delete allocated memory of TEncSampleAdaptiveOffset class.
+ */
+Void TEncSampleAdaptiveOffset::destroyEncBuffer()
+{
+  for (Int i=0;i<m_iNumTotalParts;i++)
+  {
+    for (Int j=0;j<MAX_NUM_SAO_TYPE;j++)
+    {
+      if (m_iCount [i][j])
+      {
+        delete [] m_iCount [i][j]; 
+      }
+      if (m_iOffset[i][j])
+      {
+        delete [] m_iOffset[i][j]; 
+      }
+      if (m_iOffsetOrg[i][j])
+      {
+        delete [] m_iOffsetOrg[i][j]; 
+      }
+    }
+    if (m_iRate[i])
+    {
+      delete [] m_iRate[i];
+    }
+    if (m_iDist[i])
+    {
+      delete [] m_iDist[i]; 
+    }
+    if (m_dCost[i])
+    {
+      delete [] m_dCost[i]; 
+    }
+    if (m_iCount [i])
+    {
+      delete [] m_iCount [i]; 
+    }
+    if (m_iOffset[i])
+    {
+      delete [] m_iOffset[i]; 
+    }
+    if (m_iOffsetOrg[i])
+    {
+      delete [] m_iOffsetOrg[i]; 
+    }
+
+  }
+  if (m_iDistOrg)
+  {
+    delete [] m_iDistOrg ; m_iDistOrg = NULL;
+  }
+  if (m_dCostPartBest)
+  {
+    delete [] m_dCostPartBest ; m_dCostPartBest = NULL;
+  }
+  if (m_iTypePartBest)
+  {
+    delete [] m_iTypePartBest ; m_iTypePartBest = NULL;
+  }
+  if (m_iRate)
+  {
+    delete [] m_iRate ; m_iRate = NULL;
+  }
+  if (m_iDist)
+  {
+    delete [] m_iDist ; m_iDist = NULL;
+  }
+  if (m_dCost)
+  {
+    delete [] m_dCost ; m_dCost = NULL;
+  }
+  if (m_iCount)
+  {
+    delete [] m_iCount  ; m_iCount = NULL;
+  }
+  if (m_iOffset)
+  {
+    delete [] m_iOffset ; m_iOffset = NULL;
+  }
+  if (m_iOffsetOrg)
+  {
+    delete [] m_iOffsetOrg ; m_iOffsetOrg = NULL;
+  }
+#if SAO_LCU_BOUNDARY
+  Int numLcu = m_iNumCuInWidth * m_iNumCuInHeight;
+
+  for (Int i=0;i<numLcu;i++)
+  {
+    for (Int j=0;j<3;j++)
+    {
+      for (Int k=0;k<MAX_NUM_SAO_TYPE;k++)
+      {
+        if (m_count_PreDblk [i][j][k])
+        {
+          delete [] m_count_PreDblk [i][j][k]; 
+        }
+        if (m_offsetOrg_PreDblk[i][j][k])
+        {
+          delete [] m_offsetOrg_PreDblk[i][j][k];
+        }
+      }
+      if (m_count_PreDblk [i][j])
+      {
+        delete [] m_count_PreDblk [i][j]; 
+      }
+      if (m_offsetOrg_PreDblk[i][j])
+      {
+        delete [] m_offsetOrg_PreDblk[i][j]; 
+      }
+    }
+    if (m_count_PreDblk [i])
+    {
+      delete [] m_count_PreDblk [i]; 
+    }
+    if (m_offsetOrg_PreDblk[i])
+    {
+      delete [] m_offsetOrg_PreDblk[i]; 
+    }
+  }
+  if (m_count_PreDblk)
+  {
+    delete [] m_count_PreDblk  ; m_count_PreDblk = NULL;
+  }
+  if (m_offsetOrg_PreDblk)
+  {
+    delete [] m_offsetOrg_PreDblk ; m_offsetOrg_PreDblk = NULL;
+  }
+#endif
+
+  Int iMaxDepth = 4;
+  Int iDepth;
+  for ( iDepth = 0; iDepth < iMaxDepth+1; iDepth++ )
+  {
+    for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
+    {
+      delete m_pppcRDSbacCoder[iDepth][iCIIdx];
+      delete m_pppcBinCoderCABAC[iDepth][iCIIdx];
+    }
+  }
+
+  for ( iDepth = 0; iDepth < iMaxDepth+1; iDepth++ )
+  {
+    delete [] m_pppcRDSbacCoder[iDepth];
+    delete [] m_pppcBinCoderCABAC[iDepth];
+  }
+
+  delete [] m_pppcRDSbacCoder;
+  delete [] m_pppcBinCoderCABAC;
+}
+
+/** create Encoder Buffer for SAO
+ * \param 
+ */
+Void TEncSampleAdaptiveOffset::createEncBuffer()
+{
+  m_iDistOrg = new Int64 [m_iNumTotalParts]; 
+  m_dCostPartBest = new Double [m_iNumTotalParts]; 
+  m_iTypePartBest = new Int [m_iNumTotalParts]; 
+
+  m_iRate = new Int64* [m_iNumTotalParts];
+  m_iDist = new Int64* [m_iNumTotalParts];
+  m_dCost = new Double*[m_iNumTotalParts];
+
+  m_iCount  = new Int64 **[m_iNumTotalParts];
+  m_iOffset = new Int64 **[m_iNumTotalParts];
+  m_iOffsetOrg = new Int64 **[m_iNumTotalParts];
+
+  for (Int i=0;i<m_iNumTotalParts;i++)
+  {
+    m_iRate[i] = new Int64  [MAX_NUM_SAO_TYPE];
+    m_iDist[i] = new Int64  [MAX_NUM_SAO_TYPE]; 
+    m_dCost[i] = new Double [MAX_NUM_SAO_TYPE]; 
+
+    m_iCount [i] = new Int64 *[MAX_NUM_SAO_TYPE]; 
+    m_iOffset[i] = new Int64 *[MAX_NUM_SAO_TYPE]; 
+    m_iOffsetOrg[i] = new Int64 *[MAX_NUM_SAO_TYPE]; 
+
+    for (Int j=0;j<MAX_NUM_SAO_TYPE;j++)
+    {
+      m_iCount [i][j]   = new Int64 [MAX_NUM_SAO_CLASS]; 
+      m_iOffset[i][j]   = new Int64 [MAX_NUM_SAO_CLASS]; 
+      m_iOffsetOrg[i][j]= new Int64 [MAX_NUM_SAO_CLASS]; 
+    }
+  }
+#if SAO_LCU_BOUNDARY
+  Int numLcu = m_iNumCuInWidth * m_iNumCuInHeight;
+  m_count_PreDblk  = new Int64 ***[numLcu];
+  m_offsetOrg_PreDblk = new Int64 ***[numLcu];
+  for (Int i=0; i<numLcu; i++)
+  {
+    m_count_PreDblk[i]  = new Int64 **[3];
+    m_offsetOrg_PreDblk[i] = new Int64 **[3];
+
+    for (Int j=0;j<3;j++)
+    {
+      m_count_PreDblk [i][j] = new Int64 *[MAX_NUM_SAO_TYPE]; 
+      m_offsetOrg_PreDblk[i][j] = new Int64 *[MAX_NUM_SAO_TYPE]; 
+
+      for (Int k=0;k<MAX_NUM_SAO_TYPE;k++)
+      {
+        m_count_PreDblk [i][j][k]   = new Int64 [MAX_NUM_SAO_CLASS]; 
+        m_offsetOrg_PreDblk[i][j][k]= new Int64 [MAX_NUM_SAO_CLASS]; 
+      }
+    }
+  }
+#endif
+
+  Int iMaxDepth = 4;
+  m_pppcRDSbacCoder = new TEncSbac** [iMaxDepth+1];
+#if FAST_BIT_EST
+  m_pppcBinCoderCABAC = new TEncBinCABACCounter** [iMaxDepth+1];
+#else
+  m_pppcBinCoderCABAC = new TEncBinCABAC** [iMaxDepth+1];
+#endif
+
+  for ( Int iDepth = 0; iDepth < iMaxDepth+1; iDepth++ )
+  {
+    m_pppcRDSbacCoder[iDepth] = new TEncSbac* [CI_NUM];
+#if FAST_BIT_EST
+    m_pppcBinCoderCABAC[iDepth] = new TEncBinCABACCounter* [CI_NUM];
+#else
+    m_pppcBinCoderCABAC[iDepth] = new TEncBinCABAC* [CI_NUM];
+#endif
+    for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
+    {
+      m_pppcRDSbacCoder[iDepth][iCIIdx] = new TEncSbac;
+#if FAST_BIT_EST
+      m_pppcBinCoderCABAC [iDepth][iCIIdx] = new TEncBinCABACCounter;
+#else
+      m_pppcBinCoderCABAC [iDepth][iCIIdx] = new TEncBinCABAC;
+#endif
+      m_pppcRDSbacCoder   [iDepth][iCIIdx]->init( m_pppcBinCoderCABAC [iDepth][iCIIdx] );
+    }
+  }
+}
+
+/** Start SAO encoder
+ * \param pcPic, pcEntropyCoder, pppcRDSbacCoder, pcRDGoOnSbacCoder 
+ */
+Void TEncSampleAdaptiveOffset::startSaoEnc( TComPic* pcPic, TEncEntropy* pcEntropyCoder, TEncSbac*** pppcRDSbacCoder, TEncSbac* pcRDGoOnSbacCoder)
+{
+    m_bUseSBACRD = true;
+  m_pcPic = pcPic;
+  m_pcEntropyCoder = pcEntropyCoder;
+
+  m_pcRDGoOnSbacCoder = pcRDGoOnSbacCoder;
+  m_pcEntropyCoder->setEntropyCoder(m_pcRDGoOnSbacCoder, pcPic->getSlice(0));
+  m_pcEntropyCoder->resetEntropy();
+  m_pcEntropyCoder->resetBits();
+
+  if( m_bUseSBACRD )
+  {
+    m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[0][CI_NEXT_BEST]);
+    m_pppcRDSbacCoder[0][CI_CURR_BEST]->load( m_pppcRDSbacCoder[0][CI_NEXT_BEST]);
+  }
+}
+
+/** End SAO encoder
+ */
+Void TEncSampleAdaptiveOffset::endSaoEnc()
+{
+  m_pcPic = NULL;
+  m_pcEntropyCoder = NULL;
+}
+
+inline int xSign(int x)
+{
+  return ((x >> 31) | ((int)( (((unsigned int) -x)) >> 31)));
+}
+
+/** Calculate SAO statistics for non-cross-slice or non-cross-tile processing
+ * \param  pRecStart to-be-filtered block buffer pointer
+ * \param  pOrgStart original block buffer pointer
+ * \param  stride picture buffer stride
+ * \param  ppStat statistics buffer
+ * \param  ppCount counter buffer
+ * \param  width block width
+ * \param  height block height
+ * \param  pbBorderAvail availabilities of block border pixels
+ */
+Void TEncSampleAdaptiveOffset::calcSaoStatsBlock( Pel* pRecStart, Pel* pOrgStart, Int stride, Int64** ppStats, Int64** ppCount, UInt width, UInt height, Bool* pbBorderAvail)
+{
+  Int64 *stats, *count;
+  Int classIdx, posShift, startX, endX, startY, endY, signLeft,signRight,signDown,signDown1;
+  Pel *pOrg, *pRec;
+  UInt edgeType;
+  Int x, y;
+
+  //--------- Band offset-----------//
+  stats = ppStats[SAO_BO];
+  count = ppCount[SAO_BO];
+  pOrg   = pOrgStart;
+  pRec   = pRecStart;
+  for (y=0; y< height; y++)
+  {
+    for (x=0; x< width; x++)
+    {
+      classIdx = m_lumaTableBo[pRec[x]];
+      if (classIdx)
+      {
+        stats[classIdx] += (pOrg[x] - pRec[x]); 
+        count[classIdx] ++;
+      }
+    }
+    pOrg += stride;
+    pRec += stride;
+  }
+  //---------- Edge offset 0--------------//
+  stats = ppStats[SAO_EO_0];
+  count = ppCount[SAO_EO_0];
+  pOrg   = pOrgStart;
+  pRec   = pRecStart;
+
+
+  startX = (pbBorderAvail[SGU_L]) ? 0 : 1;
+  endX   = (pbBorderAvail[SGU_R]) ? width : (width -1);
+  for (y=0; y< height; y++)
+  {
+    signLeft = xSign(pRec[startX] - pRec[startX-1]);
+    for (x=startX; x< endX; x++)
+    {
+      signRight =  xSign(pRec[x] - pRec[x+1]); 
+      edgeType =  signRight + signLeft + 2;
+      signLeft  = -signRight;
+
+      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
+      count[m_auiEoTable[edgeType]] ++;
+    }
+    pRec  += stride;
+    pOrg += stride;
+  }
+
+  //---------- Edge offset 1--------------//
+  stats = ppStats[SAO_EO_1];
+  count = ppCount[SAO_EO_1];
+  pOrg   = pOrgStart;
+  pRec   = pRecStart;
+
+  startY = (pbBorderAvail[SGU_T]) ? 0 : 1;
+  endY   = (pbBorderAvail[SGU_B]) ? height : height-1;
+  if (!pbBorderAvail[SGU_T])
+  {
+    pRec  += stride;
+    pOrg  += stride;
+  }
+
+  for (x=0; x< width; x++)
+  {
+    m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-stride]);
+  }
+  for (y=startY; y<endY; y++)
+  {
+    for (x=0; x< width; x++)
+    {
+      signDown     =  xSign(pRec[x] - pRec[x+stride]); 
+      edgeType    =  signDown + m_iUpBuff1[x] + 2;
+      m_iUpBuff1[x] = -signDown;
+
+      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
+      count[m_auiEoTable[edgeType]] ++;
+    }
+    pOrg += stride;
+    pRec += stride;
+  }
+  //---------- Edge offset 2--------------//
+  stats = ppStats[SAO_EO_2];
+  count = ppCount[SAO_EO_2];
+  pOrg   = pOrgStart;
+  pRec   = pRecStart;
+
+  posShift= stride + 1;
+
+  startX = (pbBorderAvail[SGU_L]) ? 0 : 1 ;
+  endX   = (pbBorderAvail[SGU_R]) ? width : (width-1);
+
+  //prepare 2nd line upper sign
+  pRec += stride;
+  for (x=startX; x< endX+1; x++)
+  {
+    m_iUpBuff1[x] = xSign(pRec[x] - pRec[x- posShift]);
+  }
+
+  //1st line
+  pRec -= stride;
+  if(pbBorderAvail[SGU_TL])
+  {
+    x= 0;
+    edgeType      =  xSign(pRec[x] - pRec[x- posShift]) - m_iUpBuff1[x+1] + 2;
+    stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
+    count[m_auiEoTable[edgeType]] ++;
+  }
+  if(pbBorderAvail[SGU_T])
+  {
+    for(x= 1; x< endX; x++)
+    {
+      edgeType      =  xSign(pRec[x] - pRec[x- posShift]) - m_iUpBuff1[x+1] + 2;
+      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
+      count[m_auiEoTable[edgeType]] ++;
+    }
+  }
+  pRec   += stride;
+  pOrg   += stride;
+
+  //middle lines
+  for (y= 1; y< height-1; y++)
+  {
+    for (x=startX; x<endX; x++)
+    {
+      signDown1      =  xSign(pRec[x] - pRec[x+ posShift]) ;
+      edgeType      =  signDown1 + m_iUpBuff1[x] + 2;
+      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
+      count[m_auiEoTable[edgeType]] ++;
+
+      m_iUpBufft[x+1] = -signDown1; 
+    }
+    m_iUpBufft[startX] = xSign(pRec[stride+startX] - pRec[startX-1]);
+
+    ipSwap     = m_iUpBuff1;
+    m_iUpBuff1 = m_iUpBufft;
+    m_iUpBufft = ipSwap;
+
+    pRec  += stride;
+    pOrg  += stride;
+  }
+
+  //last line
+  if(pbBorderAvail[SGU_B])
+  {
+    for(x= startX; x< width-1; x++)
+    {
+      edgeType =  xSign(pRec[x] - pRec[x+ posShift]) + m_iUpBuff1[x] + 2;
+      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
+      count[m_auiEoTable[edgeType]] ++;
+    }
+  }
+  if(pbBorderAvail[SGU_BR])
+  {
+    x= width -1;
+    edgeType =  xSign(pRec[x] - pRec[x+ posShift]) + m_iUpBuff1[x] + 2;
+    stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
+    count[m_auiEoTable[edgeType]] ++;
+  }
+
+  //---------- Edge offset 3--------------//
+
+  stats = ppStats[SAO_EO_3];
+  count = ppCount[SAO_EO_3];
+  pOrg   = pOrgStart;
+  pRec   = pRecStart;
+
+  posShift     = stride - 1;
+  startX = (pbBorderAvail[SGU_L]) ? 0 : 1;
+  endX   = (pbBorderAvail[SGU_R]) ? width : (width -1);
+
+  //prepare 2nd line upper sign
+  pRec += stride;
+  for (x=startX-1; x< endX; x++)
+  {
+    m_iUpBuff1[x] = xSign(pRec[x] - pRec[x- posShift]);
+  }
+
+
+  //first line
+  pRec -= stride;
+  if(pbBorderAvail[SGU_T])
+  {
+    for(x= startX; x< width -1; x++)
+    {
+      edgeType = xSign(pRec[x] - pRec[x- posShift]) -m_iUpBuff1[x-1] + 2;
+      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
+      count[m_auiEoTable[edgeType]] ++;
+    }
+  }
+  if(pbBorderAvail[SGU_TR])
+  {
+    x= width-1;
+    edgeType = xSign(pRec[x] - pRec[x- posShift]) -m_iUpBuff1[x-1] + 2;
+    stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
+    count[m_auiEoTable[edgeType]] ++;
+  }
+  pRec  += stride;
+  pOrg  += stride;
+
+  //middle lines
+  for (y= 1; y< height-1; y++)
+  {
+    for(x= startX; x< endX; x++)
+    {
+      signDown1      =  xSign(pRec[x] - pRec[x+ posShift]) ;
+      edgeType      =  signDown1 + m_iUpBuff1[x] + 2;
+
+      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
+      count[m_auiEoTable[edgeType]] ++;
+      m_iUpBuff1[x-1] = -signDown1; 
+
+    }
+    m_iUpBuff1[endX-1] = xSign(pRec[endX-1 + stride] - pRec[endX]);
+
+    pRec  += stride;
+    pOrg  += stride;
+  }
+
+  //last line
+  if(pbBorderAvail[SGU_BL])
+  {
+    x= 0;
+    edgeType = xSign(pRec[x] - pRec[x+ posShift]) + m_iUpBuff1[x] + 2;
+    stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
+    count[m_auiEoTable[edgeType]] ++;
+
+  }
+  if(pbBorderAvail[SGU_B])
+  {
+    for(x= 1; x< endX; x++)
+    {
+      edgeType = xSign(pRec[x] - pRec[x+ posShift]) + m_iUpBuff1[x] + 2;
+      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
+      count[m_auiEoTable[edgeType]] ++;
+    }
+  }
+}
+
+/** Calculate SAO statistics for current LCU
+ * \param  iAddr,  iPartIdx,  iYCbCr
+ */
+Void TEncSampleAdaptiveOffset::calcSaoStatsCu(Int iAddr, Int iPartIdx, Int iYCbCr)
+{
+  if(!m_bUseNIF)
+  {
+    calcSaoStatsCuOrg( iAddr, iPartIdx, iYCbCr);
+  }
+  else
+  {
+    Int64** ppStats = m_iOffsetOrg[iPartIdx];
+    Int64** ppCount = m_iCount    [iPartIdx];
+
+    //parameters
+    Int  isChroma = (iYCbCr != 0)? 1:0;
+    Int  stride   = (iYCbCr != 0)?(m_pcPic->getCStride()):(m_pcPic->getStride());
+    Pel* pPicOrg = getPicYuvAddr (m_pcPic->getPicYuvOrg(), iYCbCr);
+    Pel* pPicRec  = getPicYuvAddr(m_pcYuvTmp, iYCbCr);
+
+    std::vector<NDBFBlockInfo>& vFilterBlocks = *(m_pcPic->getCU(iAddr)->getNDBFilterBlocks());
+
+    //variables
+    UInt  xPos, yPos, width, height;
+    Bool* pbBorderAvail;
+    UInt  posOffset;
+
+    for(Int i=0; i< vFilterBlocks.size(); i++)
+    {
+      xPos        = vFilterBlocks[i].posX   >> isChroma;
+      yPos        = vFilterBlocks[i].posY   >> isChroma;
+      width       = vFilterBlocks[i].width  >> isChroma;
+      height      = vFilterBlocks[i].height >> isChroma;
+      pbBorderAvail = vFilterBlocks[i].isBorderAvailable;
+
+      posOffset = (yPos* stride) + xPos;
+
+      calcSaoStatsBlock(pPicRec+ posOffset, pPicOrg+ posOffset, stride, ppStats, ppCount,width, height, pbBorderAvail);
+    }
+  }
+
+}
+
+/** Calculate SAO statistics for current LCU without non-crossing slice
+ * \param  iAddr,  iPartIdx,  iYCbCr
+ */
+Void TEncSampleAdaptiveOffset::calcSaoStatsCuOrg(Int iAddr, Int iPartIdx, Int iYCbCr)
+{
+  Int x,y;
+  TComDataCU *pTmpCu = m_pcPic->getCU(iAddr);
+  TComSPS *pTmpSPS =  m_pcPic->getSlice(0)->getSPS();
+
+  Pel* pOrg;
+  Pel* pRec;
+  Int iStride;
+  Int iLcuWidth  = pTmpSPS->getMaxCUHeight();
+  Int iLcuHeight = pTmpSPS->getMaxCUWidth();
+  UInt uiLPelX   = pTmpCu->getCUPelX();
+  UInt uiTPelY   = pTmpCu->getCUPelY();
+  UInt uiRPelX;
+  UInt uiBPelY;
+  Int64* iStats;
+  Int64* iCount;
+  Int iClassIdx;
+  Int iPicWidthTmp;
+  Int iPicHeightTmp;
+  Int iStartX;
+  Int iStartY;
+  Int iEndX;
+  Int iEndY;
+
+  Int iIsChroma = (iYCbCr!=0)? 1:0;
+  Int numSkipLine = iIsChroma? 2:4;
+  if (m_saoLcuBasedOptimization == 0)
+  {
+    numSkipLine = 0;
+  }
+
+#if SAO_SKIP_RIGHT
+  Int numSkipLineRight = iIsChroma? 3:5;
+  if (m_saoLcuBasedOptimization == 0)
+  {
+    numSkipLineRight = 0;
+  }
+#endif
+
+  iPicWidthTmp  = m_iPicWidth  >> iIsChroma;
+  iPicHeightTmp = m_iPicHeight >> iIsChroma;
+  iLcuWidth     = iLcuWidth    >> iIsChroma;
+  iLcuHeight    = iLcuHeight   >> iIsChroma;
+  uiLPelX       = uiLPelX      >> iIsChroma;
+  uiTPelY       = uiTPelY      >> iIsChroma;
+  uiRPelX       = uiLPelX + iLcuWidth  ;
+  uiBPelY       = uiTPelY + iLcuHeight ;
+  uiRPelX       = uiRPelX > iPicWidthTmp  ? iPicWidthTmp  : uiRPelX;
+  uiBPelY       = uiBPelY > iPicHeightTmp ? iPicHeightTmp : uiBPelY;
+  iLcuWidth     = uiRPelX - uiLPelX;
+  iLcuHeight    = uiBPelY - uiTPelY;
+
+  iStride    =  (iYCbCr == 0)? m_pcPic->getStride(): m_pcPic->getCStride();
+
+//if(iSaoType == BO_0 || iSaoType == BO_1)
+  {
+#if SAO_LCU_BOUNDARY
+    if( m_saoLcuBasedOptimization && m_saoLcuBoundary )
+    {
+      numSkipLine = iIsChroma? 1:3;
+      numSkipLineRight = iIsChroma? 2:4;
+    }
+#endif
+    iStats = m_iOffsetOrg[iPartIdx][SAO_BO];
+    iCount = m_iCount    [iPartIdx][SAO_BO];
+
+    pOrg = getPicYuvAddr(m_pcPic->getPicYuvOrg(), iYCbCr, iAddr);
+    pRec = getPicYuvAddr(m_pcPic->getPicYuvRec(), iYCbCr, iAddr);
+
+#if SAO_SKIP_RIGHT
+    iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth : iLcuWidth-numSkipLineRight;
+#endif
+
+    iEndY   = (uiBPelY == iPicHeightTmp) ? iLcuHeight : iLcuHeight-numSkipLine;
+    for (y=0; y<iEndY; y++)
+    {
+#if SAO_SKIP_RIGHT
+      for (x=0; x<iEndX; x++)
+#else
+      for (x=0; x<iLcuWidth; x++)
+#endif
+      {
+        iClassIdx = m_lumaTableBo[pRec[x]];
+        if (iClassIdx)
+        {
+          iStats[iClassIdx] += (pOrg[x] - pRec[x]); 
+          iCount[iClassIdx] ++;
+        }
+      }
+      pOrg += iStride;
+      pRec += iStride;
+    }
+
+  }
+  Int iSignLeft;
+  Int iSignRight;
+  Int iSignDown;
+  Int iSignDown1;
+  Int iSignDown2;
+
+  UInt uiEdgeType;
+
+//if (iSaoType == EO_0  || iSaoType == EO_1 || iSaoType == EO_2 || iSaoType == EO_3)
+  {
+  //if (iSaoType == EO_0)
+    {
+#if SAO_LCU_BOUNDARY
+      if( m_saoLcuBasedOptimization && m_saoLcuBoundary )
+      {
+        numSkipLine = iIsChroma? 1:3;
+        numSkipLineRight = iIsChroma? 3:5;
+      }
+#endif
+      iStats = m_iOffsetOrg[iPartIdx][SAO_EO_0];
+      iCount = m_iCount    [iPartIdx][SAO_EO_0];
+
+      pOrg = getPicYuvAddr(m_pcPic->getPicYuvOrg(), iYCbCr, iAddr);
+      pRec = getPicYuvAddr(m_pcPic->getPicYuvRec(), iYCbCr, iAddr);
+
+      iStartX = (uiLPelX == 0) ? 1 : 0;
+#if SAO_SKIP_RIGHT
+      iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth-1 : iLcuWidth-numSkipLineRight;
+#else
+      iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth-1 : iLcuWidth;
+#endif
+      for (y=0; y<iLcuHeight-numSkipLine; y++)
+      {
+        iSignLeft = xSign(pRec[iStartX] - pRec[iStartX-1]);
+        for (x=iStartX; x< iEndX; x++)
+        {
+          iSignRight =  xSign(pRec[x] - pRec[x+1]); 
+          uiEdgeType =  iSignRight + iSignLeft + 2;
+          iSignLeft  = -iSignRight;
+
+          iStats[m_auiEoTable[uiEdgeType]] += (pOrg[x] - pRec[x]);
+          iCount[m_auiEoTable[uiEdgeType]] ++;
+        }
+        pOrg += iStride;
+        pRec += iStride;
+      }
+    }
+
+  //if (iSaoType == EO_1)
+    {
+#if SAO_LCU_BOUNDARY
+      if( m_saoLcuBasedOptimization && m_saoLcuBoundary )
+      {
+        numSkipLine = iIsChroma? 2:4;
+        numSkipLineRight = iIsChroma? 2:4;
+      }
+#endif
+      iStats = m_iOffsetOrg[iPartIdx][SAO_EO_1];
+      iCount = m_iCount    [iPartIdx][SAO_EO_1];
+
+      pOrg = getPicYuvAddr(m_pcPic->getPicYuvOrg(), iYCbCr, iAddr);
+      pRec = getPicYuvAddr(m_pcPic->getPicYuvRec(), iYCbCr, iAddr);
+
+      iStartY = (uiTPelY == 0) ? 1 : 0;
+#if SAO_SKIP_RIGHT
+      iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth : iLcuWidth-numSkipLineRight;
+#endif
+      iEndY   = (uiBPelY == iPicHeightTmp) ? iLcuHeight-1 : iLcuHeight-numSkipLine;
+      if (uiTPelY == 0)
+      {
+        pOrg += iStride;
+        pRec += iStride;
+      }
+
+      for (x=0; x< iLcuWidth; x++)
+      {
+        m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-iStride]);
+      }
+      for (y=iStartY; y<iEndY; y++)
+      {
+#if SAO_SKIP_RIGHT
+        for (x=0; x<iEndX; x++)
+#else
+        for (x=0; x<iLcuWidth; x++)
+#endif
+        {
+          iSignDown     =  xSign(pRec[x] - pRec[x+iStride]); 
+          uiEdgeType    =  iSignDown + m_iUpBuff1[x] + 2;
+          m_iUpBuff1[x] = -iSignDown;
+
+          iStats[m_auiEoTable[uiEdgeType]] += (pOrg[x] - pRec[x]);
+          iCount[m_auiEoTable[uiEdgeType]] ++;
+        }
+        pOrg += iStride;
+        pRec += iStride;
+      }
+    }
+  //if (iSaoType == EO_2)
+    {
+#if SAO_LCU_BOUNDARY
+      if( m_saoLcuBasedOptimization && m_saoLcuBoundary )
+      {
+        numSkipLine = iIsChroma? 2:4;
+        numSkipLineRight = iIsChroma? 3:5;
+      }
+#endif
+      iStats = m_iOffsetOrg[iPartIdx][SAO_EO_2];
+      iCount = m_iCount    [iPartIdx][SAO_EO_2];
+
+      pOrg = getPicYuvAddr(m_pcPic->getPicYuvOrg(), iYCbCr, iAddr);
+      pRec = getPicYuvAddr(m_pcPic->getPicYuvRec(), iYCbCr, iAddr);
+
+      iStartX = (uiLPelX == 0) ? 1 : 0;
+#if SAO_SKIP_RIGHT
+      iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth-1 : iLcuWidth-numSkipLineRight;
+#else
+      iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth-1 : iLcuWidth;
+#endif
+
+      iStartY = (uiTPelY == 0) ? 1 : 0;
+      iEndY   = (uiBPelY == iPicHeightTmp) ? iLcuHeight-1 : iLcuHeight-numSkipLine;
+      if (uiTPelY == 0)
+      {
+        pOrg += iStride;
+        pRec += iStride;
+      }
+
+      for (x=iStartX; x<iEndX; x++)
+      {
+        m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-iStride-1]);
+      }
+      for (y=iStartY; y<iEndY; y++)
+      {
+        iSignDown2 = xSign(pRec[iStride+iStartX] - pRec[iStartX-1]);
+        for (x=iStartX; x<iEndX; x++)
+        {
+          iSignDown1      =  xSign(pRec[x] - pRec[x+iStride+1]) ;
+          uiEdgeType      =  iSignDown1 + m_iUpBuff1[x] + 2;
+          m_iUpBufft[x+1] = -iSignDown1; 
+          iStats[m_auiEoTable[uiEdgeType]] += (pOrg[x] - pRec[x]);
+          iCount[m_auiEoTable[uiEdgeType]] ++;
+        }
+        m_iUpBufft[iStartX] = iSignDown2;
+        ipSwap     = m_iUpBuff1;
+        m_iUpBuff1 = m_iUpBufft;
+        m_iUpBufft = ipSwap;
+
+        pRec += iStride;
+        pOrg += iStride;
+      }
+    } 
+  //if (iSaoType == EO_3  )
+    {
+#if SAO_LCU_BOUNDARY
+      if( m_saoLcuBasedOptimization && m_saoLcuBoundary )
+      {
+        numSkipLine = iIsChroma? 2:4;
+        numSkipLineRight = iIsChroma? 3:5;
+      }
+#endif
+      iStats = m_iOffsetOrg[iPartIdx][SAO_EO_3];
+      iCount = m_iCount    [iPartIdx][SAO_EO_3];
+
+      pOrg = getPicYuvAddr(m_pcPic->getPicYuvOrg(), iYCbCr, iAddr);
+      pRec = getPicYuvAddr(m_pcPic->getPicYuvRec(), iYCbCr, iAddr);
+
+      iStartX = (uiLPelX == 0) ? 1 : 0;
+#if SAO_SKIP_RIGHT
+      iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth-1 : iLcuWidth-numSkipLineRight;
+#else
+      iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth-1 : iLcuWidth;
+#endif
+
+      iStartY = (uiTPelY == 0) ? 1 : 0;
+      iEndY   = (uiBPelY == iPicHeightTmp) ? iLcuHeight-1 : iLcuHeight-numSkipLine;
+      if (iStartY == 1)
+      {
+        pOrg += iStride;
+        pRec += iStride;
+      }
+
+      for (x=iStartX-1; x<iEndX; x++)
+      {
+        m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-iStride+1]);
+      }
+
+      for (y=iStartY; y<iEndY; y++)
+      {
+        for (x=iStartX; x<iEndX; x++)
+        {
+          iSignDown1      =  xSign(pRec[x] - pRec[x+iStride-1]) ;
+          uiEdgeType      =  iSignDown1 + m_iUpBuff1[x] + 2;
+          m_iUpBuff1[x-1] = -iSignDown1; 
+          iStats[m_auiEoTable[uiEdgeType]] += (pOrg[x] - pRec[x]);
+          iCount[m_auiEoTable[uiEdgeType]] ++;
+        }
+        m_iUpBuff1[iEndX-1] = xSign(pRec[iEndX-1 + iStride] - pRec[iEndX]);
+
+        pRec += iStride;
+        pOrg += iStride;
+      } 
+    } 
+  }
+}
+
+
+#if SAO_LCU_BOUNDARY
+Void TEncSampleAdaptiveOffset::calcSaoStatsCu_BeforeDblk( TComPic* pcPic )
+{
+  Int addr, yCbCr;
+  Int x,y;
+  TComSPS *pTmpSPS =  pcPic->getSlice(0)->getSPS();
+
+  Pel* pOrg;
+  Pel* pRec;
+  Int stride;
+  Int lcuWidth  = pTmpSPS->getMaxCUHeight();
+  Int lcuHeight = pTmpSPS->getMaxCUWidth();
+  UInt rPelX;
+  UInt bPelY;
+  Int64* stats;
+  Int64* count;
+  Int classIdx;
+  Int picWidthTmp = 0;
+  Int picHeightTmp = 0;
+  Int startX;
+  Int startY;
+  Int endX;
+  Int endY;
+  Int firstX, firstY;
+
+  Int idxY;
+  Int idxX;
+  Int frameHeightInCU = m_iNumCuInHeight;
+  Int frameWidthInCU  = m_iNumCuInWidth;
+  Int j, k;
+
+  Int isChroma;
+  Int numSkipLine, numSkipLineRight;
+
+  UInt lPelX, tPelY;
+  TComDataCU *pTmpCu;
+
+  for (idxY = 0; idxY< frameHeightInCU; idxY++)
+  {
+    for (idxX = 0; idxX< frameWidthInCU; idxX++)
+    {
+      lcuWidth  = pTmpSPS->getMaxCUHeight();
+      lcuHeight = pTmpSPS->getMaxCUWidth();
+      addr     = idxX  + frameWidthInCU*idxY;
+      pTmpCu = pcPic->getCU(addr);
+      lPelX   = pTmpCu->getCUPelX();
+      tPelY   = pTmpCu->getCUPelY();
+      for( yCbCr = 0; yCbCr < 3; yCbCr++ )
+      {
+        isChroma = (yCbCr!=0)? 1:0;
+
+        for ( j=0;j<MAX_NUM_SAO_TYPE;j++)
+        {
+          for ( k=0;k< MAX_NUM_SAO_CLASS;k++)
+          {
+            m_count_PreDblk    [addr][yCbCr][j][k] = 0;
+            m_offsetOrg_PreDblk[addr][yCbCr][j][k] = 0;
+          }  
+        }
+        if( yCbCr == 0 )
+        {
+          picWidthTmp  = m_iPicWidth;
+          picHeightTmp = m_iPicHeight;
+        }
+        else if( yCbCr == 1 )
+        {
+          picWidthTmp  = m_iPicWidth  >> isChroma;
+          picHeightTmp = m_iPicHeight >> isChroma;
+          lcuWidth     = lcuWidth    >> isChroma;
+          lcuHeight    = lcuHeight   >> isChroma;
+          lPelX       = lPelX      >> isChroma;
+          tPelY       = tPelY      >> isChroma;
+        }
+        rPelX       = lPelX + lcuWidth  ;
+        bPelY       = tPelY + lcuHeight ;
+        rPelX       = rPelX > picWidthTmp  ? picWidthTmp  : rPelX;
+        bPelY       = bPelY > picHeightTmp ? picHeightTmp : bPelY;
+        lcuWidth     = rPelX - lPelX;
+        lcuHeight    = bPelY - tPelY;
+
+        stride    =  (yCbCr == 0)? pcPic->getStride(): pcPic->getCStride();
+
+        //if(iSaoType == BO)
+
+        numSkipLine = isChroma? 1:3;
+        numSkipLineRight = isChroma? 2:4;
+
+        stats = m_offsetOrg_PreDblk[addr][yCbCr][SAO_BO];
+        count = m_count_PreDblk[addr][yCbCr][SAO_BO];
+
+        pOrg = getPicYuvAddr(pcPic->getPicYuvOrg(), yCbCr, addr);
+        pRec = getPicYuvAddr(pcPic->getPicYuvRec(), yCbCr, addr);
+
+        startX   = (rPelX == picWidthTmp) ? lcuWidth : lcuWidth-numSkipLineRight;
+        startY   = (bPelY == picHeightTmp) ? lcuHeight : lcuHeight-numSkipLine;
+
+        for (y=0; y<lcuHeight; y++)
+        {
+          for (x=0; x<lcuWidth; x++)
+          {
+            if( x < startX && y < startY )
+              continue;
+
+            classIdx = m_lumaTableBo[pRec[x]];
+            if (classIdx)
+            {
+              stats[classIdx] += (pOrg[x] - pRec[x]); 
+              count[classIdx] ++;
+            }
+          }
+          pOrg += stride;
+          pRec += stride;
+        }
+
+        Int signLeft;
+        Int signRight;
+        Int signDown;
+        Int signDown1;
+        Int signDown2;
+
+        UInt uiEdgeType;
+
+        //if (iSaoType == EO_0)
+
+        numSkipLine = isChroma? 1:3;
+        numSkipLineRight = isChroma? 3:5;
+
+        stats = m_offsetOrg_PreDblk[addr][yCbCr][SAO_EO_0];
+        count = m_count_PreDblk[addr][yCbCr][SAO_EO_0];
+
+        pOrg = getPicYuvAddr(pcPic->getPicYuvOrg(), yCbCr, addr);
+        pRec = getPicYuvAddr(pcPic->getPicYuvRec(), yCbCr, addr);
+
+        startX   = (rPelX == picWidthTmp) ? lcuWidth-1 : lcuWidth-numSkipLineRight;
+        startY   = (bPelY == picHeightTmp) ? lcuHeight : lcuHeight-numSkipLine;
+        firstX   = (lPelX == 0) ? 1 : 0;
+        endX   = (rPelX == picWidthTmp) ? lcuWidth-1 : lcuWidth;
+
+        for (y=0; y<lcuHeight; y++)
+        {
+          signLeft = xSign(pRec[firstX] - pRec[firstX-1]);
+          for (x=firstX; x< endX; x++)
+          {
+            signRight =  xSign(pRec[x] - pRec[x+1]); 
+            uiEdgeType =  signRight + signLeft + 2;
+            signLeft  = -signRight;
+
+            if( x < startX && y < startY )
+              continue;
+
+            stats[m_auiEoTable[uiEdgeType]] += (pOrg[x] - pRec[x]);
+            count[m_auiEoTable[uiEdgeType]] ++;
+          }
+          pOrg += stride;
+          pRec += stride;
+        }
+
+        //if (iSaoType == EO_1)
+
+        numSkipLine = isChroma? 2:4;
+        numSkipLineRight = isChroma? 2:4;
+
+        stats = m_offsetOrg_PreDblk[addr][yCbCr][SAO_EO_1];
+        count = m_count_PreDblk[addr][yCbCr][SAO_EO_1];
+
+        pOrg = getPicYuvAddr(pcPic->getPicYuvOrg(), yCbCr, addr);
+        pRec = getPicYuvAddr(pcPic->getPicYuvRec(), yCbCr, addr);
+
+        startX   = (rPelX == picWidthTmp) ? lcuWidth : lcuWidth-numSkipLineRight;
+        startY   = (bPelY == picHeightTmp) ? lcuHeight-1 : lcuHeight-numSkipLine;
+        firstY = (tPelY == 0) ? 1 : 0;
+        endY   = (bPelY == picHeightTmp) ? lcuHeight-1 : lcuHeight;
+        if (firstY == 1)
+        {
+          pOrg += stride;
+          pRec += stride;
+        }
+
+        for (x=0; x< lcuWidth; x++)
+        {
+          m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-stride]);
+        }
+        for (y=firstY; y<endY; y++)
+        {
+          for (x=0; x<lcuWidth; x++)
+          {
+            signDown     =  xSign(pRec[x] - pRec[x+stride]); 
+            uiEdgeType    =  signDown + m_iUpBuff1[x] + 2;
+            m_iUpBuff1[x] = -signDown;
+
+            if( x < startX && y < startY )
+              continue;
+
+            stats[m_auiEoTable[uiEdgeType]] += (pOrg[x] - pRec[x]);
+            count[m_auiEoTable[uiEdgeType]] ++;
+          }
+          pOrg += stride;
+          pRec += stride;
+        }
+
+        //if (iSaoType == EO_2)
+
+        numSkipLine = isChroma? 2:4;
+        numSkipLineRight = isChroma? 3:5;
+
+        stats = m_offsetOrg_PreDblk[addr][yCbCr][SAO_EO_2];
+        count = m_count_PreDblk[addr][yCbCr][SAO_EO_2];
+
+        pOrg = getPicYuvAddr(pcPic->getPicYuvOrg(), yCbCr, addr);
+        pRec = getPicYuvAddr(pcPic->getPicYuvRec(), yCbCr, addr);
+
+        startX   = (rPelX == picWidthTmp) ? lcuWidth-1 : lcuWidth-numSkipLineRight;
+        startY   = (bPelY == picHeightTmp) ? lcuHeight-1 : lcuHeight-numSkipLine;
+        firstX   = (lPelX == 0) ? 1 : 0;
+        firstY = (tPelY == 0) ? 1 : 0;
+        endX   = (rPelX == picWidthTmp) ? lcuWidth-1 : lcuWidth;
+        endY   = (bPelY == picHeightTmp) ? lcuHeight-1 : lcuHeight;
+        if (firstY == 1)
+        {
+          pOrg += stride;
+          pRec += stride;
+        }
+
+        for (x=firstX; x<endX; x++)
+        {
+          m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-stride-1]);
+        }
+        for (y=firstY; y<endY; y++)
+        {
+          signDown2 = xSign(pRec[stride+startX] - pRec[startX-1]);
+          for (x=firstX; x<endX; x++)
+          {
+            signDown1      =  xSign(pRec[x] - pRec[x+stride+1]) ;
+            uiEdgeType      =  signDown1 + m_iUpBuff1[x] + 2;
+            m_iUpBufft[x+1] = -signDown1; 
+
+            if( x < startX && y < startY )
+              continue;
+
+            stats[m_auiEoTable[uiEdgeType]] += (pOrg[x] - pRec[x]);
+            count[m_auiEoTable[uiEdgeType]] ++;
+          }
+          m_iUpBufft[firstX] = signDown2;
+          ipSwap     = m_iUpBuff1;
+          m_iUpBuff1 = m_iUpBufft;
+          m_iUpBufft = ipSwap;
+
+          pRec += stride;
+          pOrg += stride;
+        }
+
+        //if (iSaoType == EO_3)
+
+        numSkipLine = isChroma? 2:4;
+        numSkipLineRight = isChroma? 3:5;
+
+        stats = m_offsetOrg_PreDblk[addr][yCbCr][SAO_EO_3];
+        count = m_count_PreDblk[addr][yCbCr][SAO_EO_3];
+
+        pOrg = getPicYuvAddr(pcPic->getPicYuvOrg(), yCbCr, addr);
+        pRec = getPicYuvAddr(pcPic->getPicYuvRec(), yCbCr, addr);
+
+        startX   = (rPelX == picWidthTmp) ? lcuWidth-1 : lcuWidth-numSkipLineRight;
+        startY   = (bPelY == picHeightTmp) ? lcuHeight-1 : lcuHeight-numSkipLine;
+        firstX   = (lPelX == 0) ? 1 : 0;
+        firstY = (tPelY == 0) ? 1 : 0;
+        endX   = (rPelX == picWidthTmp) ? lcuWidth-1 : lcuWidth;
+        endY   = (bPelY == picHeightTmp) ? lcuHeight-1 : lcuHeight;
+        if (firstY == 1)
+        {
+          pOrg += stride;
+          pRec += stride;
+        }
+
+        for (x=firstX-1; x<endX; x++)
+        {
+          m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-stride+1]);
+        }
+
+        for (y=firstY; y<endY; y++)
+        {
+          for (x=firstX; x<endX; x++)
+          {
+            signDown1      =  xSign(pRec[x] - pRec[x+stride-1]) ;
+            uiEdgeType      =  signDown1 + m_iUpBuff1[x] + 2;
+            m_iUpBuff1[x-1] = -signDown1; 
+
+            if( x < startX && y < startY )
+              continue;
+
+            stats[m_auiEoTable[uiEdgeType]] += (pOrg[x] - pRec[x]);
+            count[m_auiEoTable[uiEdgeType]] ++;
+          }
+          m_iUpBuff1[endX-1] = xSign(pRec[endX-1 + stride] - pRec[endX]);
+
+          pRec += stride;
+          pOrg += stride;
+        }
+      }
+    }
+  }
+}
+#endif
+
+
+/** get SAO statistics
+ * \param  *psQTPart,  iYCbCr
+ */
+Void TEncSampleAdaptiveOffset::getSaoStats(SAOQTPart *psQTPart, Int iYCbCr)
+{
+  Int iLevelIdx, iPartIdx, iTypeIdx, iClassIdx;
+  Int i;
+  Int iNumTotalType = MAX_NUM_SAO_TYPE;
+  Int LcuIdxX;
+  Int LcuIdxY;
+  Int iAddr;
+  Int iFrameWidthInCU = m_pcPic->getFrameWidthInCU();
+  Int iDownPartIdx;
+  Int iPartStart;
+  Int iPartEnd;
+  SAOQTPart*  pOnePart; 
+
+  if (m_uiMaxSplitLevel == 0)
+  {
+    iPartIdx = 0;
+    pOnePart = &(psQTPart[iPartIdx]);
+    for (LcuIdxY = pOnePart->StartCUY; LcuIdxY<= pOnePart->EndCUY; LcuIdxY++)
+    {
+      for (LcuIdxX = pOnePart->StartCUX; LcuIdxX<= pOnePart->EndCUX; LcuIdxX++)
+      {
+        iAddr = LcuIdxY*iFrameWidthInCU + LcuIdxX;
+        calcSaoStatsCu(iAddr, iPartIdx, iYCbCr);
+      }
+    }
+  }
+  else
+  {
+    for(iPartIdx=m_aiNumCulPartsLevel[m_uiMaxSplitLevel-1]; iPartIdx<m_aiNumCulPartsLevel[m_uiMaxSplitLevel]; iPartIdx++)
+    {
+      pOnePart = &(psQTPart[iPartIdx]);
+      for (LcuIdxY = pOnePart->StartCUY; LcuIdxY<= pOnePart->EndCUY; LcuIdxY++)
+      {
+        for (LcuIdxX = pOnePart->StartCUX; LcuIdxX<= pOnePart->EndCUX; LcuIdxX++)
+        {
+          iAddr = LcuIdxY*iFrameWidthInCU + LcuIdxX;
+          calcSaoStatsCu(iAddr, iPartIdx, iYCbCr);
+        }
+      }
+    }
+    for (iLevelIdx = m_uiMaxSplitLevel-1; iLevelIdx>=0; iLevelIdx-- )
+    {
+      iPartStart = (iLevelIdx > 0) ? m_aiNumCulPartsLevel[iLevelIdx-1] : 0;
+      iPartEnd   = m_aiNumCulPartsLevel[iLevelIdx];
+
+      for(iPartIdx = iPartStart; iPartIdx < iPartEnd; iPartIdx++)
+      {
+        pOnePart = &(psQTPart[iPartIdx]);
+        for (i=0; i< NUM_DOWN_PART; i++)
+        {
+          iDownPartIdx = pOnePart->DownPartsIdx[i];
+          for (iTypeIdx=0; iTypeIdx<iNumTotalType; iTypeIdx++)
+          {
+            for (iClassIdx=0; iClassIdx< (iTypeIdx < SAO_BO ? m_iNumClass[iTypeIdx] : SAO_MAX_BO_CLASSES) +1; iClassIdx++)
+            {
+              m_iOffsetOrg[iPartIdx][iTypeIdx][iClassIdx] += m_iOffsetOrg[iDownPartIdx][iTypeIdx][iClassIdx];
+              m_iCount [iPartIdx][iTypeIdx][iClassIdx]    += m_iCount [iDownPartIdx][iTypeIdx][iClassIdx];
+            }
+          }
+        }
+      }
+    }
+  }
+}
+
+/** reset offset statistics 
+ * \param 
+ */
+Void TEncSampleAdaptiveOffset::resetStats()
+{
+  for (Int i=0;i<m_iNumTotalParts;i++)
+  {
+    m_dCostPartBest[i] = MAX_DOUBLE;
+    m_iTypePartBest[i] = -1;
+    m_iDistOrg[i] = 0;
+    for (Int j=0;j<MAX_NUM_SAO_TYPE;j++)
+    {
+      m_iDist[i][j] = 0;
+      m_iRate[i][j] = 0;
+      m_dCost[i][j] = 0;
+      for (Int k=0;k<MAX_NUM_SAO_CLASS;k++)
+      {
+        m_iCount [i][j][k] = 0;
+        m_iOffset[i][j][k] = 0;
+        m_iOffsetOrg[i][j][k] = 0;
+      }  
+    }
+  }
+}
+
+#if SAO_CHROMA_LAMBDA 
+/** Sample adaptive offset process
+ * \param pcSaoParam
+ * \param dLambdaLuma
+ * \param dLambdaChroma
+ */
+#if SAO_ENCODING_CHOICE
+Void TEncSampleAdaptiveOffset::SAOProcess(SAOParam *pcSaoParam, Double dLambdaLuma, Double dLambdaChroma, Int depth)
+#else
+Void TEncSampleAdaptiveOffset::SAOProcess(SAOParam *pcSaoParam, Double dLambdaLuma, Double dLambdaChroma)
+#endif
+#else
+/** Sample adaptive offset process
+ * \param dLambda
+ */
+Void TEncSampleAdaptiveOffset::SAOProcess(SAOParam *pcSaoParam, Double dLambda)
+#endif
+{
+
+  m_eSliceType          =  m_pcPic->getSlice(0)->getSliceType();
+  m_iPicNalReferenceIdc = (m_pcPic->getSlice(0)->isReferenced() ? 1 :0);
+
+#if SAO_CHROMA_LAMBDA 
+  m_dLambdaLuma    = dLambdaLuma;
+  m_dLambdaChroma  = dLambdaChroma;
+#else
+  m_dLambdaLuma    = dLambda;
+  m_dLambdaChroma  = dLambda;
+#endif
+
+  if(m_bUseNIF)
+  {
+    m_pcPic->getPicYuvRec()->copyToPic(m_pcYuvTmp);
+  }
+
+#if FULL_NBIT
+  m_uiSaoBitIncrease = g_uiBitDepth + (g_uiBitDepth-8) - min((Int)(g_uiBitDepth + (g_uiBitDepth-8)), 10);
+#else
+  m_uiSaoBitIncrease = g_uiBitDepth + g_uiBitIncrement - min((Int)(g_uiBitDepth + g_uiBitIncrement), 10);
+#endif
+  
+#if FULL_NBIT
+  m_iOffsetTh = 1 << ( min((Int)(g_uiBitDepth + (g_uiBitDepth-8)-5),5) );
+#else
+  m_iOffsetTh = 1 << ( min((Int)(g_uiBitDepth + g_uiBitIncrement-5),5) );
+#endif
+  resetSAOParam(pcSaoParam);
+#if SAO_LCU_BOUNDARY
+  if( !m_saoLcuBasedOptimization || !m_saoLcuBoundary )
+  {
+    resetStats();
+  }
+#else
+  resetStats();
+#endif
+#if !SAO_TYPE_SHARING
+  Int iY  = 0;
+#endif
+  Double dCostFinal = 0;
+  if ( m_saoLcuBasedOptimization)
+  {
+#if SAO_ENCODING_CHOICE
+    rdoSaoUnitAll(pcSaoParam, dLambdaLuma, dLambdaChroma, depth);
+#else
+    rdoSaoUnitAll(pcSaoParam, dLambdaLuma, dLambdaChroma);
+#endif
+  }
+  else
+  {
+#if SAO_TYPE_SHARING
+    pcSaoParam->bSaoFlag[0] = 1;
+    pcSaoParam->bSaoFlag[1] = 0;
+    dCostFinal = 0;
+    Double lambdaRdo =  dLambdaLuma;
+    resetStats();
+    getSaoStats(pcSaoParam->psSaoPart[0], 0);
+#if PICTURE_SAO_RDO_FIX
+    runQuadTreeDecision(pcSaoParam->psSaoPart[0], 0, dCostFinal, m_uiMaxSplitLevel, lambdaRdo, 0);
+#else
+    runQuadTreeDecision(pcSaoParam->psSaoPart[0], 0, dCostFinal, m_uiMaxSplitLevel, lambdaRdo);
+#endif
+    pcSaoParam->bSaoFlag[0] = dCostFinal < 0 ? 1:0;
+    if(pcSaoParam->bSaoFlag[0])
+    {
+      convertQT2SaoUnit(pcSaoParam, 0, 0);
+      assignSaoUnitSyntax(pcSaoParam->saoLcuParam[0],  pcSaoParam->psSaoPart[0], pcSaoParam->oneUnitFlag[0], 0);
+    }
+#else
+    pcSaoParam->bSaoFlag[0] = 1;
+    pcSaoParam->bSaoFlag[1] = 0;
+    pcSaoParam->bSaoFlag[2] = 0;
+    for (Int compIdx=0;compIdx<3;compIdx++)
+    {
+      if (pcSaoParam->bSaoFlag[iY])
+      {
+        dCostFinal = 0;
+        Double lambdaRdo = (compIdx==0 ? dLambdaLuma: dLambdaChroma);
+        resetStats();
+        getSaoStats(pcSaoParam->psSaoPart[compIdx], compIdx);
+#if PICTURE_SAO_RDO_FIX
+        runQuadTreeDecision(pcSaoParam->psSaoPart[compIdx], 0, dCostFinal, m_uiMaxSplitLevel, lambdaRdo, compIdx);        
+#else
+        runQuadTreeDecision(pcSaoParam->psSaoPart[compIdx], 0, dCostFinal, m_uiMaxSplitLevel, lambdaRdo);
+#endif
+
+        pcSaoParam->bSaoFlag[compIdx] = dCostFinal < 0 ? 1:0;
+        if(pcSaoParam->bSaoFlag[compIdx])
+        {
+          convertQT2SaoUnit(pcSaoParam, 0, compIdx);
+          assignSaoUnitSyntax(pcSaoParam->saoLcuParam[compIdx],  pcSaoParam->psSaoPart[compIdx], pcSaoParam->oneUnitFlag[compIdx], compIdx);
+        }
+      }
+    }
+#endif
+  }
+#if SAO_TYPE_SHARING
+  if (pcSaoParam->bSaoFlag[0])
+  {
+    processSaoUnitAll( pcSaoParam->saoLcuParam[0], pcSaoParam->oneUnitFlag[0], 0);
+  }
+  if (pcSaoParam->bSaoFlag[1])
+  {
+    processSaoUnitAll( pcSaoParam->saoLcuParam[1], pcSaoParam->oneUnitFlag[1], 1);
+    processSaoUnitAll( pcSaoParam->saoLcuParam[2], pcSaoParam->oneUnitFlag[2], 2);
+  }
+#else
+  for (Int compIdx=0;compIdx<3;compIdx++)
+  {
+    if (pcSaoParam->bSaoFlag[compIdx])
+    {
+      processSaoUnitAll( pcSaoParam->saoLcuParam[compIdx], pcSaoParam->oneUnitFlag[compIdx], compIdx);
+    }
+  }
+#endif
+}
+/** Check merge SAO unit
+ * \param saoUnitCurr current SAO unit 
+ * \param saoUnitCheck SAO unit tobe check
+ * \param dir direction
+ */
+Void TEncSampleAdaptiveOffset::checkMerge(SaoLcuParam * saoUnitCurr, SaoLcuParam * saoUnitCheck, Int dir)
+{
+  Int i ;
+  Int countDiff = 0;
+  if (saoUnitCurr->partIdx != saoUnitCheck->partIdx)
+  {
+    if (saoUnitCurr->typeIdx !=-1)
+    {
+      if (saoUnitCurr->typeIdx == saoUnitCheck->typeIdx)
+      {
+        for (i=0;i<saoUnitCurr->length;i++)
+        {
+          countDiff += (saoUnitCurr->offset[i] != saoUnitCheck->offset[i]);
+        }
+#if SAO_TYPE_CODING
+        countDiff += (saoUnitCurr->subTypeIdx != saoUnitCheck->subTypeIdx);
+#else
+        countDiff += (saoUnitCurr->bandPosition != saoUnitCheck->bandPosition);
+#endif
+        if (countDiff ==0)
+        {
+          saoUnitCurr->partIdx = saoUnitCheck->partIdx;
+          if (dir == 1)
+          {
+            saoUnitCurr->mergeUpFlag = 1;
+            saoUnitCurr->mergeLeftFlag = 0;
+          }
+          else
+          {
+            saoUnitCurr->mergeUpFlag = 0;
+            saoUnitCurr->mergeLeftFlag = 1;
+          }
+        }
+      }
+    }
+    else
+    {
+      if (saoUnitCurr->typeIdx == saoUnitCheck->typeIdx)
+      {
+        saoUnitCurr->partIdx = saoUnitCheck->partIdx;
+        if (dir == 1)
+        {
+          saoUnitCurr->mergeUpFlag = 1;
+          saoUnitCurr->mergeLeftFlag = 0;
+        }
+        else
+        {
+          saoUnitCurr->mergeUpFlag = 0;
+          saoUnitCurr->mergeLeftFlag = 1;
+        }
+      }
+    }
+  }
+}
+/** Assign SAO unit syntax from picture-based algorithm
+ * \param saoLcuParam SAO LCU parameters
+ * \param saoPart SAO part
+ * \param oneUnitFlag SAO one unit flag
+ * \param iYCbCr color component Index
+ */
+Void TEncSampleAdaptiveOffset::assignSaoUnitSyntax(SaoLcuParam* saoLcuParam,  SAOQTPart* saoPart, Bool &oneUnitFlag, Int yCbCr)
+{
+  if (saoPart->bSplit == 0)
+  {
+    oneUnitFlag = 1;
+  }
+  else
+  {
+    Int i,j, addr, addrUp, addrLeft,  idx, idxUp, idxLeft,  idxCount;
+
+    oneUnitFlag = 0;
+
+    idxCount = -1;
+    saoLcuParam[0].mergeUpFlag = 0;
+    saoLcuParam[0].mergeLeftFlag = 0;
+
+    for (j=0;j<m_iNumCuInHeight;j++)
+    {
+      for (i=0;i<m_iNumCuInWidth;i++)
+      {
+        addr     = i + j*m_iNumCuInWidth;
+        addrLeft = (addr%m_iNumCuInWidth == 0) ? -1 : addr - 1;
+        addrUp   = (addr<m_iNumCuInWidth)      ? -1 : addr - m_iNumCuInWidth;
+        idx      = saoLcuParam[addr].partIdxTmp;
+        idxLeft  = (addrLeft == -1) ? -1 : saoLcuParam[addrLeft].partIdxTmp;
+        idxUp    = (addrUp == -1)   ? -1 : saoLcuParam[addrUp].partIdxTmp;
+
+        if(idx!=idxLeft && idx!=idxUp)
+        {
+          saoLcuParam[addr].mergeUpFlag   = 0; idxCount++;
+          saoLcuParam[addr].mergeLeftFlag = 0;
+          saoLcuParam[addr].partIdx = idxCount;
+        }
+        else if (idx==idxLeft)
+        {
+          saoLcuParam[addr].mergeUpFlag   = 1;
+          saoLcuParam[addr].mergeLeftFlag = 1;
+          saoLcuParam[addr].partIdx = saoLcuParam[addrLeft].partIdx;
+        }
+        else if (idx==idxUp)
+        {
+          saoLcuParam[addr].mergeUpFlag   = 1;
+          saoLcuParam[addr].mergeLeftFlag = 0;
+          saoLcuParam[addr].partIdx = saoLcuParam[addrUp].partIdx;
+        }
+        if (addrUp != -1)
+        {
+          checkMerge(&saoLcuParam[addr], &saoLcuParam[addrUp], 1);
+        }
+        if (addrLeft != -1)
+        {
+          checkMerge(&saoLcuParam[addr], &saoLcuParam[addrLeft], 0);
+        }
+      }
+    }
+  }
+}
+/** rate distortion optimization of all SAO units
+ * \param saoParam SAO parameters
+ * \param lambda 
+ * \param lambdaChroma
+ */
+#if SAO_ENCODING_CHOICE
+Void TEncSampleAdaptiveOffset::rdoSaoUnitAll(SAOParam *saoParam, Double lambda, Double lambdaChroma, Int depth)
+#else
+Void TEncSampleAdaptiveOffset::rdoSaoUnitAll(SAOParam *saoParam, Double lambda, Double lambdaChroma)
+#endif
+{
+
+  Int idxY;
+  Int idxX;
+  Int frameHeightInCU = saoParam->numCuInHeight;
+  Int frameWidthInCU  = saoParam->numCuInWidth;
+  Int j, k;
+  Int addr = 0;
+  Int addrUp = -1;
+  Int addrLeft = -1;
+  Int compIdx = 0;
+#if !SAO_TYPE_SHARING
+  Double lambdaComp;
+#endif
+#if SAO_SINGLE_MERGE 
+  SaoLcuParam mergeSaoParam[3][2];
+  Double compDistortion[3];
+#endif
+
+  saoParam->bSaoFlag[0] = true;
+  saoParam->bSaoFlag[1] = true;
+#if !SAO_TYPE_SHARING
+  saoParam->bSaoFlag[2] = true;
+#endif
+  saoParam->oneUnitFlag[0] = false;
+  saoParam->oneUnitFlag[1] = false;
+  saoParam->oneUnitFlag[2] = false;
+
+#if SAO_ENCODING_CHOICE
+#if SAO_ENCODING_CHOICE_CHROMA
+  Int numNoSao[2];
+  numNoSao[0] = 0;// Luma 
+  numNoSao[1] = 0;// Chroma 
+  if( depth > 0 && m_depthSaoRate[0][depth-1] > SAO_ENCODING_RATE )
+  {
+    saoParam->bSaoFlag[0] = false;
+  }
+  if( depth > 0 && m_depthSaoRate[1][depth-1] > SAO_ENCODING_RATE_CHROMA )
+  {
+    saoParam->bSaoFlag[1] = false;
+#if !SAO_TYPE_SHARING
+    saoParam->bSaoFlag[2] = false;
+#endif
+  }
+#else
+  Int numNoSao = 0;
+
+  if( depth > 0 && m_depth0SaoRate > SAO_ENCODING_RATE )
+  {
+    saoParam->bSaoFlag[0] = false;
+    saoParam->bSaoFlag[1] = false;
+#if !SAO_TYPE_SHARING
+    saoParam->bSaoFlag[2] = false;
+#endif
+  }
+#endif
+#endif
+
+  for (idxY = 0; idxY< frameHeightInCU; idxY++)
+  {
+    for (idxX = 0; idxX< frameWidthInCU; idxX++)
+    {
+      addr     = idxX  + frameWidthInCU*idxY;
+      addrUp   = addr < frameWidthInCU ? -1:idxX   + frameWidthInCU*(idxY-1);
+      addrLeft = idxX == 0               ? -1:idxX-1 + frameWidthInCU*idxY;
+#if SAO_SINGLE_MERGE
+      Int allowMergeLeft = 1;
+      Int allowMergeUp   = 1;
+      UInt rate;
+      Double bestCost, mergeCost;
+      if (idxX!=0)
+      { 
+        // check tile id and slice id 
+        if ( (m_pcPic->getPicSym()->getTileIdxMap(addr-1) != m_pcPic->getPicSym()->getTileIdxMap(addr)) || (m_pcPic->getCU(addr-1)->getSlice()->getSliceIdx() != m_pcPic->getCU(addr)->getSlice()->getSliceIdx()))
+        {
+          allowMergeLeft = 0;
+        }
+      }
+      else
+      {
+        allowMergeLeft = 0;
+      }
+      if (idxY!=0)
+      {
+        if ( (m_pcPic->getPicSym()->getTileIdxMap(addr-m_iNumCuInWidth) != m_pcPic->getPicSym()->getTileIdxMap(addr)) || (m_pcPic->getCU(addr-m_iNumCuInWidth)->getSlice()->getSliceIdx() != m_pcPic->getCU(addr)->getSlice()->getSliceIdx()))
+        {
+          allowMergeUp = 0;
+        }
+      }
+      else
+      {
+        allowMergeUp = 0;
+      }
+
+      compDistortion[0] = 0; 
+      compDistortion[1] = 0; 
+      compDistortion[2] = 0;
+      m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_CURR_BEST]);
+      if (allowMergeLeft)
+      {
+#if SAO_MERGE_ONE_CTX
+        m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMerge(0); 
+#else
+        m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMergeLeft(0, 0); 
+#endif
+      }
+      if (allowMergeUp)
+      {
+#if SAO_MERGE_ONE_CTX
+        m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMerge(0);
+#else
+        m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMergeUp(0);
+#endif
+      }
+      m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[0][CI_TEMP_BEST] );
+#endif
+      // reset stats Y, Cb, Cr
+      for ( compIdx=0;compIdx<3;compIdx++)
+      {
+        for ( j=0;j<MAX_NUM_SAO_TYPE;j++)
+        {
+          for ( k=0;k< MAX_NUM_SAO_CLASS;k++)
+          {
+#if SAO_LCU_BOUNDARY
+            m_iOffset   [compIdx][j][k] = 0;
+            if( m_saoLcuBasedOptimization && m_saoLcuBoundary ){
+              m_iCount    [compIdx][j][k] = m_count_PreDblk    [addr][compIdx][j][k];
+              m_iOffsetOrg[compIdx][j][k] = m_offsetOrg_PreDblk[addr][compIdx][j][k];
+            }
+            else
+            {
+              m_iCount    [compIdx][j][k] = 0;
+              m_iOffsetOrg[compIdx][j][k] = 0;
+            }
+#else
+            m_iCount    [compIdx][j][k] = 0;
+            m_iOffset   [compIdx][j][k] = 0;
+            m_iOffsetOrg[compIdx][j][k] = 0;
+#endif
+          }  
+        }
+        saoParam->saoLcuParam[compIdx][addr].typeIdx       =  -1;
+        saoParam->saoLcuParam[compIdx][addr].mergeUpFlag   = 0;
+        saoParam->saoLcuParam[compIdx][addr].mergeLeftFlag = 0;
+#if SAO_TYPE_CODING
+        saoParam->saoLcuParam[compIdx][addr].subTypeIdx    = 0;
+#else
+        saoParam->saoLcuParam[compIdx][addr].bandPosition  = 0;
+#endif
+#if !SAO_TYPE_SHARING
+       lambdaComp = compIdx==0 ? lambda : lambdaChroma;
+#endif
+#if SAO_ENCODING_CHOICE
+#if SAO_TYPE_SHARING
+  if( (compIdx ==0 && saoParam->bSaoFlag[0])|| (compIdx >0 && saoParam->bSaoFlag[1]) )
+#else
+  if( saoParam->bSaoFlag[compIdx] )
+#endif
+#endif
+        {
+          calcSaoStatsCu(addr, compIdx,  compIdx);
+
+#if SAO_TYPE_SHARING
+       }
+      }
+      saoComponentParamDist(allowMergeLeft, allowMergeUp, saoParam, addr, addrUp, addrLeft, 0,  lambda, &mergeSaoParam[0][0], &compDistortion[0]);
+      sao2ChromaParamDist(allowMergeLeft, allowMergeUp, saoParam, addr, addrUp, addrLeft, lambdaChroma, &mergeSaoParam[1][0], &mergeSaoParam[2][0], &compDistortion[0]);
+#else
+#if SAO_SINGLE_MERGE
+          saoComponentParamDist(allowMergeLeft, allowMergeUp, saoParam, addr, addrUp, addrLeft, compIdx,  lambdaComp, &mergeSaoParam[compIdx][0], &compDistortion[0]);
+#else
+          rdoSaoUnit (idxX, idxY, saoParam, addr, addrUp, addrLeft, compIdx,  lambdaComp);
+#endif
+#if SAO_ENCODING_CHOICE
+#if !SAO_SINGLE_MERGE
+#if SAO_ENCODING_CHOICE_CHROMA
+          if( saoParam->saoLcuParam[compIdx][addr].typeIdx == -1)
+          {
+            numNoSao[compIdx>0?1:0]++;
+          }
+#else
+          if( depth == 0 && saoParam->saoLcuParam[compIdx][addr].typeIdx == -1)
+          {
+            numNoSao++;
+          }
+#endif
+#endif
+        }
+#endif
+#if !REMOVE_SAO_LCU_ENC_CONSTRAINTS_3
+        if (compIdx!=0)
+        {
+          if ( saoParam->saoLcuParam[compIdx][0].typeIdx == -1 )
+          {
+            saoParam->bSaoFlag[compIdx] = false;
+          }
+        }
+#endif
+      }
+#endif
+#if SAO_SINGLE_MERGE   
+#if SAO_TYPE_SHARING
+     if( saoParam->bSaoFlag[0] || saoParam->bSaoFlag[1] )
+#else
+     if( saoParam->bSaoFlag[0] || saoParam->bSaoFlag[1] || saoParam->bSaoFlag[2])
+#endif
+      {
+        // Cost of new SAO_params
+        m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_CURR_BEST]);
+        m_pcRDGoOnSbacCoder->resetBits();
+        if (allowMergeLeft)
+        {
+#if SAO_MERGE_ONE_CTX
+          m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMerge(0); 
+#else
+          m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMergeLeft(0, 0); 
+#endif
+        }
+        if (allowMergeUp)
+        {
+#if SAO_MERGE_ONE_CTX
+          m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMerge(0);
+#else
+          m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMergeUp(0);
+#endif
+        }
+        for ( compIdx=0;compIdx<3;compIdx++)
+        {
+#if SAO_TYPE_SHARING
+        if( (compIdx ==0 && saoParam->bSaoFlag[0]) || (compIdx >0 && saoParam->bSaoFlag[1]))
+#else
+        if( saoParam->bSaoFlag[compIdx])
+#endif
+          {
+#if SAO_TYPE_SHARING
+           m_pcEntropyCoder->encodeSaoOffset(&saoParam->saoLcuParam[compIdx][addr], compIdx);
+#else
+           m_pcEntropyCoder->encodeSaoOffset(&saoParam->saoLcuParam[compIdx][addr]);
+#endif
+          }
+        }
+
+        rate = m_pcEntropyCoder->getNumberOfWrittenBits();
+        bestCost = compDistortion[0] + (Double)rate;
+        m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[0][CI_TEMP_BEST]);
+
+        // Cost of Merge
+        for(Int mergeUp=0; mergeUp<2; ++mergeUp)
+        {
+          if ( (allowMergeLeft && (mergeUp==0)) || (allowMergeUp && (mergeUp==1)) )
+          {
+            m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_CURR_BEST]);
+            m_pcRDGoOnSbacCoder->resetBits();
+            if (allowMergeLeft)
+            {
+#if SAO_MERGE_ONE_CTX
+              m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMerge(1-mergeUp); 
+#else
+              m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMergeLeft(1-mergeUp, 0); 
+#endif
+            }
+            if ( allowMergeUp && (mergeUp==1) )
+            {
+#if SAO_MERGE_ONE_CTX
+              m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMerge(1); 
+#else
+              m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMergeUp(1); 
+#endif
+            }
+
+            rate = m_pcEntropyCoder->getNumberOfWrittenBits();
+            mergeCost = compDistortion[mergeUp+1] + (Double)rate;
+            if (mergeCost < bestCost)
+            {
+              bestCost = mergeCost;
+              m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[0][CI_TEMP_BEST]);              
+              for ( compIdx=0;compIdx<3;compIdx++)
+              {
+                mergeSaoParam[compIdx][mergeUp].mergeLeftFlag = 1-mergeUp;
+                mergeSaoParam[compIdx][mergeUp].mergeUpFlag = mergeUp;
+#if SAO_TYPE_SHARING
+                if( (compIdx==0 && saoParam->bSaoFlag[0]) || (compIdx>0 && saoParam->bSaoFlag[1]))
+#else
+                if( saoParam->bSaoFlag[compIdx])
+#endif
+                {
+                  copySaoUnit(&saoParam->saoLcuParam[compIdx][addr], &mergeSaoParam[compIdx][mergeUp] );             
+                }
+              }
+            }
+          }
+        }
+#if SAO_ENCODING_CHOICE
+#if SAO_ENCODING_CHOICE_CHROMA
+if( saoParam->saoLcuParam[0][addr].typeIdx == -1)
+{
+  numNoSao[0]++;
+}
+#if SAO_TYPE_SHARING
+if( saoParam->saoLcuParam[1][addr].typeIdx == -1)
+{
+  numNoSao[1]+=2;
+}
+#else
+if( saoParam->saoLcuParam[1][addr].typeIdx == -1)
+{
+  numNoSao[1]++;
+}
+if( saoParam->saoLcuParam[2][addr].typeIdx == -1)
+{
+  numNoSao[1]++;
+}
+#endif
+#else
+        for ( compIdx=0;compIdx<3;compIdx++)
+        {
+          if( depth == 0 && saoParam->saoLcuParam[compIdx][addr].typeIdx == -1)
+          {
+            numNoSao++;
+          }
+        }
+#endif
+#endif
+        m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_TEMP_BEST]);
+        m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[0][CI_CURR_BEST]);
+      }
+#endif
+    }
+  }
+#if SAO_ENCODING_CHOICE
+#if SAO_ENCODING_CHOICE_CHROMA
+m_depthSaoRate[0][depth] = numNoSao[0]/((Double) frameHeightInCU*frameWidthInCU);
+m_depthSaoRate[1][depth] = numNoSao[1]/((Double) frameHeightInCU*frameWidthInCU*2);
+#else
+  if( depth == 0)
+  {
+    // update SAO Rate
+    m_depth0SaoRate = numNoSao/((Double) frameHeightInCU*frameWidthInCU*3);
+  }
+#endif
+#endif
+
+}
+/** rate distortion optimization of SAO unit 
+ * \param saoParam SAO parameters
+ * \param addr address 
+ * \param addrUp above address
+ * \param addrLeft left address 
+ * \param yCbCr color component index
+ * \param lambda 
+ */
+inline Int64 TEncSampleAdaptiveOffset::estSaoTypeDist(Int compIdx, Int typeIdx, Int shift, Double lambda, Int *currentDistortionTableBo, Double *currentRdCostTableBo)
+{
+  Int64 estDist = 0;
+  Int classIdx;
+  for(classIdx=1; classIdx < ( (typeIdx < SAO_BO) ?  m_iNumClass[typeIdx]+1 : SAO_MAX_BO_CLASSES+1); classIdx++)
+  {
+    if( typeIdx == SAO_BO)
+    {
+      currentDistortionTableBo[classIdx-1] = 0;
+      currentRdCostTableBo[classIdx-1] = lambda;
+    }
+    if(m_iCount [compIdx][typeIdx][classIdx])
+    {
+#if FULL_NBIT
+      m_iOffset[compIdx][typeIdx][classIdx] = (Int64) xRoundIbdi((Double)(m_iOffsetOrg[compIdx][typeIdx][classIdx]<<g_uiBitDepth-8)   / (Double)(m_iCount [compIdx][typeIdx][classIdx]<<m_uiSaoBitIncrease));
+#else
+      m_iOffset[compIdx][typeIdx][classIdx] = (Int64) xRoundIbdi((Double)(m_iOffsetOrg[compIdx][typeIdx][classIdx]<<g_uiBitIncrement) / (Double)(m_iCount [compIdx][typeIdx][classIdx]<<m_uiSaoBitIncrease));
+#endif
+      m_iOffset[compIdx][typeIdx][classIdx] = Clip3(-m_iOffsetTh+1, m_iOffsetTh-1, (Int)m_iOffset[compIdx][typeIdx][classIdx]);
+      if (typeIdx < 4)
+      {
+        if ( m_iOffset[compIdx][typeIdx][classIdx]<0 && classIdx<3 )
+        {
+          m_iOffset[compIdx][typeIdx][classIdx] = 0;
+        }
+        if ( m_iOffset[compIdx][typeIdx][classIdx]>0 && classIdx>=3)
+        {
+          m_iOffset[compIdx][typeIdx][classIdx] = 0;
+        }
+      }
+      m_iOffset[compIdx][typeIdx][classIdx] = estIterOffset( typeIdx, classIdx, lambda, m_iOffset[compIdx][typeIdx][classIdx], m_iCount [compIdx][typeIdx][classIdx], m_iOffsetOrg[compIdx][typeIdx][classIdx], shift, m_uiSaoBitIncrease, currentDistortionTableBo, currentRdCostTableBo );
+    }
+    else
+    {
+      m_iOffsetOrg[compIdx][typeIdx][classIdx] = 0;
+      m_iOffset[compIdx][typeIdx][classIdx] = 0;
+    }
+    if( typeIdx != SAO_BO )
+    {
+      estDist   += estSaoDist( m_iCount [compIdx][typeIdx][classIdx], m_iOffset[compIdx][typeIdx][classIdx] << m_uiSaoBitIncrease, m_iOffsetOrg[compIdx][typeIdx][classIdx], shift);
+    }
+
+  }
+  return estDist;
+}
+
+inline Int64 TEncSampleAdaptiveOffset::estSaoDist(Int64 count, Int64 offset, Int64 offsetOrg, Int shift)
+{
+  return (( count*offset*offset-offsetOrg*offset*2 ) >> shift);
+}
+inline Int64 TEncSampleAdaptiveOffset::estIterOffset(Int typeIdx, Int classIdx, double lambda, Int64 offsetInput, Int64 count, Int64 offsetOrg, Int shift, Int bitIncrease, Int *currentDistortionTableBo, Double *currentRdCostTableBo )
+{
+  //Clean up, best_q_offset.
+  Int64 iterOffset, tempOffset;
+  Int64 tempDist, tempRate;
+  Double tempCost, tempMinCost;
+  Int64 offsetOutput = 0;
+  iterOffset = offsetInput;
+  // Assuming sending quantized value 0 results in zero offset and sending the value zero needs 1 bit. entropy coder can be used to measure the exact rate here. 
+  tempMinCost = lambda; 
+  while (iterOffset != 0)
+  {
+    // Calculate the bits required for signalling the offset
+    tempRate = (typeIdx == SAO_BO) ? (abs((Int)iterOffset)+2) : (abs((Int)iterOffset)+1);
+    if (abs((Int)iterOffset)==m_iOffsetTh-1) 
+    {  
+      tempRate --;
+    }
+    // Do the dequntization before distorion calculation
+    tempOffset  = iterOffset << bitIncrease;
+    tempDist    = estSaoDist( count, tempOffset, offsetOrg, shift);
+    tempCost    = ((Double)tempDist + lambda * (Double) tempRate);
+    if(tempCost < tempMinCost)
+    {
+      tempMinCost = tempCost;
+      offsetOutput = iterOffset;
+      if(typeIdx == SAO_BO)
+      {
+        currentDistortionTableBo[classIdx-1] = (Int) tempDist;
+        currentRdCostTableBo[classIdx-1] = tempCost;
+      }
+    }
+    iterOffset = (iterOffset > 0) ? (iterOffset-1):(iterOffset+1);
+  }
+  return offsetOutput;
+}
+
+
+#if SAO_SINGLE_MERGE
+Void TEncSampleAdaptiveOffset::saoComponentParamDist(Int allowMergeLeft, Int allowMergeUp, SAOParam *saoParam, Int addr, Int addrUp, Int addrLeft, Int yCbCr, Double lambda, SaoLcuParam *compSaoParam, Double *compDistortion)
+{
+  Int typeIdx;
+
+  Int64 estDist;
+  Int classIdx;
+  Int shift = g_uiBitIncrement << 1;
+  Int64 bestDist;
+
+  SaoLcuParam*  saoLcuParam = &(saoParam->saoLcuParam[yCbCr][addr]);
+  SaoLcuParam*  saoLcuParamNeighbor = NULL; 
+
+  resetSaoUnit(saoLcuParam);
+  resetSaoUnit(&compSaoParam[0]);
+  resetSaoUnit(&compSaoParam[1]);
+
+
+  Double dCostPartBest = MAX_DOUBLE;
+
+  Double  bestRDCostTableBo = MAX_DOUBLE;
+  Int     bestClassTableBo    = 0;
+  Int     currentDistortionTableBo[MAX_NUM_SAO_CLASS];
+  Double  currentRdCostTableBo[MAX_NUM_SAO_CLASS];
+
+
+  SaoLcuParam   saoLcuParamRdo;   
+  Double   estRate = 0;
+
+  resetSaoUnit(&saoLcuParamRdo);
+
+  m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_TEMP_BEST]);
+  m_pcRDGoOnSbacCoder->resetBits();
+#if SAO_TYPE_SHARING
+ m_pcEntropyCoder->encodeSaoOffset(&saoLcuParamRdo, yCbCr);
+#else
+ m_pcEntropyCoder->encodeSaoOffset(&saoLcuParamRdo);
+#endif
+  
+  dCostPartBest = m_pcEntropyCoder->getNumberOfWrittenBits()*lambda ; 
+  copySaoUnit(saoLcuParam, &saoLcuParamRdo );
+  bestDist = 0;
+  
+
+
+  for (typeIdx=0; typeIdx<MAX_NUM_SAO_TYPE; typeIdx++)
+  {
+    estDist = estSaoTypeDist(yCbCr, typeIdx, shift, lambda, currentDistortionTableBo, currentRdCostTableBo);
+
+    if( typeIdx == SAO_BO )
+    {
+      // Estimate Best Position
+      Double currentRDCost = 0.0;
+
+      for(Int i=0; i< SAO_MAX_BO_CLASSES -SAO_BO_LEN +1; i++)
+      {
+        currentRDCost = 0.0;
+        for(UInt uj = i; uj < i+SAO_BO_LEN; uj++)
+        {
+          currentRDCost += currentRdCostTableBo[uj];
+        }
+
+        if( currentRDCost < bestRDCostTableBo)
+        {
+          bestRDCostTableBo = currentRDCost;
+          bestClassTableBo  = i;
+        }
+      }
+
+      // Re code all Offsets
+      // Code Center
+      estDist = 0;
+      for(classIdx = bestClassTableBo; classIdx < bestClassTableBo+SAO_BO_LEN; classIdx++)
+      {
+        estDist += currentDistortionTableBo[classIdx];
+      }
+    }
+    resetSaoUnit(&saoLcuParamRdo);
+    saoLcuParamRdo.length = m_iNumClass[typeIdx];
+    saoLcuParamRdo.typeIdx = typeIdx;
+    saoLcuParamRdo.mergeLeftFlag = 0;
+    saoLcuParamRdo.mergeUpFlag   = 0;
+#if SAO_TYPE_CODING
+    saoLcuParamRdo.subTypeIdx = (typeIdx == SAO_BO) ? bestClassTableBo : 0;
+#else
+    saoLcuParamRdo.bandPosition = (typeIdx == SAO_BO) ? bestClassTableBo : 0;
+#endif
+    for (classIdx = 0; classIdx < saoLcuParamRdo.length; classIdx++)
+    {
+#if SAO_TYPE_CODING
+      saoLcuParamRdo.offset[classIdx] = (Int)m_iOffset[yCbCr][typeIdx][classIdx+saoLcuParamRdo.subTypeIdx+1];
+#else
+      saoLcuParamRdo.offset[classIdx] = (Int)m_iOffset[yCbCr][typeIdx][classIdx+saoLcuParamRdo.bandPosition+1];
+#endif
+    }
+    m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_TEMP_BEST]);
+    m_pcRDGoOnSbacCoder->resetBits();
+#if SAO_TYPE_SHARING
+    m_pcEntropyCoder->encodeSaoOffset(&saoLcuParamRdo, yCbCr);
+#else
+    m_pcEntropyCoder->encodeSaoOffset(&saoLcuParamRdo);
+#endif
+
+    estRate = m_pcEntropyCoder->getNumberOfWrittenBits();
+    m_dCost[yCbCr][typeIdx] = (Double)((Double)estDist + lambda * (Double) estRate);
+
+    if(m_dCost[yCbCr][typeIdx] < dCostPartBest)
+    {
+      dCostPartBest = m_dCost[yCbCr][typeIdx];
+      copySaoUnit(saoLcuParam, &saoLcuParamRdo );
+      bestDist = estDist;       
+    }
+  }
+  compDistortion[0] += ((Double)bestDist/lambda);
+  m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_TEMP_BEST]);
+#if SAO_TYPE_SHARING
+ m_pcEntropyCoder->encodeSaoOffset(saoLcuParam, yCbCr);
+#else
+ m_pcEntropyCoder->encodeSaoOffset(saoLcuParam);
+#endif 
+  m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[0][CI_TEMP_BEST] );
+
+
+  // merge left or merge up
+
+  for (Int idxNeighbor=0;idxNeighbor<2;idxNeighbor++) 
+  {
+    saoLcuParamNeighbor = NULL;
+    if (allowMergeLeft && addrLeft>=0 && idxNeighbor ==0)
+    {
+      saoLcuParamNeighbor = &(saoParam->saoLcuParam[yCbCr][addrLeft]);
+    }
+    else if (allowMergeUp && addrUp>=0 && idxNeighbor ==1)
+    {
+      saoLcuParamNeighbor = &(saoParam->saoLcuParam[yCbCr][addrUp]);
+    }
+    if (saoLcuParamNeighbor!=NULL)
+    {
+      estDist = 0;
+      typeIdx = saoLcuParamNeighbor->typeIdx;
+      if (typeIdx>=0) 
+      {
+#if SAO_TYPE_CODING
+        Int mergeBandPosition = (typeIdx == SAO_BO)?saoLcuParamNeighbor->subTypeIdx:0;
+#else
+        Int mergeBandPosition = (typeIdx == SAO_BO)?saoLcuParamNeighbor->bandPosition:0;
+#endif        
+        Int   merge_iOffset;
+        for(classIdx = 0; classIdx < m_iNumClass[typeIdx]; classIdx++)
+        {
+          merge_iOffset = saoLcuParamNeighbor->offset[classIdx];
+          estDist   += estSaoDist(m_iCount [yCbCr][typeIdx][classIdx+mergeBandPosition+1], merge_iOffset, m_iOffsetOrg[yCbCr][typeIdx][classIdx+mergeBandPosition+1],  shift);
+        }
+      }
+      else
+      {
+        estDist = 0;
+      }
+
+      copySaoUnit(&compSaoParam[idxNeighbor], saoLcuParamNeighbor );
+      compSaoParam[idxNeighbor].mergeUpFlag   = idxNeighbor;
+      compSaoParam[idxNeighbor].mergeLeftFlag = !idxNeighbor;
+
+      compDistortion[idxNeighbor+1] += ((Double)estDist/lambda);
+    } 
+  } 
+}
+#if SAO_TYPE_SHARING
+Void TEncSampleAdaptiveOffset::sao2ChromaParamDist(Int allowMergeLeft, Int allowMergeUp, SAOParam *saoParam, Int addr, Int addrUp, Int addrLeft, Double lambda, SaoLcuParam *crSaoParam, SaoLcuParam *cbSaoParam, Double *distortion)
+{
+  Int typeIdx;
+
+  Int64 estDist[2];
+  Int classIdx;
+  Int shift = g_uiBitIncrement << 1;
+  Int64 bestDist = 0;
+
+  SaoLcuParam*  saoLcuParam[2] = {&(saoParam->saoLcuParam[1][addr]), &(saoParam->saoLcuParam[2][addr])};
+  SaoLcuParam*  saoLcuParamNeighbor[2] = {NULL, NULL}; 
+  SaoLcuParam*  saoMergeParam[2][2];
+  saoMergeParam[0][0] = &crSaoParam[0];
+  saoMergeParam[0][1] = &crSaoParam[1]; 
+  saoMergeParam[1][0] = &cbSaoParam[0];
+  saoMergeParam[1][1] = &cbSaoParam[1];
+
+  resetSaoUnit(saoLcuParam[0]);
+  resetSaoUnit(saoLcuParam[1]);
+  resetSaoUnit(saoMergeParam[0][0]);
+  resetSaoUnit(saoMergeParam[0][1]);
+  resetSaoUnit(saoMergeParam[1][0]);
+  resetSaoUnit(saoMergeParam[1][1]);
+
+
+  Double costPartBest = MAX_DOUBLE;
+
+  Double  bestRDCostTableBo;
+  Int     bestClassTableBo[2]    = {0, 0};
+  Int     currentDistortionTableBo[MAX_NUM_SAO_CLASS];
+  Double  currentRdCostTableBo[MAX_NUM_SAO_CLASS];
+
+  SaoLcuParam   saoLcuParamRdo[2];   
+  Double   estRate = 0;
+
+  resetSaoUnit(&saoLcuParamRdo[0]);
+  resetSaoUnit(&saoLcuParamRdo[1]);
+
+  m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_TEMP_BEST]);
+  m_pcRDGoOnSbacCoder->resetBits();
+  m_pcEntropyCoder->encodeSaoOffset(&saoLcuParamRdo[0], 1);
+  m_pcEntropyCoder->encodeSaoOffset(&saoLcuParamRdo[1], 2);
+  
+  costPartBest = m_pcEntropyCoder->getNumberOfWrittenBits()*lambda ; 
+  copySaoUnit(saoLcuParam[0], &saoLcuParamRdo[0] );
+  copySaoUnit(saoLcuParam[1], &saoLcuParamRdo[1] );
+
+  for (typeIdx=0; typeIdx<MAX_NUM_SAO_TYPE; typeIdx++)
+  {
+    if( typeIdx == SAO_BO )
+    {
+      // Estimate Best Position
+      for(Int compIdx = 0; compIdx < 2; compIdx++)
+      {
+        Double currentRDCost = 0.0;
+        bestRDCostTableBo = MAX_DOUBLE;
+        estDist[compIdx] = estSaoTypeDist(compIdx+1, typeIdx, shift, lambda, currentDistortionTableBo, currentRdCostTableBo);
+        for(Int i=0; i< SAO_MAX_BO_CLASSES -SAO_BO_LEN +1; i++)
+        {
+          currentRDCost = 0.0;
+          for(UInt uj = i; uj < i+SAO_BO_LEN; uj++)
+          {
+            currentRDCost += currentRdCostTableBo[uj];
+          }
+
+          if( currentRDCost < bestRDCostTableBo)
+          {
+            bestRDCostTableBo = currentRDCost;
+            bestClassTableBo[compIdx]  = i;
+          }
+        }
+
+        // Re code all Offsets
+        // Code Center
+        estDist[compIdx] = 0;
+        for(classIdx = bestClassTableBo[compIdx]; classIdx < bestClassTableBo[compIdx]+SAO_BO_LEN; classIdx++)
+        {
+          estDist[compIdx] += currentDistortionTableBo[classIdx];
+        }
+      }
+    }
+    else
+    {
+      estDist[0] = estSaoTypeDist(1, typeIdx, shift, lambda, currentDistortionTableBo, currentRdCostTableBo);
+      estDist[1] = estSaoTypeDist(2, typeIdx, shift, lambda, currentDistortionTableBo, currentRdCostTableBo);
+    }
+
+    m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_TEMP_BEST]);
+    m_pcRDGoOnSbacCoder->resetBits();
+
+    for(Int compIdx = 0; compIdx < 2; compIdx++)
+    {
+      resetSaoUnit(&saoLcuParamRdo[compIdx]);
+      saoLcuParamRdo[compIdx].length = m_iNumClass[typeIdx];
+      saoLcuParamRdo[compIdx].typeIdx = typeIdx;
+      saoLcuParamRdo[compIdx].mergeLeftFlag = 0;
+      saoLcuParamRdo[compIdx].mergeUpFlag   = 0;
+#if SAO_TYPE_CODING
+      saoLcuParamRdo[compIdx].subTypeIdx = (typeIdx == SAO_BO) ? bestClassTableBo[compIdx] : 0;
+#else
+      saoLcuParamRdo[compIdx].bandPosition = (typeIdx == SAO_BO) ? bestClassTableBo[compIdx] : 0;
+#endif
+      for (classIdx = 0; classIdx < saoLcuParamRdo[compIdx].length; classIdx++)
+      {
+#if SAO_TYPE_CODING
+        saoLcuParamRdo[compIdx].offset[classIdx] = (Int)m_iOffset[compIdx+1][typeIdx][classIdx+saoLcuParamRdo[compIdx].subTypeIdx+1];
+#else
+        saoLcuParamRdo[compIdx].offset[classIdx] = (Int)m_iOffset[compIdx+1][typeIdx][classIdx+saoLcuParamRdo[compIdx].bandPosition+1];
+#endif
+      }
+
+      m_pcEntropyCoder->encodeSaoOffset(&saoLcuParamRdo[compIdx], compIdx+1);
+    }
+    estRate = m_pcEntropyCoder->getNumberOfWrittenBits();
+    m_dCost[1][typeIdx] = (Double)((Double)(estDist[0] + estDist[1])  + lambda * (Double) estRate);
+    
+    if(m_dCost[1][typeIdx] < costPartBest)
+    {
+      costPartBest = m_dCost[1][typeIdx];
+      copySaoUnit(saoLcuParam[0], &saoLcuParamRdo[0] );
+      copySaoUnit(saoLcuParam[1], &saoLcuParamRdo[1] );
+      bestDist = (estDist[0]+estDist[1]);       
+    }
+  }
+
+  distortion[0] += ((Double)bestDist/lambda);
+  m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_TEMP_BEST]);
+  m_pcEntropyCoder->encodeSaoOffset(saoLcuParam[0], 1);
+  m_pcEntropyCoder->encodeSaoOffset(saoLcuParam[1], 2);
+  m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[0][CI_TEMP_BEST] );
+
+  // merge left or merge up
+
+  for (Int idxNeighbor=0;idxNeighbor<2;idxNeighbor++) 
+  {
+    for(Int compIdx = 0; compIdx < 2; compIdx++)
+    {
+      saoLcuParamNeighbor[compIdx] = NULL;
+      if (allowMergeLeft && addrLeft>=0 && idxNeighbor ==0)
+      {
+        saoLcuParamNeighbor[compIdx] = &(saoParam->saoLcuParam[compIdx+1][addrLeft]);
+      }
+      else if (allowMergeUp && addrUp>=0 && idxNeighbor ==1)
+      {
+        saoLcuParamNeighbor[compIdx] = &(saoParam->saoLcuParam[compIdx+1][addrUp]);
+      }
+      if (saoLcuParamNeighbor[compIdx]!=NULL)
+      {
+        estDist[compIdx] = 0;
+        typeIdx = saoLcuParamNeighbor[compIdx]->typeIdx;
+        if (typeIdx>=0) 
+        {
+#if SAO_TYPE_CODING
+          Int mergeBandPosition = (typeIdx == SAO_BO)?saoLcuParamNeighbor[compIdx]->subTypeIdx:0;
+#else
+          Int mergeBandPosition = (typeIdx == SAO_BO)?saoLcuParamNeighbor[compIdx]->bandPosition:0;
+#endif
+          Int   merge_iOffset;
+          for(classIdx = 0; classIdx < m_iNumClass[typeIdx]; classIdx++)
+          {
+            merge_iOffset = saoLcuParamNeighbor[compIdx]->offset[classIdx];
+            estDist[compIdx]   += estSaoDist(m_iCount [compIdx+1][typeIdx][classIdx+mergeBandPosition+1], merge_iOffset, m_iOffsetOrg[compIdx+1][typeIdx][classIdx+mergeBandPosition+1],  shift);
+          }
+        }
+        else
+        {
+          estDist[compIdx] = 0;
+        }
+
+        copySaoUnit(saoMergeParam[compIdx][idxNeighbor], saoLcuParamNeighbor[compIdx] );
+        saoMergeParam[compIdx][idxNeighbor]->mergeUpFlag   = idxNeighbor;
+        saoMergeParam[compIdx][idxNeighbor]->mergeLeftFlag = !idxNeighbor;
+        distortion[idxNeighbor+1] += ((Double)estDist[compIdx]/lambda);
+      }
+    } 
+  } 
+}
+#endif
+#else
+Void TEncSampleAdaptiveOffset::rdoSaoUnit(Int rx, Int ry, SAOParam *saoParam, Int addr, Int addrUp, Int addrLeft, Int yCbCr, Double lambda)
+{
+  Int typeIdx;
+
+  Int64 estDist;
+  Int classIdx;
+  Int shift = g_uiBitIncrement << 1;
+  //   Double dAreaWeight =  0;
+  SaoLcuParam*  saoLcuParam = NULL;   
+  SaoLcuParam*  saoLcuParamNeighbor = NULL; 
+  Int   merge_iOffset [33];
+  Double merge_dCost;
+  saoLcuParam = &(saoParam->saoLcuParam[yCbCr][addr]);
+  saoLcuParam->mergeUpFlag   = 0;
+  saoLcuParam->mergeLeftFlag = 0;
+
+  m_iTypePartBest[yCbCr] = -1;
+  m_dCostPartBest[yCbCr] = MAX_DOUBLE;
+
+  Double  bestRDCostTableBo = MAX_DOUBLE;
+  Int     bestClassTableBo    = 0;
+  Int     currentDistortionTableBo[MAX_NUM_SAO_CLASS];
+  Double  currentRdCostTableBo[MAX_NUM_SAO_CLASS];
+  Int     bestClassTableBoMerge = 0;
+
+  SaoLcuParam   saoLcuParamRdo;   
+  Double   estRate = 0;
+
+  resetSaoUnit(saoLcuParam);
+  resetSaoUnit(&saoLcuParamRdo);
+
+  m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_CURR_BEST]);
+  m_pcRDGoOnSbacCoder->resetBits();
+  Int allowMergeLeft = 1;
+  Int allowMergeUp   = 1;
+  if (rx!=0)
+  { 
+    // check tile id and slice id 
+    if ( (m_pcPic->getPicSym()->getTileIdxMap(addr-1) != m_pcPic->getPicSym()->getTileIdxMap(addr)) || (m_pcPic->getCU(addr-1)->getSlice()->getSliceIdx() != m_pcPic->getCU(addr)->getSlice()->getSliceIdx()))
+    {
+      allowMergeLeft = 0;
+    }
+  }
+  if (ry!=0)
+  {
+    if ( (m_pcPic->getPicSym()->getTileIdxMap(addr-m_iNumCuInWidth) != m_pcPic->getPicSym()->getTileIdxMap(addr)) || (m_pcPic->getCU(addr-m_iNumCuInWidth)->getSlice()->getSliceIdx() != m_pcPic->getCU(addr)->getSlice()->getSliceIdx()))
+    {
+      allowMergeUp = 0;
+    }
+  }
+  m_pcEntropyCoder->encodeSaoUnitInterleaving(yCbCr, 1, rx, ry,  &saoLcuParamRdo, 1,  1,  allowMergeLeft, allowMergeUp);
+  m_dCostPartBest[yCbCr] = m_pcEntropyCoder->getNumberOfWrittenBits()*lambda ; 
+  m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[0][CI_TEMP_BEST] );
+
+  for (typeIdx=0; typeIdx<MAX_NUM_SAO_TYPE; typeIdx++)
+  {
+    estDist = estSaoTypeDist(yCbCr, typeIdx, shift, lambda, currentDistortionTableBo, currentRdCostTableBo);
+
+    if( typeIdx == SAO_BO )
+    {
+      // Estimate Best Position
+      Double currentRDCost = 0.0;
+
+      for(Int i=0; i< SAO_MAX_BO_CLASSES -SAO_BO_LEN +1; i++)
+      {
+        currentRDCost = 0.0;
+        for(UInt uj = i; uj < i+SAO_BO_LEN; uj++)
+        {
+          currentRDCost += currentRdCostTableBo[uj];
+        }
+
+        if( currentRDCost < bestRDCostTableBo)
+        {
+          bestRDCostTableBo = currentRDCost;
+          bestClassTableBo  = i;
+        }
+      }
+
+      // Re code all Offsets
+      // Code Center
+      estDist = 0;
+      for(classIdx = bestClassTableBo; classIdx < bestClassTableBo+SAO_BO_LEN; classIdx++)
+      {
+        estDist += currentDistortionTableBo[classIdx];
+      }
+    }
+    resetSaoUnit(&saoLcuParamRdo);
+    saoLcuParamRdo.length = m_iNumClass[typeIdx];
+    saoLcuParamRdo.typeIdx = typeIdx;
+    saoLcuParamRdo.mergeLeftFlag = 0;
+    saoLcuParamRdo.mergeUpFlag   = 0;
+    saoLcuParamRdo.bandPosition = (typeIdx == SAO_BO) ? bestClassTableBo : 0;
+    for (classIdx = 0; classIdx < saoLcuParamRdo.length; classIdx++)
+    {
+      saoLcuParamRdo.offset[classIdx] = (Int)m_iOffset[yCbCr][typeIdx][classIdx+saoLcuParamRdo.bandPosition+1];
+    }
+    m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_CURR_BEST]);
+    m_pcRDGoOnSbacCoder->resetBits();
+    m_pcEntropyCoder->encodeSaoUnitInterleaving(yCbCr, 1, rx, ry,  &saoLcuParamRdo, 1,  1,  allowMergeLeft, allowMergeUp);
+    estRate = m_pcEntropyCoder->getNumberOfWrittenBits();
+    m_dCost[yCbCr][typeIdx] = (Double)((Double)estDist + lambda * (Double) estRate);
+
+    if(m_dCost[yCbCr][typeIdx] < m_dCostPartBest[yCbCr])
+    {
+      m_dCostPartBest[yCbCr] = m_dCost[yCbCr][typeIdx];
+      m_iTypePartBest[yCbCr] = typeIdx;
+      m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[0][CI_TEMP_BEST] );
+    }
+  }
+
+  // merge left or merge up
+
+  for (Int idxNeighbor=0;idxNeighbor<2;idxNeighbor++) 
+  {
+    saoLcuParamNeighbor = NULL;
+    if (addrLeft>=0 && idxNeighbor ==0)
+    {
+      saoLcuParamNeighbor = &(saoParam->saoLcuParam[yCbCr][addrLeft]);
+    }
+    else if (addrUp>=0 && idxNeighbor ==1)
+    {
+      saoLcuParamNeighbor = &(saoParam->saoLcuParam[yCbCr][addrUp]);
+    }
+    if (saoLcuParamNeighbor!=NULL)
+    {
+        Int mergeBandPosition = 0;
+        estDist = 0;
+        typeIdx = saoLcuParamNeighbor->typeIdx;
+        if (saoLcuParamNeighbor->typeIdx>=0) //new
+        {
+          mergeBandPosition = (saoLcuParamNeighbor->typeIdx == SAO_BO)?saoLcuParamNeighbor->bandPosition:0;
+          for(classIdx = mergeBandPosition+1; classIdx < mergeBandPosition+m_iNumClass[typeIdx]+1; classIdx++)
+          {
+            merge_iOffset[classIdx] = saoLcuParamNeighbor->offset[classIdx-1-saoLcuParamNeighbor->bandPosition];
+            estDist   += estSaoDist(m_iCount [yCbCr][typeIdx][classIdx], merge_iOffset[classIdx], m_iOffsetOrg[yCbCr][typeIdx][classIdx],  shift);
+          }
+        }
+        else
+        {
+          saoLcuParamRdo.typeIdx = -1;
+          saoLcuParamRdo.length  = 0;
+          estDist = 0;
+        }
+        m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_CURR_BEST]);
+        m_pcRDGoOnSbacCoder->resetBits();
+        saoLcuParamRdo.mergeUpFlag   = idxNeighbor;
+        saoLcuParamRdo.mergeLeftFlag = !idxNeighbor;
+        m_pcEntropyCoder->encodeSaoUnitInterleaving(yCbCr, 1, rx, ry,  &saoLcuParamRdo, 1,  1,  allowMergeLeft, allowMergeUp);
+        estRate = m_pcEntropyCoder->getNumberOfWrittenBits();
+
+        merge_dCost = (Double)((Double)estDist + m_dLambdaLuma * estRate) ;
+
+        if(merge_dCost < m_dCostPartBest[yCbCr])
+        {
+          m_dCostPartBest[yCbCr] = merge_dCost;
+          m_iTypePartBest[yCbCr] = typeIdx;
+          if (typeIdx>=0)
+          {
+            bestClassTableBoMerge   = mergeBandPosition;
+            for(classIdx = mergeBandPosition+1; classIdx < mergeBandPosition+m_iNumClass[typeIdx]+1; classIdx++)
+            {
+              m_iOffset[yCbCr][typeIdx][classIdx] = merge_iOffset[classIdx];
+            }
+          }
+          saoLcuParam->mergeUpFlag   = idxNeighbor;
+          saoLcuParam->mergeLeftFlag = !idxNeighbor;
+          m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[0][CI_TEMP_BEST] );
+        }
+    }
+  } 
+
+  saoLcuParam->typeIdx  = m_iTypePartBest[yCbCr];
+  if (saoLcuParam->typeIdx != -1)
+  {
+    saoLcuParam->length = m_iNumClass[saoLcuParam->typeIdx];
+    Int minIndex = 0;
+    if( saoLcuParam->typeIdx == SAO_BO )
+    {
+      if ((saoLcuParam->mergeUpFlag )||(saoLcuParam->mergeLeftFlag)) 
+      {
+        saoLcuParam->bandPosition = bestClassTableBoMerge;
+      }
+      else
+      {
+        saoLcuParam->bandPosition = bestClassTableBo;
+      }
+      minIndex = saoLcuParam->bandPosition;
+    }
+    for (Int i=0; i< saoLcuParam->length ; i++)
+    {
+      saoLcuParam->offset[i] = (Int) m_iOffset[yCbCr][saoLcuParam->typeIdx][minIndex+i+1];
+    }
+  }
+  else
+  {
+    saoLcuParam->length = 0;
+  }
+
+  m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[0][CI_TEMP_BEST] );
+  m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[0][CI_CURR_BEST] );
+}
+#endif
+
+//! \}
Index: /trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h	(revision 2)
@@ -0,0 +1,152 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncAdaptiveLoopFilter.h
+ \brief    estimation part of sample adaptive offset class (header)
+ */
+
+#ifndef __TENCSAMPLEADAPTIVEOFFSET__
+#define __TENCSAMPLEADAPTIVEOFFSET__
+
+#include "TLibCommon/TComSampleAdaptiveOffset.h"
+#include "TLibCommon/TComPic.h"
+
+#include "TEncEntropy.h"
+#include "TEncSbac.h"
+#include "TLibCommon/TComBitCounter.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+class TEncSampleAdaptiveOffset : public TComSampleAdaptiveOffset
+{
+private:
+  Double            m_dLambdaLuma;
+  Double            m_dLambdaChroma;
+
+  TEncEntropy*      m_pcEntropyCoder;
+  TEncSbac***       m_pppcRDSbacCoder;              ///< for CABAC
+  TEncSbac*         m_pcRDGoOnSbacCoder;
+#if FAST_BIT_EST
+  TEncBinCABACCounter*** m_pppcBinCoderCABAC;            ///< temporal CABAC state storage for RD computation
+#else
+  TEncBinCABAC***   m_pppcBinCoderCABAC;            ///< temporal CABAC state storage for RD computation
+#endif
+  
+  Int64  ***m_iCount;      //[MAX_NUM_SAO_PART][MAX_NUM_SAO_TYPE][MAX_NUM_SAO_CLASS]; 
+  Int64  ***m_iOffset;     //[MAX_NUM_SAO_PART][MAX_NUM_SAO_TYPE][MAX_NUM_SAO_CLASS]; 
+  Int64  ***m_iOffsetOrg;  //[MAX_NUM_SAO_PART][MAX_NUM_SAO_TYPE]; 
+#if SAO_LCU_BOUNDARY
+  Int64  ****m_count_PreDblk;      //[LCU][YCbCr][MAX_NUM_SAO_TYPE][MAX_NUM_SAO_CLASS]; 
+  Int64  ****m_offsetOrg_PreDblk;  //[LCU][YCbCr][MAX_NUM_SAO_TYPE][MAX_NUM_SAO_CLASS]; 
+#endif
+  Int64  **m_iRate;        //[MAX_NUM_SAO_PART][MAX_NUM_SAO_TYPE]; 
+  Int64  **m_iDist;        //[MAX_NUM_SAO_PART][MAX_NUM_SAO_TYPE]; 
+  Double **m_dCost;        //[MAX_NUM_SAO_PART][MAX_NUM_SAO_TYPE]; 
+  Double *m_dCostPartBest; //[MAX_NUM_SAO_PART]; 
+  Int64  *m_iDistOrg;      //[MAX_NUM_SAO_PART]; 
+  Int    *m_iTypePartBest; //[MAX_NUM_SAO_PART]; 
+  Int     m_iOffsetTh;
+  Bool    m_bUseSBACRD;
+#if SAO_ENCODING_CHOICE
+#if SAO_ENCODING_CHOICE_CHROMA
+  Double  m_depthSaoRate[2][4];
+#else
+  Double  m_depth0SaoRate;
+#endif
+#endif
+
+public:
+  TEncSampleAdaptiveOffset         ();
+  virtual ~TEncSampleAdaptiveOffset();
+
+  Void startSaoEnc( TComPic* pcPic, TEncEntropy* pcEntropyCoder, TEncSbac*** pppcRDSbacCoder, TEncSbac* pcRDGoOnSbacCoder);
+  Void endSaoEnc();
+  Void resetStats();
+#if SAO_CHROMA_LAMBDA
+#if SAO_ENCODING_CHOICE
+  Void SAOProcess(SAOParam *pcSaoParam, Double dLambda, Double dLambdaChroma, Int depth);
+#else
+  Void SAOProcess(SAOParam *pcSaoParam, Double dLambda, Double dLambdaChroma);
+#endif
+#else
+  Void SAOProcess(SAOParam *pcSaoParam, Double dLambda);
+#endif
+
+#if PICTURE_SAO_RDO_FIX  
+  Void runQuadTreeDecision(SAOQTPart *psQTPart, Int iPartIdx, Double &dCostFinal, Int iMaxLevel, Double dLambda, Int yCbCr);
+  Void rdoSaoOnePart(SAOQTPart *psQTPart, Int iPartIdx, Double dLambda, Int yCbCr);
+#else
+  Void runQuadTreeDecision(SAOQTPart *psQTPart, Int iPartIdx, Double &dCostFinal, Int iMaxLevel, Double dLambda);
+  Void rdoSaoOnePart(SAOQTPart *psQTPart, Int iPartIdx, Double dLambda);
+#endif
+  
+  Void disablePartTree(SAOQTPart *psQTPart, Int iPartIdx);
+  Void getSaoStats(SAOQTPart *psQTPart, Int iYCbCr);
+  Void calcSaoStatsCu(Int iAddr, Int iPartIdx, Int iYCbCr);
+  Void calcSaoStatsBlock( Pel* pRecStart, Pel* pOrgStart, Int stride, Int64** ppStats, Int64** ppCount, UInt width, UInt height, Bool* pbBorderAvail);
+  Void calcSaoStatsCuOrg(Int iAddr, Int iPartIdx, Int iYCbCr);
+#if SAO_LCU_BOUNDARY
+  Void calcSaoStatsCu_BeforeDblk( TComPic* pcPic );
+#endif
+  Void destroyEncBuffer();
+  Void createEncBuffer();
+  Void assignSaoUnitSyntax(SaoLcuParam* saoLcuParam,  SAOQTPart* saoPart, Bool &oneUnitFlag, Int yCbCr);
+  Void checkMerge(SaoLcuParam * lcuParamCurr,SaoLcuParam * lcuParamCheck, Int dir);
+#if SAO_ENCODING_CHOICE
+  Void rdoSaoUnitAll(SAOParam *saoParam, Double lambda, Double lambdaChroma, Int depth);
+#else
+  Void rdoSaoUnitAll(SAOParam *saoParam, Double lambda, Double lambdaChroma);
+#endif
+#if SAO_SINGLE_MERGE
+  Void saoComponentParamDist(Int allowMergeLeft, Int allowMergeUp, SAOParam *saoParam, Int addr, Int addrUp, Int addrLeft, Int yCbCr, Double lambda, SaoLcuParam *compSaoParam, Double *distortion);
+#if SAO_TYPE_SHARING
+  Void sao2ChromaParamDist(Int allowMergeLeft, Int allowMergeUp, SAOParam *saoParam, Int addr, Int addrUp, Int addrLeft, Double lambda, SaoLcuParam *crSaoParam, SaoLcuParam *cbSaoParam, Double *distortion);
+#endif
+#else
+  Void rdoSaoUnit(Int rx, Int ry, SAOParam *saoParam, Int addr, Int addrUp, Int addrLeft, Int yCbCr, Double lambda);
+#endif
+  inline Int64 estSaoDist(Int64 count, Int64 offset, Int64 offsetOrg, Int shift);
+  inline Int64 estIterOffset(Int typeIdx, Int classIdx, double lambda, Int64 offsetInput, Int64 count, Int64 offsetOrg, Int shift, Int bitIncrease, Int *currentDistortionTableBo, Double *currentRdCostTableBo );
+  inline Int64 estSaoTypeDist(Int compIdx, Int typeIdx, Int shift, Double lambda, Int *currentDistortionTableBo, Double *currentRdCostTableBo);
+  Void setMaxNumOffsetsPerPic(Int iVal) {m_maxNumOffsetsPerPic = iVal; }
+  Int  getMaxNumOffsetsPerPic() {return m_maxNumOffsetsPerPic; }
+};
+
+//! \}
+
+#endif
Index: /trunk/source/Lib/TLibEncoder/TEncSbac.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncSbac.cpp	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/TEncSbac.cpp	(revision 2)
@@ -0,0 +1,1956 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncSbac.cpp
+    \brief    SBAC encoder class
+*/
+
+#include "TEncTop.h"
+#include "TEncSbac.h"
+
+#include <map>
+#include <algorithm>
+
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TEncSbac::TEncSbac()
+// new structure here
+: m_pcBitIf                   ( NULL )
+, m_pcSlice                   ( NULL )
+, m_pcBinIf                   ( NULL )
+, m_uiCoeffCost               ( 0 )
+, m_numContextModels          ( 0 )
+, m_cCUSplitFlagSCModel       ( 1,             1,               NUM_SPLIT_FLAG_CTX            , m_contextModels + m_numContextModels, m_numContextModels )
+, m_cCUSkipFlagSCModel        ( 1,             1,               NUM_SKIP_FLAG_CTX             , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUMergeFlagExtSCModel    ( 1,             1,               NUM_MERGE_FLAG_EXT_CTX        , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUMergeIdxExtSCModel     ( 1,             1,               NUM_MERGE_IDX_EXT_CTX         , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUPartSizeSCModel        ( 1,             1,               NUM_PART_SIZE_CTX             , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUPredModeSCModel        ( 1,             1,               NUM_PRED_MODE_CTX             , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUAlfCtrlFlagSCModel     ( 1,             1,               NUM_ALF_CTRL_FLAG_CTX         , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUIntraPredSCModel       ( 1,             1,               NUM_ADI_CTX                   , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUChromaPredSCModel      ( 1,             1,               NUM_CHROMA_PRED_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUDeltaQpSCModel         ( 1,             1,               NUM_DELTA_QP_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUInterDirSCModel        ( 1,             1,               NUM_INTER_DIR_CTX             , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCURefPicSCModel          ( 1,             1,               NUM_REF_NO_CTX                , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUMvdSCModel             ( 1,             1,               NUM_MV_RES_CTX                , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUQtCbfSCModel           ( 1,             2,               NUM_QT_CBF_CTX                , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUTransSubdivFlagSCModel ( 1,             1,               NUM_TRANS_SUBDIV_FLAG_CTX     , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUQtRootCbfSCModel       ( 1,             1,               NUM_QT_ROOT_CBF_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUSigCoeffGroupSCModel   ( 1,             2,               NUM_SIG_CG_FLAG_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUSigSCModel             ( 1,             1,               NUM_SIG_FLAG_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCuCtxLastX               ( 1,             2,               NUM_CTX_LAST_FLAG_XY          , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCuCtxLastY               ( 1,             2,               NUM_CTX_LAST_FLAG_XY          , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUOneSCModel             ( 1,             1,               NUM_ONE_FLAG_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUAbsSCModel             ( 1,             1,               NUM_ABS_FLAG_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cMVPIdxSCModel            ( 1,             1,               NUM_MVP_IDX_CTX               , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cALFFlagSCModel           ( 1,             1,               NUM_ALF_FLAG_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cALFUvlcSCModel           ( 1,             1,               NUM_ALF_UVLC_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cALFSvlcSCModel           ( 1,             1,               NUM_ALF_SVLC_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUAMPSCModel             ( 1,             1,               NUM_CU_AMP_CTX                , m_contextModels + m_numContextModels, m_numContextModels)
+#if !SAO_ABS_BY_PASS
+, m_cSaoUvlcSCModel           ( 1,             1,               NUM_SAO_UVLC_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+#endif
+#if SAO_MERGE_ONE_CTX
+, m_cSaoMergeSCModel          ( 1,             1,               NUM_SAO_MERGE_FLAG_CTX   , m_contextModels + m_numContextModels, m_numContextModels)
+#else
+, m_cSaoMergeLeftSCModel      ( 1,             1,               NUM_SAO_MERGE_LEFT_FLAG_CTX   , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSaoMergeUpSCModel        ( 1,             1,               NUM_SAO_MERGE_UP_FLAG_CTX     , m_contextModels + m_numContextModels, m_numContextModels)
+#endif
+#if INTRA_BL
+, m_cIntraBLPredFlagSCModel   (1,              1,               NUM_INTRA_BL_PRED_CTX         , m_contextModels + m_numContextModels, m_numContextModels)
+#endif
+, m_cSaoTypeIdxSCModel        ( 1,             1,               NUM_SAO_TYPE_IDX_CTX          , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cTransformSkipSCModel     ( 1,             2,               NUM_TRANSFORMSKIP_FLAG_CTX    , m_contextModels + m_numContextModels, m_numContextModels)
+, m_CUTransquantBypassFlagSCModel( 1,          1,               NUM_CU_TRANSQUANT_BYPASS_FLAG_CTX, m_contextModels + m_numContextModels, m_numContextModels)
+{
+  assert( m_numContextModels <= MAX_NUM_CTX_MOD );
+#if !REMOVE_FGS
+  m_iSliceGranularity = 0;
+#endif
+}
+
+TEncSbac::~TEncSbac()
+{
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+Void TEncSbac::resetEntropy           ()
+{
+  Int  iQp              = m_pcSlice->getSliceQp();
+  SliceType eSliceType  = m_pcSlice->getSliceType();
+  
+  Int  encCABACTableIdx = m_pcSlice->getPPS()->getEncCABACTableIdx();
+  if (!m_pcSlice->isIntra() && (encCABACTableIdx==B_SLICE || encCABACTableIdx==P_SLICE) && m_pcSlice->getPPS()->getCabacInitPresentFlag())
+  {
+    eSliceType = (SliceType) encCABACTableIdx;
+  }
+
+  m_cCUSplitFlagSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_SPLIT_FLAG );
+  
+  m_cCUSkipFlagSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_SKIP_FLAG );
+  m_cCUAlfCtrlFlagSCModel.initBuffer     ( eSliceType, iQp, (UChar*)INIT_ALF_CTRL_FLAG );
+  m_cCUMergeFlagExtSCModel.initBuffer    ( eSliceType, iQp, (UChar*)INIT_MERGE_FLAG_EXT);
+  m_cCUMergeIdxExtSCModel.initBuffer     ( eSliceType, iQp, (UChar*)INIT_MERGE_IDX_EXT);
+  m_cCUPartSizeSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_PART_SIZE );
+  m_cCUAMPSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_CU_AMP_POS );
+  m_cCUPredModeSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_PRED_MODE );
+  m_cCUIntraPredSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_INTRA_PRED_MODE );
+  m_cCUChromaPredSCModel.initBuffer      ( eSliceType, iQp, (UChar*)INIT_CHROMA_PRED_MODE );
+  m_cCUInterDirSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_INTER_DIR );
+  m_cCUMvdSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_MVD );
+  m_cCURefPicSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_REF_PIC );
+  m_cCUDeltaQpSCModel.initBuffer         ( eSliceType, iQp, (UChar*)INIT_DQP );
+  m_cCUQtCbfSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_QT_CBF );
+  m_cCUQtRootCbfSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_QT_ROOT_CBF );
+  m_cCUSigCoeffGroupSCModel.initBuffer   ( eSliceType, iQp, (UChar*)INIT_SIG_CG_FLAG );
+  m_cCUSigSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_SIG_FLAG );
+  m_cCuCtxLastX.initBuffer               ( eSliceType, iQp, (UChar*)INIT_LAST );
+  m_cCuCtxLastY.initBuffer               ( eSliceType, iQp, (UChar*)INIT_LAST );
+  m_cCUOneSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_ONE_FLAG );
+  m_cCUAbsSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_ABS_FLAG );
+  m_cMVPIdxSCModel.initBuffer            ( eSliceType, iQp, (UChar*)INIT_MVP_IDX );
+  m_cALFFlagSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_ALF_FLAG );
+  m_cALFUvlcSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_ALF_UVLC );
+  m_cALFSvlcSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_ALF_SVLC );
+  m_cCUTransSubdivFlagSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_TRANS_SUBDIV_FLAG );
+#if !SAO_ABS_BY_PASS
+  m_cSaoUvlcSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_SAO_UVLC );
+#endif
+#if SAO_MERGE_ONE_CTX
+  m_cSaoMergeSCModel.initBuffer      ( eSliceType, iQp, (UChar*)INIT_SAO_MERGE_FLAG );
+#else
+  m_cSaoMergeLeftSCModel.initBuffer      ( eSliceType, iQp, (UChar*)INIT_SAO_MERGE_LEFT_FLAG );
+  m_cSaoMergeUpSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_SAO_MERGE_UP_FLAG );
+#endif
+#if INTRA_BL
+  m_cIntraBLPredFlagSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_INTRA_BL_PRED_FLAG );
+#endif
+  m_cSaoTypeIdxSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_SAO_TYPE_IDX );
+  m_cTransformSkipSCModel.initBuffer     ( eSliceType, iQp, (UChar*)INIT_TRANSFORMSKIP_FLAG );
+  m_CUTransquantBypassFlagSCModel.initBuffer( eSliceType, iQp, (UChar*)INIT_CU_TRANSQUANT_BYPASS_FLAG );
+  // new structure
+  m_uiLastQp = iQp;
+  
+  m_pcBinIf->start();
+  
+  return;
+}
+
+/** The function does the following: 
+ * If current slice type is P/B then it determines the distance of initialisation type 1 and 2 from the current CABAC states and 
+ * stores the index of the closest table.  This index is used for the next P/B slice when cabac_init_present_flag is true.
+ */
+Void TEncSbac::determineCabacInitIdx()
+{
+  Int  qp              = m_pcSlice->getSliceQp();
+
+  if (!m_pcSlice->isIntra())
+  {
+    SliceType aSliceTypeChoices[] = {B_SLICE, P_SLICE};
+
+    UInt bestCost             = MAX_UINT;
+    SliceType bestSliceType   = aSliceTypeChoices[0];
+    for (UInt idx=0; idx<2; idx++)
+    {
+      UInt curCost          = 0;
+      SliceType curSliceType  = aSliceTypeChoices[idx];
+
+      curCost  = m_cCUSplitFlagSCModel.calcCost       ( curSliceType, qp, (UChar*)INIT_SPLIT_FLAG );
+      curCost += m_cCUSkipFlagSCModel.calcCost        ( curSliceType, qp, (UChar*)INIT_SKIP_FLAG );
+#if INTRA_BL
+      curCost += m_cIntraBLPredFlagSCModel.calcCost   ( curSliceType, qp, (UChar*)INIT_INTRA_BL_PRED_FLAG );
+#endif
+      curCost += m_cCUAlfCtrlFlagSCModel.calcCost     ( curSliceType, qp, (UChar*)INIT_ALF_CTRL_FLAG );
+      curCost += m_cCUMergeFlagExtSCModel.calcCost    ( curSliceType, qp, (UChar*)INIT_MERGE_FLAG_EXT);
+      curCost += m_cCUMergeIdxExtSCModel.calcCost     ( curSliceType, qp, (UChar*)INIT_MERGE_IDX_EXT);
+      curCost += m_cCUPartSizeSCModel.calcCost        ( curSliceType, qp, (UChar*)INIT_PART_SIZE );
+      curCost += m_cCUAMPSCModel.calcCost             ( curSliceType, qp, (UChar*)INIT_CU_AMP_POS );
+      curCost += m_cCUPredModeSCModel.calcCost        ( curSliceType, qp, (UChar*)INIT_PRED_MODE );
+      curCost += m_cCUIntraPredSCModel.calcCost       ( curSliceType, qp, (UChar*)INIT_INTRA_PRED_MODE );
+      curCost += m_cCUChromaPredSCModel.calcCost      ( curSliceType, qp, (UChar*)INIT_CHROMA_PRED_MODE );
+      curCost += m_cCUInterDirSCModel.calcCost        ( curSliceType, qp, (UChar*)INIT_INTER_DIR );
+      curCost += m_cCUMvdSCModel.calcCost             ( curSliceType, qp, (UChar*)INIT_MVD );
+      curCost += m_cCURefPicSCModel.calcCost          ( curSliceType, qp, (UChar*)INIT_REF_PIC );
+      curCost += m_cCUDeltaQpSCModel.calcCost         ( curSliceType, qp, (UChar*)INIT_DQP );
+      curCost += m_cCUQtCbfSCModel.calcCost           ( curSliceType, qp, (UChar*)INIT_QT_CBF );
+      curCost += m_cCUQtRootCbfSCModel.calcCost       ( curSliceType, qp, (UChar*)INIT_QT_ROOT_CBF );
+      curCost += m_cCUSigCoeffGroupSCModel.calcCost   ( curSliceType, qp, (UChar*)INIT_SIG_CG_FLAG );
+      curCost += m_cCUSigSCModel.calcCost             ( curSliceType, qp, (UChar*)INIT_SIG_FLAG );
+      curCost += m_cCuCtxLastX.calcCost               ( curSliceType, qp, (UChar*)INIT_LAST );
+      curCost += m_cCuCtxLastY.calcCost               ( curSliceType, qp, (UChar*)INIT_LAST );
+      curCost += m_cCUOneSCModel.calcCost             ( curSliceType, qp, (UChar*)INIT_ONE_FLAG );
+      curCost += m_cCUAbsSCModel.calcCost             ( curSliceType, qp, (UChar*)INIT_ABS_FLAG );
+      curCost += m_cMVPIdxSCModel.calcCost            ( curSliceType, qp, (UChar*)INIT_MVP_IDX );
+      curCost += m_cALFFlagSCModel.calcCost           ( curSliceType, qp, (UChar*)INIT_ALF_FLAG );
+      curCost += m_cALFUvlcSCModel.calcCost           ( curSliceType, qp, (UChar*)INIT_ALF_UVLC );
+      curCost += m_cALFSvlcSCModel.calcCost           ( curSliceType, qp, (UChar*)INIT_ALF_SVLC );
+      curCost += m_cCUTransSubdivFlagSCModel.calcCost ( curSliceType, qp, (UChar*)INIT_TRANS_SUBDIV_FLAG );
+#if !SAO_ABS_BY_PASS
+      curCost += m_cSaoUvlcSCModel.calcCost           ( curSliceType, qp, (UChar*)INIT_SAO_UVLC );
+#endif
+#if SAO_MERGE_ONE_CTX
+      curCost += m_cSaoMergeSCModel.calcCost      ( curSliceType, qp, (UChar*)INIT_SAO_MERGE_FLAG );
+#else
+      curCost += m_cSaoMergeLeftSCModel.calcCost      ( curSliceType, qp, (UChar*)INIT_SAO_MERGE_LEFT_FLAG );
+      curCost += m_cSaoMergeUpSCModel.calcCost        ( curSliceType, qp, (UChar*)INIT_SAO_MERGE_UP_FLAG );
+#endif
+      curCost += m_cSaoTypeIdxSCModel.calcCost        ( curSliceType, qp, (UChar*)INIT_SAO_TYPE_IDX );
+      curCost += m_cTransformSkipSCModel.calcCost     ( curSliceType, qp, (UChar*)INIT_TRANSFORMSKIP_FLAG );
+      curCost += m_CUTransquantBypassFlagSCModel.calcCost( curSliceType, qp, (UChar*)INIT_CU_TRANSQUANT_BYPASS_FLAG );
+      if (curCost < bestCost)
+      {
+        bestSliceType = curSliceType;
+        bestCost      = curCost;
+      }
+    }
+    m_pcSlice->getPPS()->setEncCABACTableIdx( bestSliceType );
+  }
+  else
+  {
+    m_pcSlice->getPPS()->setEncCABACTableIdx( I_SLICE );
+  }  
+}
+
+
+/** The function does the followng: Write out terminate bit. Flush CABAC. Intialize CABAC states. Start CABAC.
+ */
+Void TEncSbac::updateContextTables( SliceType eSliceType, Int iQp, Bool bExecuteFinish )
+{
+  m_pcBinIf->encodeBinTrm(1);
+  if (bExecuteFinish) m_pcBinIf->finish();
+  m_cCUSplitFlagSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_SPLIT_FLAG );
+  
+  m_cCUSkipFlagSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_SKIP_FLAG );
+  m_cCUAlfCtrlFlagSCModel.initBuffer     ( eSliceType, iQp, (UChar*)INIT_ALF_CTRL_FLAG );
+  m_cCUMergeFlagExtSCModel.initBuffer    ( eSliceType, iQp, (UChar*)INIT_MERGE_FLAG_EXT);
+  m_cCUMergeIdxExtSCModel.initBuffer     ( eSliceType, iQp, (UChar*)INIT_MERGE_IDX_EXT);
+  m_cCUPartSizeSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_PART_SIZE );
+  m_cCUAMPSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_CU_AMP_POS );
+  m_cCUPredModeSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_PRED_MODE );
+  m_cCUIntraPredSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_INTRA_PRED_MODE );
+  m_cCUChromaPredSCModel.initBuffer      ( eSliceType, iQp, (UChar*)INIT_CHROMA_PRED_MODE );
+  m_cCUInterDirSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_INTER_DIR );
+  m_cCUMvdSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_MVD );
+  m_cCURefPicSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_REF_PIC );
+  m_cCUDeltaQpSCModel.initBuffer         ( eSliceType, iQp, (UChar*)INIT_DQP );
+  m_cCUQtCbfSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_QT_CBF );
+  m_cCUQtRootCbfSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_QT_ROOT_CBF );
+  m_cCUSigCoeffGroupSCModel.initBuffer   ( eSliceType, iQp, (UChar*)INIT_SIG_CG_FLAG );
+  m_cCUSigSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_SIG_FLAG );
+  m_cCuCtxLastX.initBuffer               ( eSliceType, iQp, (UChar*)INIT_LAST );
+  m_cCuCtxLastY.initBuffer               ( eSliceType, iQp, (UChar*)INIT_LAST );
+  m_cCUOneSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_ONE_FLAG );
+  m_cCUAbsSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_ABS_FLAG );
+  m_cMVPIdxSCModel.initBuffer            ( eSliceType, iQp, (UChar*)INIT_MVP_IDX );
+  m_cALFFlagSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_ALF_FLAG );
+  m_cALFUvlcSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_ALF_UVLC );
+  m_cALFSvlcSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_ALF_SVLC );
+  m_cCUTransSubdivFlagSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_TRANS_SUBDIV_FLAG );
+#if !SAO_ABS_BY_PASS
+  m_cSaoUvlcSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_SAO_UVLC );
+#endif
+#if SAO_MERGE_ONE_CTX
+  m_cSaoMergeSCModel.initBuffer      ( eSliceType, iQp, (UChar*)INIT_SAO_MERGE_FLAG );
+#else
+  m_cSaoMergeLeftSCModel.initBuffer      ( eSliceType, iQp, (UChar*)INIT_SAO_MERGE_LEFT_FLAG );
+  m_cSaoMergeUpSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_SAO_MERGE_UP_FLAG );
+#endif
+
+#if INTRA_BL
+  m_cIntraBLPredFlagSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_INTRA_BL_PRED_FLAG );
+#endif  
+  m_cSaoTypeIdxSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_SAO_TYPE_IDX );
+  m_cTransformSkipSCModel.initBuffer     ( eSliceType, iQp, (UChar*)INIT_TRANSFORMSKIP_FLAG );
+  m_CUTransquantBypassFlagSCModel.initBuffer( eSliceType, iQp, (UChar*)INIT_CU_TRANSQUANT_BYPASS_FLAG );
+  m_pcBinIf->start();
+}
+
+Void TEncSbac::codeVPS( TComVPS* pcVPS )
+{
+  assert (0);
+  return;
+}
+
+Void TEncSbac::codeSPS( TComSPS* pcSPS )
+{
+  assert (0);
+  return;
+}
+
+Void TEncSbac::codePPS( TComPPS* pcPPS )
+{
+  assert (0);
+  return;
+}
+
+Void TEncSbac::codeSliceHeader( TComSlice* pcSlice )
+{
+  assert (0);
+  return;
+}
+
+Void TEncSbac::codeTilesWPPEntryPoint( TComSlice* pSlice )
+{
+  assert (0);
+  return;
+}
+
+Void TEncSbac::codeTerminatingBit( UInt uilsLast )
+{
+  m_pcBinIf->encodeBinTrm( uilsLast );
+}
+
+Void TEncSbac::codeSliceFinish()
+{
+  m_pcBinIf->finish();
+}
+
+Void TEncSbac::codeFlush()
+{
+  m_pcBinIf->flush();
+}
+
+Void TEncSbac::encodeStart()
+{
+  m_pcBinIf->start();
+}
+
+Void TEncSbac::xWriteUnarySymbol( UInt uiSymbol, ContextModel* pcSCModel, Int iOffset )
+{
+  m_pcBinIf->encodeBin( uiSymbol ? 1 : 0, pcSCModel[0] );
+  
+  if( 0 == uiSymbol)
+  {
+    return;
+  }
+  
+  while( uiSymbol-- )
+  {
+    m_pcBinIf->encodeBin( uiSymbol ? 1 : 0, pcSCModel[ iOffset ] );
+  }
+  
+  return;
+}
+
+Void TEncSbac::xWriteUnaryMaxSymbol( UInt uiSymbol, ContextModel* pcSCModel, Int iOffset, UInt uiMaxSymbol )
+{
+  if (uiMaxSymbol == 0)
+  {
+    return;
+  }
+  
+  m_pcBinIf->encodeBin( uiSymbol ? 1 : 0, pcSCModel[ 0 ] );
+  
+  if ( uiSymbol == 0 )
+  {
+    return;
+  }
+  
+  Bool bCodeLast = ( uiMaxSymbol > uiSymbol );
+  
+  while( --uiSymbol )
+  {
+    m_pcBinIf->encodeBin( 1, pcSCModel[ iOffset ] );
+  }
+  if( bCodeLast )
+  {
+    m_pcBinIf->encodeBin( 0, pcSCModel[ iOffset ] );
+  }
+  
+  return;
+}
+
+Void TEncSbac::xWriteEpExGolomb( UInt uiSymbol, UInt uiCount )
+{
+  UInt bins = 0;
+  Int numBins = 0;
+  
+  while( uiSymbol >= (UInt)(1<<uiCount) )
+  {
+    bins = 2 * bins + 1;
+    numBins++;
+    uiSymbol -= 1 << uiCount;
+    uiCount  ++;
+  }
+  bins = 2 * bins + 0;
+  numBins++;
+  
+  bins = (bins << uiCount) | uiSymbol;
+  numBins += uiCount;
+  
+  assert( numBins <= 32 );
+  m_pcBinIf->encodeBinsEP( bins, numBins );
+}
+
+/** Coding of coeff_abs_level_minus3
+ * \param uiSymbol value of coeff_abs_level_minus3
+ * \param ruiGoRiceParam reference to Rice parameter
+ * \returns Void
+ */
+Void TEncSbac::xWriteCoefRemainExGolomb ( UInt symbol, UInt &rParam )
+{
+  Int codeNumber  = (Int)symbol;
+  UInt length;
+#if COEF_REMAIN_BIN_REDUCTION
+  if (codeNumber < (COEF_REMAIN_BIN_REDUCTION << rParam))
+#else
+  if (codeNumber < (8 << rParam))
+#endif
+  {
+    length = codeNumber>>rParam;
+    m_pcBinIf->encodeBinsEP( (1<<(length+1))-2 , length+1);
+    m_pcBinIf->encodeBinsEP((codeNumber%(1<<rParam)),rParam);
+  }
+  else
+  {
+    length = rParam;
+#if COEF_REMAIN_BIN_REDUCTION
+    codeNumber  = codeNumber - ( COEF_REMAIN_BIN_REDUCTION << rParam);
+#else
+    codeNumber  = codeNumber - ( 8 << rParam);    
+#endif
+    while (codeNumber >= (1<<length))
+    {
+      codeNumber -=  (1<<(length++));    
+    }
+#if COEF_REMAIN_BIN_REDUCTION
+    m_pcBinIf->encodeBinsEP((1<<(COEF_REMAIN_BIN_REDUCTION+length+1-rParam))-2,COEF_REMAIN_BIN_REDUCTION+length+1-rParam);
+#else
+    m_pcBinIf->encodeBinsEP((1<<(8+length+1-rParam))-2,8+length+1-rParam);
+#endif
+    m_pcBinIf->encodeBinsEP(codeNumber,length);
+  }
+}
+
+// SBAC RD
+Void  TEncSbac::load ( TEncSbac* pSrc)
+{
+  this->xCopyFrom(pSrc);
+}
+
+Void  TEncSbac::loadIntraDirModeLuma( TEncSbac* pSrc)
+{
+  m_pcBinIf->copyState( pSrc->m_pcBinIf );
+  
+  this->m_cCUIntraPredSCModel      .copyFrom( &pSrc->m_cCUIntraPredSCModel       );
+}
+
+
+Void  TEncSbac::store( TEncSbac* pDest)
+{
+  pDest->xCopyFrom( this );
+}
+
+
+Void TEncSbac::xCopyFrom( TEncSbac* pSrc )
+{
+  m_pcBinIf->copyState( pSrc->m_pcBinIf );
+  
+  this->m_uiCoeffCost = pSrc->m_uiCoeffCost;
+  this->m_uiLastQp    = pSrc->m_uiLastQp;
+  
+  memcpy( m_contextModels, pSrc->m_contextModels, m_numContextModels * sizeof( ContextModel ) );
+}
+
+Void TEncSbac::codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
+{
+  Int iSymbol = pcCU->getMVPIdx(eRefList, uiAbsPartIdx);
+  Int iNum = AMVP_MAX_NUM_CANDS;
+
+  xWriteUnaryMaxSymbol(iSymbol, m_cMVPIdxSCModel.get(0), 1, iNum-1);
+}
+
+Void TEncSbac::codePartSize( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  PartSize eSize         = pcCU->getPartitionSize( uiAbsPartIdx );
+#if INTRA_BL
+  assert( !pcCU->isIntraBL( uiAbsPartIdx ) );
+#endif
+
+  if ( pcCU->isIntra( uiAbsPartIdx ) )
+  {
+    if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+    {
+      m_pcBinIf->encodeBin( eSize == SIZE_2Nx2N? 1 : 0, m_cCUPartSizeSCModel.get( 0, 0, 0 ) );
+    }
+    return;
+  }
+  
+  switch(eSize)
+  {
+    case SIZE_2Nx2N:
+    {
+      m_pcBinIf->encodeBin( 1, m_cCUPartSizeSCModel.get( 0, 0, 0) );
+      break;
+    }
+    case SIZE_2NxN:
+    case SIZE_2NxnU:
+    case SIZE_2NxnD:
+    {
+      m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 0) );
+      m_pcBinIf->encodeBin( 1, m_cCUPartSizeSCModel.get( 0, 0, 1) );
+      if ( pcCU->getSlice()->getSPS()->getAMPAcc( uiDepth ) )
+      {
+        if (eSize == SIZE_2NxN)
+        {
+          m_pcBinIf->encodeBin(1, m_cCUAMPSCModel.get( 0, 0, 0 ));
+        }
+        else
+        {
+          m_pcBinIf->encodeBin(0, m_cCUAMPSCModel.get( 0, 0, 0 ));          
+          m_pcBinIf->encodeBinEP((eSize == SIZE_2NxnU? 0: 1));
+        }
+      }
+      break;
+    }
+    case SIZE_Nx2N:
+    case SIZE_nLx2N:
+    case SIZE_nRx2N:
+    {
+      m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 0) );
+      m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 1) );
+      if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth && !( pcCU->getWidth(uiAbsPartIdx) == 8 && pcCU->getHeight(uiAbsPartIdx) == 8 ) )
+      {
+        m_pcBinIf->encodeBin( 1, m_cCUPartSizeSCModel.get( 0, 0, 2) );
+      }
+      if ( pcCU->getSlice()->getSPS()->getAMPAcc( uiDepth ) )
+      {
+        if (eSize == SIZE_Nx2N)
+        {
+          m_pcBinIf->encodeBin(1, m_cCUAMPSCModel.get( 0, 0, 0 ));
+        }
+        else
+        {
+          m_pcBinIf->encodeBin(0, m_cCUAMPSCModel.get( 0, 0, 0 ));
+          m_pcBinIf->encodeBinEP((eSize == SIZE_nLx2N? 0: 1));
+        }
+      }
+      break;
+    }
+    case SIZE_NxN:
+    {
+      if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth && !( pcCU->getWidth(uiAbsPartIdx) == 8 && pcCU->getHeight(uiAbsPartIdx) == 8 ) )
+      {
+        m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 0) );
+        m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 1) );
+        m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 2) );
+      }
+      break;
+    }
+    default:
+    {
+      assert(0);
+    }
+  }
+}
+
+/** code prediction mode
+ * \param pcCU
+ * \param uiAbsPartIdx  
+ * \returns Void
+ */
+Void TEncSbac::codePredMode( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  // get context function is here
+  Int iPredMode = pcCU->getPredictionMode( uiAbsPartIdx );
+  m_pcBinIf->encodeBin( iPredMode == MODE_INTER ? 0 : 1, m_cCUPredModeSCModel.get( 0, 0, 0 ) );
+}
+
+Void TEncSbac::codeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  UInt uiSymbol = pcCU->getCUTransquantBypass(uiAbsPartIdx);
+  m_pcBinIf->encodeBin( uiSymbol, m_CUTransquantBypassFlagSCModel.get( 0, 0, 0 ) );
+}
+
+/** code skip flag
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \returns Void
+ */
+Void TEncSbac::codeSkipFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  // get context function is here
+  UInt uiSymbol = pcCU->isSkipped( uiAbsPartIdx ) ? 1 : 0;
+  UInt uiCtxSkip = pcCU->getCtxSkipFlag( uiAbsPartIdx ) ;
+  m_pcBinIf->encodeBin( uiSymbol, m_cCUSkipFlagSCModel.get( 0, 0, uiCtxSkip ) );
+  DTRACE_CABAC_VL( g_nSymbolCounter++ );
+  DTRACE_CABAC_T( "\tSkipFlag" );
+  DTRACE_CABAC_T( "\tuiCtxSkip: ");
+  DTRACE_CABAC_V( uiCtxSkip );
+  DTRACE_CABAC_T( "\tuiSymbol: ");
+  DTRACE_CABAC_V( uiSymbol );
+  DTRACE_CABAC_T( "\n");
+}
+
+#if INTRA_BL
+/** code intra_bl flag
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \returns Void
+ */
+Void TEncSbac::codeIntraBLFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  // get context function is here
+  UInt uiSymbol = pcCU->isIntraBL( uiAbsPartIdx ) ? 1 : 0;
+
+  UInt uiCtxIntraBL = pcCU->getCtxIntraBLFlag( uiAbsPartIdx ) ;
+  m_pcBinIf->encodeBin(uiSymbol, m_cIntraBLPredFlagSCModel.get( 0, 0, uiCtxIntraBL )); 
+
+  DTRACE_CABAC_VL( g_nSymbolCounter++ );
+  DTRACE_CABAC_T( "\tuiSymbol: ");
+  DTRACE_CABAC_V( uiSymbol );
+  DTRACE_CABAC_T( "\n");
+}
+#endif
+
+/** code merge flag
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \returns Void
+ */
+Void TEncSbac::codeMergeFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  const UInt uiSymbol = pcCU->getMergeFlag( uiAbsPartIdx ) ? 1 : 0;
+  m_pcBinIf->encodeBin( uiSymbol, *m_cCUMergeFlagExtSCModel.get( 0 ) );
+
+  DTRACE_CABAC_VL( g_nSymbolCounter++ );
+  DTRACE_CABAC_T( "\tMergeFlag: " );
+  DTRACE_CABAC_V( uiSymbol );
+  DTRACE_CABAC_T( "\tAddress: " );
+  DTRACE_CABAC_V( pcCU->getAddr() );
+  DTRACE_CABAC_T( "\tuiAbsPartIdx: " );
+  DTRACE_CABAC_V( uiAbsPartIdx );
+  DTRACE_CABAC_T( "\n" );
+}
+
+/** code merge index
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \returns Void
+ */
+Void TEncSbac::codeMergeIndex( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  UInt uiUnaryIdx = pcCU->getMergeIndex( uiAbsPartIdx );
+  UInt uiNumCand = pcCU->getSlice()->getMaxNumMergeCand();
+  if ( uiNumCand > 1 )
+  {
+    for( UInt ui = 0; ui < uiNumCand - 1; ++ui )
+    {
+      const UInt uiSymbol = ui == uiUnaryIdx ? 0 : 1;
+      if ( ui==0 )
+      {
+        m_pcBinIf->encodeBin( uiSymbol, m_cCUMergeIdxExtSCModel.get( 0, 0, 0 ) );
+      }
+      else
+      {
+        m_pcBinIf->encodeBinEP( uiSymbol );
+      }
+      if( uiSymbol == 0 )
+      {
+        break;
+      }
+    }
+  }
+  DTRACE_CABAC_VL( g_nSymbolCounter++ );
+  DTRACE_CABAC_T( "\tparseMergeIndex()" );
+  DTRACE_CABAC_T( "\tuiMRGIdx= " );
+  DTRACE_CABAC_V( pcCU->getMergeIndex( uiAbsPartIdx ) );
+  DTRACE_CABAC_T( "\n" );
+}
+
+Void TEncSbac::codeSplitFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+    return;
+  
+  UInt uiCtx           = pcCU->getCtxSplitFlag( uiAbsPartIdx, uiDepth );
+  UInt uiCurrSplitFlag = ( pcCU->getDepth( uiAbsPartIdx ) > uiDepth ) ? 1 : 0;
+  
+  assert( uiCtx < 3 );
+  m_pcBinIf->encodeBin( uiCurrSplitFlag, m_cCUSplitFlagSCModel.get( 0, 0, uiCtx ) );
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tSplitFlag\n" )
+  return;
+}
+
+Void TEncSbac::codeTransformSubdivFlag( UInt uiSymbol, UInt uiCtx )
+{
+  m_pcBinIf->encodeBin( uiSymbol, m_cCUTransSubdivFlagSCModel.get( 0, 0, uiCtx ) );
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tparseTransformSubdivFlag()" )
+  DTRACE_CABAC_T( "\tsymbol=" )
+  DTRACE_CABAC_V( uiSymbol )
+  DTRACE_CABAC_T( "\tctx=" )
+  DTRACE_CABAC_V( uiCtx )
+  DTRACE_CABAC_T( "\n" )
+}
+
+Void TEncSbac::codeIntraDirLumaAng( TComDataCU* pcCU, UInt absPartIdx, Bool isMultiple)
+{
+  UInt dir[4],j;
+  Int preds[4][3] = {{-1, -1, -1},{-1, -1, -1},{-1, -1, -1},{-1, -1, -1}};
+  Int predNum[4], predIdx[4] ={ -1,-1,-1,-1};
+  PartSize mode = pcCU->getPartitionSize( absPartIdx );
+  UInt partNum = isMultiple?(mode==SIZE_NxN?4:1):1;
+  UInt partOffset = ( pcCU->getPic()->getNumPartInCU() >> ( pcCU->getDepth(absPartIdx) << 1 ) ) >> 2;
+  for (j=0;j<partNum;j++)
+  {
+    dir[j] = pcCU->getLumaIntraDir( absPartIdx+partOffset*j );
+    predNum[j] = pcCU->getIntraDirLumaPredictor(absPartIdx+partOffset*j, preds[j]);  
+    for(UInt i = 0; i < predNum[j]; i++)
+    {
+      if(dir[j] == preds[j][i])
+      {
+        predIdx[j] = i;
+      }
+    }
+    m_pcBinIf->encodeBin((predIdx[j] != -1)? 1 : 0, m_cCUIntraPredSCModel.get( 0, 0, 0 ) );
+  }  
+  for (j=0;j<partNum;j++)
+  {
+    if(predIdx[j] != -1)
+    {
+      m_pcBinIf->encodeBinEP( predIdx[j] ? 1 : 0 );
+      if (predIdx[j])
+      {
+        m_pcBinIf->encodeBinEP( predIdx[j]-1 );
+      }
+    }
+    else
+    {
+      if (preds[j][0] > preds[j][1])
+      { 
+        std::swap(preds[j][0], preds[j][1]); 
+      }
+      if (preds[j][0] > preds[j][2])
+      {
+        std::swap(preds[j][0], preds[j][2]);
+      }
+      if (preds[j][1] > preds[j][2])
+      {
+        std::swap(preds[j][1], preds[j][2]);
+      }
+      for(Int i = (predNum[j] - 1); i >= 0; i--)
+      {
+        dir[j] = dir[j] > preds[j][i] ? dir[j] - 1 : dir[j];
+      }
+      m_pcBinIf->encodeBinsEP( dir[j], 5 );
+    }
+  }
+  return;
+}
+
+Void TEncSbac::codeIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  UInt uiIntraDirChroma = pcCU->getChromaIntraDir( uiAbsPartIdx );
+
+  if( uiIntraDirChroma == DM_CHROMA_IDX ) 
+  {
+    m_pcBinIf->encodeBin( 0, m_cCUChromaPredSCModel.get( 0, 0, 0 ) );
+  }
+#if !REMOVE_LMCHROMA
+  else if( uiIntraDirChroma == LM_CHROMA_IDX )
+  {
+    m_pcBinIf->encodeBin( 1, m_cCUChromaPredSCModel.get( 0, 0, 0 ) );
+    m_pcBinIf->encodeBin( 0, m_cCUChromaPredSCModel.get( 0, 0, 1 ) );
+  }
+#endif
+  else
+  { 
+    UInt uiAllowedChromaDir[ NUM_CHROMA_MODE ];
+    pcCU->getAllowedChromaDir( uiAbsPartIdx, uiAllowedChromaDir );
+
+#if REMOVE_LMCHROMA
+    for( Int i = 0; i < NUM_CHROMA_MODE - 1; i++ )
+#else
+    for( Int i = 0; i < NUM_CHROMA_MODE - 2; i++ )
+#endif
+    {
+      if( uiIntraDirChroma == uiAllowedChromaDir[i] )
+      {
+        uiIntraDirChroma = i;
+        break;
+      }
+    }
+    m_pcBinIf->encodeBin( 1, m_cCUChromaPredSCModel.get( 0, 0, 0 ) );
+
+#if !REMOVE_LMCHROMA
+    if (pcCU->getSlice()->getSPS()->getUseLMChroma())
+    {
+      m_pcBinIf->encodeBin( 1, m_cCUChromaPredSCModel.get( 0, 0, 1 ));
+    }
+#endif
+    m_pcBinIf->encodeBinsEP( uiIntraDirChroma, 2 );
+  }
+  return;
+}
+
+Void TEncSbac::codeInterDir( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  const UInt uiInterDir = pcCU->getInterDir( uiAbsPartIdx ) - 1;
+  const UInt uiCtx      = pcCU->getCtxInterDir( uiAbsPartIdx );
+  ContextModel *pCtx    = m_cCUInterDirSCModel.get( 0 );
+#if DISALLOW_BIPRED_IN_8x4_4x8PUS
+  if (pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_2Nx2N || pcCU->getHeight(uiAbsPartIdx) != 8 )
+  {
+#endif
+    m_pcBinIf->encodeBin( uiInterDir == 2 ? 1 : 0, *( pCtx + uiCtx ) );
+#if DISALLOW_BIPRED_IN_8x4_4x8PUS
+  }
+#endif
+  if (uiInterDir < 2)
+  {
+    m_pcBinIf->encodeBin( uiInterDir, *( pCtx + 4 ) );
+  }
+  return;
+}
+
+Void TEncSbac::codeRefFrmIdx( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
+{
+  {
+    Int iRefFrame = pcCU->getCUMvField( eRefList )->getRefIdx( uiAbsPartIdx );
+    ContextModel *pCtx = m_cCURefPicSCModel.get( 0 );
+    m_pcBinIf->encodeBin( ( iRefFrame == 0 ? 0 : 1 ), *pCtx );
+    
+    if( iRefFrame > 0 )
+    {
+#if REF_IDX_BYPASS
+      UInt uiRefNum = pcCU->getSlice()->getNumRefIdx( eRefList ) - 2;
+      pCtx++;
+      iRefFrame--;
+      for( UInt ui = 0; ui < uiRefNum; ++ui )
+      {
+        const UInt uiSymbol = ui == iRefFrame ? 0 : 1;
+        if( ui == 0 )
+        {
+          m_pcBinIf->encodeBin( uiSymbol, *pCtx );       
+        }
+        else
+        {
+          m_pcBinIf->encodeBinEP( uiSymbol );
+        }
+        if( uiSymbol == 0 )
+        {
+          break;
+        }
+      }
+#else
+      xWriteUnaryMaxSymbol( iRefFrame - 1, pCtx + 1, 1, pcCU->getSlice()->getNumRefIdx( eRefList )-2 );
+#endif
+    }
+  }
+  return;
+}
+
+Void TEncSbac::codeMvd( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
+{
+  if(pcCU->getSlice()->getMvdL1ZeroFlag() && eRefList == REF_PIC_LIST_1 && pcCU->getInterDir(uiAbsPartIdx)==3)
+  {
+    return;
+  }
+
+  const TComCUMvField* pcCUMvField = pcCU->getCUMvField( eRefList );
+  const Int iHor = pcCUMvField->getMvd( uiAbsPartIdx ).getHor();
+  const Int iVer = pcCUMvField->getMvd( uiAbsPartIdx ).getVer();
+  ContextModel* pCtx = m_cCUMvdSCModel.get( 0 );
+
+  m_pcBinIf->encodeBin( iHor != 0 ? 1 : 0, *pCtx );
+  m_pcBinIf->encodeBin( iVer != 0 ? 1 : 0, *pCtx );
+
+  const Bool bHorAbsGr0 = iHor != 0;
+  const Bool bVerAbsGr0 = iVer != 0;
+  const UInt uiHorAbs   = 0 > iHor ? -iHor : iHor;
+  const UInt uiVerAbs   = 0 > iVer ? -iVer : iVer;
+  pCtx++;
+
+  if( bHorAbsGr0 )
+  {
+    m_pcBinIf->encodeBin( uiHorAbs > 1 ? 1 : 0, *pCtx );
+  }
+
+  if( bVerAbsGr0 )
+  {
+    m_pcBinIf->encodeBin( uiVerAbs > 1 ? 1 : 0, *pCtx );
+  }
+
+  if( bHorAbsGr0 )
+  {
+    if( uiHorAbs > 1 )
+    {
+      xWriteEpExGolomb( uiHorAbs-2, 1 );
+    }
+
+    m_pcBinIf->encodeBinEP( 0 > iHor ? 1 : 0 );
+  }
+
+  if( bVerAbsGr0 )
+  {
+    if( uiVerAbs > 1 )
+    {
+      xWriteEpExGolomb( uiVerAbs-2, 1 );
+    }
+
+    m_pcBinIf->encodeBinEP( 0 > iVer ? 1 : 0 );
+  }
+  
+  return;
+}
+
+Void TEncSbac::codeDeltaQP( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  Int iDQp  = pcCU->getQP( uiAbsPartIdx ) - pcCU->getRefQP( uiAbsPartIdx );
+  
+  Int qpBdOffsetY =  pcCU->getSlice()->getSPS()->getQpBDOffsetY();
+  iDQp = (iDQp + 78 + qpBdOffsetY + (qpBdOffsetY/2)) % (52 + qpBdOffsetY) - 26 - (qpBdOffsetY/2);
+
+#if CU_DQP_TU_EG
+  UInt uiAbsDQp = (UInt)((iDQp > 0)? iDQp  : (-iDQp));
+  UInt TUValue = min((Int)uiAbsDQp, CU_DQP_TU_CMAX);
+  xWriteUnaryMaxSymbol( TUValue, &m_cCUDeltaQpSCModel.get( 0, 0, 0 ), 1, CU_DQP_TU_CMAX);
+  if( uiAbsDQp >= CU_DQP_TU_CMAX )
+  {
+    xWriteEpExGolomb( uiAbsDQp - CU_DQP_TU_CMAX, CU_DQP_EG_k );
+  }
+
+  if ( uiAbsDQp > 0)
+  {
+    UInt uiSign = (iDQp > 0 ? 0 : 1);
+    m_pcBinIf->encodeBinEP(uiSign);
+  }
+#else
+  if ( iDQp == 0 )
+  {
+    m_pcBinIf->encodeBin( 0, m_cCUDeltaQpSCModel.get( 0, 0, 0 ) );
+  }
+  else
+  {
+    m_pcBinIf->encodeBin( 1, m_cCUDeltaQpSCModel.get( 0, 0, 0 ) );
+   
+    UInt uiSign = (iDQp > 0 ? 0 : 1);
+
+    m_pcBinIf->encodeBinEP(uiSign);
+
+    assert(iDQp >= -(26+(qpBdOffsetY/2)));
+    assert(iDQp <=  (25+(qpBdOffsetY/2)));
+
+    UInt uiMaxAbsDQpMinus1 = 24 + (qpBdOffsetY/2) + (uiSign);
+    UInt uiAbsDQpMinus1 = (UInt)((iDQp > 0)? iDQp  : (-iDQp)) - 1;
+    xWriteUnaryMaxSymbol( uiAbsDQpMinus1, &m_cCUDeltaQpSCModel.get( 0, 0, 1 ), 1, uiMaxAbsDQpMinus1);
+  }
+#endif
+
+  return;
+}
+
+Void TEncSbac::codeQtCbf( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth )
+{
+  UInt uiCbf = pcCU->getCbf     ( uiAbsPartIdx, eType, uiTrDepth );
+  UInt uiCtx = pcCU->getCtxQtCbf( uiAbsPartIdx, eType, uiTrDepth );
+  m_pcBinIf->encodeBin( uiCbf , m_cCUQtCbfSCModel.get( 0, eType ? TEXT_CHROMA : eType, uiCtx ) );
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tparseQtCbf()" )
+  DTRACE_CABAC_T( "\tsymbol=" )
+  DTRACE_CABAC_V( uiCbf )
+  DTRACE_CABAC_T( "\tctx=" )
+  DTRACE_CABAC_V( uiCtx )
+  DTRACE_CABAC_T( "\tetype=" )
+  DTRACE_CABAC_V( eType )
+  DTRACE_CABAC_T( "\tuiAbsPartIdx=" )
+  DTRACE_CABAC_V( uiAbsPartIdx )
+  DTRACE_CABAC_T( "\n" )
+}
+
+void TEncSbac::codeTransformSkipFlags (TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, UInt uiDepth, TextType eTType )
+{
+  if (pcCU->getCUTransquantBypass(uiAbsPartIdx))
+  {
+    return;
+  }
+#if !INTER_TRANSFORMSKIP
+  if(!pcCU->isIntra(uiAbsPartIdx))
+  {
+    return;
+  }
+#endif
+  if(width != 4 || height != 4)
+  {
+    return;
+  }
+
+  UInt useTransformSkip = pcCU->getTransformSkip( uiAbsPartIdx,eTType);
+  m_pcBinIf->encodeBin( useTransformSkip, m_cTransformSkipSCModel.get( 0, eTType? TEXT_CHROMA: TEXT_LUMA, 0 ) );
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T("\tparseTransformSkip()");
+  DTRACE_CABAC_T( "\tsymbol=" )
+  DTRACE_CABAC_V( useTransformSkip )
+  DTRACE_CABAC_T( "\tAddr=" )
+  DTRACE_CABAC_V( pcCU->getAddr() )
+  DTRACE_CABAC_T( "\tetype=" )
+  DTRACE_CABAC_V( eTType )
+  DTRACE_CABAC_T( "\tuiAbsPartIdx=" )
+  DTRACE_CABAC_V( uiAbsPartIdx )
+  DTRACE_CABAC_T( "\n" )
+}
+
+/** Code I_PCM information. 
+ * \param pcCU pointer to CU
+ * \param uiAbsPartIdx CU index
+ * \param numIPCM the number of succesive IPCM blocks with the same size 
+ * \param firstIPCMFlag 
+ * \returns Void
+ */
+Void TEncSbac::codeIPCMInfo( TComDataCU* pcCU, UInt uiAbsPartIdx, Int numIPCM, Bool firstIPCMFlag)
+{
+  UInt uiIPCM = (pcCU->getIPCMFlag(uiAbsPartIdx) == true)? 1 : 0;
+
+  Bool writePCMSampleFlag = pcCU->getIPCMFlag(uiAbsPartIdx);
+
+  if( uiIPCM == 0 || firstIPCMFlag)
+  {
+    m_pcBinIf->encodeBinTrm (uiIPCM);
+
+    if ( firstIPCMFlag )
+    {
+      m_pcBinIf->encodeNumSubseqIPCM( numIPCM - 1 );
+      m_pcBinIf->encodePCMAlignBits();
+    }
+  }
+
+  if (writePCMSampleFlag)
+  {
+    UInt uiMinCoeffSize = pcCU->getPic()->getMinCUWidth()*pcCU->getPic()->getMinCUHeight();
+    UInt uiLumaOffset   = uiMinCoeffSize*uiAbsPartIdx;
+    UInt uiChromaOffset = uiLumaOffset>>2;
+    Pel* piPCMSample;
+    UInt uiWidth;
+    UInt uiHeight;
+    UInt uiSampleBits;
+    UInt uiX, uiY;
+
+    piPCMSample = pcCU->getPCMSampleY() + uiLumaOffset;
+    uiWidth = pcCU->getWidth(uiAbsPartIdx);
+    uiHeight = pcCU->getHeight(uiAbsPartIdx);
+    uiSampleBits = pcCU->getSlice()->getSPS()->getPCMBitDepthLuma();
+
+    for(uiY = 0; uiY < uiHeight; uiY++)
+    {
+      for(uiX = 0; uiX < uiWidth; uiX++)
+      {
+        UInt uiSample = piPCMSample[uiX];
+
+        m_pcBinIf->xWritePCMCode(uiSample, uiSampleBits);
+      }
+      piPCMSample += uiWidth;
+    }
+
+    piPCMSample = pcCU->getPCMSampleCb() + uiChromaOffset;
+    uiWidth = pcCU->getWidth(uiAbsPartIdx)/2;
+    uiHeight = pcCU->getHeight(uiAbsPartIdx)/2;
+    uiSampleBits = pcCU->getSlice()->getSPS()->getPCMBitDepthChroma();
+
+    for(uiY = 0; uiY < uiHeight; uiY++)
+    {
+      for(uiX = 0; uiX < uiWidth; uiX++)
+      {
+        UInt uiSample = piPCMSample[uiX];
+
+        m_pcBinIf->xWritePCMCode(uiSample, uiSampleBits);
+      }
+      piPCMSample += uiWidth;
+    }
+
+    piPCMSample = pcCU->getPCMSampleCr() + uiChromaOffset;
+    uiWidth = pcCU->getWidth(uiAbsPartIdx)/2;
+    uiHeight = pcCU->getHeight(uiAbsPartIdx)/2;
+    uiSampleBits = pcCU->getSlice()->getSPS()->getPCMBitDepthChroma();
+
+    for(uiY = 0; uiY < uiHeight; uiY++)
+    {
+      for(uiX = 0; uiX < uiWidth; uiX++)
+      {
+        UInt uiSample = piPCMSample[uiX];
+
+        m_pcBinIf->xWritePCMCode(uiSample, uiSampleBits);
+      }
+      piPCMSample += uiWidth;
+    }
+    numIPCM--;
+    if(numIPCM == 0)
+    {
+      m_pcBinIf->resetBac();
+    }
+  }
+}
+
+Void TEncSbac::codeQtRootCbf( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  UInt uiCbf = pcCU->getQtRootCbf( uiAbsPartIdx );
+  UInt uiCtx = 0;
+  m_pcBinIf->encodeBin( uiCbf , m_cCUQtRootCbfSCModel.get( 0, 0, uiCtx ) );
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tparseQtRootCbf()" )
+  DTRACE_CABAC_T( "\tsymbol=" )
+  DTRACE_CABAC_V( uiCbf )
+  DTRACE_CABAC_T( "\tctx=" )
+  DTRACE_CABAC_V( uiCtx )
+  DTRACE_CABAC_T( "\tuiAbsPartIdx=" )
+  DTRACE_CABAC_V( uiAbsPartIdx )
+  DTRACE_CABAC_T( "\n" )
+}
+
+#if TU_ZERO_CBF_RDO
+Void TEncSbac::codeQtCbfZero( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth )
+{
+  // this function is only used to estimate the bits when cbf is 0
+  // and will never be called when writing the bistream. do not need to write log
+  UInt uiCbf = 0;
+  UInt uiCtx = pcCU->getCtxQtCbf( uiAbsPartIdx, eType, uiTrDepth );
+  m_pcBinIf->encodeBin( uiCbf , m_cCUQtCbfSCModel.get( 0, eType ? TEXT_CHROMA : eType, uiCtx ) );
+}
+
+Void TEncSbac::codeQtRootCbfZero( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  // this function is only used to estimate the bits when cbf is 0
+  // and will never be called when writing the bistream. do not need to write log
+  UInt uiCbf = 0;
+  UInt uiCtx = 0;
+  m_pcBinIf->encodeBin( uiCbf , m_cCUQtRootCbfSCModel.get( 0, 0, uiCtx ) );
+}
+#endif
+
+/** Encode (X,Y) position of the last significant coefficient
+ * \param uiPosX X component of last coefficient
+ * \param uiPosY Y component of last coefficient
+ * \param width  Block width
+ * \param height Block height
+ * \param eTType plane type / luminance or chrominance
+ * \param uiScanIdx scan type (zig-zag, hor, ver)
+ * This method encodes the X and Y component within a block of the last significant coefficient.
+ */
+Void TEncSbac::codeLastSignificantXY( UInt uiPosX, UInt uiPosY, Int width, Int height, TextType eTType, UInt uiScanIdx )
+{  
+  // swap
+  if( uiScanIdx == SCAN_VER )
+  {
+    swap( uiPosX, uiPosY );
+  }
+
+  UInt uiCtxLast;
+  ContextModel *pCtxX = m_cCuCtxLastX.get( 0, eTType );
+  ContextModel *pCtxY = m_cCuCtxLastY.get( 0, eTType );
+  UInt uiGroupIdxX    = g_uiGroupIdx[ uiPosX ];
+  UInt uiGroupIdxY    = g_uiGroupIdx[ uiPosY ];
+
+
+  Int blkSizeOffsetX, blkSizeOffsetY, shiftX, shiftY;
+  blkSizeOffsetX = eTType ? 0: (g_aucConvertToBit[ width ] *3 + ((g_aucConvertToBit[ width ] +1)>>2));
+  blkSizeOffsetY = eTType ? 0: (g_aucConvertToBit[ height ]*3 + ((g_aucConvertToBit[ height ]+1)>>2));
+  shiftX= eTType ? g_aucConvertToBit[ width  ] :((g_aucConvertToBit[ width  ]+3)>>2);
+  shiftY= eTType ? g_aucConvertToBit[ height ] :((g_aucConvertToBit[ height ]+3)>>2);
+  // posX
+  for( uiCtxLast = 0; uiCtxLast < uiGroupIdxX; uiCtxLast++ )
+  {
+      m_pcBinIf->encodeBin( 1, *( pCtxX + blkSizeOffsetX + (uiCtxLast >>shiftX) ) );
+  }
+  if( uiGroupIdxX < g_uiGroupIdx[ width - 1 ])
+  {
+      m_pcBinIf->encodeBin( 0, *( pCtxX + blkSizeOffsetX + (uiCtxLast >>shiftX) ) );
+  }
+
+  // posY
+  for( uiCtxLast = 0; uiCtxLast < uiGroupIdxY; uiCtxLast++ )
+  {
+    m_pcBinIf->encodeBin( 1, *( pCtxY + blkSizeOffsetY + (uiCtxLast >>shiftY) ) );
+  }
+  if( uiGroupIdxY < g_uiGroupIdx[ height - 1 ])
+  {
+    m_pcBinIf->encodeBin( 0, *( pCtxY + blkSizeOffsetY + (uiCtxLast >>shiftY) ) );
+  }
+  if ( uiGroupIdxX > 3 )
+  {      
+    UInt uiCount = ( uiGroupIdxX - 2 ) >> 1;
+    uiPosX       = uiPosX - g_uiMinInGroup[ uiGroupIdxX ];
+    for (Int i = uiCount - 1 ; i >= 0; i-- )
+    {
+      m_pcBinIf->encodeBinEP( ( uiPosX >> i ) & 1 );
+    }
+  }
+  if ( uiGroupIdxY > 3 )
+  {      
+    UInt uiCount = ( uiGroupIdxY - 2 ) >> 1;
+    uiPosY       = uiPosY - g_uiMinInGroup[ uiGroupIdxY ];
+    for ( Int i = uiCount - 1 ; i >= 0; i-- )
+    {
+      m_pcBinIf->encodeBinEP( ( uiPosY >> i ) & 1 );
+    }
+  }
+}
+
+Void TEncSbac::codeCoeffNxN( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType )
+{
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tparseCoeffNxN()\teType=" )
+  DTRACE_CABAC_V( eTType )
+  DTRACE_CABAC_T( "\twidth=" )
+  DTRACE_CABAC_V( uiWidth )
+  DTRACE_CABAC_T( "\theight=" )
+  DTRACE_CABAC_V( uiHeight )
+  DTRACE_CABAC_T( "\tdepth=" )
+  DTRACE_CABAC_V( uiDepth )
+  DTRACE_CABAC_T( "\tabspartidx=" )
+  DTRACE_CABAC_V( uiAbsPartIdx )
+  DTRACE_CABAC_T( "\ttoCU-X=" )
+  DTRACE_CABAC_V( pcCU->getCUPelX() )
+  DTRACE_CABAC_T( "\ttoCU-Y=" )
+  DTRACE_CABAC_V( pcCU->getCUPelY() )
+  DTRACE_CABAC_T( "\tCU-addr=" )
+  DTRACE_CABAC_V(  pcCU->getAddr() )
+  DTRACE_CABAC_T( "\tinCU-X=" )
+  DTRACE_CABAC_V( g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ] )
+  DTRACE_CABAC_T( "\tinCU-Y=" )
+  DTRACE_CABAC_V( g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ] )
+  DTRACE_CABAC_T( "\tpredmode=" )
+  DTRACE_CABAC_V(  pcCU->getPredictionMode( uiAbsPartIdx ) )
+  DTRACE_CABAC_T( "\n" )
+
+  if( uiWidth > m_pcSlice->getSPS()->getMaxTrSize() )
+  {
+    uiWidth  = m_pcSlice->getSPS()->getMaxTrSize();
+    uiHeight = m_pcSlice->getSPS()->getMaxTrSize();
+  }
+  
+  UInt uiNumSig = 0;
+  
+  // compute number of significant coefficients
+  uiNumSig = TEncEntropy::countNonZeroCoeffs(pcCoef, uiWidth * uiHeight);
+  
+  if ( uiNumSig == 0 )
+    return;
+#if PPS_TS_FLAG
+  if(pcCU->getSlice()->getPPS()->getUseTransformSkip())
+#else
+  if(pcCU->getSlice()->getSPS()->getUseTransformSkip())
+#endif
+  {
+    codeTransformSkipFlags( pcCU,uiAbsPartIdx, uiWidth, uiHeight, uiDepth, eTType );
+  }
+  eTType = eTType == TEXT_LUMA ? TEXT_LUMA : ( eTType == TEXT_NONE ? TEXT_NONE : TEXT_CHROMA );
+  
+  //----- encode significance map -----
+  const UInt   uiLog2BlockSize   = g_aucConvertToBit[ uiWidth ] + 2;
+  UInt uiScanIdx = pcCU->getCoefScanIdx(uiAbsPartIdx, uiWidth, eTType==TEXT_LUMA, pcCU->isIntra(uiAbsPartIdx));
+  if (uiScanIdx == SCAN_ZIGZAG)
+  {
+    // Map zigzag to diagonal scan
+    uiScanIdx = SCAN_DIAG;
+  }
+  Int blockType = uiLog2BlockSize;
+  if (uiWidth != uiHeight)
+  {
+    uiScanIdx = SCAN_DIAG;
+    blockType = 4;
+  }
+  
+#if REMOVE_NSQT
+  const UInt *scan = g_auiSigLastScan[ uiScanIdx ][ uiLog2BlockSize - 1 ];
+#else
+  const UInt * scan;
+  if (uiWidth == uiHeight)
+  {
+    scan = g_auiSigLastScan[ uiScanIdx ][ uiLog2BlockSize - 1 ];
+  }
+  else
+  {
+    scan = g_sigScanNSQT[ uiLog2BlockSize - 2 ];
+  }
+#endif
+  
+  Bool beValid;
+  if (pcCU->getCUTransquantBypass(uiAbsPartIdx))
+  {
+    beValid = false;
+  }
+  else 
+  {
+    beValid = pcCU->getSlice()->getPPS()->getSignHideFlag() > 0;
+  }
+
+  // Find position of last coefficient
+  Int scanPosLast = -1;
+  Int posLast;
+
+  const UInt * scanCG;
+#if !REMOVE_NSQT
+  if (uiWidth == uiHeight)
+#endif
+  {
+    scanCG = g_auiSigLastScan[ uiScanIdx ][ uiLog2BlockSize > 3 ? uiLog2BlockSize-2-1 : 0 ];
+    if( uiLog2BlockSize == 3 )
+    {
+      scanCG = g_sigLastScan8x8[ uiScanIdx ];
+    }
+    else if( uiLog2BlockSize == 5 )
+    {
+      scanCG = g_sigLastScanCG32x32;
+    }
+  }
+#if !REMOVE_NSQT
+  else
+  {
+    scanCG = g_sigCGScanNSQT[ uiLog2BlockSize - 2 ];
+  }
+#endif
+  UInt uiSigCoeffGroupFlag[ MLS_GRP_NUM ];
+  static const UInt uiShift = MLS_CG_SIZE >> 1;
+  const UInt uiNumBlkSide = uiWidth >> uiShift;
+
+    ::memset( uiSigCoeffGroupFlag, 0, sizeof(UInt) * MLS_GRP_NUM );
+
+    do
+    {
+      posLast = scan[ ++scanPosLast ];
+
+      // get L1 sig map
+      UInt uiPosY    = posLast >> uiLog2BlockSize;
+      UInt uiPosX    = posLast - ( uiPosY << uiLog2BlockSize );
+      UInt uiBlkIdx  = uiNumBlkSide * (uiPosY >> uiShift) + (uiPosX >> uiShift);
+#if !REMOVAL_8x2_2x8_CG
+      if( uiWidth == 8 && uiHeight == 8 && (uiScanIdx == SCAN_HOR || uiScanIdx == SCAN_VER) )
+      {
+        if( uiScanIdx == SCAN_HOR )
+        {
+          uiBlkIdx = uiPosY >> 1;
+        }
+        else if( uiScanIdx == SCAN_VER )
+        {
+          uiBlkIdx = uiPosX >> 1;
+        }
+      }
+#endif
+      if( pcCoef[ posLast ] )
+      {
+        uiSigCoeffGroupFlag[ uiBlkIdx ] = 1;
+      }
+
+      uiNumSig -= ( pcCoef[ posLast ] != 0 );
+    }
+    while ( uiNumSig > 0 );
+
+  // Code position of last coefficient
+  Int posLastY = posLast >> uiLog2BlockSize;
+  Int posLastX = posLast - ( posLastY << uiLog2BlockSize );
+  codeLastSignificantXY(posLastX, posLastY, uiWidth, uiHeight, eTType, uiScanIdx);
+  
+  //===== code significance flag =====
+  ContextModel * const baseCoeffGroupCtx = m_cCUSigCoeffGroupSCModel.get( 0, eTType );
+  ContextModel * const baseCtx = (eTType==TEXT_LUMA) ? m_cCUSigSCModel.get( 0, 0 ) : m_cCUSigSCModel.get( 0, 0 ) + NUM_SIG_FLAG_CTX_LUMA;
+
+
+  const Int  iLastScanSet      = scanPosLast >> LOG2_SCAN_SET_SIZE;
+#if REMOVE_NUM_GREATER1
+  UInt c1 = 1;
+#else
+  UInt uiNumOne                = 0;
+#endif
+  UInt uiGoRiceParam           = 0;
+  Int  iScanPosSig             = scanPosLast;
+
+  for( Int iSubSet = iLastScanSet; iSubSet >= 0; iSubSet-- )
+  {
+    Int numNonZero = 0;
+    Int  iSubPos     = iSubSet << LOG2_SCAN_SET_SIZE;
+    uiGoRiceParam    = 0;
+    Int absCoeff[16];
+    UInt coeffSigns = 0;
+
+    Int lastNZPosInCG = -1, firstNZPosInCG = SCAN_SET_SIZE;
+
+    if( iScanPosSig == scanPosLast )
+    {
+      absCoeff[ 0 ] = abs( pcCoef[ posLast ] );
+      coeffSigns    = ( pcCoef[ posLast ] < 0 );
+      numNonZero    = 1;
+      lastNZPosInCG  = iScanPosSig;
+      firstNZPosInCG = iScanPosSig;
+      iScanPosSig--;
+    }
+
+      // encode significant_coeffgroup_flag
+      Int iCGBlkPos = scanCG[ iSubSet ];
+      Int iCGPosY   = iCGBlkPos / uiNumBlkSide;
+      Int iCGPosX   = iCGBlkPos - (iCGPosY * uiNumBlkSide);
+#if !REMOVAL_8x2_2x8_CG
+      if( uiWidth == 8 && uiHeight == 8 && (uiScanIdx == SCAN_HOR || uiScanIdx == SCAN_VER) )
+      {
+        iCGPosY = (uiScanIdx == SCAN_HOR ? iCGBlkPos : 0);
+        iCGPosX = (uiScanIdx == SCAN_VER ? iCGBlkPos : 0);
+      }
+#endif
+      if( iSubSet == iLastScanSet || iSubSet == 0)
+      {
+        uiSigCoeffGroupFlag[ iCGBlkPos ] = 1;
+      }
+      else
+      {
+          UInt uiSigCoeffGroup   = (uiSigCoeffGroupFlag[ iCGBlkPos ] != 0);
+          UInt uiCtxSig  = TComTrQuant::getSigCoeffGroupCtxInc( uiSigCoeffGroupFlag, iCGPosX, iCGPosY, uiScanIdx, uiWidth, uiHeight );
+          m_pcBinIf->encodeBin( uiSigCoeffGroup, baseCoeffGroupCtx[ uiCtxSig ] );
+      }
+      
+      // encode significant_coeff_flag
+      if( uiSigCoeffGroupFlag[ iCGBlkPos ] )
+      {
+        Int patternSigCtx = TComTrQuant::calcPatternSigCtx( uiSigCoeffGroupFlag, iCGPosX, iCGPosY, uiWidth, uiHeight );
+        UInt uiBlkPos, uiPosY, uiPosX, uiSig, uiCtxSig;
+        for( ; iScanPosSig >= iSubPos; iScanPosSig-- )
+        {
+          uiBlkPos  = scan[ iScanPosSig ]; 
+          uiPosY    = uiBlkPos >> uiLog2BlockSize;
+          uiPosX    = uiBlkPos - ( uiPosY << uiLog2BlockSize );
+          uiSig     = (pcCoef[ uiBlkPos ] != 0);
+          if( iScanPosSig > iSubPos || iSubSet == 0 || numNonZero )
+          {
+#if REMOVAL_8x2_2x8_CG
+            uiCtxSig  = TComTrQuant::getSigCtxInc( patternSigCtx, uiScanIdx, uiPosX, uiPosY, blockType, uiWidth, uiHeight, eTType );
+#else
+            uiCtxSig  = TComTrQuant::getSigCtxInc( patternSigCtx, uiPosX, uiPosY, blockType, uiWidth, uiHeight, eTType );
+#endif
+            m_pcBinIf->encodeBin( uiSig, baseCtx[ uiCtxSig ] );
+          }
+          if( uiSig )
+          {
+            absCoeff[ numNonZero ] = abs( pcCoef[ uiBlkPos ] );
+            coeffSigns = 2 * coeffSigns + ( pcCoef[ uiBlkPos ] < 0 );
+            numNonZero++;
+            if( lastNZPosInCG == -1 )
+            {
+              lastNZPosInCG = iScanPosSig;
+            }
+            firstNZPosInCG = iScanPosSig;
+          }
+        }
+      }
+      else
+      {
+        iScanPosSig = iSubPos - 1;
+      }
+
+    if( numNonZero > 0 )
+    {
+      Bool signHidden = ( lastNZPosInCG - firstNZPosInCG >= SBH_THRESHOLD );
+#if !REMOVE_NUM_GREATER1
+      UInt c1 = 1;
+#endif
+      UInt uiCtxSet = (iSubSet > 0 && eTType==TEXT_LUMA) ? 2 : 0;
+      
+#if REMOVE_NUM_GREATER1
+      if( c1 == 0 )
+#else
+      if( uiNumOne > 0 )
+#endif
+      {
+        uiCtxSet++;
+      }
+#if REMOVE_NUM_GREATER1
+      c1 = 1;
+#else
+      uiNumOne       >>= 1;
+#endif
+      ContextModel *baseCtxMod = ( eTType==TEXT_LUMA ) ? m_cCUOneSCModel.get( 0, 0 ) + 4 * uiCtxSet : m_cCUOneSCModel.get( 0, 0 ) + NUM_ONE_FLAG_CTX_LUMA + 4 * uiCtxSet;
+      
+      Int numC1Flag = min(numNonZero, C1FLAG_NUMBER);
+      Int firstC2FlagIdx = -1;
+      for( Int idx = 0; idx < numC1Flag; idx++ )
+      {
+        UInt uiSymbol = absCoeff[ idx ] > 1;
+        m_pcBinIf->encodeBin( uiSymbol, baseCtxMod[c1] );
+        if( uiSymbol )
+        {
+          c1 = 0;
+
+          if (firstC2FlagIdx == -1)
+          {
+            firstC2FlagIdx = idx;
+          }
+        }
+        else if( (c1 < 3) && (c1 > 0) )
+        {
+          c1++;
+        }
+      }
+      
+      if (c1 == 0)
+      {
+
+        baseCtxMod = ( eTType==TEXT_LUMA ) ? m_cCUAbsSCModel.get( 0, 0 ) + uiCtxSet : m_cCUAbsSCModel.get( 0, 0 ) + NUM_ABS_FLAG_CTX_LUMA + uiCtxSet;
+        if ( firstC2FlagIdx != -1)
+        {
+          UInt symbol = absCoeff[ firstC2FlagIdx ] > 2;
+          m_pcBinIf->encodeBin( symbol, baseCtxMod[0] );
+        }
+      }
+      
+      if( beValid && signHidden )
+      {
+        m_pcBinIf->encodeBinsEP( (coeffSigns >> 1), numNonZero-1 );
+      }
+      else
+      {
+        m_pcBinIf->encodeBinsEP( coeffSigns, numNonZero );
+      }
+      
+      Int iFirstCoeff2 = 1;    
+      if (c1 == 0 || numNonZero > C1FLAG_NUMBER)
+      {
+        for ( Int idx = 0; idx < numNonZero; idx++ )
+        {
+          UInt baseLevel  = (idx < C1FLAG_NUMBER)? (2 + iFirstCoeff2 ) : 1;
+
+          if( absCoeff[ idx ] >= baseLevel)
+          {
+            xWriteCoefRemainExGolomb( absCoeff[ idx ] - baseLevel, uiGoRiceParam );
+            if(absCoeff[idx] > 3*(1<<uiGoRiceParam))
+            {
+               uiGoRiceParam = min<UInt>(uiGoRiceParam+ 1, 4);
+            }
+          }
+          if(absCoeff[ idx ] >= 2)  
+          {
+            iFirstCoeff2 = 0;
+#if !REMOVE_NUM_GREATER1
+            uiNumOne++;
+#endif
+          }
+        }        
+      }
+    }
+#if !REMOVE_NUM_GREATER1
+    else
+    {
+      uiNumOne >>= 1;
+    }
+#endif
+  }
+
+  return;
+}
+
+#if !REMOVE_ALF
+Void TEncSbac::codeAlfCtrlFlag( Int compIdx, UInt code )
+{
+  m_pcBinIf->encodeBin( code, m_cCUAlfCtrlFlagSCModel.get( 0, 0, 0) );
+
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "codeAlfCtrlFlag()" )
+  DTRACE_CABAC_T( "\tsymbol=" )
+  DTRACE_CABAC_V( code )
+  DTRACE_CABAC_T( "\tcompIdx=" )
+  DTRACE_CABAC_V( compIdx )
+  DTRACE_CABAC_T( "\n" )
+}
+#endif
+
+/** code SAO offset sign
+ * \param code sign value
+ */
+Void TEncSbac::codeSAOSign( UInt code )
+{
+  m_pcBinIf->encodeBinEP( code );
+}
+
+Void TEncSbac::codeSaoMaxUvlc    ( UInt code, UInt maxSymbol )
+{
+  if (maxSymbol == 0)
+  {
+    return;
+  }
+
+  Int i;
+  Bool bCodeLast = ( maxSymbol > code );
+
+  if ( code == 0 )
+  {
+#if SAO_ABS_BY_PASS
+    m_pcBinIf->encodeBinEP( 0 );
+#else
+    m_pcBinIf->encodeBin( 0, m_cSaoUvlcSCModel.get( 0, 0, 0 ) );
+#endif
+  }
+  else
+  {
+#if SAO_ABS_BY_PASS
+    m_pcBinIf->encodeBinEP( 1 );
+#else
+    m_pcBinIf->encodeBin( 1, m_cSaoUvlcSCModel.get( 0, 0, 0 ) );
+#endif
+    for ( i=0; i<code-1; i++ )
+    {
+#if SAO_ABS_BY_PASS
+      m_pcBinIf->encodeBinEP( 1 );
+#else
+      m_pcBinIf->encodeBin( 1, m_cSaoUvlcSCModel.get( 0, 0, 1 ) );
+#endif
+    }
+    if( bCodeLast )
+    {
+#if SAO_ABS_BY_PASS
+      m_pcBinIf->encodeBinEP( 0 );
+#else
+      m_pcBinIf->encodeBin( 0, m_cSaoUvlcSCModel.get( 0, 0, 1 ) );
+#endif
+    }
+  }
+}
+
+
+#if SAO_TYPE_CODING
+/** Code SAO EO class or BO band position 
+ * \param uiLength
+ * \param uiCode
+ */
+Void TEncSbac::codeSaoUflc       ( UInt uiLength, UInt uiCode )
+{
+   m_pcBinIf->encodeBinsEP ( uiCode, uiLength );
+}
+#else
+/** Code SAO band position 
+ * \param uiCode
+ */
+Void TEncSbac::codeSaoUflc       ( UInt uiCode )
+{
+    m_pcBinIf->encodeBinsEP ( uiCode, 5 );
+}
+#endif
+#if SAO_MERGE_ONE_CTX
+/** Code SAO merge flags
+ * \param uiCode
+ * \param uiCompIdx
+ */
+Void TEncSbac::codeSaoMerge       ( UInt uiCode )
+#else
+/** Code SAO merge left flag 
+ * \param uiCode
+ * \param uiCompIdx
+ */
+Void TEncSbac::codeSaoMergeLeft       ( UInt uiCode, UInt uiCompIdx )
+#endif
+{
+  if (uiCode == 0)
+  {
+#if SAO_MERGE_ONE_CTX
+    m_pcBinIf->encodeBin(0,  m_cSaoMergeSCModel.get( 0, 0, 0 ));
+#else
+#if SAO_SINGLE_MERGE
+    m_pcBinIf->encodeBin(0,  m_cSaoMergeLeftSCModel.get( 0, 0, 0 ));
+#else
+    m_pcBinIf->encodeBin(0,  m_cSaoMergeLeftSCModel.get( 0, 0, uiCompIdx ));
+#endif
+#endif
+  }
+  else
+  {
+#if SAO_MERGE_ONE_CTX
+    m_pcBinIf->encodeBin(1,  m_cSaoMergeSCModel.get( 0, 0, 0 ));
+#else
+#if SAO_SINGLE_MERGE
+    m_pcBinIf->encodeBin(1,  m_cSaoMergeLeftSCModel.get( 0, 0, 0 ));
+#else
+    m_pcBinIf->encodeBin(1,  m_cSaoMergeLeftSCModel.get( 0, 0, uiCompIdx ));
+#endif
+#endif
+  }
+}
+#if !SAO_MERGE_ONE_CTX
+/** Code SAO merge up flag 
+ * \param uiCode
+ */
+Void TEncSbac::codeSaoMergeUp       ( UInt uiCode)
+{
+  if (uiCode == 0)
+  {
+    m_pcBinIf->encodeBin(0,  m_cSaoMergeUpSCModel.get( 0, 0, 0 ));
+  }
+  else
+  {
+    m_pcBinIf->encodeBin(1,  m_cSaoMergeUpSCModel.get( 0, 0, 0 ));
+  }
+}
+#endif
+/** Code SAO type index 
+ * \param uiCode
+ */
+Void TEncSbac::codeSaoTypeIdx       ( UInt uiCode)
+{
+#if SAO_TYPE_CODING
+  if (uiCode == 0)
+  {
+    m_pcBinIf->encodeBin( 0, m_cSaoTypeIdxSCModel.get( 0, 0, 0 ) );
+  }
+  else
+  {
+    m_pcBinIf->encodeBin( 1, m_cSaoTypeIdxSCModel.get( 0, 0, 0 ) );
+    m_pcBinIf->encodeBinEP( uiCode <= 4 ? 1 : 0 );
+  }
+#else
+  Int i;
+  if ( uiCode == 0 )
+  {
+    m_pcBinIf->encodeBin( 0, m_cSaoTypeIdxSCModel.get( 0, 0, 0 ) );
+  }
+  else
+  {
+    m_pcBinIf->encodeBin( 1, m_cSaoTypeIdxSCModel.get( 0, 0, 0 ) );
+    for ( i=0; i<uiCode-1; i++ )
+    {
+      m_pcBinIf->encodeBin( 1, m_cSaoTypeIdxSCModel.get( 0, 0, 1 ) );
+    }
+    m_pcBinIf->encodeBin( 0, m_cSaoTypeIdxSCModel.get( 0, 0, 1 ) );
+  }
+#endif
+}
+/*!
+ ****************************************************************************
+ * \brief
+ *   estimate bit cost for CBP, significant map and significant coefficients
+ ****************************************************************************
+ */
+Void TEncSbac::estBit( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType )
+{
+  estCBFBit( pcEstBitsSbac, 0, eTType );
+
+  estSignificantCoeffGroupMapBit( pcEstBitsSbac, 0, eTType );
+  
+  // encode significance map
+  estSignificantMapBit( pcEstBitsSbac, width, height, eTType );
+  
+  // encode significant coefficients
+  estSignificantCoefficientsBit( pcEstBitsSbac, 0, eTType );
+}
+
+/*!
+ ****************************************************************************
+ * \brief
+ *    estimate bit cost for each CBP bit
+ ****************************************************************************
+ */
+Void TEncSbac::estCBFBit( estBitsSbacStruct* pcEstBitsSbac, UInt uiCTXIdx, TextType eTType )
+{
+  ContextModel *pCtx = m_cCUQtCbfSCModel.get( 0 );
+
+  for( UInt uiCtxInc = 0; uiCtxInc < 3*NUM_QT_CBF_CTX; uiCtxInc++ )
+  {
+    pcEstBitsSbac->blockCbpBits[ uiCtxInc ][ 0 ] = pCtx[ uiCtxInc ].getEntropyBits( 0 );
+    pcEstBitsSbac->blockCbpBits[ uiCtxInc ][ 1 ] = pCtx[ uiCtxInc ].getEntropyBits( 1 );
+  }
+
+  pCtx = m_cCUQtRootCbfSCModel.get( 0 );
+  
+  for( UInt uiCtxInc = 0; uiCtxInc < 4; uiCtxInc++ )
+  {
+    pcEstBitsSbac->blockRootCbpBits[ uiCtxInc ][ 0 ] = pCtx[ uiCtxInc ].getEntropyBits( 0 );
+    pcEstBitsSbac->blockRootCbpBits[ uiCtxInc ][ 1 ] = pCtx[ uiCtxInc ].getEntropyBits( 1 );
+  }
+}
+
+
+/*!
+ ****************************************************************************
+ * \brief
+ *    estimate SAMBAC bit cost for significant coefficient group map
+ ****************************************************************************
+ */
+Void TEncSbac::estSignificantCoeffGroupMapBit( estBitsSbacStruct* pcEstBitsSbac, UInt uiCTXIdx, TextType eTType )
+{
+  Int firstCtx = 0, numCtx = NUM_SIG_CG_FLAG_CTX;
+
+  for ( Int ctxIdx = firstCtx; ctxIdx < firstCtx + numCtx; ctxIdx++ )
+  {
+    for( UInt uiBin = 0; uiBin < 2; uiBin++ )
+    {
+      pcEstBitsSbac->significantCoeffGroupBits[ ctxIdx ][ uiBin ] = m_cCUSigCoeffGroupSCModel.get(  0, eTType, ctxIdx ).getEntropyBits( uiBin );
+    }
+  }
+}
+
+
+/*!
+ ****************************************************************************
+ * \brief
+ *    estimate SAMBAC bit cost for significant coefficient map
+ ****************************************************************************
+ */
+Void TEncSbac::estSignificantMapBit( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType )
+{
+  Int firstCtx = 1, numCtx = 8;
+  if (max(width, height) >= 16)
+  {
+#if REMOVAL_8x2_2x8_CG
+    firstCtx = (eTType == TEXT_LUMA) ? 21 : 12;
+#else
+    firstCtx = 18;
+#endif
+    numCtx = (eTType == TEXT_LUMA) ? 6 : 3;
+  }
+  else if (width == 8)
+  {
+    firstCtx = 9;
+#if REMOVAL_8x2_2x8_CG
+    numCtx = (eTType == TEXT_LUMA) ? 12 : 3;
+#else
+    numCtx = 9;
+#endif
+  }
+  
+  if (eTType == TEXT_LUMA )
+  {
+    for( UInt bin = 0; bin < 2; bin++ )
+    {
+      pcEstBitsSbac->significantBits[ 0 ][ bin ] = m_cCUSigSCModel.get(  0, 0, 0 ).getEntropyBits( bin );
+    }
+
+    for ( Int ctxIdx = firstCtx; ctxIdx < firstCtx + numCtx; ctxIdx++ )
+    {
+      for( UInt uiBin = 0; uiBin < 2; uiBin++ )
+      {
+        pcEstBitsSbac->significantBits[ ctxIdx ][ uiBin ] = m_cCUSigSCModel.get(  0, 0, ctxIdx ).getEntropyBits( uiBin );
+      }
+    }
+  }
+  else
+  {
+    for( UInt bin = 0; bin < 2; bin++ )
+    {
+      pcEstBitsSbac->significantBits[ 0 ][ bin ] = m_cCUSigSCModel.get(  0, 0, NUM_SIG_FLAG_CTX_LUMA + 0 ).getEntropyBits( bin );
+    }
+    for ( Int ctxIdx = firstCtx; ctxIdx < firstCtx + numCtx; ctxIdx++ )
+    {
+      for( UInt uiBin = 0; uiBin < 2; uiBin++ )
+      {
+        pcEstBitsSbac->significantBits[ ctxIdx ][ uiBin ] = m_cCUSigSCModel.get(  0, 0, NUM_SIG_FLAG_CTX_LUMA + ctxIdx ).getEntropyBits( uiBin );
+      }
+    }
+  }
+  Int iBitsX = 0, iBitsY = 0;
+  Int blkSizeOffsetX, blkSizeOffsetY, shiftX, shiftY;
+
+  blkSizeOffsetX = eTType ? 0: (g_aucConvertToBit[ width ] *3 + ((g_aucConvertToBit[ width ] +1)>>2));
+  blkSizeOffsetY = eTType ? 0: (g_aucConvertToBit[ height ]*3 + ((g_aucConvertToBit[ height ]+1)>>2));
+  shiftX = eTType ? g_aucConvertToBit[ width  ] :((g_aucConvertToBit[ width  ]+3)>>2);
+  shiftY = eTType ? g_aucConvertToBit[ height ] :((g_aucConvertToBit[ height ]+3)>>2);
+
+  Int ctx;
+  ContextModel *pCtxX      = m_cCuCtxLastX.get( 0, eTType );
+  for (ctx = 0; ctx < g_uiGroupIdx[ width - 1 ]; ctx++)
+  {
+    Int ctxOffset = blkSizeOffsetX + (ctx >>shiftX);
+    pcEstBitsSbac->lastXBits[ ctx ] = iBitsX + pCtxX[ ctxOffset ].getEntropyBits( 0 );
+    iBitsX += pCtxX[ ctxOffset ].getEntropyBits( 1 );
+  }
+  pcEstBitsSbac->lastXBits[ctx] = iBitsX;
+  ContextModel *pCtxY      = m_cCuCtxLastY.get( 0, eTType );
+  for (ctx = 0; ctx < g_uiGroupIdx[ height - 1 ]; ctx++)
+  {
+    Int ctxOffset = blkSizeOffsetY + (ctx >>shiftY);
+    pcEstBitsSbac->lastYBits[ ctx ] = iBitsY + pCtxY[ ctxOffset ].getEntropyBits( 0 );
+    iBitsY += pCtxY[ ctxOffset ].getEntropyBits( 1 );
+  }
+  pcEstBitsSbac->lastYBits[ctx] = iBitsY;
+}
+
+/*!
+ ****************************************************************************
+ * \brief
+ *    estimate bit cost of significant coefficient
+ ****************************************************************************
+ */
+Void TEncSbac::estSignificantCoefficientsBit( estBitsSbacStruct* pcEstBitsSbac, UInt uiCTXIdx, TextType eTType )
+{
+  if (eTType==TEXT_LUMA)
+  {
+    ContextModel *ctxOne = m_cCUOneSCModel.get(0, 0);
+    ContextModel *ctxAbs = m_cCUAbsSCModel.get(0, 0);
+
+    for (Int ctxIdx = 0; ctxIdx < NUM_ONE_FLAG_CTX_LUMA; ctxIdx++)
+    {
+      pcEstBitsSbac->m_greaterOneBits[ ctxIdx ][ 0 ] = ctxOne[ ctxIdx ].getEntropyBits( 0 );
+      pcEstBitsSbac->m_greaterOneBits[ ctxIdx ][ 1 ] = ctxOne[ ctxIdx ].getEntropyBits( 1 );    
+    }
+
+    for (Int ctxIdx = 0; ctxIdx < NUM_ABS_FLAG_CTX_LUMA; ctxIdx++)
+    {
+      pcEstBitsSbac->m_levelAbsBits[ ctxIdx ][ 0 ] = ctxAbs[ ctxIdx ].getEntropyBits( 0 );
+      pcEstBitsSbac->m_levelAbsBits[ ctxIdx ][ 1 ] = ctxAbs[ ctxIdx ].getEntropyBits( 1 );    
+    }
+  }
+  else
+  {
+    ContextModel *ctxOne = m_cCUOneSCModel.get(0, 0) + NUM_ONE_FLAG_CTX_LUMA;
+    ContextModel *ctxAbs = m_cCUAbsSCModel.get(0, 0) + NUM_ABS_FLAG_CTX_LUMA;
+
+    for (Int ctxIdx = 0; ctxIdx < NUM_ONE_FLAG_CTX_CHROMA; ctxIdx++)
+    {
+      pcEstBitsSbac->m_greaterOneBits[ ctxIdx ][ 0 ] = ctxOne[ ctxIdx ].getEntropyBits( 0 );
+      pcEstBitsSbac->m_greaterOneBits[ ctxIdx ][ 1 ] = ctxOne[ ctxIdx ].getEntropyBits( 1 );    
+    }
+
+    for (Int ctxIdx = 0; ctxIdx < NUM_ABS_FLAG_CTX_CHROMA; ctxIdx++)
+    {
+      pcEstBitsSbac->m_levelAbsBits[ ctxIdx ][ 0 ] = ctxAbs[ ctxIdx ].getEntropyBits( 0 );
+      pcEstBitsSbac->m_levelAbsBits[ ctxIdx ][ 1 ] = ctxAbs[ ctxIdx ].getEntropyBits( 1 );    
+    }
+  }
+}
+
+/**
+ - Initialize our context information from the nominated source.
+ .
+ \param pSrc From where to copy context information.
+ */
+Void TEncSbac::xCopyContextsFrom( TEncSbac* pSrc )
+{  
+  memcpy(m_contextModels, pSrc->m_contextModels, m_numContextModels*sizeof(m_contextModels[0]));
+}
+
+Void  TEncSbac::loadContexts ( TEncSbac* pScr)
+{
+  this->xCopyContextsFrom(pScr);
+}
+//! \}
Index: /trunk/source/Lib/TLibEncoder/TEncSbac.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncSbac.h	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/TEncSbac.h	(revision 2)
@@ -0,0 +1,260 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncSbac.h
+    \brief    Context-adaptive entropy encoder class (header)
+*/
+
+#ifndef __TENCSBAC__
+#define __TENCSBAC__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TLibCommon/TComBitStream.h"
+#include "TLibCommon/ContextTables.h"
+#include "TLibCommon/ContextModel.h"
+#include "TLibCommon/ContextModel3DBuffer.h"
+#include "TEncEntropy.h"
+#include "TEncBinCoder.h"
+#include "TEncBinCoderCABAC.h"
+#if FAST_BIT_EST
+#include "TEncBinCoderCABACCounter.h"
+#endif
+
+class TEncTop;
+
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// SBAC encoder class
+class TEncSbac : public TEncEntropyIf
+{
+public:
+  TEncSbac();
+  virtual ~TEncSbac();
+  
+  Void  init                   ( TEncBinIf* p )  { m_pcBinIf = p; }
+  Void  uninit                 ()                { m_pcBinIf = 0; }
+
+  //  Virtual list
+  Void  resetEntropy           ();
+  Void  determineCabacInitIdx  ();
+  Void  setBitstream           ( TComBitIf* p )  { m_pcBitIf = p; m_pcBinIf->init( p ); }
+  Void  setSlice               ( TComSlice* p )  { m_pcSlice = p;                       }
+  // SBAC RD
+  Void  resetCoeffCost         ()                { m_uiCoeffCost = 0;  }
+  UInt  getCoeffCost           ()                { return  m_uiCoeffCost;  }
+  
+  Void  load                   ( TEncSbac* pScr  );
+  Void  loadIntraDirModeLuma   ( TEncSbac* pScr  );
+  Void  store                  ( TEncSbac* pDest );
+  Void  loadContexts           ( TEncSbac* pScr  );
+  Void  resetBits              ()                { m_pcBinIf->resetBits(); m_pcBitIf->resetBits(); }
+  UInt  getNumberOfWrittenBits ()                { return m_pcBinIf->getNumWrittenBits(); }
+  //--SBAC RD
+
+  Void  codeVPS                 ( TComVPS* pcVPS );
+  Void  codeSPS                 ( TComSPS* pcSPS     );
+  Void  codePPS                 ( TComPPS* pcPPS     );
+  Void  codeSliceHeader         ( TComSlice* pcSlice );
+  Void  codeTilesWPPEntryPoint( TComSlice* pSlice );
+  Void  codeTerminatingBit      ( UInt uilsLast      );
+  Void  codeSliceFinish         ();
+  Void  codeFlush               ();
+  Void  encodeStart             ();
+#if !REMOVE_ALF
+  Void codeAlfParam(ALFParam* alfParam){printf("Not supported\n"); assert(0); exit(1);}
+  Void codeAlfCtrlFlag( Int compIdx, UInt code );
+#endif
+  Void  codeApsExtensionFlag () { assert (0); return; };
+  Void  codeSaoMaxUvlc    ( UInt code, UInt maxSymbol );
+#if SAO_MERGE_ONE_CTX
+  Void  codeSaoMerge  ( UInt  uiCode );
+#else
+  Void  codeSaoMergeLeft  ( UInt  uiCode, UInt uiCompIdx );
+  Void  codeSaoMergeUp    ( UInt  uiCode);
+#endif
+  Void  codeSaoTypeIdx    ( UInt  uiCode);
+#if SAO_TYPE_CODING
+  Void  codeSaoUflc       ( UInt uiLength, UInt  uiCode );
+#else
+  Void  codeSaoUflc       ( UInt  uiCode);
+#endif
+  Void  codeSAOSign       ( UInt  uiCode);  //<! code SAO offset sign
+  Void  codeScalingList      ( TComScalingList* scalingList     ){ assert (0);  return;};
+
+private:
+  Void  xWriteUnarySymbol    ( UInt uiSymbol, ContextModel* pcSCModel, Int iOffset );
+  Void  xWriteUnaryMaxSymbol ( UInt uiSymbol, ContextModel* pcSCModel, Int iOffset, UInt uiMaxSymbol );
+  Void  xWriteEpExGolomb     ( UInt uiSymbol, UInt uiCount );
+  Void  xWriteCoefRemainExGolomb ( UInt symbol, UInt &rParam );
+  Void  xWriteTerminatingBit ( UInt uiBit );
+  
+  Void  xCopyFrom            ( TEncSbac* pSrc );
+  Void  xCopyContextsFrom    ( TEncSbac* pSrc );  
+  
+#if !REMOVE_APS
+  Void codeAPSInitInfo(TComAPS* pcAPS) {printf("Not supported in codeAPSInitInfo()\n"); assert(0); exit(1);}
+#endif
+  Void codeFinish     (Bool bEnd)      { m_pcBinIf->encodeFlush(bEnd); }  //<! flush bits when CABAC termination
+  Void codeDFFlag( UInt uiCode, const Char *pSymbolName )       {printf("Not supported in codeDFFlag()\n"); assert(0); exit(1);};
+  Void codeDFSvlc( Int iCode, const Char *pSymbolName )         {printf("Not supported in codeDFSvlc()\n"); assert(0); exit(1);};
+
+protected:
+  TComBitIf*    m_pcBitIf;
+  TComSlice*    m_pcSlice;
+  TEncBinIf*    m_pcBinIf;
+  //SBAC RD
+  UInt          m_uiCoeffCost;
+
+#if !REMOVE_FGS
+  Int           m_iSliceGranularity; //!< slice granularity
+#endif
+  //--Adaptive loop filter
+  
+public:
+#if !REMOVE_FGS
+  /// set slice granularity
+  Void setSliceGranularity(Int iSliceGranularity)  {m_iSliceGranularity = iSliceGranularity;}
+
+  /// get slice granularity
+  Int  getSliceGranularity()                       {return m_iSliceGranularity;             }
+#endif
+  Void codeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeSkipFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeMergeFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeMergeIndex    ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeSplitFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void codeMVPIdx        ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList );
+  
+#if INTRA_BL
+  Void codeIntraBLFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#endif
+  Void codePartSize      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void codePredMode      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeIPCMInfo      ( TComDataCU* pcCU, UInt uiAbsPartIdx, Int numIPCM, Bool firstIPCMFlag);
+  Void codeTransformSubdivFlag ( UInt uiSymbol, UInt uiCtx );
+  Void codeQtCbf               ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth );
+  Void codeQtRootCbf           ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#if TU_ZERO_CBF_RDO
+  Void codeQtCbfZero           ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth );
+  Void codeQtRootCbfZero       ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#endif
+  Void codeIntraDirLumaAng     ( TComDataCU* pcCU, UInt absPartIdx, Bool isMultiple);
+  
+  Void codeIntraDirChroma      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeInterDir            ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeRefFrmIdx           ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList );
+  Void codeMvd                 ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList );
+  
+  Void codeDeltaQP             ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  
+  Void codeLastSignificantXY ( UInt uiPosX, UInt uiPosY, Int width, Int height, TextType eTType, UInt uiScanIdx );
+  Void codeCoeffNxN            ( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType );
+  void codeTransformSkipFlags ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, UInt uiDepth, TextType eTType );
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // for RD-optimizatioon
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Void estBit               (estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType);
+  Void estCBFBit                     ( estBitsSbacStruct* pcEstBitsSbac, UInt uiCTXIdx, TextType eTType );
+  Void estSignificantCoeffGroupMapBit( estBitsSbacStruct* pcEstBitsSbac, UInt uiCTXIdx, TextType eTType );
+  Void estSignificantMapBit          ( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType );
+  Void estSignificantCoefficientsBit ( estBitsSbacStruct* pcEstBitsSbac, UInt uiCTXIdx, TextType eTType );
+  
+  Void updateContextTables           ( SliceType eSliceType, Int iQp, Bool bExecuteFinish=true  );
+  Void updateContextTables           ( SliceType eSliceType, Int iQp  ) { this->updateContextTables( eSliceType, iQp, true); };
+  
+  TEncBinIf* getEncBinIf()  { return m_pcBinIf; }
+private:
+  UInt                 m_uiLastQp;
+  
+  ContextModel         m_contextModels[MAX_NUM_CTX_MOD];
+  Int                  m_numContextModels;
+  ContextModel3DBuffer m_cCUSplitFlagSCModel;
+  ContextModel3DBuffer m_cCUSkipFlagSCModel;
+  ContextModel3DBuffer m_cCUMergeFlagExtSCModel;
+  ContextModel3DBuffer m_cCUMergeIdxExtSCModel;
+  ContextModel3DBuffer m_cCUPartSizeSCModel;
+  ContextModel3DBuffer m_cCUPredModeSCModel;
+  ContextModel3DBuffer m_cCUAlfCtrlFlagSCModel;
+  ContextModel3DBuffer m_cCUIntraPredSCModel;
+  ContextModel3DBuffer m_cCUChromaPredSCModel;
+  ContextModel3DBuffer m_cCUDeltaQpSCModel;
+  ContextModel3DBuffer m_cCUInterDirSCModel;
+  ContextModel3DBuffer m_cCURefPicSCModel;
+  ContextModel3DBuffer m_cCUMvdSCModel;
+  ContextModel3DBuffer m_cCUQtCbfSCModel;
+  ContextModel3DBuffer m_cCUTransSubdivFlagSCModel;
+  ContextModel3DBuffer m_cCUQtRootCbfSCModel;
+  
+  ContextModel3DBuffer m_cCUSigCoeffGroupSCModel;
+  ContextModel3DBuffer m_cCUSigSCModel;
+  ContextModel3DBuffer m_cCuCtxLastX;
+  ContextModel3DBuffer m_cCuCtxLastY;
+  ContextModel3DBuffer m_cCUOneSCModel;
+  ContextModel3DBuffer m_cCUAbsSCModel;
+  
+  ContextModel3DBuffer m_cMVPIdxSCModel;
+  
+  ContextModel3DBuffer m_cALFFlagSCModel;
+  ContextModel3DBuffer m_cALFUvlcSCModel;
+  ContextModel3DBuffer m_cALFSvlcSCModel;
+  ContextModel3DBuffer m_cCUAMPSCModel;
+#if !SAO_ABS_BY_PASS
+  ContextModel3DBuffer m_cSaoUvlcSCModel;
+#endif
+#if SAO_MERGE_ONE_CTX
+  ContextModel3DBuffer m_cSaoMergeSCModel;
+#else
+  ContextModel3DBuffer m_cSaoMergeLeftSCModel;
+  ContextModel3DBuffer m_cSaoMergeUpSCModel;
+#endif
+#if INTRA_BL
+  ContextModel3DBuffer m_cIntraBLPredFlagSCModel;
+#endif
+  ContextModel3DBuffer m_cSaoTypeIdxSCModel;
+  ContextModel3DBuffer m_cTransformSkipSCModel;
+  ContextModel3DBuffer m_CUTransquantBypassFlagSCModel;
+};
+
+//! \}
+
+#endif // !defined(AFX_TENCSBAC_H__DDA7CDC4_EDE3_4015_9D32_2156249C82AA__INCLUDED_)
Index: /trunk/source/Lib/TLibEncoder/TEncSearch.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncSearch.cpp	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/TEncSearch.cpp	(revision 2)
@@ -0,0 +1,6406 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncSearch.cpp
+ \brief    encoder search class
+ */
+
+#include "TLibCommon/TypeDef.h"
+#include "TLibCommon/TComRom.h"
+#include "TLibCommon/TComMotionInfo.h"
+#include "TEncSearch.h"
+#include <math.h>
+
+//! \ingroup TLibEncoder
+//! \{
+
+static const TComMv s_acMvRefineH[9] =
+{
+  TComMv(  0,  0 ), // 0
+  TComMv(  0, -1 ), // 1
+  TComMv(  0,  1 ), // 2
+  TComMv( -1,  0 ), // 3
+  TComMv(  1,  0 ), // 4
+  TComMv( -1, -1 ), // 5
+  TComMv(  1, -1 ), // 6
+  TComMv( -1,  1 ), // 7
+  TComMv(  1,  1 )  // 8
+};
+
+static const TComMv s_acMvRefineQ[9] =
+{
+  TComMv(  0,  0 ), // 0
+  TComMv(  0, -1 ), // 1
+  TComMv(  0,  1 ), // 2
+  TComMv( -1, -1 ), // 5
+  TComMv(  1, -1 ), // 6
+  TComMv( -1,  0 ), // 3
+  TComMv(  1,  0 ), // 4
+  TComMv( -1,  1 ), // 7
+  TComMv(  1,  1 )  // 8
+};
+
+static const UInt s_auiDFilter[9] =
+{
+  0, 1, 0,
+  2, 3, 2,
+  0, 1, 0
+};
+
+TEncSearch::TEncSearch()
+{
+  m_ppcQTTempCoeffY  = NULL;
+  m_ppcQTTempCoeffCb = NULL;
+  m_ppcQTTempCoeffCr = NULL;
+  m_pcQTTempCoeffY   = NULL;
+  m_pcQTTempCoeffCb  = NULL;
+  m_pcQTTempCoeffCr  = NULL;
+#if ADAPTIVE_QP_SELECTION
+  m_ppcQTTempArlCoeffY  = NULL;
+  m_ppcQTTempArlCoeffCb = NULL;
+  m_ppcQTTempArlCoeffCr = NULL;
+  m_pcQTTempArlCoeffY   = NULL;
+  m_pcQTTempArlCoeffCb  = NULL;
+  m_pcQTTempArlCoeffCr  = NULL;
+#endif
+  m_puhQTTempTrIdx   = NULL;
+  m_puhQTTempCbf[0] = m_puhQTTempCbf[1] = m_puhQTTempCbf[2] = NULL;
+  m_pcQTTempTComYuv  = NULL;
+  m_pcEncCfg = NULL;
+  m_pcEntropyCoder = NULL;
+  m_pTempPel = NULL;
+  m_pSharedPredTransformSkip[0] = m_pSharedPredTransformSkip[1] = m_pSharedPredTransformSkip[2] = NULL;
+  m_pcQTTempTUCoeffY   = NULL;
+  m_pcQTTempTUCoeffCb  = NULL;
+  m_pcQTTempTUCoeffCr  = NULL;
+#if ADAPTIVE_QP_SELECTION
+  m_ppcQTTempTUArlCoeffY  = NULL;
+  m_ppcQTTempTUArlCoeffCb = NULL;
+  m_ppcQTTempTUArlCoeffCr = NULL;
+#endif
+  m_puhQTTempTransformSkipFlag[0] = NULL;
+  m_puhQTTempTransformSkipFlag[1] = NULL;
+  m_puhQTTempTransformSkipFlag[2] = NULL;
+  setWpScalingDistParam( NULL, -1, REF_PIC_LIST_X );
+}
+
+TEncSearch::~TEncSearch()
+{
+  if ( m_pTempPel )
+  {
+    delete [] m_pTempPel;
+    m_pTempPel = NULL;
+  }
+  
+  if ( m_pcEncCfg )
+  {
+    const UInt uiNumLayersAllocated = m_pcEncCfg->getQuadtreeTULog2MaxSize()-m_pcEncCfg->getQuadtreeTULog2MinSize()+1;
+    for( UInt ui = 0; ui < uiNumLayersAllocated; ++ui )
+    {
+      delete[] m_ppcQTTempCoeffY[ui];
+      delete[] m_ppcQTTempCoeffCb[ui];
+      delete[] m_ppcQTTempCoeffCr[ui];
+#if ADAPTIVE_QP_SELECTION
+      delete[] m_ppcQTTempArlCoeffY[ui];
+      delete[] m_ppcQTTempArlCoeffCb[ui];
+      delete[] m_ppcQTTempArlCoeffCr[ui];
+#endif
+      m_pcQTTempTComYuv[ui].destroy();
+    }
+  }
+  delete[] m_ppcQTTempCoeffY;
+  delete[] m_ppcQTTempCoeffCb;
+  delete[] m_ppcQTTempCoeffCr;
+  delete[] m_pcQTTempCoeffY;
+  delete[] m_pcQTTempCoeffCb;
+  delete[] m_pcQTTempCoeffCr;
+#if ADAPTIVE_QP_SELECTION
+  delete[] m_ppcQTTempArlCoeffY;
+  delete[] m_ppcQTTempArlCoeffCb;
+  delete[] m_ppcQTTempArlCoeffCr;
+  delete[] m_pcQTTempArlCoeffY;
+  delete[] m_pcQTTempArlCoeffCb;
+  delete[] m_pcQTTempArlCoeffCr;
+#endif
+  delete[] m_puhQTTempTrIdx;
+  delete[] m_puhQTTempCbf[0];
+  delete[] m_puhQTTempCbf[1];
+  delete[] m_puhQTTempCbf[2];
+  delete[] m_pcQTTempTComYuv;
+  delete[] m_pSharedPredTransformSkip[0];
+  delete[] m_pSharedPredTransformSkip[1];
+  delete[] m_pSharedPredTransformSkip[2];
+  delete[] m_pcQTTempTUCoeffY;
+  delete[] m_pcQTTempTUCoeffCb;
+  delete[] m_pcQTTempTUCoeffCr;
+#if ADAPTIVE_QP_SELECTION
+  delete[] m_ppcQTTempTUArlCoeffY;
+  delete[] m_ppcQTTempTUArlCoeffCb;
+  delete[] m_ppcQTTempTUArlCoeffCr;
+#endif
+  delete[] m_puhQTTempTransformSkipFlag[0];
+  delete[] m_puhQTTempTransformSkipFlag[1];
+  delete[] m_puhQTTempTransformSkipFlag[2];
+  m_pcQTTempTransformSkipTComYuv.destroy();
+  m_tmpYuvPred.destroy();
+}
+
+void TEncSearch::init(TEncCfg*      pcEncCfg,
+                      TComTrQuant*  pcTrQuant,
+                      Int           iSearchRange,
+                      Int           bipredSearchRange,
+                      Int           iFastSearch,
+                      Int           iMaxDeltaQP,
+                      TEncEntropy*  pcEntropyCoder,
+                      TComRdCost*   pcRdCost,
+                      TEncSbac*** pppcRDSbacCoder,
+                      TEncSbac*   pcRDGoOnSbacCoder
+                      )
+{
+  m_pcEncCfg             = pcEncCfg;
+  m_pcTrQuant            = pcTrQuant;
+  m_iSearchRange         = iSearchRange;
+  m_bipredSearchRange    = bipredSearchRange;
+  m_iFastSearch          = iFastSearch;
+  m_iMaxDeltaQP          = iMaxDeltaQP;
+  m_pcEntropyCoder       = pcEntropyCoder;
+  m_pcRdCost             = pcRdCost;
+  
+  m_pppcRDSbacCoder     = pppcRDSbacCoder;
+  m_pcRDGoOnSbacCoder   = pcRDGoOnSbacCoder;
+  
+  m_bUseSBACRD          = pppcRDSbacCoder ? true : false;
+  
+  for (Int iDir = 0; iDir < 2; iDir++)
+  {
+    for (Int iRefIdx = 0; iRefIdx < 33; iRefIdx++)
+    {
+      m_aaiAdaptSR[iDir][iRefIdx] = iSearchRange;
+    }
+  }
+  
+  m_puiDFilter = s_auiDFilter + 4;
+  
+  // initialize motion cost
+#if !FIX203
+  m_pcRdCost->initRateDistortionModel( m_iSearchRange << 2 );
+#endif
+  
+  for( Int iNum = 0; iNum < AMVP_MAX_NUM_CANDS+1; iNum++)
+  {
+    for( Int iIdx = 0; iIdx < AMVP_MAX_NUM_CANDS; iIdx++)
+    {
+      if (iIdx < iNum)
+        m_auiMVPIdxCost[iIdx][iNum] = xGetMvpIdxBits(iIdx, iNum);
+      else
+        m_auiMVPIdxCost[iIdx][iNum] = MAX_INT;
+    }
+  }
+  
+  initTempBuff();
+  
+  m_pTempPel = new Pel[g_uiMaxCUWidth*g_uiMaxCUHeight];
+  
+  const UInt uiNumLayersToAllocate = pcEncCfg->getQuadtreeTULog2MaxSize()-pcEncCfg->getQuadtreeTULog2MinSize()+1;
+  m_ppcQTTempCoeffY  = new TCoeff*[uiNumLayersToAllocate];
+  m_ppcQTTempCoeffCb = new TCoeff*[uiNumLayersToAllocate];
+  m_ppcQTTempCoeffCr = new TCoeff*[uiNumLayersToAllocate];
+  m_pcQTTempCoeffY   = new TCoeff [g_uiMaxCUWidth*g_uiMaxCUHeight   ];
+  m_pcQTTempCoeffCb  = new TCoeff [g_uiMaxCUWidth*g_uiMaxCUHeight>>2];
+  m_pcQTTempCoeffCr  = new TCoeff [g_uiMaxCUWidth*g_uiMaxCUHeight>>2];
+#if ADAPTIVE_QP_SELECTION
+  m_ppcQTTempArlCoeffY  = new Int*[uiNumLayersToAllocate];
+  m_ppcQTTempArlCoeffCb = new Int*[uiNumLayersToAllocate];
+  m_ppcQTTempArlCoeffCr = new Int*[uiNumLayersToAllocate];
+  m_pcQTTempArlCoeffY   = new Int [g_uiMaxCUWidth*g_uiMaxCUHeight   ];
+  m_pcQTTempArlCoeffCb  = new Int [g_uiMaxCUWidth*g_uiMaxCUHeight>>2];
+  m_pcQTTempArlCoeffCr  = new Int [g_uiMaxCUWidth*g_uiMaxCUHeight>>2];
+#endif
+  
+  const UInt uiNumPartitions = 1<<(g_uiMaxCUDepth<<1);
+  m_puhQTTempTrIdx   = new UChar  [uiNumPartitions];
+  m_puhQTTempCbf[0]  = new UChar  [uiNumPartitions];
+  m_puhQTTempCbf[1]  = new UChar  [uiNumPartitions];
+  m_puhQTTempCbf[2]  = new UChar  [uiNumPartitions];
+  m_pcQTTempTComYuv  = new TComYuv[uiNumLayersToAllocate];
+  for( UInt ui = 0; ui < uiNumLayersToAllocate; ++ui )
+  {
+    m_ppcQTTempCoeffY[ui]  = new TCoeff[g_uiMaxCUWidth*g_uiMaxCUHeight   ];
+    m_ppcQTTempCoeffCb[ui] = new TCoeff[g_uiMaxCUWidth*g_uiMaxCUHeight>>2];
+    m_ppcQTTempCoeffCr[ui] = new TCoeff[g_uiMaxCUWidth*g_uiMaxCUHeight>>2];
+#if ADAPTIVE_QP_SELECTION
+    m_ppcQTTempArlCoeffY[ui]  = new Int[g_uiMaxCUWidth*g_uiMaxCUHeight   ];
+    m_ppcQTTempArlCoeffCb[ui] = new Int[g_uiMaxCUWidth*g_uiMaxCUHeight>>2];
+    m_ppcQTTempArlCoeffCr[ui] = new Int[g_uiMaxCUWidth*g_uiMaxCUHeight>>2];
+#endif
+    m_pcQTTempTComYuv[ui].create( g_uiMaxCUWidth, g_uiMaxCUHeight );
+  }
+  m_pSharedPredTransformSkip[0] = new Pel[MAX_TS_WIDTH*MAX_TS_HEIGHT];
+  m_pSharedPredTransformSkip[1] = new Pel[MAX_TS_WIDTH*MAX_TS_HEIGHT];
+  m_pSharedPredTransformSkip[2] = new Pel[MAX_TS_WIDTH*MAX_TS_HEIGHT];
+  m_pcQTTempTUCoeffY  = new TCoeff[MAX_TS_WIDTH*MAX_TS_HEIGHT];
+  m_pcQTTempTUCoeffCb = new TCoeff[MAX_TS_WIDTH*MAX_TS_HEIGHT];
+  m_pcQTTempTUCoeffCr = new TCoeff[MAX_TS_WIDTH*MAX_TS_HEIGHT];
+#if ADAPTIVE_QP_SELECTION
+  m_ppcQTTempTUArlCoeffY  = new Int[MAX_TS_WIDTH*MAX_TS_HEIGHT];
+  m_ppcQTTempTUArlCoeffCb = new Int[MAX_TS_WIDTH*MAX_TS_HEIGHT];
+  m_ppcQTTempTUArlCoeffCr = new Int[MAX_TS_WIDTH*MAX_TS_HEIGHT];
+#endif
+  m_pcQTTempTransformSkipTComYuv.create( g_uiMaxCUWidth, g_uiMaxCUHeight );
+
+  m_puhQTTempTransformSkipFlag[0] = new UChar  [uiNumPartitions];
+  m_puhQTTempTransformSkipFlag[1] = new UChar  [uiNumPartitions];
+  m_puhQTTempTransformSkipFlag[2] = new UChar  [uiNumPartitions];
+  m_tmpYuvPred.create(MAX_CU_SIZE, MAX_CU_SIZE);
+}
+
+#if FASTME_SMOOTHER_MV
+#define FIRSTSEARCHSTOP     1
+#else
+#define FIRSTSEARCHSTOP     0
+#endif
+
+#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         = FIRSTSEARCHSTOP;                                                        \
+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) */  \
+
+
+__inline Void TEncSearch::xTZSearchHelp( TComPattern* pcPatternKey, IntTZSearchStruct& rcStruct, const Int iSearchX, const Int iSearchY, const UChar ucPointNr, const UInt uiDistance )
+{
+  UInt  uiSad;
+  
+  Pel*  piRefSrch;
+  
+  piRefSrch = rcStruct.piRefY + iSearchY * rcStruct.iYStride + iSearchX;
+  
+  //-- jclee for using the SAD function pointer
+  m_pcRdCost->setDistParam( pcPatternKey, piRefSrch, rcStruct.iYStride,  m_cDistParam );
+  
+  // 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(0);  // Y component
+
+  // distortion
+  uiSad = m_cDistParam.DistFunc( &m_cDistParam );
+  
+  // motion cost
+  uiSad += m_pcRdCost->getCost( iSearchX, iSearchY );
+  
+  if( uiSad < rcStruct.uiBestSad )
+  {
+    rcStruct.uiBestSad      = uiSad;
+    rcStruct.iBestX         = iSearchX;
+    rcStruct.iBestY         = iSearchY;
+    rcStruct.uiBestDistance = uiDistance;
+    rcStruct.uiBestRound    = 0;
+    rcStruct.ucPointNr      = ucPointNr;
+  }
+}
+
+__inline Void TEncSearch::xTZ2PointSearch( TComPattern* pcPatternKey, IntTZSearchStruct& rcStruct, TComMv* pcMvSrchRngLT, TComMv* pcMvSrchRngRB )
+{
+  Int   iSrchRngHorLeft   = pcMvSrchRngLT->getHor();
+  Int   iSrchRngHorRight  = pcMvSrchRngRB->getHor();
+  Int   iSrchRngVerTop    = pcMvSrchRngLT->getVer();
+  Int   iSrchRngVerBottom = pcMvSrchRngRB->getVer();
+  
+  // 2 point search,                   //   1 2 3
+  // check only the 2 untested points  //   4 0 5
+  // around the start point            //   6 7 8
+  Int iStartX = rcStruct.iBestX;
+  Int iStartY = rcStruct.iBestY;
+  switch( rcStruct.ucPointNr )
+  {
+    case 1:
+    {
+      if ( (iStartX - 1) >= iSrchRngHorLeft )
+      {
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX - 1, iStartY, 0, 2 );
+      }
+      if ( (iStartY - 1) >= iSrchRngVerTop )
+      {
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iStartY - 1, 0, 2 );
+      }
+    }
+      break;
+    case 2:
+    {
+      if ( (iStartY - 1) >= iSrchRngVerTop )
+      {
+        if ( (iStartX - 1) >= iSrchRngHorLeft )
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iStartX - 1, iStartY - 1, 0, 2 );
+        }
+        if ( (iStartX + 1) <= iSrchRngHorRight )
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iStartX + 1, iStartY - 1, 0, 2 );
+        }
+      }
+    }
+      break;
+    case 3:
+    {
+      if ( (iStartY - 1) >= iSrchRngVerTop )
+      {
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iStartY - 1, 0, 2 );
+      }
+      if ( (iStartX + 1) <= iSrchRngHorRight )
+      {
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX + 1, iStartY, 0, 2 );
+      }
+    }
+      break;
+    case 4:
+    {
+      if ( (iStartX - 1) >= iSrchRngHorLeft )
+      {
+        if ( (iStartY + 1) <= iSrchRngVerBottom )
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iStartX - 1, iStartY + 1, 0, 2 );
+        }
+        if ( (iStartY - 1) >= iSrchRngVerTop )
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iStartX - 1, iStartY - 1, 0, 2 );
+        }
+      }
+    }
+      break;
+    case 5:
+    {
+      if ( (iStartX + 1) <= iSrchRngHorRight )
+      {
+        if ( (iStartY - 1) >= iSrchRngVerTop )
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iStartX + 1, iStartY - 1, 0, 2 );
+        }
+        if ( (iStartY + 1) <= iSrchRngVerBottom )
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iStartX + 1, iStartY + 1, 0, 2 );
+        }
+      }
+    }
+      break;
+    case 6:
+    {
+      if ( (iStartX - 1) >= iSrchRngHorLeft )
+      {
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX - 1, iStartY , 0, 2 );
+      }
+      if ( (iStartY + 1) <= iSrchRngVerBottom )
+      {
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iStartY + 1, 0, 2 );
+      }
+    }
+      break;
+    case 7:
+    {
+      if ( (iStartY + 1) <= iSrchRngVerBottom )
+      {
+        if ( (iStartX - 1) >= iSrchRngHorLeft )
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iStartX - 1, iStartY + 1, 0, 2 );
+        }
+        if ( (iStartX + 1) <= iSrchRngHorRight )
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iStartX + 1, iStartY + 1, 0, 2 );
+        }
+      }
+    }
+      break;
+    case 8:
+    {
+      if ( (iStartX + 1) <= iSrchRngHorRight )
+      {
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX + 1, iStartY, 0, 2 );
+      }
+      if ( (iStartY + 1) <= iSrchRngVerBottom )
+      {
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iStartY + 1, 0, 2 );
+      }
+    }
+      break;
+    default:
+    {
+      assert( false );
+    }
+      break;
+  } // switch( rcStruct.ucPointNr )
+}
+
+__inline Void TEncSearch::xTZ8PointSquareSearch( TComPattern* pcPatternKey, IntTZSearchStruct& rcStruct, TComMv* pcMvSrchRngLT, TComMv* 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();
+  
+  // 8 point search,                   //   1 2 3
+  // search around the start point     //   4 0 5
+  // with the required  distance       //   6 7 8
+  assert( iDist != 0 );
+  const Int iTop        = iStartY - iDist;
+  const Int iBottom     = iStartY + iDist;
+  const Int iLeft       = iStartX - iDist;
+  const Int iRight      = iStartX + iDist;
+  rcStruct.uiBestRound += 1;
+  
+  if ( iTop >= iSrchRngVerTop ) // check top
+  {
+    if ( iLeft >= iSrchRngHorLeft ) // check top left
+    {
+      xTZSearchHelp( pcPatternKey, rcStruct, iLeft, iTop, 1, iDist );
+    }
+    // top middle
+    xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iTop, 2, iDist );
+    
+    if ( iRight <= iSrchRngHorRight ) // check top right
+    {
+      xTZSearchHelp( pcPatternKey, rcStruct, iRight, iTop, 3, iDist );
+    }
+  } // check top
+  if ( iLeft >= iSrchRngHorLeft ) // check middle left
+  {
+    xTZSearchHelp( pcPatternKey, rcStruct, iLeft, iStartY, 4, iDist );
+  }
+  if ( iRight <= iSrchRngHorRight ) // check middle right
+  {
+    xTZSearchHelp( pcPatternKey, rcStruct, iRight, iStartY, 5, iDist );
+  }
+  if ( iBottom <= iSrchRngVerBottom ) // check bottom
+  {
+    if ( iLeft >= iSrchRngHorLeft ) // check bottom left
+    {
+      xTZSearchHelp( pcPatternKey, rcStruct, iLeft, iBottom, 6, iDist );
+    }
+    // check bottom middle
+    xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iBottom, 7, iDist );
+    
+    if ( iRight <= iSrchRngHorRight ) // check bottom right
+    {
+      xTZSearchHelp( pcPatternKey, rcStruct, iRight, iBottom, 8, iDist );
+    }
+  } // check bottom
+}
+
+__inline Void TEncSearch::xTZ8PointDiamondSearch( TComPattern* pcPatternKey, IntTZSearchStruct& rcStruct, TComMv* pcMvSrchRngLT, TComMv* 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();
+  
+  // 8 point search,                   //   1 2 3
+  // search around the start point     //   4 0 5
+  // with the required  distance       //   6 7 8
+  assert ( iDist != 0 );
+  const Int iTop        = iStartY - iDist;
+  const Int iBottom     = iStartY + iDist;
+  const Int iLeft       = iStartX - iDist;
+  const Int iRight      = iStartX + iDist;
+  rcStruct.uiBestRound += 1;
+  
+  if ( iDist == 1 ) // iDist == 1
+  {
+    if ( iTop >= iSrchRngVerTop ) // check top
+    {
+      xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iTop, 2, iDist );
+    }
+    if ( iLeft >= iSrchRngHorLeft ) // check middle left
+    {
+      xTZSearchHelp( pcPatternKey, rcStruct, iLeft, iStartY, 4, iDist );
+    }
+    if ( iRight <= iSrchRngHorRight ) // check middle right
+    {
+      xTZSearchHelp( pcPatternKey, rcStruct, iRight, iStartY, 5, iDist );
+    }
+    if ( iBottom <= iSrchRngVerBottom ) // check bottom
+    {
+      xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iBottom, 7, iDist );
+    }
+  }
+  else // if (iDist != 1)
+  {
+    if ( iDist <= 8 )
+    {
+      const Int iTop_2      = iStartY - (iDist>>1);
+      const Int iBottom_2   = iStartY + (iDist>>1);
+      const Int iLeft_2     = iStartX - (iDist>>1);
+      const Int iRight_2    = iStartX + (iDist>>1);
+      
+      if (  iTop >= iSrchRngVerTop && iLeft >= iSrchRngHorLeft &&
+          iRight <= iSrchRngHorRight && iBottom <= iSrchRngVerBottom ) // check border
+      {
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX,  iTop,      2, iDist    );
+        xTZSearchHelp( pcPatternKey, rcStruct, iLeft_2,  iTop_2,    1, iDist>>1 );
+        xTZSearchHelp( pcPatternKey, rcStruct, iRight_2, iTop_2,    3, iDist>>1 );
+        xTZSearchHelp( pcPatternKey, rcStruct, iLeft,    iStartY,   4, iDist    );
+        xTZSearchHelp( pcPatternKey, rcStruct, iRight,   iStartY,   5, iDist    );
+        xTZSearchHelp( pcPatternKey, rcStruct, iLeft_2,  iBottom_2, 6, iDist>>1 );
+        xTZSearchHelp( pcPatternKey, rcStruct, iRight_2, iBottom_2, 8, iDist>>1 );
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX,  iBottom,   7, iDist    );
+      }
+      else // check border
+      {
+        if ( iTop >= iSrchRngVerTop ) // check top
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iTop, 2, iDist );
+        }
+        if ( iTop_2 >= iSrchRngVerTop ) // check half top
+        {
+          if ( iLeft_2 >= iSrchRngHorLeft ) // check half left
+          {
+            xTZSearchHelp( pcPatternKey, rcStruct, iLeft_2, iTop_2, 1, (iDist>>1) );
+          }
+          if ( iRight_2 <= iSrchRngHorRight ) // check half right
+          {
+            xTZSearchHelp( pcPatternKey, rcStruct, iRight_2, iTop_2, 3, (iDist>>1) );
+          }
+        } // check half top
+        if ( iLeft >= iSrchRngHorLeft ) // check left
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iLeft, iStartY, 4, iDist );
+        }
+        if ( iRight <= iSrchRngHorRight ) // check right
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iRight, iStartY, 5, iDist );
+        }
+        if ( iBottom_2 <= iSrchRngVerBottom ) // check half bottom
+        {
+          if ( iLeft_2 >= iSrchRngHorLeft ) // check half left
+          {
+            xTZSearchHelp( pcPatternKey, rcStruct, iLeft_2, iBottom_2, 6, (iDist>>1) );
+          }
+          if ( iRight_2 <= iSrchRngHorRight ) // check half right
+          {
+            xTZSearchHelp( pcPatternKey, rcStruct, iRight_2, iBottom_2, 8, (iDist>>1) );
+          }
+        } // check half bottom
+        if ( iBottom <= iSrchRngVerBottom ) // check bottom
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iBottom, 7, iDist );
+        }
+      } // check border
+    }
+    else // iDist > 8
+    {
+      if ( iTop >= iSrchRngVerTop && iLeft >= iSrchRngHorLeft &&
+          iRight <= iSrchRngHorRight && iBottom <= iSrchRngVerBottom ) // check border
+      {
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iTop,    0, iDist );
+        xTZSearchHelp( pcPatternKey, rcStruct, iLeft,   iStartY, 0, iDist );
+        xTZSearchHelp( pcPatternKey, rcStruct, iRight,  iStartY, 0, iDist );
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iBottom, 0, iDist );
+        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);
+          xTZSearchHelp( pcPatternKey, rcStruct, iPosXL, iPosYT, 0, iDist );
+          xTZSearchHelp( pcPatternKey, rcStruct, iPosXR, iPosYT, 0, iDist );
+          xTZSearchHelp( pcPatternKey, rcStruct, iPosXL, iPosYB, 0, iDist );
+          xTZSearchHelp( pcPatternKey, rcStruct, iPosXR, iPosYB, 0, iDist );
+        }
+      }
+      else // check border
+      {
+        if ( iTop >= iSrchRngVerTop ) // check top
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iTop, 0, iDist );
+        }
+        if ( iLeft >= iSrchRngHorLeft ) // check left
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iLeft, iStartY, 0, iDist );
+        }
+        if ( iRight <= iSrchRngHorRight ) // check right
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iRight, iStartY, 0, iDist );
+        }
+        if ( iBottom <= iSrchRngVerBottom ) // check bottom
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iBottom, 0, iDist );
+        }
+        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);
+          
+          if ( iPosYT >= iSrchRngVerTop ) // check top
+          {
+            if ( iPosXL >= iSrchRngHorLeft ) // check left
+            {
+              xTZSearchHelp( pcPatternKey, rcStruct, iPosXL, iPosYT, 0, iDist );
+            }
+            if ( iPosXR <= iSrchRngHorRight ) // check right
+            {
+              xTZSearchHelp( pcPatternKey, rcStruct, iPosXR, iPosYT, 0, iDist );
+            }
+          } // check top
+          if ( iPosYB <= iSrchRngVerBottom ) // check bottom
+          {
+            if ( iPosXL >= iSrchRngHorLeft ) // check left
+            {
+              xTZSearchHelp( pcPatternKey, rcStruct, iPosXL, iPosYB, 0, iDist );
+            }
+            if ( iPosXR <= iSrchRngHorRight ) // check right
+            {
+              xTZSearchHelp( pcPatternKey, rcStruct, iPosXR, iPosYB, 0, iDist );
+            }
+          } // check bottom
+        } // for ...
+      } // check border
+    } // iDist <= 8
+  } // iDist == 1
+}
+
+//<--
+
+UInt TEncSearch::xPatternRefinement( TComPattern* pcPatternKey,
+                                    TComMv baseRefMv,
+                                    Int iFrac, TComMv& rcMvFrac )
+{
+  UInt  uiDist;
+  UInt  uiDistBest  = MAX_UINT;
+  UInt  uiDirecBest = 0;
+  
+  Pel*  piRefPos;
+  Int iRefStride = m_filteredBlock[0][0].getStride();
+#if NS_HAD
+  m_pcRdCost->setDistParam( pcPatternKey, m_filteredBlock[0][0].getLumaAddr(), iRefStride, 1, m_cDistParam, m_pcEncCfg->getUseHADME(), m_pcEncCfg->getUseNSQT() );
+#else
+  m_pcRdCost->setDistParam( pcPatternKey, m_filteredBlock[0][0].getLumaAddr(), iRefStride, 1, m_cDistParam, m_pcEncCfg->getUseHADME() );
+#endif
+  
+  const TComMv* pcMvRefine = (iFrac == 2 ? s_acMvRefineH : s_acMvRefineQ);
+  
+  for (UInt i = 0; i < 9; i++)
+  {
+    TComMv cMvTest = pcMvRefine[i];
+    cMvTest += baseRefMv;
+    
+    Int horVal = cMvTest.getHor() * iFrac;
+    Int verVal = cMvTest.getVer() * iFrac;
+    piRefPos = m_filteredBlock[ verVal & 3 ][ horVal & 3 ].getLumaAddr();
+    if ( horVal == 2 && ( verVal & 1 ) == 0 )
+      piRefPos += 1;
+    if ( ( horVal & 1 ) == 0 && verVal == 2 )
+      piRefPos += iRefStride;
+    cMvTest = pcMvRefine[i];
+    cMvTest += rcMvFrac;
+
+    setDistParamComp(0);  // Y component
+
+    m_cDistParam.pCur = piRefPos;
+    uiDist = m_cDistParam.DistFunc( &m_cDistParam );
+    uiDist += m_pcRdCost->getCost( cMvTest.getHor(), cMvTest.getVer() );
+    
+    if ( uiDist < uiDistBest )
+    {
+      uiDistBest  = uiDist;
+      uiDirecBest = i;
+    }
+  }
+  
+  rcMvFrac = pcMvRefine[uiDirecBest];
+  
+  return uiDistBest;
+}
+
+Void
+TEncSearch::xEncSubdivCbfQT( TComDataCU*  pcCU,
+                            UInt         uiTrDepth,
+                            UInt         uiAbsPartIdx,
+                            Bool         bLuma,
+                            Bool         bChroma )
+{
+  UInt  uiFullDepth     = pcCU->getDepth(0) + uiTrDepth;
+  UInt  uiTrMode        = pcCU->getTransformIdx( uiAbsPartIdx );
+  UInt  uiSubdiv        = ( uiTrMode > uiTrDepth ? 1 : 0 );
+  UInt  uiLog2TrafoSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth()] + 2 - uiFullDepth;
+
+  {
+    if( pcCU->getPredictionMode(0) == MODE_INTRA && pcCU->getPartitionSize(0) == SIZE_NxN && uiTrDepth == 0 )
+    {
+      assert( uiSubdiv );
+    }
+    else if( uiLog2TrafoSize > pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() )
+    {
+      assert( uiSubdiv );
+    }
+    else if( uiLog2TrafoSize == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+    {
+      assert( !uiSubdiv );
+    }
+    else if( uiLog2TrafoSize == pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
+    {
+      assert( !uiSubdiv );
+    }
+    else
+    {
+      assert( uiLog2TrafoSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) );
+      if( bLuma )
+      {
+#if TRANS_SPLIT_FLAG_CTX_REDUCTION
+        m_pcEntropyCoder->encodeTransformSubdivFlag( uiSubdiv, 5 - uiLog2TrafoSize );
+#else
+        m_pcEntropyCoder->encodeTransformSubdivFlag( uiSubdiv, uiFullDepth );
+#endif
+      }
+    }
+  }
+  
+  if ( bChroma )
+  {
+    if( uiLog2TrafoSize > 2 )
+    {
+      if( uiTrDepth==0 || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth-1 ) )
+        m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth );
+      if( uiTrDepth==0 || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth-1 ) )
+        m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth );
+    }
+  }
+
+  if( uiSubdiv )
+  {
+    UInt uiQPartNum = pcCU->getPic()->getNumPartInCU() >> ( ( uiFullDepth + 1 ) << 1 );
+    for( UInt uiPart = 0; uiPart < 4; uiPart++ )
+    {
+      xEncSubdivCbfQT( pcCU, uiTrDepth + 1, uiAbsPartIdx + uiPart * uiQPartNum, bLuma, bChroma );
+    }
+    return;
+  }
+  
+  {
+    //===== Cbfs =====
+    if( bLuma )
+    {
+      m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
+    }
+  }
+}
+
+Void
+TEncSearch::xEncCoeffQT( TComDataCU*  pcCU,
+                        UInt         uiTrDepth,
+                        UInt         uiAbsPartIdx,
+                        TextType     eTextType,
+                        Bool         bRealCoeff )
+{
+  UInt  uiFullDepth     = pcCU->getDepth(0) + uiTrDepth;
+  UInt  uiTrMode        = pcCU->getTransformIdx( uiAbsPartIdx );
+  UInt  uiSubdiv        = ( uiTrMode > uiTrDepth ? 1 : 0 );
+  UInt  uiLog2TrafoSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth()] + 2 - uiFullDepth;
+  UInt  uiChroma        = ( eTextType != TEXT_LUMA ? 1 : 0 );
+  
+  if( uiSubdiv )
+  {
+    UInt uiQPartNum = pcCU->getPic()->getNumPartInCU() >> ( ( uiFullDepth + 1 ) << 1 );
+      for( UInt uiPart = 0; uiPart < 4; uiPart++ )
+      {
+        xEncCoeffQT( pcCU, uiTrDepth + 1, uiAbsPartIdx + uiPart * uiQPartNum, eTextType, bRealCoeff );
+      }
+    return;
+  }
+  
+  if( eTextType != TEXT_LUMA && uiLog2TrafoSize == 2 )
+  {
+    assert( uiTrDepth > 0 );
+    uiTrDepth--;
+    UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrDepth ) << 1 );
+    Bool bFirstQ = ( ( uiAbsPartIdx % uiQPDiv ) == 0 );
+    if( !bFirstQ )
+    {
+      return;
+    }
+  }
+  
+  //===== coefficients =====
+  UInt    uiWidth         = pcCU->getWidth  ( 0 ) >> ( uiTrDepth + uiChroma );
+  UInt    uiHeight        = pcCU->getHeight ( 0 ) >> ( uiTrDepth + uiChroma );
+  UInt    uiCoeffOffset   = ( pcCU->getPic()->getMinCUWidth() * pcCU->getPic()->getMinCUHeight() * uiAbsPartIdx ) >> ( uiChroma << 1 );
+  UInt    uiQTLayer       = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrafoSize;
+  TCoeff* pcCoeff         = 0;
+  switch( eTextType )
+  {
+    case TEXT_LUMA:     pcCoeff = ( bRealCoeff ? pcCU->getCoeffY () : m_ppcQTTempCoeffY [uiQTLayer] );  break;
+    case TEXT_CHROMA_U: pcCoeff = ( bRealCoeff ? pcCU->getCoeffCb() : m_ppcQTTempCoeffCb[uiQTLayer] );  break;
+    case TEXT_CHROMA_V: pcCoeff = ( bRealCoeff ? pcCU->getCoeffCr() : m_ppcQTTempCoeffCr[uiQTLayer] );  break;
+    default:            assert(0);
+  }
+  pcCoeff += uiCoeffOffset;
+  
+  m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeff, uiAbsPartIdx, uiWidth, uiHeight, uiFullDepth, eTextType );
+}
+
+
+Void
+TEncSearch::xEncIntraHeader( TComDataCU*  pcCU,
+                            UInt         uiTrDepth,
+                            UInt         uiAbsPartIdx,
+                            Bool         bLuma,
+                            Bool         bChroma )
+{
+#if INTRA_BL
+  if ( pcCU->isIntraBL( 0 ))
+  {
+    return;
+  }
+#endif
+
+  if( bLuma )
+  {
+    // CU header
+    if( uiAbsPartIdx == 0 )
+    {
+      if( !pcCU->getSlice()->isIntra() )
+      {
+        if (pcCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
+        {
+          m_pcEntropyCoder->encodeCUTransquantBypassFlag( pcCU, 0, true );
+        }
+        m_pcEntropyCoder->encodeSkipFlag( pcCU, 0, true );
+        m_pcEntropyCoder->encodePredMode( pcCU, 0, true );
+      }
+#if INTRA_BL
+      m_pcEntropyCoder->encodeIntraBLFlag ( pcCU, 0, true );
+#endif
+      
+      m_pcEntropyCoder  ->encodePartSize( pcCU, 0, pcCU->getDepth(0), true );
+
+      if (pcCU->isIntra(0) && pcCU->getPartitionSize(0) == SIZE_2Nx2N )
+      {
+        m_pcEntropyCoder->encodeIPCMInfo( pcCU, 0, true );
+
+        if ( pcCU->getIPCMFlag (0))
+        {
+          return;
+        }
+      }
+    }
+    // luma prediction mode
+    if( pcCU->getPartitionSize(0) == SIZE_2Nx2N )
+    {
+      if( uiAbsPartIdx == 0 )
+      {
+        m_pcEntropyCoder->encodeIntraDirModeLuma ( pcCU, 0 );
+      }
+    }
+    else
+    {
+      UInt uiQNumParts = pcCU->getTotalNumPart() >> 2;
+      if( uiTrDepth == 0 )
+      {
+        assert( uiAbsPartIdx == 0 );
+        for( UInt uiPart = 0; uiPart < 4; uiPart++ )
+        {
+          m_pcEntropyCoder->encodeIntraDirModeLuma ( pcCU, uiPart * uiQNumParts );
+        }
+      }
+      else if( ( uiAbsPartIdx % uiQNumParts ) == 0 )
+      {
+        m_pcEntropyCoder->encodeIntraDirModeLuma ( pcCU, uiAbsPartIdx );
+      }
+    }
+  }
+  if( bChroma )
+  {
+    // chroma prediction mode
+    if( uiAbsPartIdx == 0 )
+    {
+      m_pcEntropyCoder->encodeIntraDirModeChroma( pcCU, 0, true );
+    }
+  }
+}
+
+
+UInt
+TEncSearch::xGetIntraBitsQT( TComDataCU*  pcCU,
+                            UInt         uiTrDepth,
+                            UInt         uiAbsPartIdx,
+                            Bool         bLuma,
+                            Bool         bChroma,
+                            Bool         bRealCoeff /* just for test */ )
+{
+  m_pcEntropyCoder->resetBits();
+  xEncIntraHeader ( pcCU, uiTrDepth, uiAbsPartIdx, bLuma, bChroma );
+  xEncSubdivCbfQT ( pcCU, uiTrDepth, uiAbsPartIdx, bLuma, bChroma );
+  
+  if( bLuma )
+  {
+    xEncCoeffQT   ( pcCU, uiTrDepth, uiAbsPartIdx, TEXT_LUMA,      bRealCoeff );
+  }
+  if( bChroma )
+  {
+    xEncCoeffQT   ( pcCU, uiTrDepth, uiAbsPartIdx, TEXT_CHROMA_U,  bRealCoeff );
+    xEncCoeffQT   ( pcCU, uiTrDepth, uiAbsPartIdx, TEXT_CHROMA_V,  bRealCoeff );
+  }
+  UInt   uiBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+  return uiBits;
+}
+
+UInt
+TEncSearch::xGetIntraBitsQTChroma( TComDataCU*  pcCU,
+                                  UInt         uiTrDepth,
+                                  UInt         uiAbsPartIdx,
+                                  UInt         uiChromaId,
+                                  Bool         bRealCoeff /* just for test */ )
+{
+  m_pcEntropyCoder->resetBits();
+  if( uiChromaId == TEXT_CHROMA_U)
+  {
+    xEncCoeffQT   ( pcCU, uiTrDepth, uiAbsPartIdx, TEXT_CHROMA_U,  bRealCoeff );
+  }
+  else if(uiChromaId == TEXT_CHROMA_V)
+  {
+    xEncCoeffQT   ( pcCU, uiTrDepth, uiAbsPartIdx, TEXT_CHROMA_V,  bRealCoeff );
+  }
+
+  UInt   uiBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+  return uiBits;
+}
+
+Void
+TEncSearch::xIntraCodingLumaBlk( TComDataCU* pcCU,
+                                UInt        uiTrDepth,
+                                UInt        uiAbsPartIdx,
+                                TComYuv*    pcOrgYuv, 
+                                TComYuv*    pcPredYuv, 
+                                TComYuv*    pcResiYuv, 
+                                UInt&       ruiDist,
+                                Int        default0Save1Load2 )
+{
+  UInt    uiLumaPredMode    = pcCU     ->getLumaIntraDir     ( uiAbsPartIdx );
+  UInt    uiFullDepth       = pcCU     ->getDepth   ( 0 )  + uiTrDepth;
+  UInt    uiWidth           = pcCU     ->getWidth   ( 0 ) >> uiTrDepth;
+  UInt    uiHeight          = pcCU     ->getHeight  ( 0 ) >> uiTrDepth;
+  UInt    uiStride          = pcOrgYuv ->getStride  ();
+  Pel*    piOrg             = pcOrgYuv ->getLumaAddr( uiAbsPartIdx );
+  Pel*    piPred            = pcPredYuv->getLumaAddr( uiAbsPartIdx );
+  Pel*    piResi            = pcResiYuv->getLumaAddr( uiAbsPartIdx );
+  Pel*    piReco            = pcPredYuv->getLumaAddr( uiAbsPartIdx );
+  
+  UInt    uiLog2TrSize      = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiFullDepth ] + 2;
+  UInt    uiQTLayer         = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+  UInt    uiNumCoeffPerInc  = pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() >> ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 );
+  TCoeff* pcCoeff           = m_ppcQTTempCoeffY[ uiQTLayer ] + uiNumCoeffPerInc * uiAbsPartIdx;
+#if ADAPTIVE_QP_SELECTION
+  Int*    pcArlCoeff        = m_ppcQTTempArlCoeffY[ uiQTLayer ] + uiNumCoeffPerInc * uiAbsPartIdx;
+#endif
+  Pel*    piRecQt           = m_pcQTTempTComYuv[ uiQTLayer ].getLumaAddr( uiAbsPartIdx );
+  UInt    uiRecQtStride     = m_pcQTTempTComYuv[ uiQTLayer ].getStride  ();
+  
+  UInt    uiZOrder          = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
+  Pel*    piRecIPred        = pcCU->getPic()->getPicYuvRec()->getLumaAddr( pcCU->getAddr(), uiZOrder );
+  UInt    uiRecIPredStride  = pcCU->getPic()->getPicYuvRec()->getStride  ();
+  Bool    useTransformSkip  = pcCU->getTransformSkip(uiAbsPartIdx, TEXT_LUMA);
+  //===== init availability pattern =====
+  Bool  bAboveAvail = false;
+  Bool  bLeftAvail  = false;
+  if(default0Save1Load2 != 2)
+  {
+    pcCU->getPattern()->initPattern   ( pcCU, uiTrDepth, uiAbsPartIdx );
+    pcCU->getPattern()->initAdiPattern( pcCU, uiAbsPartIdx, uiTrDepth, m_piYuvExt, m_iYuvExtStride, m_iYuvExtHeight, bAboveAvail, bLeftAvail );
+    //===== get prediction signal =====
+#if INTRA_BL
+    if(pcCU->isIntraBL ( uiAbsPartIdx ) )
+    {
+      pcCU->getBaseLumaBlk( uiWidth, uiHeight, uiAbsPartIdx, piPred, uiStride );
+    }
+    else
+#endif
+    {
+      predIntraLumaAng( pcCU->getPattern(), uiLumaPredMode, piPred, uiStride, uiWidth, uiHeight, pcCU, bAboveAvail, bLeftAvail );
+    }
+    // save prediction 
+    if(default0Save1Load2 == 1)
+    {
+      Pel*  pPred   = piPred;
+      Pel*  pPredBuf = m_pSharedPredTransformSkip[0];
+      Int k = 0;
+      for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+      {
+        for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+        {
+          pPredBuf[ k ++ ] = pPred[ uiX ];
+        }
+        pPred += uiStride;
+      }
+    }
+  }
+  else 
+  {
+    // load prediction
+    Pel*  pPred   = piPred;
+    Pel*  pPredBuf = m_pSharedPredTransformSkip[0];
+    Int k = 0;
+    for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+    {
+      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+      {
+        pPred[ uiX ] = pPredBuf[ k ++ ];
+      }
+      pPred += uiStride;
+    }
+  }
+  //===== get residual signal =====
+  {
+    // get residual
+    Pel*  pOrg    = piOrg;
+    Pel*  pPred   = piPred;
+    Pel*  pResi   = piResi;
+    for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+    {
+      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+      {
+        pResi[ uiX ] = pOrg[ uiX ] - pPred[ uiX ];
+      }
+      pOrg  += uiStride;
+      pResi += uiStride;
+      pPred += uiStride;
+    }
+  }
+  
+  //===== transform and quantization =====
+  //--- init rate estimation arrays for RDOQ ---
+  if(m_pcEncCfg->getUseRDOQ() && useTransformSkip == false)
+  {
+    m_pcEntropyCoder->estimateBit( m_pcTrQuant->m_pcEstBitsSbac, uiWidth, uiWidth, TEXT_LUMA );
+  }
+  //--- transform and quantization ---
+  UInt uiAbsSum = 0;
+  pcCU       ->setTrIdxSubParts ( uiTrDepth, uiAbsPartIdx, uiFullDepth );
+
+  m_pcTrQuant->setQPforQuant    ( pcCU->getQP( 0 ), TEXT_LUMA, pcCU->getSlice()->getSPS()->getQpBDOffsetY(), 0 );
+
+#if RDOQ_CHROMA_LAMBDA 
+  m_pcTrQuant->selectLambda     (TEXT_LUMA);  
+#endif
+
+  m_pcTrQuant->transformNxN     ( pcCU, piResi, uiStride, pcCoeff, 
+#if ADAPTIVE_QP_SELECTION
+    pcArlCoeff, 
+#endif
+    uiWidth, uiHeight, uiAbsSum, TEXT_LUMA, uiAbsPartIdx,useTransformSkip );
+  
+  //--- set coded block flag ---
+  pcCU->setCbfSubParts          ( ( uiAbsSum ? 1 : 0 ) << uiTrDepth, TEXT_LUMA, uiAbsPartIdx, uiFullDepth );
+  //--- inverse transform ---
+  if( uiAbsSum )
+  {
+    Int scalingListType = 0 + g_eTTable[(Int)TEXT_LUMA];
+    assert(scalingListType < 6);
+    m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_LUMA,pcCU->getLumaIntraDir( uiAbsPartIdx ), piResi, uiStride, pcCoeff, uiWidth, uiHeight, scalingListType, useTransformSkip );
+  }
+  else
+  {
+    Pel* pResi = piResi;
+    memset( pcCoeff, 0, sizeof( TCoeff ) * uiWidth * uiHeight );
+    for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+    {
+      memset( pResi, 0, sizeof( Pel ) * uiWidth );
+      pResi += uiStride;
+    }
+  }
+  
+  //===== reconstruction =====
+  {
+    Pel* pPred      = piPred;
+    Pel* pResi      = piResi;
+    Pel* pReco      = piReco;
+    Pel* pRecQt     = piRecQt;
+    Pel* pRecIPred  = piRecIPred;
+    for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+    {
+      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+      {
+        pReco    [ uiX ] = Clip( pPred[ uiX ] + pResi[ uiX ] );
+        pRecQt   [ uiX ] = pReco[ uiX ];
+        pRecIPred[ uiX ] = pReco[ uiX ];
+      }
+      pPred     += uiStride;
+      pResi     += uiStride;
+      pReco     += uiStride;
+      pRecQt    += uiRecQtStride;
+      pRecIPred += uiRecIPredStride;
+    }
+  }
+  
+  //===== update distortion =====
+  ruiDist += m_pcRdCost->getDistPart( piReco, uiStride, piOrg, uiStride, uiWidth, uiHeight );
+}
+
+Void
+TEncSearch::xIntraCodingChromaBlk( TComDataCU* pcCU,
+                                  UInt        uiTrDepth,
+                                  UInt        uiAbsPartIdx,
+                                  TComYuv*    pcOrgYuv, 
+                                  TComYuv*    pcPredYuv, 
+                                  TComYuv*    pcResiYuv, 
+                                  UInt&       ruiDist,
+                                  UInt        uiChromaId,
+                                  Int        default0Save1Load2 )
+{
+  UInt uiOrgTrDepth = uiTrDepth;
+  UInt uiFullDepth  = pcCU->getDepth( 0 ) + uiTrDepth;
+  UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiFullDepth ] + 2;
+  if( uiLog2TrSize == 2 )
+  {
+    assert( uiTrDepth > 0 );
+    uiTrDepth--;
+    UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrDepth ) << 1 );
+    Bool bFirstQ = ( ( uiAbsPartIdx % uiQPDiv ) == 0 );
+    if( !bFirstQ )
+    {
+      return;
+    }
+  }
+  
+  TextType  eText             = ( uiChromaId > 0 ? TEXT_CHROMA_V : TEXT_CHROMA_U );
+  UInt      uiChromaPredMode  = pcCU     ->getChromaIntraDir( uiAbsPartIdx );
+  UInt      uiWidth           = pcCU     ->getWidth   ( 0 ) >> ( uiTrDepth + 1 );
+  UInt      uiHeight          = pcCU     ->getHeight  ( 0 ) >> ( uiTrDepth + 1 );
+  UInt      uiStride          = pcOrgYuv ->getCStride ();
+  Pel*      piOrg             = ( uiChromaId > 0 ? pcOrgYuv ->getCrAddr( uiAbsPartIdx ) : pcOrgYuv ->getCbAddr( uiAbsPartIdx ) );
+  Pel*      piPred            = ( uiChromaId > 0 ? pcPredYuv->getCrAddr( uiAbsPartIdx ) : pcPredYuv->getCbAddr( uiAbsPartIdx ) );
+  Pel*      piResi            = ( uiChromaId > 0 ? pcResiYuv->getCrAddr( uiAbsPartIdx ) : pcResiYuv->getCbAddr( uiAbsPartIdx ) );
+  Pel*      piReco            = ( uiChromaId > 0 ? pcPredYuv->getCrAddr( uiAbsPartIdx ) : pcPredYuv->getCbAddr( uiAbsPartIdx ) );
+  
+  UInt      uiQTLayer         = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+  UInt      uiNumCoeffPerInc  = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() >> ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 ) ) >> 2;
+  TCoeff*   pcCoeff           = ( uiChromaId > 0 ? m_ppcQTTempCoeffCr[ uiQTLayer ] : m_ppcQTTempCoeffCb[ uiQTLayer ] ) + uiNumCoeffPerInc * uiAbsPartIdx;
+#if ADAPTIVE_QP_SELECTION
+  Int*      pcArlCoeff        = ( uiChromaId > 0 ? m_ppcQTTempArlCoeffCr[ uiQTLayer ] : m_ppcQTTempArlCoeffCb[ uiQTLayer ] ) + uiNumCoeffPerInc * uiAbsPartIdx;
+#endif
+  Pel*      piRecQt           = ( uiChromaId > 0 ? m_pcQTTempTComYuv[ uiQTLayer ].getCrAddr( uiAbsPartIdx ) : m_pcQTTempTComYuv[ uiQTLayer ].getCbAddr( uiAbsPartIdx ) );
+  UInt      uiRecQtStride     = m_pcQTTempTComYuv[ uiQTLayer ].getCStride();
+  
+  UInt      uiZOrder          = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
+  Pel*      piRecIPred        = ( uiChromaId > 0 ? pcCU->getPic()->getPicYuvRec()->getCrAddr( pcCU->getAddr(), uiZOrder ) : pcCU->getPic()->getPicYuvRec()->getCbAddr( pcCU->getAddr(), uiZOrder ) );
+  UInt      uiRecIPredStride  = pcCU->getPic()->getPicYuvRec()->getCStride();
+  Bool      useTransformSkipChroma       = pcCU->getTransformSkip(uiAbsPartIdx, eText);
+  //===== update chroma mode =====
+  if( uiChromaPredMode == DM_CHROMA_IDX )
+  {
+    uiChromaPredMode          = pcCU->getLumaIntraDir( 0 );
+  }
+  
+  //===== init availability pattern =====
+  Bool  bAboveAvail = false;
+  Bool  bLeftAvail  = false;
+  if( default0Save1Load2 != 2 )
+  {
+    pcCU->getPattern()->initPattern         ( pcCU, uiTrDepth, uiAbsPartIdx );
+
+#if !REMOVE_LMCHROMA
+    if( uiChromaPredMode == LM_CHROMA_IDX && uiChromaId == 0 )
+    {
+      pcCU->getPattern()->initAdiPattern( pcCU, uiAbsPartIdx, uiTrDepth, m_piYuvExt, m_iYuvExtStride, m_iYuvExtHeight, bAboveAvail, bLeftAvail, true );
+      getLumaRecPixels( pcCU->getPattern(), uiWidth, uiHeight );
+    }
+#endif
+    
+    pcCU->getPattern()->initAdiPatternChroma( pcCU, uiAbsPartIdx, uiTrDepth, m_piYuvExt, m_iYuvExtStride, m_iYuvExtHeight, bAboveAvail, bLeftAvail );
+    Int*  pPatChroma  = ( uiChromaId > 0 ? pcCU->getPattern()->getAdiCrBuf( uiWidth, uiHeight, m_piYuvExt ) : pcCU->getPattern()->getAdiCbBuf( uiWidth, uiHeight, m_piYuvExt ) );
+
+    //===== get prediction signal =====
+#if INTRA_BL
+  if(pcCU->isIntraBL ( uiAbsPartIdx ) )
+  {
+    pcCU->getBaseChromaBlk( uiWidth, uiHeight, uiAbsPartIdx, piPred, uiStride, uiChromaId );
+  }
+  else
+#endif
+#if !REMOVE_LMCHROMA
+    if( uiChromaPredMode == LM_CHROMA_IDX )
+    {
+      predLMIntraChroma( pcCU->getPattern(), pPatChroma, piPred, uiStride, uiWidth, uiHeight, uiChromaId );
+    }
+    else
+#endif
+    {
+      predIntraChromaAng( pcCU->getPattern(), pPatChroma, uiChromaPredMode, piPred, uiStride, uiWidth, uiHeight, pcCU, bAboveAvail, bLeftAvail );  
+    }
+
+    // save prediction 
+    if( default0Save1Load2 == 1 )
+    {
+      Pel*  pPred   = piPred;
+      Pel*  pPredBuf = m_pSharedPredTransformSkip[1 + uiChromaId];
+      Int k = 0;
+      for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+      {
+        for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+        {
+          pPredBuf[ k ++ ] = pPred[ uiX ];
+        }
+        pPred += uiStride;
+      }
+    }
+  }
+  else
+  {
+    // load prediction 
+    Pel*  pPred   = piPred;
+    Pel*  pPredBuf = m_pSharedPredTransformSkip[1 + uiChromaId];
+    Int k = 0;
+    for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+    {
+      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+      {
+        pPred[ uiX ] = pPredBuf[ k ++ ];
+      }
+      pPred += uiStride;
+    }
+  }
+  //===== get residual signal =====
+  {
+    // get residual
+    Pel*  pOrg    = piOrg;
+    Pel*  pPred   = piPred;
+    Pel*  pResi   = piResi;
+    for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+    {
+      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+      {
+        pResi[ uiX ] = pOrg[ uiX ] - pPred[ uiX ];
+      }
+      pOrg  += uiStride;
+      pResi += uiStride;
+      pPred += uiStride;
+    }
+  }
+  
+  //===== transform and quantization =====
+  {
+    //--- init rate estimation arrays for RDOQ ---
+    if( m_pcEncCfg->getUseRDOQ() && !useTransformSkipChroma)
+    {
+      m_pcEntropyCoder->estimateBit( m_pcTrQuant->m_pcEstBitsSbac, uiWidth, uiWidth, eText );
+    }
+    //--- transform and quantization ---
+    UInt uiAbsSum = 0;
+
+#if CHROMA_QP_EXTENSION
+    Int curChromaQpOffset;
+    if(eText == TEXT_CHROMA_U)
+    {
+      curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCbQpOffset() + pcCU->getSlice()->getSliceQpDeltaCb();
+    }
+    else
+    {
+      curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCrQpOffset() + pcCU->getSlice()->getSliceQpDeltaCr();
+    }
+    m_pcTrQuant->setQPforQuant     ( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
+#else
+    if(eText == TEXT_CHROMA_U)
+    {
+      m_pcTrQuant->setQPforQuant     ( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), pcCU->getSlice()->getPPS()->getChromaCbQpOffset() );
+    }
+    else
+    {
+      m_pcTrQuant->setQPforQuant     ( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), pcCU->getSlice()->getPPS()->getChromaCrQpOffset() );
+    }
+#endif
+
+#if RDOQ_CHROMA_LAMBDA 
+    m_pcTrQuant->selectLambda      (TEXT_CHROMA);  
+#endif
+    m_pcTrQuant->transformNxN      ( pcCU, piResi, uiStride, pcCoeff, 
+#if ADAPTIVE_QP_SELECTION
+                                     pcArlCoeff, 
+#endif
+                                     uiWidth, uiHeight, uiAbsSum, eText, uiAbsPartIdx, useTransformSkipChroma );
+    //--- set coded block flag ---
+    pcCU->setCbfSubParts           ( ( uiAbsSum ? 1 : 0 ) << uiOrgTrDepth, eText, uiAbsPartIdx, pcCU->getDepth(0) + uiTrDepth );
+    //--- inverse transform ---
+    if( uiAbsSum )
+    {
+      Int scalingListType = 0 + g_eTTable[(Int)eText];
+      assert(scalingListType < 6);
+      m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_CHROMA, REG_DCT, piResi, uiStride, pcCoeff, uiWidth, uiHeight, scalingListType, useTransformSkipChroma );
+    }
+    else
+    {
+      Pel* pResi = piResi;
+      memset( pcCoeff, 0, sizeof( TCoeff ) * uiWidth * uiHeight );
+      for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+      {
+        memset( pResi, 0, sizeof( Pel ) * uiWidth );
+        pResi += uiStride;
+      }
+    }
+  }
+  
+  //===== reconstruction =====
+  {
+    Pel* pPred      = piPred;
+    Pel* pResi      = piResi;
+    Pel* pReco      = piReco;
+    Pel* pRecQt     = piRecQt;
+    Pel* pRecIPred  = piRecIPred;
+    for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+    {
+      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+      {
+        pReco    [ uiX ] = Clip( pPred[ uiX ] + pResi[ uiX ] );
+        pRecQt   [ uiX ] = pReco[ uiX ];
+        pRecIPred[ uiX ] = pReco[ uiX ];
+      }
+      pPred     += uiStride;
+      pResi     += uiStride;
+      pReco     += uiStride;
+      pRecQt    += uiRecQtStride;
+      pRecIPred += uiRecIPredStride;
+    }
+  }
+  
+  //===== update distortion =====
+#if WEIGHTED_CHROMA_DISTORTION
+  ruiDist += m_pcRdCost->getDistPart( piReco, uiStride, piOrg, uiStride, uiWidth, uiHeight, true );
+#else
+  ruiDist += m_pcRdCost->getDistPart( piReco, uiStride, piOrg, uiStride, uiWidth, uiHeight );
+#endif
+}
+
+
+
+Void 
+TEncSearch::xRecurIntraCodingQT( TComDataCU*  pcCU, 
+                                UInt         uiTrDepth,
+                                UInt         uiAbsPartIdx, 
+                                Bool         bLumaOnly,
+                                TComYuv*     pcOrgYuv, 
+                                TComYuv*     pcPredYuv, 
+                                TComYuv*     pcResiYuv, 
+                                UInt&        ruiDistY,
+                                UInt&        ruiDistC,
+#if HHI_RQT_INTRA_SPEEDUP
+                                Bool         bCheckFirst,
+#endif
+                                Double&      dRDCost )
+{
+  UInt    uiFullDepth   = pcCU->getDepth( 0 ) +  uiTrDepth;
+  UInt    uiLog2TrSize  = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiFullDepth ] + 2;
+  Bool    bCheckFull    = ( uiLog2TrSize  <= pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() );
+  Bool    bCheckSplit   = ( uiLog2TrSize  >  pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) );
+  
+#if HHI_RQT_INTRA_SPEEDUP
+  if( bCheckFirst && bCheckFull )
+  {
+    bCheckSplit = false;
+  }
+#endif
+  Double  dSingleCost   = MAX_DOUBLE;
+  UInt    uiSingleDistY = 0;
+  UInt    uiSingleDistC = 0;
+  UInt    uiSingleCbfY  = 0;
+  UInt    uiSingleCbfU  = 0;
+  UInt    uiSingleCbfV  = 0;
+#if PPS_TS_FLAG
+  Bool    checkTransformSkip  = pcCU->getSlice()->getPPS()->getUseTransformSkip();
+#else
+  Bool    checkTransformSkip  = pcCU->getSlice()->getSPS()->getUseTransformSkip();
+#endif 
+  UInt    widthTransformSkip  = pcCU->getWidth ( 0 ) >> uiTrDepth;
+  UInt    heightTransformSkip = pcCU->getHeight( 0 ) >> uiTrDepth;
+  Int     bestModeId    = 0;
+  Int     bestModeIdUV[2] = {0, 0};
+  checkTransformSkip         &= (widthTransformSkip == 4 && heightTransformSkip == 4);
+  checkTransformSkip         &= (!pcCU->getCUTransquantBypass(0));
+  checkTransformSkip         &= (!((pcCU->getQP( 0 ) == 0) && (pcCU->getSlice()->getSPS()->getUseLossless())));
+#if INTRA_TRANSFORMSKIP_FAST
+  if ( m_pcEncCfg->getUseTransformSkipFast() )
+  {
+    checkTransformSkip       &= (pcCU->getPartitionSize(uiAbsPartIdx)==SIZE_NxN);
+  }
+#endif
+  if( bCheckFull )
+  {
+    if(checkTransformSkip == true)
+    {
+      //----- store original entropy coding status -----
+      if( m_bUseSBACRD)
+      {
+        m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
+      }
+      UInt   singleDistYTmp     = 0;
+      UInt   singleDistCTmp     = 0;
+      UInt   singleCbfYTmp      = 0;
+      UInt   singleCbfUTmp      = 0;
+      UInt   singleCbfVTmp      = 0;
+      Double singleCostTmp      = 0;
+      Int    default0Save1Load2 = 0;
+      Int    firstCheckId       = 0;
+
+      UInt   uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + (uiTrDepth - 1) ) << 1 );
+      Bool   bFirstQ = ( ( uiAbsPartIdx % uiQPDiv ) == 0 );
+
+      for(Int modeId = firstCheckId; modeId < 2; modeId ++)
+      {
+        singleDistYTmp = 0;
+        singleDistCTmp = 0;
+        pcCU ->setTransformSkipSubParts ( modeId, TEXT_LUMA, uiAbsPartIdx, uiFullDepth ); 
+        if(modeId == firstCheckId)
+        {
+          default0Save1Load2 = 1;
+        }
+        else
+        {
+          default0Save1Load2 = 2;
+        }
+        //----- code luma block with given intra prediction mode and store Cbf-----
+        xIntraCodingLumaBlk( pcCU, uiTrDepth, uiAbsPartIdx, pcOrgYuv, pcPredYuv, pcResiYuv, singleDistYTmp,default0Save1Load2); 
+        singleCbfYTmp = pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA, uiTrDepth );
+        //----- code chroma blocks with given intra prediction mode and store Cbf-----
+        if( !bLumaOnly )
+        {
+          if(bFirstQ)
+          {
+            pcCU ->setTransformSkipSubParts ( modeId, TEXT_CHROMA_U, uiAbsPartIdx, uiFullDepth); 
+            pcCU ->setTransformSkipSubParts ( modeId, TEXT_CHROMA_V, uiAbsPartIdx, uiFullDepth); 
+          }
+          xIntraCodingChromaBlk ( pcCU, uiTrDepth, uiAbsPartIdx, pcOrgYuv, pcPredYuv, pcResiYuv, singleDistCTmp, 0, default0Save1Load2); 
+          xIntraCodingChromaBlk ( pcCU, uiTrDepth, uiAbsPartIdx, pcOrgYuv, pcPredYuv, pcResiYuv, singleDistCTmp, 1, default0Save1Load2); 
+          singleCbfUTmp = pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth );
+          singleCbfVTmp = pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth );
+        }
+        //----- determine rate and r-d cost -----
+        if(modeId == 1 && singleCbfYTmp == 0)
+        {
+          //In order not to code TS flag when cbf is zero, the case for TS with cbf being zero is forbidden.
+          singleCostTmp = MAX_DOUBLE; 
+        }
+        else
+        {
+          UInt uiSingleBits = xGetIntraBitsQT( pcCU, uiTrDepth, uiAbsPartIdx, true, !bLumaOnly, false );
+          singleCostTmp     = m_pcRdCost->calcRdCost( uiSingleBits, singleDistYTmp + singleDistCTmp );
+        }
+
+        if(singleCostTmp < dSingleCost)
+        {
+          dSingleCost   = singleCostTmp;
+          uiSingleDistY = singleDistYTmp;
+          uiSingleDistC = singleDistCTmp;
+          uiSingleCbfY  = singleCbfYTmp;
+          uiSingleCbfU  = singleCbfUTmp;
+          uiSingleCbfV  = singleCbfVTmp;
+          bestModeId    = modeId;
+          if(bestModeId == firstCheckId)
+          {
+            xStoreIntraResultQT(pcCU, uiTrDepth, uiAbsPartIdx,bLumaOnly );
+            if( m_bUseSBACRD) 
+            {
+              m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_TEMP_BEST ] );
+            }
+          }
+        }
+        if(modeId == firstCheckId)
+        {
+          m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
+        }
+      }
+
+      pcCU ->setTransformSkipSubParts ( bestModeId, TEXT_LUMA, uiAbsPartIdx, uiFullDepth ); 
+
+      if(bestModeId == firstCheckId)
+      {
+        xLoadIntraResultQT(pcCU, uiTrDepth, uiAbsPartIdx,bLumaOnly );
+        pcCU->setCbfSubParts  ( uiSingleCbfY << uiTrDepth, TEXT_LUMA, uiAbsPartIdx, uiFullDepth );
+        if( !bLumaOnly )
+        {
+          if(bFirstQ)
+          {
+            pcCU->setCbfSubParts( uiSingleCbfU << uiTrDepth, TEXT_CHROMA_U, uiAbsPartIdx, pcCU->getDepth( 0 ) + uiTrDepth - 1 );
+            pcCU->setCbfSubParts( uiSingleCbfV << uiTrDepth, TEXT_CHROMA_V, uiAbsPartIdx, pcCU->getDepth( 0 ) + uiTrDepth - 1 );
+          }
+        }
+        if(m_bUseSBACRD)
+        {
+          m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiFullDepth ][ CI_TEMP_BEST ] );
+        } 
+      }
+
+      if( !bLumaOnly )
+      {
+        bestModeIdUV[0] = bestModeIdUV[1] = bestModeId;
+        if(bFirstQ && bestModeId == 1)
+        {
+          //In order not to code TS flag when cbf is zero, the case for TS with cbf being zero is forbidden.
+          if(uiSingleCbfU == 0)
+          {
+            pcCU ->setTransformSkipSubParts ( 0, TEXT_CHROMA_U, uiAbsPartIdx, uiFullDepth); 
+            bestModeIdUV[0] = 0;
+          }
+          if(uiSingleCbfV == 0)
+          {
+            pcCU ->setTransformSkipSubParts ( 0, TEXT_CHROMA_V, uiAbsPartIdx, uiFullDepth); 
+            bestModeIdUV[1] = 0;
+          }
+        }
+      }
+    }
+    else
+    {
+      pcCU ->setTransformSkipSubParts ( 0, TEXT_LUMA, uiAbsPartIdx, uiFullDepth ); 
+      //----- store original entropy coding status -----
+      if( m_bUseSBACRD && bCheckSplit )
+      {
+        m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
+      }
+      //----- code luma block with given intra prediction mode and store Cbf-----
+      dSingleCost   = 0.0;
+      xIntraCodingLumaBlk( pcCU, uiTrDepth, uiAbsPartIdx, pcOrgYuv, pcPredYuv, pcResiYuv, uiSingleDistY ); 
+      if( bCheckSplit )
+      {
+        uiSingleCbfY = pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA, uiTrDepth );
+      }
+      //----- code chroma blocks with given intra prediction mode and store Cbf-----
+      if( !bLumaOnly )
+      {
+        pcCU ->setTransformSkipSubParts ( 0, TEXT_CHROMA_U, uiAbsPartIdx, uiFullDepth ); 
+        pcCU ->setTransformSkipSubParts ( 0, TEXT_CHROMA_V, uiAbsPartIdx, uiFullDepth ); 
+        xIntraCodingChromaBlk ( pcCU, uiTrDepth, uiAbsPartIdx, pcOrgYuv, pcPredYuv, pcResiYuv, uiSingleDistC, 0 ); 
+        xIntraCodingChromaBlk ( pcCU, uiTrDepth, uiAbsPartIdx, pcOrgYuv, pcPredYuv, pcResiYuv, uiSingleDistC, 1 ); 
+        if( bCheckSplit )
+        {
+          uiSingleCbfU = pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth );
+          uiSingleCbfV = pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth );
+        }
+      }
+      //----- determine rate and r-d cost -----
+      UInt uiSingleBits = xGetIntraBitsQT( pcCU, uiTrDepth, uiAbsPartIdx, true, !bLumaOnly, false );
+      dSingleCost       = m_pcRdCost->calcRdCost( uiSingleBits, uiSingleDistY + uiSingleDistC );
+    }
+  }
+  
+  if( bCheckSplit )
+  {
+    //----- store full entropy coding status, load original entropy coding status -----
+    if( m_bUseSBACRD )
+    {
+      if( bCheckFull )
+      {
+        m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_TEST ] );
+        m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
+      }
+      else
+      {
+        m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
+      }
+    }
+    //----- code splitted block -----
+    Double  dSplitCost      = 0.0;
+    UInt    uiSplitDistY    = 0;
+    UInt    uiSplitDistC    = 0;
+    UInt    uiQPartsDiv     = pcCU->getPic()->getNumPartInCU() >> ( ( uiFullDepth + 1 ) << 1 );
+    UInt    uiAbsPartIdxSub = uiAbsPartIdx;
+
+    UInt    uiSplitCbfY = 0;
+    UInt    uiSplitCbfU = 0;
+    UInt    uiSplitCbfV = 0;
+
+    for( UInt uiPart = 0; uiPart < 4; uiPart++, uiAbsPartIdxSub += uiQPartsDiv )
+    {
+#if HHI_RQT_INTRA_SPEEDUP
+      xRecurIntraCodingQT( pcCU, uiTrDepth + 1, uiAbsPartIdxSub, bLumaOnly, pcOrgYuv, pcPredYuv, pcResiYuv, uiSplitDistY, uiSplitDistC, bCheckFirst, dSplitCost );
+#else
+      xRecurIntraCodingQT( pcCU, uiTrDepth + 1, uiAbsPartIdxSub, bLumaOnly, pcOrgYuv, pcPredYuv, pcResiYuv, uiSplitDistY, uiSplitDistC, dSplitCost );
+#endif
+
+      uiSplitCbfY |= pcCU->getCbf( uiAbsPartIdxSub, TEXT_LUMA, uiTrDepth + 1 );
+      if(!bLumaOnly)
+      {
+        uiSplitCbfU |= pcCU->getCbf( uiAbsPartIdxSub, TEXT_CHROMA_U, uiTrDepth + 1 );
+        uiSplitCbfV |= pcCU->getCbf( uiAbsPartIdxSub, TEXT_CHROMA_V, uiTrDepth + 1 );
+      }
+    }
+
+    for( UInt uiOffs = 0; uiOffs < 4 * uiQPartsDiv; uiOffs++ )
+    {
+      pcCU->getCbf( TEXT_LUMA )[ uiAbsPartIdx + uiOffs ] |= ( uiSplitCbfY << uiTrDepth );
+    }
+    if( !bLumaOnly )
+    {
+      for( UInt uiOffs = 0; uiOffs < 4 * uiQPartsDiv; uiOffs++ )
+      {
+        pcCU->getCbf( TEXT_CHROMA_U )[ uiAbsPartIdx + uiOffs ] |= ( uiSplitCbfU << uiTrDepth );
+        pcCU->getCbf( TEXT_CHROMA_V )[ uiAbsPartIdx + uiOffs ] |= ( uiSplitCbfV << uiTrDepth );
+      }
+    }
+    //----- restore context states -----
+    if( m_bUseSBACRD )
+    {
+      m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
+    }
+    //----- determine rate and r-d cost -----
+    UInt uiSplitBits = xGetIntraBitsQT( pcCU, uiTrDepth, uiAbsPartIdx, true, !bLumaOnly, false );
+    dSplitCost       = m_pcRdCost->calcRdCost( uiSplitBits, uiSplitDistY + uiSplitDistC );
+    
+    //===== compare and set best =====
+    if( dSplitCost < dSingleCost )
+    {
+      //--- update cost ---
+      ruiDistY += uiSplitDistY;
+      ruiDistC += uiSplitDistC;
+      dRDCost  += dSplitCost;
+      return;
+    }
+    //----- set entropy coding status -----
+    if( m_bUseSBACRD )
+    {
+      m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_TEST ] );
+    }
+    
+    //--- set transform index and Cbf values ---
+    pcCU->setTrIdxSubParts( uiTrDepth, uiAbsPartIdx, uiFullDepth );
+    pcCU->setCbfSubParts  ( uiSingleCbfY << uiTrDepth, TEXT_LUMA, uiAbsPartIdx, uiFullDepth );
+    pcCU ->setTransformSkipSubParts  ( bestModeId, TEXT_LUMA, uiAbsPartIdx, uiFullDepth ); 
+    if( !bLumaOnly )
+    {
+      pcCU->setCbfSubParts( uiSingleCbfU << uiTrDepth, TEXT_CHROMA_U, uiAbsPartIdx, uiFullDepth );
+      pcCU->setCbfSubParts( uiSingleCbfV << uiTrDepth, TEXT_CHROMA_V, uiAbsPartIdx, uiFullDepth );
+      pcCU->setTransformSkipSubParts ( bestModeIdUV[0], TEXT_CHROMA_U, uiAbsPartIdx, uiFullDepth); 
+      pcCU->setTransformSkipSubParts ( bestModeIdUV[1], TEXT_CHROMA_V, uiAbsPartIdx, uiFullDepth); 
+    }
+    
+    //--- set reconstruction for next intra prediction blocks ---
+    UInt  uiWidth     = pcCU->getWidth ( 0 ) >> uiTrDepth;
+    UInt  uiHeight    = pcCU->getHeight( 0 ) >> uiTrDepth;
+    UInt  uiQTLayer   = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+    UInt  uiZOrder    = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
+    Pel*  piSrc       = m_pcQTTempTComYuv[ uiQTLayer ].getLumaAddr( uiAbsPartIdx );
+    UInt  uiSrcStride = m_pcQTTempTComYuv[ uiQTLayer ].getStride  ();
+    Pel*  piDes       = pcCU->getPic()->getPicYuvRec()->getLumaAddr( pcCU->getAddr(), uiZOrder );
+    UInt  uiDesStride = pcCU->getPic()->getPicYuvRec()->getStride  ();
+    for( UInt uiY = 0; uiY < uiHeight; uiY++, piSrc += uiSrcStride, piDes += uiDesStride )
+    {
+      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+      {
+        piDes[ uiX ] = piSrc[ uiX ];
+      }
+    }
+    if( !bLumaOnly )
+    {
+      uiWidth   >>= 1;
+      uiHeight  >>= 1;
+      piSrc       = m_pcQTTempTComYuv[ uiQTLayer ].getCbAddr  ( uiAbsPartIdx );
+      uiSrcStride = m_pcQTTempTComYuv[ uiQTLayer ].getCStride ();
+      piDes       = pcCU->getPic()->getPicYuvRec()->getCbAddr ( pcCU->getAddr(), uiZOrder );
+      uiDesStride = pcCU->getPic()->getPicYuvRec()->getCStride();
+      for( UInt uiY = 0; uiY < uiHeight; uiY++, piSrc += uiSrcStride, piDes += uiDesStride )
+      {
+        for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+        {
+          piDes[ uiX ] = piSrc[ uiX ];
+        }
+      }
+      piSrc       = m_pcQTTempTComYuv[ uiQTLayer ].getCrAddr  ( uiAbsPartIdx );
+      piDes       = pcCU->getPic()->getPicYuvRec()->getCrAddr ( pcCU->getAddr(), uiZOrder );
+      for( UInt uiY = 0; uiY < uiHeight; uiY++, piSrc += uiSrcStride, piDes += uiDesStride )
+      {
+        for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+        {
+          piDes[ uiX ] = piSrc[ uiX ];
+        }
+      }
+    }
+  }
+  ruiDistY += uiSingleDistY;
+  ruiDistC += uiSingleDistC;
+  dRDCost  += dSingleCost;
+}
+
+
+Void
+TEncSearch::xSetIntraResultQT( TComDataCU* pcCU,
+                              UInt        uiTrDepth,
+                              UInt        uiAbsPartIdx,
+                              Bool        bLumaOnly,
+                              TComYuv*    pcRecoYuv )
+{
+  UInt uiFullDepth  = pcCU->getDepth(0) + uiTrDepth;
+  UInt uiTrMode     = pcCU->getTransformIdx( uiAbsPartIdx );
+  if(  uiTrMode == uiTrDepth )
+  {
+    UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiFullDepth ] + 2;
+    UInt uiQTLayer    = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+    
+    Bool bSkipChroma  = false;
+    Bool bChromaSame  = false;
+    if( !bLumaOnly && uiLog2TrSize == 2 )
+    {
+      assert( uiTrDepth > 0 );
+      UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrDepth - 1 ) << 1 );
+      bSkipChroma  = ( ( uiAbsPartIdx % uiQPDiv ) != 0 );
+      bChromaSame  = true;
+    }
+    
+    //===== copy transform coefficients =====
+    UInt uiNumCoeffY    = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( uiFullDepth << 1 );
+    UInt uiNumCoeffIncY = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 );
+    TCoeff* pcCoeffSrcY = m_ppcQTTempCoeffY [ uiQTLayer ] + ( uiNumCoeffIncY * uiAbsPartIdx );
+    TCoeff* pcCoeffDstY = pcCU->getCoeffY ()              + ( uiNumCoeffIncY * uiAbsPartIdx );
+    ::memcpy( pcCoeffDstY, pcCoeffSrcY, sizeof( TCoeff ) * uiNumCoeffY );
+#if ADAPTIVE_QP_SELECTION
+    Int* pcArlCoeffSrcY = m_ppcQTTempArlCoeffY [ uiQTLayer ] + ( uiNumCoeffIncY * uiAbsPartIdx );
+    Int* pcArlCoeffDstY = pcCU->getArlCoeffY ()              + ( uiNumCoeffIncY * uiAbsPartIdx );
+    ::memcpy( pcArlCoeffDstY, pcArlCoeffSrcY, sizeof( Int ) * uiNumCoeffY );
+#endif
+    if( !bLumaOnly && !bSkipChroma )
+    {
+      UInt uiNumCoeffC    = ( bChromaSame ? uiNumCoeffY    : uiNumCoeffY    >> 2 );
+      UInt uiNumCoeffIncC = uiNumCoeffIncY >> 2;
+      TCoeff* pcCoeffSrcU = m_ppcQTTempCoeffCb[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+      TCoeff* pcCoeffSrcV = m_ppcQTTempCoeffCr[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+      TCoeff* pcCoeffDstU = pcCU->getCoeffCb()              + ( uiNumCoeffIncC * uiAbsPartIdx );
+      TCoeff* pcCoeffDstV = pcCU->getCoeffCr()              + ( uiNumCoeffIncC * uiAbsPartIdx );
+      ::memcpy( pcCoeffDstU, pcCoeffSrcU, sizeof( TCoeff ) * uiNumCoeffC );
+      ::memcpy( pcCoeffDstV, pcCoeffSrcV, sizeof( TCoeff ) * uiNumCoeffC );
+#if ADAPTIVE_QP_SELECTION
+      Int* pcArlCoeffSrcU = m_ppcQTTempArlCoeffCb[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+      Int* pcArlCoeffSrcV = m_ppcQTTempArlCoeffCr[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+      Int* pcArlCoeffDstU = pcCU->getArlCoeffCb()              + ( uiNumCoeffIncC * uiAbsPartIdx );
+      Int* pcArlCoeffDstV = pcCU->getArlCoeffCr()              + ( uiNumCoeffIncC * uiAbsPartIdx );
+      ::memcpy( pcArlCoeffDstU, pcArlCoeffSrcU, sizeof( Int ) * uiNumCoeffC );
+      ::memcpy( pcArlCoeffDstV, pcArlCoeffSrcV, sizeof( Int ) * uiNumCoeffC );
+#endif
+    }
+    
+    //===== copy reconstruction =====
+    m_pcQTTempTComYuv[ uiQTLayer ].copyPartToPartLuma( pcRecoYuv, uiAbsPartIdx, 1 << uiLog2TrSize, 1 << uiLog2TrSize );
+    if( !bLumaOnly && !bSkipChroma )
+    {
+      UInt uiLog2TrSizeChroma = ( bChromaSame ? uiLog2TrSize : uiLog2TrSize - 1 );
+      m_pcQTTempTComYuv[ uiQTLayer ].copyPartToPartChroma( pcRecoYuv, uiAbsPartIdx, 1 << uiLog2TrSizeChroma, 1 << uiLog2TrSizeChroma );
+    }
+  }
+  else
+  {
+    UInt uiNumQPart  = pcCU->getPic()->getNumPartInCU() >> ( ( uiFullDepth + 1 ) << 1 );
+    for( UInt uiPart = 0; uiPart < 4; uiPart++ )
+    {
+      xSetIntraResultQT( pcCU, uiTrDepth + 1, uiAbsPartIdx + uiPart * uiNumQPart, bLumaOnly, pcRecoYuv );
+    }
+  }
+}
+
+Void
+TEncSearch::xStoreIntraResultQT( TComDataCU* pcCU,
+                                UInt        uiTrDepth,
+                                UInt        uiAbsPartIdx,
+                                Bool        bLumaOnly )
+{
+  UInt uiFullDepth  = pcCU->getDepth(0) + uiTrDepth;
+  UInt uiTrMode     = pcCU->getTransformIdx( uiAbsPartIdx );
+  assert(  uiTrMode == uiTrDepth );
+  UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiFullDepth ] + 2;
+  UInt uiQTLayer    = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+
+  Bool bSkipChroma  = false;
+  Bool bChromaSame  = false;
+  if( !bLumaOnly && uiLog2TrSize == 2 )
+  {
+    assert( uiTrDepth > 0 );
+    UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrDepth - 1 ) << 1 );
+    bSkipChroma  = ( ( uiAbsPartIdx % uiQPDiv ) != 0 );
+    bChromaSame  = true;
+  }
+
+  //===== copy transform coefficients =====
+  UInt uiNumCoeffY    = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( uiFullDepth << 1 );
+  UInt uiNumCoeffIncY = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 );
+  TCoeff* pcCoeffSrcY = m_ppcQTTempCoeffY [ uiQTLayer ] + ( uiNumCoeffIncY * uiAbsPartIdx );
+  TCoeff* pcCoeffDstY = m_pcQTTempTUCoeffY;
+
+  ::memcpy( pcCoeffDstY, pcCoeffSrcY, sizeof( TCoeff ) * uiNumCoeffY );
+#if ADAPTIVE_QP_SELECTION
+  Int* pcArlCoeffSrcY = m_ppcQTTempArlCoeffY [ uiQTLayer ] + ( uiNumCoeffIncY * uiAbsPartIdx );
+  Int* pcArlCoeffDstY = m_ppcQTTempTUArlCoeffY;
+  ::memcpy( pcArlCoeffDstY, pcArlCoeffSrcY, sizeof( Int ) * uiNumCoeffY );
+#endif
+  if( !bLumaOnly && !bSkipChroma )
+  {
+    UInt uiNumCoeffC    = ( bChromaSame ? uiNumCoeffY    : uiNumCoeffY    >> 2 );
+    UInt uiNumCoeffIncC = uiNumCoeffIncY >> 2;
+    TCoeff* pcCoeffSrcU = m_ppcQTTempCoeffCb[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+    TCoeff* pcCoeffSrcV = m_ppcQTTempCoeffCr[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+    TCoeff* pcCoeffDstU = m_pcQTTempTUCoeffCb;
+    TCoeff* pcCoeffDstV = m_pcQTTempTUCoeffCr;
+    ::memcpy( pcCoeffDstU, pcCoeffSrcU, sizeof( TCoeff ) * uiNumCoeffC );
+    ::memcpy( pcCoeffDstV, pcCoeffSrcV, sizeof( TCoeff ) * uiNumCoeffC );
+#if ADAPTIVE_QP_SELECTION
+    Int* pcArlCoeffSrcU = m_ppcQTTempArlCoeffCb[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+    Int* pcArlCoeffSrcV = m_ppcQTTempArlCoeffCr[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+    Int* pcArlCoeffDstU = m_ppcQTTempTUArlCoeffCb;
+    Int* pcArlCoeffDstV = m_ppcQTTempTUArlCoeffCr;
+    ::memcpy( pcArlCoeffDstU, pcArlCoeffSrcU, sizeof( Int ) * uiNumCoeffC );
+    ::memcpy( pcArlCoeffDstV, pcArlCoeffSrcV, sizeof( Int ) * uiNumCoeffC );
+#endif
+  }
+
+  //===== copy reconstruction =====
+  m_pcQTTempTComYuv[ uiQTLayer ].copyPartToPartLuma( &m_pcQTTempTransformSkipTComYuv, uiAbsPartIdx, 1 << uiLog2TrSize, 1 << uiLog2TrSize );
+
+  if( !bLumaOnly && !bSkipChroma )
+  {
+    UInt uiLog2TrSizeChroma = ( bChromaSame ? uiLog2TrSize : uiLog2TrSize - 1 );
+    m_pcQTTempTComYuv[ uiQTLayer ].copyPartToPartChroma( &m_pcQTTempTransformSkipTComYuv, uiAbsPartIdx, 1 << uiLog2TrSizeChroma, 1 << uiLog2TrSizeChroma );
+  }
+}
+
+Void
+TEncSearch::xLoadIntraResultQT( TComDataCU* pcCU,
+                               UInt        uiTrDepth,
+                               UInt        uiAbsPartIdx,
+                               Bool        bLumaOnly )
+{
+  UInt uiFullDepth  = pcCU->getDepth(0) + uiTrDepth;
+  UInt uiTrMode     = pcCU->getTransformIdx( uiAbsPartIdx );
+  assert(  uiTrMode == uiTrDepth );
+  UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiFullDepth ] + 2;
+  UInt uiQTLayer    = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+
+  Bool bSkipChroma  = false;
+  Bool bChromaSame  = false;
+  if( !bLumaOnly && uiLog2TrSize == 2 )
+  {
+    assert( uiTrDepth > 0 );
+    UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrDepth - 1 ) << 1 );
+    bSkipChroma  = ( ( uiAbsPartIdx % uiQPDiv ) != 0 );
+    bChromaSame  = true;
+  }
+
+  //===== copy transform coefficients =====
+  UInt uiNumCoeffY    = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( uiFullDepth << 1 );
+  UInt uiNumCoeffIncY = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 );
+  TCoeff* pcCoeffDstY = m_ppcQTTempCoeffY [ uiQTLayer ] + ( uiNumCoeffIncY * uiAbsPartIdx );
+  TCoeff* pcCoeffSrcY = m_pcQTTempTUCoeffY;
+
+  ::memcpy( pcCoeffDstY, pcCoeffSrcY, sizeof( TCoeff ) * uiNumCoeffY );
+#if ADAPTIVE_QP_SELECTION
+  Int* pcArlCoeffDstY = m_ppcQTTempArlCoeffY [ uiQTLayer ] + ( uiNumCoeffIncY * uiAbsPartIdx );
+  Int* pcArlCoeffSrcY = m_ppcQTTempTUArlCoeffY;
+  ::memcpy( pcArlCoeffDstY, pcArlCoeffSrcY, sizeof( Int ) * uiNumCoeffY );
+#endif
+  if( !bLumaOnly && !bSkipChroma )
+  {
+    UInt uiNumCoeffC    = ( bChromaSame ? uiNumCoeffY    : uiNumCoeffY    >> 2 );
+    UInt uiNumCoeffIncC = uiNumCoeffIncY >> 2;
+    TCoeff* pcCoeffDstU = m_ppcQTTempCoeffCb[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+    TCoeff* pcCoeffDstV = m_ppcQTTempCoeffCr[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+    TCoeff* pcCoeffSrcU = m_pcQTTempTUCoeffCb;
+    TCoeff* pcCoeffSrcV = m_pcQTTempTUCoeffCr;
+    ::memcpy( pcCoeffDstU, pcCoeffSrcU, sizeof( TCoeff ) * uiNumCoeffC );
+    ::memcpy( pcCoeffDstV, pcCoeffSrcV, sizeof( TCoeff ) * uiNumCoeffC );
+#if ADAPTIVE_QP_SELECTION
+    Int* pcArlCoeffDstU = m_ppcQTTempArlCoeffCb[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+    Int* pcArlCoeffDstV = m_ppcQTTempArlCoeffCr[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+    Int* pcArlCoeffSrcU = m_ppcQTTempTUArlCoeffCb;
+    Int* pcArlCoeffSrcV = m_ppcQTTempTUArlCoeffCr;
+    ::memcpy( pcArlCoeffDstU, pcArlCoeffSrcU, sizeof( Int ) * uiNumCoeffC );
+    ::memcpy( pcArlCoeffDstV, pcArlCoeffSrcV, sizeof( Int ) * uiNumCoeffC );
+#endif
+  }
+
+  //===== copy reconstruction =====
+  m_pcQTTempTransformSkipTComYuv.copyPartToPartLuma( &m_pcQTTempTComYuv[ uiQTLayer ] , uiAbsPartIdx, 1 << uiLog2TrSize, 1 << uiLog2TrSize );
+
+  if( !bLumaOnly && !bSkipChroma )
+  {
+    UInt uiLog2TrSizeChroma = ( bChromaSame ? uiLog2TrSize : uiLog2TrSize - 1 );
+    m_pcQTTempTransformSkipTComYuv.copyPartToPartChroma( &m_pcQTTempTComYuv[ uiQTLayer ], uiAbsPartIdx, 1 << uiLog2TrSizeChroma, 1 << uiLog2TrSizeChroma );
+  }
+
+  UInt    uiZOrder          = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
+  Pel*    piRecIPred        = pcCU->getPic()->getPicYuvRec()->getLumaAddr( pcCU->getAddr(), uiZOrder );
+  UInt    uiRecIPredStride  = pcCU->getPic()->getPicYuvRec()->getStride  ();
+  Pel*    piRecQt           = m_pcQTTempTComYuv[ uiQTLayer ].getLumaAddr( uiAbsPartIdx );
+  UInt    uiRecQtStride     = m_pcQTTempTComYuv[ uiQTLayer ].getStride  ();
+  UInt    uiWidth           = pcCU     ->getWidth   ( 0 ) >> uiTrDepth;
+  UInt    uiHeight          = pcCU     ->getHeight  ( 0 ) >> uiTrDepth;
+  Pel* pRecQt     = piRecQt;
+  Pel* pRecIPred  = piRecIPred;
+  for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+  {
+    for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+    {
+      pRecIPred[ uiX ] = pRecQt   [ uiX ];
+    }
+    pRecQt    += uiRecQtStride;
+    pRecIPred += uiRecIPredStride;
+  }
+
+  if( !bLumaOnly && !bSkipChroma )
+  {
+    piRecIPred = pcCU->getPic()->getPicYuvRec()->getCbAddr( pcCU->getAddr(), uiZOrder );
+    piRecQt    = m_pcQTTempTComYuv[ uiQTLayer ].getCbAddr( uiAbsPartIdx );
+    pRecQt     = piRecQt;
+    pRecIPred  = piRecIPred;
+    for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+    {
+      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+      {
+        pRecIPred[ uiX ] = pRecQt[ uiX ];
+      }
+      pRecQt    += uiRecQtStride;
+      pRecIPred += uiRecIPredStride;
+    }
+
+    piRecIPred = pcCU->getPic()->getPicYuvRec()->getCrAddr( pcCU->getAddr(), uiZOrder );
+    piRecQt    = m_pcQTTempTComYuv[ uiQTLayer ].getCrAddr( uiAbsPartIdx );
+    pRecQt     = piRecQt;
+    pRecIPred  = piRecIPred;
+    for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+    {
+      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+      {
+        pRecIPred[ uiX ] = pRecQt[ uiX ];
+      }
+      pRecQt    += uiRecQtStride;
+      pRecIPred += uiRecIPredStride;
+    }
+  }
+}
+
+Void
+TEncSearch::xStoreIntraResultChromaQT( TComDataCU* pcCU,
+                                      UInt        uiTrDepth,
+                                      UInt        uiAbsPartIdx,
+                                      UInt        stateU0V1Both2 )
+{
+  UInt uiFullDepth = pcCU->getDepth(0) + uiTrDepth;
+  UInt uiTrMode    = pcCU->getTransformIdx( uiAbsPartIdx );
+  if(  uiTrMode == uiTrDepth )
+  {
+    UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiFullDepth ] + 2;
+    UInt uiQTLayer    = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+
+    Bool bChromaSame = false;
+    if( uiLog2TrSize == 2 )
+    {
+      assert( uiTrDepth > 0 );
+      uiTrDepth --;
+      UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrDepth) << 1 );
+      if( ( uiAbsPartIdx % uiQPDiv ) != 0 )
+      {
+        return;
+      }
+      bChromaSame = true;
+    }
+
+    //===== copy transform coefficients =====
+    UInt uiNumCoeffC    = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( uiFullDepth << 1 );
+    if( !bChromaSame )
+    {
+      uiNumCoeffC     >>= 2;
+    }
+    UInt uiNumCoeffIncC = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 ) + 2 );
+    if(stateU0V1Both2 == 0 || stateU0V1Both2 == 2)
+    {
+      TCoeff* pcCoeffSrcU = m_ppcQTTempCoeffCb[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+      TCoeff* pcCoeffDstU = m_pcQTTempTUCoeffCb;
+      ::memcpy( pcCoeffDstU, pcCoeffSrcU, sizeof( TCoeff ) * uiNumCoeffC );
+
+#if ADAPTIVE_QP_SELECTION    
+      Int* pcArlCoeffSrcU = m_ppcQTTempArlCoeffCb[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+      Int* pcArlCoeffDstU = m_ppcQTTempTUArlCoeffCb;
+      ::memcpy( pcArlCoeffDstU, pcArlCoeffSrcU, sizeof( Int ) * uiNumCoeffC );
+#endif
+    }
+    if(stateU0V1Both2 == 1 || stateU0V1Both2 == 2)
+    {
+      TCoeff* pcCoeffSrcV = m_ppcQTTempCoeffCr[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+      TCoeff* pcCoeffDstV = m_pcQTTempTUCoeffCr;
+      ::memcpy( pcCoeffDstV, pcCoeffSrcV, sizeof( TCoeff ) * uiNumCoeffC );
+#if ADAPTIVE_QP_SELECTION    
+      Int* pcArlCoeffSrcV = m_ppcQTTempArlCoeffCr[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+      Int* pcArlCoeffDstV = m_ppcQTTempTUArlCoeffCr;
+      ::memcpy( pcArlCoeffDstV, pcArlCoeffSrcV, sizeof( Int ) * uiNumCoeffC );
+#endif
+    }
+
+    //===== copy reconstruction =====
+    UInt uiLog2TrSizeChroma = ( bChromaSame ? uiLog2TrSize : uiLog2TrSize - 1 );
+    m_pcQTTempTComYuv[ uiQTLayer ].copyPartToPartChroma(&m_pcQTTempTransformSkipTComYuv, uiAbsPartIdx, 1 << uiLog2TrSizeChroma, 1 << uiLog2TrSizeChroma, stateU0V1Both2 );
+  }
+}
+
+
+Void
+TEncSearch::xLoadIntraResultChromaQT( TComDataCU* pcCU,
+                                     UInt        uiTrDepth,
+                                     UInt        uiAbsPartIdx,
+                                     UInt        stateU0V1Both2 )
+{
+  UInt uiFullDepth = pcCU->getDepth(0) + uiTrDepth;
+  UInt uiTrMode    = pcCU->getTransformIdx( uiAbsPartIdx );
+  if(  uiTrMode == uiTrDepth )
+  {
+    UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiFullDepth ] + 2;
+    UInt uiQTLayer    = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+
+    Bool bChromaSame = false;
+    if( uiLog2TrSize == 2 )
+    {
+      assert( uiTrDepth > 0 );
+      uiTrDepth --;
+      UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrDepth ) << 1 );
+      if( ( uiAbsPartIdx % uiQPDiv ) != 0 )
+      {
+        return;
+      }
+      bChromaSame = true;
+    }
+
+    //===== copy transform coefficients =====
+    UInt uiNumCoeffC = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( uiFullDepth << 1 );
+    if( !bChromaSame )
+    {
+      uiNumCoeffC >>= 2;
+    }
+    UInt uiNumCoeffIncC = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 ) + 2 );
+
+    if(stateU0V1Both2 ==0 || stateU0V1Both2 == 2)
+    {
+      TCoeff* pcCoeffDstU = m_ppcQTTempCoeffCb[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+      TCoeff* pcCoeffSrcU = m_pcQTTempTUCoeffCb;
+      ::memcpy( pcCoeffDstU, pcCoeffSrcU, sizeof( TCoeff ) * uiNumCoeffC );
+#if ADAPTIVE_QP_SELECTION    
+      Int* pcArlCoeffDstU = m_ppcQTTempArlCoeffCb[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+      Int* pcArlCoeffSrcU = m_ppcQTTempTUArlCoeffCb;
+      ::memcpy( pcArlCoeffDstU, pcArlCoeffSrcU, sizeof( Int ) * uiNumCoeffC );
+#endif
+    }
+    if(stateU0V1Both2 ==1 || stateU0V1Both2 == 2)
+    {
+      TCoeff* pcCoeffDstV = m_ppcQTTempCoeffCr[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+      TCoeff* pcCoeffSrcV = m_pcQTTempTUCoeffCr;
+      ::memcpy( pcCoeffDstV, pcCoeffSrcV, sizeof( TCoeff ) * uiNumCoeffC );
+#if ADAPTIVE_QP_SELECTION    
+      Int* pcArlCoeffDstV = m_ppcQTTempArlCoeffCr[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+      Int* pcArlCoeffSrcV = m_ppcQTTempTUArlCoeffCr;       
+      ::memcpy( pcArlCoeffDstV, pcArlCoeffSrcV, sizeof( Int ) * uiNumCoeffC );
+#endif
+    }
+
+    //===== copy reconstruction =====
+    UInt uiLog2TrSizeChroma = ( bChromaSame ? uiLog2TrSize : uiLog2TrSize - 1 );
+    m_pcQTTempTransformSkipTComYuv.copyPartToPartChroma( &m_pcQTTempTComYuv[ uiQTLayer ], uiAbsPartIdx, 1 << uiLog2TrSizeChroma, 1 << uiLog2TrSizeChroma, stateU0V1Both2);
+
+    UInt    uiZOrder          = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
+    UInt    uiWidth           = pcCU->getWidth   ( 0 ) >> (uiTrDepth + 1);
+    UInt    uiHeight          = pcCU->getHeight  ( 0 ) >> (uiTrDepth + 1);
+    UInt    uiRecQtStride     = m_pcQTTempTComYuv[ uiQTLayer ].getCStride  ();
+    UInt    uiRecIPredStride  = pcCU->getPic()->getPicYuvRec()->getCStride  ();
+
+    if(stateU0V1Both2 ==0 || stateU0V1Both2 == 2)
+    {
+      Pel* piRecIPred = pcCU->getPic()->getPicYuvRec()->getCbAddr( pcCU->getAddr(), uiZOrder );
+      Pel* piRecQt    = m_pcQTTempTComYuv[ uiQTLayer ].getCbAddr( uiAbsPartIdx );
+      Pel* pRecQt     = piRecQt;
+      Pel* pRecIPred  = piRecIPred;
+      for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+      {
+        for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+        {
+          pRecIPred[ uiX ] = pRecQt[ uiX ];
+        }
+        pRecQt    += uiRecQtStride;
+        pRecIPred += uiRecIPredStride;
+      }
+    }
+    if(stateU0V1Both2 == 1 || stateU0V1Both2 == 2)
+    {
+      Pel* piRecIPred = pcCU->getPic()->getPicYuvRec()->getCrAddr( pcCU->getAddr(), uiZOrder );
+      Pel* piRecQt    = m_pcQTTempTComYuv[ uiQTLayer ].getCrAddr( uiAbsPartIdx );
+      Pel* pRecQt     = piRecQt;
+      Pel* pRecIPred  = piRecIPred;
+      for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+      {
+        for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+        {
+          pRecIPred[ uiX ] = pRecQt[ uiX ];
+        }
+        pRecQt    += uiRecQtStride;
+        pRecIPred += uiRecIPredStride;
+      }
+    }
+  }
+}
+
+Void 
+TEncSearch::xRecurIntraChromaCodingQT( TComDataCU*  pcCU, 
+                                      UInt         uiTrDepth,
+                                      UInt         uiAbsPartIdx, 
+                                      TComYuv*     pcOrgYuv, 
+                                      TComYuv*     pcPredYuv, 
+                                      TComYuv*     pcResiYuv, 
+                                      UInt&        ruiDist )
+{
+  UInt uiFullDepth = pcCU->getDepth( 0 ) +  uiTrDepth;
+  UInt uiTrMode    = pcCU->getTransformIdx( uiAbsPartIdx );
+  if(  uiTrMode == uiTrDepth )
+  {
+#if PPS_TS_FLAG
+    Bool checkTransformSkip = pcCU->getSlice()->getPPS()->getUseTransformSkip();
+#else
+    Bool checkTransformSkip = pcCU->getSlice()->getSPS()->getUseTransformSkip();
+#endif
+    UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiFullDepth ] + 2;
+
+    UInt actualTrDepth = uiTrDepth;
+    if( uiLog2TrSize == 2 )
+    {
+      assert( uiTrDepth > 0 );
+      actualTrDepth--;
+      UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + actualTrDepth) << 1 );
+      Bool bFirstQ = ( ( uiAbsPartIdx % uiQPDiv ) == 0 );
+      if( !bFirstQ )
+      {
+        return;
+      }
+    }
+
+    checkTransformSkip &= (uiLog2TrSize <= 3);
+#if INTRA_TRANSFORMSKIP_FAST
+    if ( m_pcEncCfg->getUseTransformSkipFast() )
+    {
+      checkTransformSkip &= (uiLog2TrSize < 3);
+      if (checkTransformSkip)
+      {
+        Int nbLumaSkip = 0;
+        for(UInt absPartIdxSub = uiAbsPartIdx; absPartIdxSub < uiAbsPartIdx + 4; absPartIdxSub ++)
+        {
+          nbLumaSkip += pcCU->getTransformSkip(absPartIdxSub, TEXT_LUMA);
+        }
+        checkTransformSkip &= (nbLumaSkip > 0);
+      }
+    }
+#endif
+
+    if(checkTransformSkip)
+    {
+#if INTRA_TRANSFORMSKIP_FAST==0
+      Bool checkTSFast = m_pcEncCfg->getUseTransformSkipFast();
+      if(checkTSFast)
+      {
+        //fast algorithm for chroma TS
+        Bool useTransformSkip = checkTransformSkip;
+        UInt blkNumberOfTS = 0;
+        for(UInt absPartIdxSub = uiAbsPartIdx; absPartIdxSub < uiAbsPartIdx + 4; absPartIdxSub ++)
+        {
+          blkNumberOfTS += pcCU->getTransformSkip(absPartIdxSub, TEXT_LUMA);
+        }
+        if(blkNumberOfTS < 4)
+        {
+          useTransformSkip = false;
+        }
+        pcCU ->setTransformSkipSubParts( useTransformSkip, TEXT_CHROMA_U, uiAbsPartIdx, pcCU->getDepth( 0 ) +  actualTrDepth); 
+        pcCU ->setTransformSkipSubParts( useTransformSkip, TEXT_CHROMA_V, uiAbsPartIdx, pcCU->getDepth( 0 ) +  actualTrDepth); 
+        xIntraCodingChromaBlk( pcCU, uiTrDepth, uiAbsPartIdx, pcOrgYuv, pcPredYuv, pcResiYuv, ruiDist, 0 ); 
+        xIntraCodingChromaBlk( pcCU, uiTrDepth, uiAbsPartIdx, pcOrgYuv, pcPredYuv, pcResiYuv, ruiDist, 1 ); 
+        UInt singleCbfCb = pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth);
+        UInt singleCbfCr = pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth);
+        if(useTransformSkip && singleCbfCb == 0)
+        {
+          pcCU ->setTransformSkipSubParts( 0, TEXT_CHROMA_U, uiAbsPartIdx, pcCU->getDepth( 0 ) +  actualTrDepth);
+        }
+        if(useTransformSkip && singleCbfCr == 0)
+        {
+          pcCU ->setTransformSkipSubParts( 0, TEXT_CHROMA_V, uiAbsPartIdx, pcCU->getDepth( 0 ) +  actualTrDepth);
+        }
+      }
+      else
+      {
+#endif
+        //use RDO to decide whether Cr/Cb takes TS
+        if( m_bUseSBACRD )
+        {
+          m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[uiFullDepth][CI_QT_TRAFO_ROOT] );
+        }
+
+        for(Int chromaId = 0; chromaId < 2; chromaId ++)
+        {
+          Double  dSingleCost    = MAX_DOUBLE;
+          Int     bestModeId     = 0;
+          UInt    singleDistC    = 0;
+          UInt    singleCbfC     = 0;
+          UInt    singleDistCTmp = 0;
+          Double  singleCostTmp  = 0;
+          UInt    singleCbfCTmp  = 0;
+
+          Int     default0Save1Load2 = 0;
+          Int     firstCheckId       = 0;
+
+          for(Int chromaModeId = firstCheckId; chromaModeId < 2; chromaModeId ++)
+          {
+            pcCU->setTransformSkipSubParts ( chromaModeId, (TextType)(chromaId + 2), uiAbsPartIdx, pcCU->getDepth( 0 ) +  actualTrDepth); 
+            if(chromaModeId == firstCheckId)
+            {
+              default0Save1Load2 = 1;
+            }
+            else
+            {
+              default0Save1Load2 = 2;
+            }
+            singleDistCTmp = 0;
+            xIntraCodingChromaBlk( pcCU, uiTrDepth, uiAbsPartIdx, pcOrgYuv, pcPredYuv, pcResiYuv, singleDistCTmp, chromaId ,default0Save1Load2);
+            singleCbfCTmp = pcCU->getCbf( uiAbsPartIdx, (TextType)(chromaId + 2), uiTrDepth);
+            
+            if(chromaModeId == 1 && singleCbfCTmp == 0)
+            {
+              //In order not to code TS flag when cbf is zero, the case for TS with cbf being zero is forbidden.
+              singleCostTmp = MAX_DOUBLE;
+            }
+            else
+            {
+              UInt bitsTmp = xGetIntraBitsQTChroma( pcCU,uiTrDepth, uiAbsPartIdx,chromaId + 2, false );
+              singleCostTmp  = m_pcRdCost->calcRdCost( bitsTmp, singleDistCTmp);
+            }
+
+            if(singleCostTmp < dSingleCost)
+            {
+              dSingleCost = singleCostTmp;
+              singleDistC = singleDistCTmp;
+              bestModeId  = chromaModeId;
+              singleCbfC  = singleCbfCTmp;
+
+              if(bestModeId == firstCheckId)
+              {
+                xStoreIntraResultChromaQT(pcCU, uiTrDepth, uiAbsPartIdx,chromaId);
+                if( m_bUseSBACRD) 
+                {
+                  m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_TEMP_BEST ] );
+                }
+              }
+            }
+            if(chromaModeId == firstCheckId)
+            {
+              m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
+            }
+          }
+
+          if(bestModeId == firstCheckId)
+          {
+            xLoadIntraResultChromaQT(pcCU, uiTrDepth, uiAbsPartIdx,chromaId);
+            pcCU->setCbfSubParts ( singleCbfC << uiTrDepth, (TextType)(chromaId + 2), uiAbsPartIdx, pcCU->getDepth(0) + actualTrDepth );
+            if(m_bUseSBACRD)
+            {
+              m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiFullDepth ][ CI_TEMP_BEST ] );
+            } 
+          }
+          pcCU ->setTransformSkipSubParts( bestModeId, (TextType)(chromaId + 2), uiAbsPartIdx, pcCU->getDepth( 0 ) +  actualTrDepth ); 
+          ruiDist += singleDistC;
+
+          if(chromaId == 0)
+          {
+            if( m_bUseSBACRD )
+            {
+              m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[uiFullDepth][CI_QT_TRAFO_ROOT] );
+            }
+          }
+        }
+#if INTRA_TRANSFORMSKIP_FAST==0
+      }
+#endif
+    }
+    else
+    {
+      pcCU ->setTransformSkipSubParts( 0, TEXT_CHROMA_U, uiAbsPartIdx, pcCU->getDepth( 0 ) +  actualTrDepth ); 
+      pcCU ->setTransformSkipSubParts( 0, TEXT_CHROMA_V, uiAbsPartIdx, pcCU->getDepth( 0 ) +  actualTrDepth ); 
+      xIntraCodingChromaBlk( pcCU, uiTrDepth, uiAbsPartIdx, pcOrgYuv, pcPredYuv, pcResiYuv, ruiDist, 0 ); 
+      xIntraCodingChromaBlk( pcCU, uiTrDepth, uiAbsPartIdx, pcOrgYuv, pcPredYuv, pcResiYuv, ruiDist, 1 ); 
+    }
+  }
+  else
+  {
+    UInt uiSplitCbfU     = 0;
+    UInt uiSplitCbfV     = 0;
+    UInt uiQPartsDiv     = pcCU->getPic()->getNumPartInCU() >> ( ( uiFullDepth + 1 ) << 1 );
+    UInt uiAbsPartIdxSub = uiAbsPartIdx;
+    for( UInt uiPart = 0; uiPart < 4; uiPart++, uiAbsPartIdxSub += uiQPartsDiv )
+    {
+      xRecurIntraChromaCodingQT( pcCU, uiTrDepth + 1, uiAbsPartIdxSub, pcOrgYuv, pcPredYuv, pcResiYuv, ruiDist );
+      uiSplitCbfU |= pcCU->getCbf( uiAbsPartIdxSub, TEXT_CHROMA_U, uiTrDepth + 1 );
+      uiSplitCbfV |= pcCU->getCbf( uiAbsPartIdxSub, TEXT_CHROMA_V, uiTrDepth + 1 );
+    }
+    for( UInt uiOffs = 0; uiOffs < 4 * uiQPartsDiv; uiOffs++ )
+    {
+      pcCU->getCbf( TEXT_CHROMA_U )[ uiAbsPartIdx + uiOffs ] |= ( uiSplitCbfU << uiTrDepth );
+      pcCU->getCbf( TEXT_CHROMA_V )[ uiAbsPartIdx + uiOffs ] |= ( uiSplitCbfV << uiTrDepth );
+    }
+  }
+}
+
+Void
+TEncSearch::xSetIntraResultChromaQT( TComDataCU* pcCU,
+                                    UInt        uiTrDepth,
+                                    UInt        uiAbsPartIdx,
+                                    TComYuv*    pcRecoYuv )
+{
+  UInt uiFullDepth  = pcCU->getDepth(0) + uiTrDepth;
+  UInt uiTrMode     = pcCU->getTransformIdx( uiAbsPartIdx );
+  if(  uiTrMode == uiTrDepth )
+  {
+    UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiFullDepth ] + 2;
+    UInt uiQTLayer    = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+    
+    Bool bChromaSame  = false;
+    if( uiLog2TrSize == 2 )
+    {
+      assert( uiTrDepth > 0 );
+      UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrDepth - 1 ) << 1 );
+      if( ( uiAbsPartIdx % uiQPDiv ) != 0 )
+      {
+        return;
+      }
+      bChromaSame     = true;
+    }
+    
+    //===== copy transform coefficients =====
+    UInt uiNumCoeffC    = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( uiFullDepth << 1 );
+    if( !bChromaSame )
+    {
+      uiNumCoeffC     >>= 2;
+    }
+    UInt uiNumCoeffIncC = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 ) + 2 );
+    TCoeff* pcCoeffSrcU = m_ppcQTTempCoeffCb[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+    TCoeff* pcCoeffSrcV = m_ppcQTTempCoeffCr[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+    TCoeff* pcCoeffDstU = pcCU->getCoeffCb()              + ( uiNumCoeffIncC * uiAbsPartIdx );
+    TCoeff* pcCoeffDstV = pcCU->getCoeffCr()              + ( uiNumCoeffIncC * uiAbsPartIdx );
+    ::memcpy( pcCoeffDstU, pcCoeffSrcU, sizeof( TCoeff ) * uiNumCoeffC );
+    ::memcpy( pcCoeffDstV, pcCoeffSrcV, sizeof( TCoeff ) * uiNumCoeffC );
+#if ADAPTIVE_QP_SELECTION    
+    Int* pcArlCoeffSrcU = m_ppcQTTempArlCoeffCb[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+    Int* pcArlCoeffSrcV = m_ppcQTTempArlCoeffCr[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+    Int* pcArlCoeffDstU = pcCU->getArlCoeffCb()              + ( uiNumCoeffIncC * uiAbsPartIdx );
+    Int* pcArlCoeffDstV = pcCU->getArlCoeffCr()              + ( uiNumCoeffIncC * uiAbsPartIdx );
+    ::memcpy( pcArlCoeffDstU, pcArlCoeffSrcU, sizeof( Int ) * uiNumCoeffC );
+    ::memcpy( pcArlCoeffDstV, pcArlCoeffSrcV, sizeof( Int ) * uiNumCoeffC );
+#endif
+    
+    //===== copy reconstruction =====
+    UInt uiLog2TrSizeChroma = ( bChromaSame ? uiLog2TrSize : uiLog2TrSize - 1 );
+    m_pcQTTempTComYuv[ uiQTLayer ].copyPartToPartChroma( pcRecoYuv, uiAbsPartIdx, 1 << uiLog2TrSizeChroma, 1 << uiLog2TrSizeChroma );
+  }
+  else
+  {
+    UInt uiNumQPart  = pcCU->getPic()->getNumPartInCU() >> ( ( uiFullDepth + 1 ) << 1 );
+    for( UInt uiPart = 0; uiPart < 4; uiPart++ )
+    {
+      xSetIntraResultChromaQT( pcCU, uiTrDepth + 1, uiAbsPartIdx + uiPart * uiNumQPart, pcRecoYuv );
+    }
+  }
+}
+
+
+Void 
+TEncSearch::preestChromaPredMode( TComDataCU* pcCU, 
+                                 TComYuv*    pcOrgYuv, 
+                                 TComYuv*    pcPredYuv )
+{
+  UInt  uiWidth     = pcCU->getWidth ( 0 ) >> 1;
+  UInt  uiHeight    = pcCU->getHeight( 0 ) >> 1;
+  UInt  uiStride    = pcOrgYuv ->getCStride();
+  Pel*  piOrgU      = pcOrgYuv ->getCbAddr ( 0 );
+  Pel*  piOrgV      = pcOrgYuv ->getCrAddr ( 0 );
+  Pel*  piPredU     = pcPredYuv->getCbAddr ( 0 );
+  Pel*  piPredV     = pcPredYuv->getCrAddr ( 0 );
+  
+  //===== init pattern =====
+  Bool  bAboveAvail = false;
+  Bool  bLeftAvail  = false;
+  pcCU->getPattern()->initPattern         ( pcCU, 0, 0 );
+  pcCU->getPattern()->initAdiPatternChroma( pcCU, 0, 0, m_piYuvExt, m_iYuvExtStride, m_iYuvExtHeight, bAboveAvail, bLeftAvail );
+  Int*  pPatChromaU = pcCU->getPattern()->getAdiCbBuf( uiWidth, uiHeight, m_piYuvExt );
+  Int*  pPatChromaV = pcCU->getPattern()->getAdiCrBuf( uiWidth, uiHeight, m_piYuvExt );
+  
+  //===== get best prediction modes (using SAD) =====
+  UInt  uiMinMode   = 0;
+  UInt  uiMaxMode   = 4;
+  UInt  uiBestMode  = MAX_UINT;
+  UInt  uiMinSAD    = MAX_UINT;
+  for( UInt uiMode  = uiMinMode; uiMode < uiMaxMode; uiMode++ )
+  {
+    //--- get prediction ---
+    predIntraChromaAng( pcCU->getPattern(), pPatChromaU, uiMode, piPredU, uiStride, uiWidth, uiHeight, pcCU, bAboveAvail, bLeftAvail );
+    predIntraChromaAng( pcCU->getPattern(), pPatChromaV, uiMode, piPredV, uiStride, uiWidth, uiHeight, pcCU, bAboveAvail, bLeftAvail );
+    
+    //--- get SAD ---
+    UInt  uiSAD  = m_pcRdCost->calcHAD( piOrgU, uiStride, piPredU, uiStride, uiWidth, uiHeight );
+    uiSAD       += m_pcRdCost->calcHAD( piOrgV, uiStride, piPredV, uiStride, uiWidth, uiHeight );
+    //--- check ---
+    if( uiSAD < uiMinSAD )
+    {
+      uiMinSAD   = uiSAD;
+      uiBestMode = uiMode;
+    }
+  }
+  
+  //===== set chroma pred mode =====
+  pcCU->setChromIntraDirSubParts( uiBestMode, 0, pcCU->getDepth( 0 ) );
+}
+
+Void 
+TEncSearch::estIntraPredQT( TComDataCU* pcCU, 
+                           TComYuv*    pcOrgYuv, 
+                           TComYuv*    pcPredYuv, 
+                           TComYuv*    pcResiYuv, 
+                           TComYuv*    pcRecoYuv,
+                           UInt&       ruiDistC,
+                           Bool        bLumaOnly )
+{
+  UInt    uiDepth        = pcCU->getDepth(0);
+  UInt    uiNumPU        = pcCU->getNumPartInter();
+  UInt    uiInitTrDepth  = pcCU->getPartitionSize(0) == SIZE_2Nx2N ? 0 : 1;
+  UInt    uiWidth        = pcCU->getWidth (0) >> uiInitTrDepth;
+  UInt    uiHeight       = pcCU->getHeight(0) >> uiInitTrDepth;
+  UInt    uiQNumParts    = pcCU->getTotalNumPart() >> 2;
+  UInt    uiWidthBit     = pcCU->getIntraSizeIdx(0);
+  UInt    uiOverallDistY = 0;
+  UInt    uiOverallDistC = 0;
+  UInt    CandNum;
+  Double  CandCostList[ FAST_UDI_MAX_RDMODE_NUM ];
+  
+  //===== set QP and clear Cbf =====
+  if ( pcCU->getSlice()->getPPS()->getUseDQP() == true)
+  {
+    pcCU->setQPSubParts( pcCU->getQP(0), 0, uiDepth );
+  }
+  else
+  {
+    pcCU->setQPSubParts( pcCU->getSlice()->getSliceQp(), 0, uiDepth );
+  }
+  
+  //===== loop over partitions =====
+  UInt uiPartOffset = 0;
+  for( UInt uiPU = 0; uiPU < uiNumPU; uiPU++, uiPartOffset += uiQNumParts )
+  {
+    //===== init pattern for luma prediction =====
+    Bool bAboveAvail = false;
+    Bool bLeftAvail  = false;
+    pcCU->getPattern()->initPattern   ( pcCU, uiInitTrDepth, uiPartOffset );
+    pcCU->getPattern()->initAdiPattern( pcCU, uiPartOffset, uiInitTrDepth, m_piYuvExt, m_iYuvExtStride, m_iYuvExtHeight, bAboveAvail, bLeftAvail );
+    
+    //===== determine set of modes to be tested (using prediction signal only) =====
+    Int numModesAvailable     = 35; //total number of Intra modes
+    Pel* piOrg         = pcOrgYuv ->getLumaAddr( uiPU, uiWidth );
+    Pel* piPred        = pcPredYuv->getLumaAddr( uiPU, uiWidth );
+    UInt uiStride      = pcPredYuv->getStride();
+    UInt uiRdModeList[FAST_UDI_MAX_RDMODE_NUM];
+    Int numModesForFullRD = g_aucIntraModeNumFast[ uiWidthBit ];
+    
+    Bool doFastSearch = (numModesForFullRD != numModesAvailable);
+    if (doFastSearch)
+    {
+      assert(numModesForFullRD < numModesAvailable);
+
+      for( Int i=0; i < numModesForFullRD; i++ ) 
+      {
+        CandCostList[ i ] = MAX_DOUBLE;
+      }
+      CandNum = 0;
+      
+      for( Int modeIdx = 0; modeIdx < numModesAvailable; modeIdx++ )
+      {
+        UInt uiMode = modeIdx;
+
+        predIntraLumaAng( pcCU->getPattern(), uiMode, piPred, uiStride, uiWidth, uiHeight, pcCU, bAboveAvail, bLeftAvail );
+        
+        // use hadamard transform here
+        UInt uiSad = m_pcRdCost->calcHAD( piOrg, uiStride, piPred, uiStride, uiWidth, uiHeight );
+        
+        UInt   iModeBits = xModeBitsIntra( pcCU, uiMode, uiPU, uiPartOffset, uiDepth, uiInitTrDepth );
+        Double cost      = (Double)uiSad + (Double)iModeBits * m_pcRdCost->getSqrtLambda();
+        
+        CandNum += xUpdateCandList( uiMode, cost, numModesForFullRD, uiRdModeList, CandCostList );
+      }
+    
+#if FAST_UDI_USE_MPM
+      Int uiPreds[3] = {-1, -1, -1};
+      Int iMode = -1;
+      Int numCand = pcCU->getIntraDirLumaPredictor( uiPartOffset, uiPreds, &iMode );
+      if( iMode >= 0 )
+      {
+        numCand = iMode;
+      }
+      
+      for( Int j=0; j < numCand; j++)
+
+      {
+        Bool mostProbableModeIncluded = false;
+        Int mostProbableMode = uiPreds[j];
+        
+        for( Int i=0; i < numModesForFullRD; i++)
+        {
+          mostProbableModeIncluded |= (mostProbableMode == uiRdModeList[i]);
+        }
+        if (!mostProbableModeIncluded)
+        {
+          uiRdModeList[numModesForFullRD++] = mostProbableMode;
+        }
+      }
+#endif // FAST_UDI_USE_MPM
+    }
+    else
+    {
+      for( Int i=0; i < numModesForFullRD; i++)
+      {
+        uiRdModeList[i] = i;
+      }
+    }
+    
+    //===== check modes (using r-d costs) =====
+#if HHI_RQT_INTRA_SPEEDUP_MOD
+    UInt   uiSecondBestMode  = MAX_UINT;
+    Double dSecondBestPUCost = MAX_DOUBLE;
+#endif
+    
+    UInt    uiBestPUMode  = 0;
+    UInt    uiBestPUDistY = 0;
+    UInt    uiBestPUDistC = 0;
+    Double  dBestPUCost   = MAX_DOUBLE;
+    for( UInt uiMode = 0; uiMode < numModesForFullRD; uiMode++ )
+    {
+      // set luma prediction mode
+      UInt uiOrgMode = uiRdModeList[uiMode];
+      
+      pcCU->setLumaIntraDirSubParts ( uiOrgMode, uiPartOffset, uiDepth + uiInitTrDepth );
+      
+      // set context models
+      if( m_bUseSBACRD )
+      {
+        m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
+      }
+      
+      // determine residual for partition
+      UInt   uiPUDistY = 0;
+      UInt   uiPUDistC = 0;
+      Double dPUCost   = 0.0;
+#if HHI_RQT_INTRA_SPEEDUP
+      xRecurIntraCodingQT( pcCU, uiInitTrDepth, uiPartOffset, bLumaOnly, pcOrgYuv, pcPredYuv, pcResiYuv, uiPUDistY, uiPUDistC, true, dPUCost );
+#else
+      xRecurIntraCodingQT( pcCU, uiInitTrDepth, uiPartOffset, bLumaOnly, pcOrgYuv, pcPredYuv, pcResiYuv, uiPUDistY, uiPUDistC, dPUCost );
+#endif
+      
+      // check r-d cost
+      if( dPUCost < dBestPUCost )
+      {
+#if HHI_RQT_INTRA_SPEEDUP_MOD
+        uiSecondBestMode  = uiBestPUMode;
+        dSecondBestPUCost = dBestPUCost;
+#endif
+        uiBestPUMode  = uiOrgMode;
+        uiBestPUDistY = uiPUDistY;
+        uiBestPUDistC = uiPUDistC;
+        dBestPUCost   = dPUCost;
+        
+        xSetIntraResultQT( pcCU, uiInitTrDepth, uiPartOffset, bLumaOnly, pcRecoYuv );
+        
+        UInt uiQPartNum = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth(0) + uiInitTrDepth ) << 1 );
+        ::memcpy( m_puhQTTempTrIdx,  pcCU->getTransformIdx()       + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+        ::memcpy( m_puhQTTempCbf[0], pcCU->getCbf( TEXT_LUMA     ) + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+        ::memcpy( m_puhQTTempCbf[1], pcCU->getCbf( TEXT_CHROMA_U ) + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+        ::memcpy( m_puhQTTempCbf[2], pcCU->getCbf( TEXT_CHROMA_V ) + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+        ::memcpy( m_puhQTTempTransformSkipFlag[0], pcCU->getTransformSkip(TEXT_LUMA)     + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+        ::memcpy( m_puhQTTempTransformSkipFlag[1], pcCU->getTransformSkip(TEXT_CHROMA_U) + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+        ::memcpy( m_puhQTTempTransformSkipFlag[2], pcCU->getTransformSkip(TEXT_CHROMA_V) + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+      }
+#if HHI_RQT_INTRA_SPEEDUP_MOD
+      else if( dPUCost < dSecondBestPUCost )
+      {
+        uiSecondBestMode  = uiOrgMode;
+        dSecondBestPUCost = dPUCost;
+      }
+#endif
+    } // Mode loop
+    
+#if HHI_RQT_INTRA_SPEEDUP
+#if HHI_RQT_INTRA_SPEEDUP_MOD
+    for( UInt ui =0; ui < 2; ++ui )
+#endif
+    {
+#if HHI_RQT_INTRA_SPEEDUP_MOD
+      UInt uiOrgMode   = ui ? uiSecondBestMode  : uiBestPUMode;
+      if( uiOrgMode == MAX_UINT )
+      {
+        break;
+      }
+#else
+      UInt uiOrgMode = uiBestPUMode;
+#endif
+      
+      pcCU->setLumaIntraDirSubParts ( uiOrgMode, uiPartOffset, uiDepth + uiInitTrDepth );
+      
+      // set context models
+      if( m_bUseSBACRD )
+      {
+        m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
+      }
+      
+      // determine residual for partition
+      UInt   uiPUDistY = 0;
+      UInt   uiPUDistC = 0;
+      Double dPUCost   = 0.0;
+      xRecurIntraCodingQT( pcCU, uiInitTrDepth, uiPartOffset, bLumaOnly, pcOrgYuv, pcPredYuv, pcResiYuv, uiPUDistY, uiPUDistC, false, dPUCost );
+      
+      // check r-d cost
+      if( dPUCost < dBestPUCost )
+      {
+        uiBestPUMode  = uiOrgMode;
+        uiBestPUDistY = uiPUDistY;
+        uiBestPUDistC = uiPUDistC;
+        dBestPUCost   = dPUCost;
+        
+        xSetIntraResultQT( pcCU, uiInitTrDepth, uiPartOffset, bLumaOnly, pcRecoYuv );
+        
+        UInt uiQPartNum = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth(0) + uiInitTrDepth ) << 1 );
+        ::memcpy( m_puhQTTempTrIdx,  pcCU->getTransformIdx()       + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+        ::memcpy( m_puhQTTempCbf[0], pcCU->getCbf( TEXT_LUMA     ) + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+        ::memcpy( m_puhQTTempCbf[1], pcCU->getCbf( TEXT_CHROMA_U ) + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+        ::memcpy( m_puhQTTempCbf[2], pcCU->getCbf( TEXT_CHROMA_V ) + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+        ::memcpy( m_puhQTTempTransformSkipFlag[0], pcCU->getTransformSkip(TEXT_LUMA)     + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+        ::memcpy( m_puhQTTempTransformSkipFlag[1], pcCU->getTransformSkip(TEXT_CHROMA_U) + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+        ::memcpy( m_puhQTTempTransformSkipFlag[2], pcCU->getTransformSkip(TEXT_CHROMA_V) + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+      }
+    } // Mode loop
+#endif
+    
+    //--- update overall distortion ---
+    uiOverallDistY += uiBestPUDistY;
+    uiOverallDistC += uiBestPUDistC;
+    
+    //--- update transform index and cbf ---
+    UInt uiQPartNum = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth(0) + uiInitTrDepth ) << 1 );
+    ::memcpy( pcCU->getTransformIdx()       + uiPartOffset, m_puhQTTempTrIdx,  uiQPartNum * sizeof( UChar ) );
+    ::memcpy( pcCU->getCbf( TEXT_LUMA     ) + uiPartOffset, m_puhQTTempCbf[0], uiQPartNum * sizeof( UChar ) );
+    ::memcpy( pcCU->getCbf( TEXT_CHROMA_U ) + uiPartOffset, m_puhQTTempCbf[1], uiQPartNum * sizeof( UChar ) );
+    ::memcpy( pcCU->getCbf( TEXT_CHROMA_V ) + uiPartOffset, m_puhQTTempCbf[2], uiQPartNum * sizeof( UChar ) );
+    ::memcpy( pcCU->getTransformSkip(TEXT_LUMA)     + uiPartOffset, m_puhQTTempTransformSkipFlag[0], uiQPartNum * sizeof( UChar ) );
+    ::memcpy( pcCU->getTransformSkip(TEXT_CHROMA_U) + uiPartOffset, m_puhQTTempTransformSkipFlag[1], uiQPartNum * sizeof( UChar ) );
+    ::memcpy( pcCU->getTransformSkip(TEXT_CHROMA_V) + uiPartOffset, m_puhQTTempTransformSkipFlag[2], uiQPartNum * sizeof( UChar ) );
+    //--- set reconstruction for next intra prediction blocks ---
+    if( uiPU != uiNumPU - 1 )
+    {
+      Bool bSkipChroma  = false;
+      Bool bChromaSame  = false;
+      UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> ( pcCU->getDepth(0) + uiInitTrDepth ) ] + 2;
+      if( !bLumaOnly && uiLog2TrSize == 2 )
+      {
+        assert( uiInitTrDepth  > 0 );
+        bSkipChroma  = ( uiPU != 0 );
+        bChromaSame  = true;
+      }
+      
+      UInt    uiCompWidth   = pcCU->getWidth ( 0 ) >> uiInitTrDepth;
+      UInt    uiCompHeight  = pcCU->getHeight( 0 ) >> uiInitTrDepth;
+      UInt    uiZOrder      = pcCU->getZorderIdxInCU() + uiPartOffset;
+      Pel*    piDes         = pcCU->getPic()->getPicYuvRec()->getLumaAddr( pcCU->getAddr(), uiZOrder );
+      UInt    uiDesStride   = pcCU->getPic()->getPicYuvRec()->getStride();
+      Pel*    piSrc         = pcRecoYuv->getLumaAddr( uiPartOffset );
+      UInt    uiSrcStride   = pcRecoYuv->getStride();
+      for( UInt uiY = 0; uiY < uiCompHeight; uiY++, piSrc += uiSrcStride, piDes += uiDesStride )
+      {
+        for( UInt uiX = 0; uiX < uiCompWidth; uiX++ )
+        {
+          piDes[ uiX ] = piSrc[ uiX ];
+        }
+      }
+      if( !bLumaOnly && !bSkipChroma )
+      {
+        if( !bChromaSame )
+        {
+          uiCompWidth   >>= 1;
+          uiCompHeight  >>= 1;
+        }
+        piDes         = pcCU->getPic()->getPicYuvRec()->getCbAddr( pcCU->getAddr(), uiZOrder );
+        uiDesStride   = pcCU->getPic()->getPicYuvRec()->getCStride();
+        piSrc         = pcRecoYuv->getCbAddr( uiPartOffset );
+        uiSrcStride   = pcRecoYuv->getCStride();
+        for( UInt uiY = 0; uiY < uiCompHeight; uiY++, piSrc += uiSrcStride, piDes += uiDesStride )
+        {
+          for( UInt uiX = 0; uiX < uiCompWidth; uiX++ )
+          {
+            piDes[ uiX ] = piSrc[ uiX ];
+          }
+        }
+        piDes         = pcCU->getPic()->getPicYuvRec()->getCrAddr( pcCU->getAddr(), uiZOrder );
+        piSrc         = pcRecoYuv->getCrAddr( uiPartOffset );
+        for( UInt uiY = 0; uiY < uiCompHeight; uiY++, piSrc += uiSrcStride, piDes += uiDesStride )
+        {
+          for( UInt uiX = 0; uiX < uiCompWidth; uiX++ )
+          {
+            piDes[ uiX ] = piSrc[ uiX ];
+          }
+        }
+      }
+    }
+    
+    //=== update PU data ====
+    pcCU->setLumaIntraDirSubParts     ( uiBestPUMode, uiPartOffset, uiDepth + uiInitTrDepth );
+    pcCU->copyToPic                   ( uiDepth, uiPU, uiInitTrDepth );
+  } // PU loop
+  
+  
+  if( uiNumPU > 1 )
+  { // set Cbf for all blocks
+    UInt uiCombCbfY = 0;
+    UInt uiCombCbfU = 0;
+    UInt uiCombCbfV = 0;
+    UInt uiPartIdx  = 0;
+    for( UInt uiPart = 0; uiPart < 4; uiPart++, uiPartIdx += uiQNumParts )
+    {
+      uiCombCbfY |= pcCU->getCbf( uiPartIdx, TEXT_LUMA,     1 );
+      uiCombCbfU |= pcCU->getCbf( uiPartIdx, TEXT_CHROMA_U, 1 );
+      uiCombCbfV |= pcCU->getCbf( uiPartIdx, TEXT_CHROMA_V, 1 );
+    }
+    for( UInt uiOffs = 0; uiOffs < 4 * uiQNumParts; uiOffs++ )
+    {
+      pcCU->getCbf( TEXT_LUMA     )[ uiOffs ] |= uiCombCbfY;
+      pcCU->getCbf( TEXT_CHROMA_U )[ uiOffs ] |= uiCombCbfU;
+      pcCU->getCbf( TEXT_CHROMA_V )[ uiOffs ] |= uiCombCbfV;
+    }
+  }
+  
+  //===== reset context models =====
+  if(m_bUseSBACRD)
+  {
+    m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
+  }
+  
+  //===== set distortion (rate and r-d costs are determined later) =====
+  ruiDistC                   = uiOverallDistC;
+  pcCU->getTotalDistortion() = uiOverallDistY + uiOverallDistC;
+}
+
+#if INTRA_BL
+Void 
+TEncSearch::estIntraBLPredQT( TComDataCU* pcCU, 
+                           TComYuv*    pcOrgYuv, 
+                           TComYuv*    pcPredYuv, 
+                           TComYuv*    pcResiYuv,
+                           TComYuv*    pcRecoYuv )
+{
+  UInt    uiDepth        = pcCU->getDepth(0);
+  UInt    uiOverallDistY = 0;
+  UInt    uiOverallDistC = 0;
+  
+  //===== set QP and clear Cbf =====
+  if ( pcCU->getSlice()->getPPS()->getUseDQP() == true)
+  {
+    pcCU->setQPSubParts( pcCU->getQP(0), 0, uiDepth );
+  }
+  else
+  {
+    pcCU->setQPSubParts( pcCU->getSlice()->getSliceQp(), 0, uiDepth );
+  }
+  
+  //===== init pattern for luma prediction =====
+  Bool bAboveAvail = false;
+  Bool bLeftAvail  = false;
+  pcCU->getPattern()->initPattern   ( pcCU, 0, 0 );
+  pcCU->getPattern()->initAdiPattern( pcCU, 0, 0, m_piYuvExt, m_iYuvExtStride, m_iYuvExtHeight, bAboveAvail, bLeftAvail );
+  
+  pcCU->setLumaIntraDirSubParts ( DC_IDX, 0, uiDepth );
+  
+  // set context models
+  if( m_bUseSBACRD )
+  {
+    m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
+  }
+  
+  // determine residual for partition
+  Double dPUCost   = 0.0;
+  xRecurIntraCodingQT( pcCU, 0, 0, false, pcOrgYuv, pcPredYuv, pcResiYuv, uiOverallDistY, uiOverallDistC, false, dPUCost );
+  xSetIntraResultQT( pcCU, 0, 0, false, pcRecoYuv );
+  
+  //=== update PU data ====
+  pcCU->copyToPic( uiDepth, 0, 0 );
+   
+  //===== reset context models =====
+  if(m_bUseSBACRD)
+  {
+    m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
+  }
+
+  //===== set distortion (rate and r-d costs are determined later) =====
+  pcCU->getTotalDistortion() = uiOverallDistY + uiOverallDistC;
+}
+
+#endif
+
+Void 
+TEncSearch::estIntraPredChromaQT( TComDataCU* pcCU, 
+                                 TComYuv*    pcOrgYuv, 
+                                 TComYuv*    pcPredYuv, 
+                                 TComYuv*    pcResiYuv, 
+                                 TComYuv*    pcRecoYuv,
+                                 UInt        uiPreCalcDistC )
+{
+  UInt    uiDepth     = pcCU->getDepth(0);
+  UInt    uiBestMode  = 0;
+  UInt    uiBestDist  = 0;
+  Double  dBestCost   = MAX_DOUBLE;
+  
+  //----- init mode list -----
+  UInt  uiMinMode = 0;
+  UInt  uiModeList[ NUM_CHROMA_MODE ];
+  pcCU->getAllowedChromaDir( 0, uiModeList );
+  UInt  uiMaxMode = NUM_CHROMA_MODE;
+
+  //----- check chroma modes -----
+  for( UInt uiMode = uiMinMode; uiMode < uiMaxMode; uiMode++ )
+  {
+#if !REMOVE_LMCHROMA
+    if ( !pcCU->getSlice()->getSPS()->getUseLMChroma() && uiModeList[uiMode] == LM_CHROMA_IDX )
+    {
+      continue;
+    }
+#endif
+    //----- restore context models -----
+    if( m_bUseSBACRD )
+    {
+      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
+    }
+    
+    //----- chroma coding -----
+    UInt    uiDist = 0;
+    pcCU->setChromIntraDirSubParts  ( uiModeList[uiMode], 0, uiDepth );
+    xRecurIntraChromaCodingQT       ( pcCU,   0, 0, pcOrgYuv, pcPredYuv, pcResiYuv, uiDist );
+#if PPS_TS_FLAG
+#if INTRA_TRANSFORMSKIP_FAST
+    if( m_bUseSBACRD && pcCU->getSlice()->getPPS()->getUseTransformSkip() )
+#else
+    if( m_bUseSBACRD && pcCU->getSlice()->getPPS()->getUseTransformSkip() && !m_pcEncCfg->getUseTransformSkipFast())
+#endif
+#else
+#if INTRA_TRANSFORMSKIP_FAST
+    if( m_bUseSBACRD && pcCU->getSlice()->getSPS()->getUseTransformSkip() )
+#else
+    if( m_bUseSBACRD && pcCU->getSlice()->getSPS()->getUseTransformSkip() && !m_pcEncCfg->getUseTransformSkipFast())
+#endif
+#endif
+    {
+      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
+    }
+    UInt    uiBits = xGetIntraBitsQT( pcCU,   0, 0, false, true, false );
+    Double  dCost  = m_pcRdCost->calcRdCost( uiBits, uiDist );
+    
+    //----- compare -----
+    if( dCost < dBestCost )
+    {
+      dBestCost   = dCost;
+      uiBestDist  = uiDist;
+      uiBestMode  = uiModeList[uiMode];
+      UInt  uiQPN = pcCU->getPic()->getNumPartInCU() >> ( uiDepth << 1 );
+      xSetIntraResultChromaQT( pcCU, 0, 0, pcRecoYuv );
+      ::memcpy( m_puhQTTempCbf[1], pcCU->getCbf( TEXT_CHROMA_U ), uiQPN * sizeof( UChar ) );
+      ::memcpy( m_puhQTTempCbf[2], pcCU->getCbf( TEXT_CHROMA_V ), uiQPN * sizeof( UChar ) );
+      ::memcpy( m_puhQTTempTransformSkipFlag[1], pcCU->getTransformSkip( TEXT_CHROMA_U ), uiQPN * sizeof( UChar ) );
+      ::memcpy( m_puhQTTempTransformSkipFlag[2], pcCU->getTransformSkip( TEXT_CHROMA_V ), uiQPN * sizeof( UChar ) );
+    }
+  }
+  
+  //----- set data -----
+  UInt  uiQPN = pcCU->getPic()->getNumPartInCU() >> ( uiDepth << 1 );
+  ::memcpy( pcCU->getCbf( TEXT_CHROMA_U ), m_puhQTTempCbf[1], uiQPN * sizeof( UChar ) );
+  ::memcpy( pcCU->getCbf( TEXT_CHROMA_V ), m_puhQTTempCbf[2], uiQPN * sizeof( UChar ) );
+  ::memcpy( pcCU->getTransformSkip( TEXT_CHROMA_U ), m_puhQTTempTransformSkipFlag[1], uiQPN * sizeof( UChar ) );
+  ::memcpy( pcCU->getTransformSkip( TEXT_CHROMA_V ), m_puhQTTempTransformSkipFlag[2], uiQPN * sizeof( UChar ) );
+  pcCU->setChromIntraDirSubParts( uiBestMode, 0, uiDepth );
+  pcCU->getTotalDistortion      () += uiBestDist - uiPreCalcDistC;
+  
+  //----- restore context models -----
+  if( m_bUseSBACRD )
+  {
+    m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
+  }
+}
+
+/** Function for encoding and reconstructing luma/chroma samples of a PCM mode CU.
+ * \param pcCU pointer to current CU
+ * \param uiAbsPartIdx part index
+ * \param piOrg pointer to original sample arrays
+ * \param piPCM pointer to PCM code arrays
+ * \param piPred pointer to prediction signal arrays
+ * \param piResi pointer to residual signal arrays
+ * \param piReco pointer to reconstructed sample arrays
+ * \param uiStride stride of the original/prediction/residual sample arrays
+ * \param uiWidth block width
+ * \param uiHeight block height
+ * \param ttText texture component type
+ * \returns Void
+ */
+Void TEncSearch::xEncPCM (TComDataCU* pcCU, UInt uiAbsPartIdx, Pel* piOrg, Pel* piPCM, Pel* piPred, Pel* piResi, Pel* piReco, UInt uiStride, UInt uiWidth, UInt uiHeight, TextType eText )
+{
+  UInt uiX, uiY;
+  UInt uiReconStride;
+  Pel* pOrg  = piOrg;
+  Pel* pPCM  = piPCM;
+  Pel* pPred = piPred;
+  Pel* pResi = piResi;
+  Pel* pReco = piReco;
+  Pel* pRecoPic;
+  UInt uiInternalBitDepth = g_uiBitDepth + g_uiBitIncrement;
+  UInt uiPCMBitDepth;
+
+  if( eText == TEXT_LUMA)
+  {
+    uiReconStride = pcCU->getPic()->getPicYuvRec()->getStride();
+    pRecoPic      = pcCU->getPic()->getPicYuvRec()->getLumaAddr(pcCU->getAddr(), pcCU->getZorderIdxInCU()+uiAbsPartIdx);
+    uiPCMBitDepth = pcCU->getSlice()->getSPS()->getPCMBitDepthLuma();
+  }
+  else
+  {
+    uiReconStride = pcCU->getPic()->getPicYuvRec()->getCStride();
+
+    if( eText == TEXT_CHROMA_U )
+    {
+      pRecoPic = pcCU->getPic()->getPicYuvRec()->getCbAddr(pcCU->getAddr(), pcCU->getZorderIdxInCU()+uiAbsPartIdx);
+    }
+    else
+    {
+      pRecoPic = pcCU->getPic()->getPicYuvRec()->getCrAddr(pcCU->getAddr(), pcCU->getZorderIdxInCU()+uiAbsPartIdx);
+    }
+    uiPCMBitDepth = pcCU->getSlice()->getSPS()->getPCMBitDepthChroma();
+  }
+
+  // Reset pred and residual
+  for( uiY = 0; uiY < uiHeight; uiY++ )
+  {
+    for( uiX = 0; uiX < uiWidth; uiX++ )
+    {
+      pPred[uiX] = 0;
+      pResi[uiX] = 0;
+    }
+    pPred += uiStride;
+    pResi += uiStride;
+  }
+
+  // Encode
+  for( uiY = 0; uiY < uiHeight; uiY++ )
+  {
+    for( uiX = 0; uiX < uiWidth; uiX++ )
+    {
+      pPCM[uiX] = (pOrg[uiX]>>(uiInternalBitDepth - uiPCMBitDepth));
+    }
+    pPCM += uiWidth;
+    pOrg += uiStride;
+  }
+
+  pPCM  = piPCM;
+
+  // Reconstruction
+  for( uiY = 0; uiY < uiHeight; uiY++ )
+  {
+    for( uiX = 0; uiX < uiWidth; uiX++ )
+    {
+      pReco   [uiX] = (pPCM[uiX]<<(uiInternalBitDepth - uiPCMBitDepth));
+      pRecoPic[uiX] = pReco[uiX];
+    }
+    pPCM += uiWidth;
+    pReco += uiStride;
+    pRecoPic += uiReconStride;
+  }
+}
+
+/**  Function for PCM mode estimation.
+ * \param pcCU
+ * \param pcOrgYuv
+ * \param rpcPredYuv
+ * \param rpcResiYuv
+ * \param rpcRecoYuv
+ * \returns Void
+ */
+Void TEncSearch::IPCMSearch( TComDataCU* pcCU, TComYuv* pcOrgYuv, TComYuv*& rpcPredYuv, TComYuv*& rpcResiYuv, TComYuv*& rpcRecoYuv )
+{
+  UInt   uiDepth        = pcCU->getDepth(0);
+  UInt   uiWidth        = pcCU->getWidth(0);
+  UInt   uiHeight       = pcCU->getHeight(0);
+  UInt   uiStride       = rpcPredYuv->getStride();
+  UInt   uiStrideC      = rpcPredYuv->getCStride();
+  UInt   uiWidthC       = uiWidth  >> 1;
+  UInt   uiHeightC      = uiHeight >> 1;
+  UInt   uiDistortion = 0;
+  UInt   uiBits;
+
+  Double dCost;
+
+  Pel*    pOrig;
+  Pel*    pResi;
+  Pel*    pReco;
+  Pel*    pPred;
+  Pel*    pPCM;
+
+  UInt uiAbsPartIdx = 0;
+
+  UInt uiMinCoeffSize = pcCU->getPic()->getMinCUWidth()*pcCU->getPic()->getMinCUHeight();
+  UInt uiLumaOffset   = uiMinCoeffSize*uiAbsPartIdx;
+  UInt uiChromaOffset = uiLumaOffset>>2;
+
+  // Luminance
+  pOrig    = pcOrgYuv->getLumaAddr(0, uiWidth);
+  pResi    = rpcResiYuv->getLumaAddr(0, uiWidth);
+  pPred    = rpcPredYuv->getLumaAddr(0, uiWidth);
+  pReco    = rpcRecoYuv->getLumaAddr(0, uiWidth);
+  pPCM     = pcCU->getPCMSampleY() + uiLumaOffset;
+
+  xEncPCM ( pcCU, 0, pOrig, pPCM, pPred, pResi, pReco, uiStride, uiWidth, uiHeight, TEXT_LUMA );
+
+  // Chroma U
+  pOrig    = pcOrgYuv->getCbAddr();
+  pResi    = rpcResiYuv->getCbAddr();
+  pPred    = rpcPredYuv->getCbAddr();
+  pReco    = rpcRecoYuv->getCbAddr();
+  pPCM     = pcCU->getPCMSampleCb() + uiChromaOffset;
+
+  xEncPCM ( pcCU, 0, pOrig, pPCM, pPred, pResi, pReco, uiStrideC, uiWidthC, uiHeightC, TEXT_CHROMA_U );
+
+  // Chroma V
+  pOrig    = pcOrgYuv->getCrAddr();
+  pResi    = rpcResiYuv->getCrAddr();
+  pPred    = rpcPredYuv->getCrAddr();
+  pReco    = rpcRecoYuv->getCrAddr();
+  pPCM     = pcCU->getPCMSampleCr() + uiChromaOffset;
+
+  xEncPCM ( pcCU, 0, pOrig, pPCM, pPred, pResi, pReco, uiStrideC, uiWidthC, uiHeightC, TEXT_CHROMA_V );
+
+  m_pcEntropyCoder->resetBits();
+  xEncIntraHeader ( pcCU, uiDepth, uiAbsPartIdx, true, false);
+  uiBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+
+  dCost = m_pcRdCost->calcRdCost( uiBits, uiDistortion );
+
+  if(m_bUseSBACRD)
+  {
+    m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
+  }
+
+  pcCU->getTotalBits()       = uiBits;
+  pcCU->getTotalCost()       = dCost;
+  pcCU->getTotalDistortion() = uiDistortion;
+
+  pcCU->copyToPic(uiDepth, 0, 0);
+}
+
+Void TEncSearch::xGetInterPredictionError( TComDataCU* pcCU, TComYuv* pcYuvOrg, Int iPartIdx, UInt& ruiErr, Bool bHadamard )
+{
+  motionCompensation( pcCU, &m_tmpYuvPred, REF_PIC_LIST_X, iPartIdx );
+
+  UInt uiAbsPartIdx = 0;
+  Int iWidth = 0;
+  Int iHeight = 0;
+  pcCU->getPartIndexAndSize( iPartIdx, uiAbsPartIdx, iWidth, iHeight );
+
+  DistParam cDistParam;
+
+  cDistParam.bApplyWeight = false;
+
+  m_pcRdCost->setDistParam( cDistParam, 
+                            pcYuvOrg->getLumaAddr( uiAbsPartIdx ), pcYuvOrg->getStride(), 
+                            m_tmpYuvPred .getLumaAddr( uiAbsPartIdx ), m_tmpYuvPred .getStride(), 
+#if NS_HAD
+                            iWidth, iHeight, m_pcEncCfg->getUseHADME(), m_pcEncCfg->getUseNSQT() );
+#else
+                            iWidth, iHeight, m_pcEncCfg->getUseHADME() );
+#endif
+  ruiErr = cDistParam.DistFunc( &cDistParam );
+}
+
+/** estimation of best merge coding
+ * \param pcCU
+ * \param pcYuvOrg
+ * \param iPUIdx
+ * \param uiInterDir
+ * \param pacMvField
+ * \param uiMergeIndex
+ * \param ruiCost
+ * \param ruiBits
+ * \param puhNeighCands
+ * \param bValid 
+ * \returns Void
+ */
+Void TEncSearch::xMergeEstimation( TComDataCU* pcCU, TComYuv* pcYuvOrg, Int iPUIdx, UInt& uiInterDir, TComMvField* pacMvField, UInt& uiMergeIndex, UInt& ruiCost, TComMvField* cMvFieldNeighbours, UChar* uhInterDirNeighbours, Int& numValidMergeCand )
+{
+  UInt uiAbsPartIdx = 0;
+  Int iWidth = 0;
+  Int iHeight = 0; 
+
+#if REF_IDX_FRAMEWORK  // HM bug fix
+  for( UInt uiMergeCand = 0; uiMergeCand < pcCU->getSlice()->getMaxNumMergeCand(); ++uiMergeCand )
+  {
+    uhInterDirNeighbours[uiMergeCand] = 0;
+    cMvFieldNeighbours[0 + 2*uiMergeCand].setMvField(TComMv(), NOT_VALID);
+	  cMvFieldNeighbours[1 + 2*uiMergeCand].setMvField(TComMv(), NOT_VALID);
+  }
+#endif
+  pcCU->getPartIndexAndSize( iPUIdx, uiAbsPartIdx, iWidth, iHeight );
+  UInt uiDepth = pcCU->getDepth( uiAbsPartIdx );
+  PartSize partSize = pcCU->getPartitionSize( 0 );
+  if ( pcCU->getSlice()->getPPS()->getLog2ParallelMergeLevelMinus2() && partSize != SIZE_2Nx2N && pcCU->getWidth( 0 ) <= 8 )
+  {
+    pcCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uiDepth );
+    if ( iPUIdx == 0 )
+    {
+      pcCU->getInterMergeCandidates( 0, 0, uiDepth, cMvFieldNeighbours,uhInterDirNeighbours, numValidMergeCand );
+    }
+    pcCU->setPartSizeSubParts( partSize, 0, uiDepth );
+  }
+  else
+  {
+    pcCU->getInterMergeCandidates( uiAbsPartIdx, iPUIdx, uiDepth, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand );
+  }
+  xRestrictBipredMergeCand( pcCU, iPUIdx, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand );
+
+  ruiCost = MAX_UINT;
+  for( UInt uiMergeCand = 0; uiMergeCand < numValidMergeCand; ++uiMergeCand )
+  {
+    {
+      UInt uiCostCand = MAX_UINT;
+      UInt uiBitsCand = 0;
+      
+      PartSize ePartSize = pcCU->getPartitionSize( 0 );
+
+      pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvField( cMvFieldNeighbours[0 + 2*uiMergeCand], ePartSize, uiAbsPartIdx, 0, iPUIdx );
+      pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvField( cMvFieldNeighbours[1 + 2*uiMergeCand], ePartSize, uiAbsPartIdx, 0, iPUIdx );
+
+      xGetInterPredictionError( pcCU, pcYuvOrg, iPUIdx, uiCostCand, m_pcEncCfg->getUseHADME() );
+      uiBitsCand = uiMergeCand + 1;
+      if (uiMergeCand == m_pcEncCfg->getMaxNumMergeCand() -1)
+      {
+         uiBitsCand--;
+      }
+      uiCostCand = uiCostCand + m_pcRdCost->getCost( uiBitsCand );
+      if ( uiCostCand < ruiCost )
+      {
+        ruiCost = uiCostCand;
+        pacMvField[0] = cMvFieldNeighbours[0 + 2*uiMergeCand];
+        pacMvField[1] = cMvFieldNeighbours[1 + 2*uiMergeCand];
+        uiInterDir = uhInterDirNeighbours[uiMergeCand];
+        uiMergeIndex = uiMergeCand;
+      }
+    }
+  }
+}
+
+/** convert bi-pred merge candidates to uni-pred
+ * \param pcCU
+ * \param puIdx
+ * \param mvFieldNeighbours
+ * \param interDirNeighbours
+ * \param numValidMergeCand
+ * \returns Void
+ */
+Void TEncSearch::xRestrictBipredMergeCand( TComDataCU* pcCU, UInt puIdx, TComMvField* mvFieldNeighbours, UChar* interDirNeighbours, Int numValidMergeCand )
+{
+  if ( pcCU->isBipredRestriction(puIdx) )
+  {
+    for( UInt mergeCand = 0; mergeCand < numValidMergeCand; ++mergeCand )
+    {
+      if ( interDirNeighbours[mergeCand] == 3 )
+      {
+        interDirNeighbours[mergeCand] = 1;
+        mvFieldNeighbours[(mergeCand << 1) + 1].setMvField(TComMv(0,0), -1);
+      }
+    }
+  }
+}
+
+/** search of the best candidate for inter prediction
+ * \param pcCU
+ * \param pcOrgYuv
+ * \param rpcPredYuv
+ * \param rpcResiYuv
+ * \param rpcRecoYuv
+ * \param bUseRes
+ * \returns Void
+ */
+#if AMP_MRG
+Void TEncSearch::predInterSearch( TComDataCU* pcCU, TComYuv* pcOrgYuv, TComYuv*& rpcPredYuv, TComYuv*& rpcResiYuv, TComYuv*& rpcRecoYuv, Bool bUseRes, Bool bUseMRG )
+#else
+Void TEncSearch::predInterSearch( TComDataCU* pcCU, TComYuv* pcOrgYuv, TComYuv*& rpcPredYuv, TComYuv*& rpcResiYuv, TComYuv*& rpcRecoYuv, Bool bUseRes )
+#endif
+{
+  m_acYuvPred[0].clear();
+  m_acYuvPred[1].clear();
+  m_cYuvPredTemp.clear();
+  rpcPredYuv->clear();
+  
+  if ( !bUseRes )
+  {
+    rpcResiYuv->clear();
+  }
+  
+  rpcRecoYuv->clear();
+  
+  TComMv        cMvSrchRngLT;
+  TComMv        cMvSrchRngRB;
+  
+  TComMv        cMvZero;
+  TComMv        TempMv; //kolya
+  
+  TComMv        cMv[2];
+  TComMv        cMvBi[2];
+  TComMv        cMvTemp[2][33];
+  
+  Int           iNumPart    = pcCU->getNumPartInter();
+  Int           iNumPredDir = pcCU->getSlice()->isInterP() ? 1 : 2;
+  
+  TComMv        cMvPred[2][33];
+  
+  TComMv        cMvPredBi[2][33];
+  Int           aaiMvpIdxBi[2][33];
+  
+  Int           aaiMvpIdx[2][33];
+  Int           aaiMvpNum[2][33];
+  
+  AMVPInfo aacAMVPInfo[2][33];
+  
+  Int           iRefIdx[2]={0,0}; //If un-initialized, may cause SEGV in bi-directional prediction iterative stage.
+  Int           iRefIdxBi[2];
+  
+  UInt          uiPartAddr;
+  Int           iRoiWidth, iRoiHeight;
+  
+  UInt          uiMbBits[3] = {1, 1, 0};
+  
+  UInt          uiLastMode = 0;
+  Int           iRefStart, iRefEnd;
+  
+  PartSize      ePartSize = pcCU->getPartitionSize( 0 );
+
+  Int           bestBiPRefIdxL1 = 0;
+  Int           bestBiPMvpL1 = 0;
+  UInt          biPDistTemp = MAX_INT;
+
+#if ZERO_MVD_EST
+  Int           aiZeroMvdMvpIdx[2] = {-1, -1};
+  Int           aiZeroMvdRefIdx[2] = {0, 0};
+  Int           iZeroMvdDir = -1;
+#endif
+
+  TComMvField cMvFieldNeighbours[MRG_MAX_NUM_CANDS << 1]; // double length for mv of both lists
+  UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS];
+  Int numValidMergeCand = 0 ;
+
+  for ( Int iPartIdx = 0; iPartIdx < iNumPart; iPartIdx++ )
+  {
+    UInt          uiCost[2] = { MAX_UINT, MAX_UINT };
+    UInt          uiCostBi  =   MAX_UINT;
+    UInt          uiCostTemp;
+    
+    UInt          uiBits[3];
+    UInt          uiBitsTemp;
+#if ZERO_MVD_EST
+    UInt          uiZeroMvdCost = MAX_UINT;
+    UInt          uiZeroMvdCostTemp;
+    UInt          uiZeroMvdBitsTemp;
+    UInt          uiZeroMvdDistTemp = MAX_UINT;
+    UInt          auiZeroMvdBits[3];
+#endif
+    UInt          bestBiPDist = MAX_INT;
+
+    UInt          uiCostTempL0[MAX_NUM_REF];
+    for (Int iNumRef=0; iNumRef < MAX_NUM_REF; iNumRef++) uiCostTempL0[iNumRef] = MAX_UINT;
+    UInt          uiBitsTempL0[MAX_NUM_REF];
+
+    xGetBlkBits( ePartSize, pcCU->getSlice()->isInterP(), iPartIdx, uiLastMode, uiMbBits);
+    
+    pcCU->getPartIndexAndSize( iPartIdx, uiPartAddr, iRoiWidth, iRoiHeight );
+    
+#if AMP_MRG
+    Bool bTestNormalMC = true;
+    
+    if ( bUseMRG && pcCU->getWidth( 0 ) > 8 && iNumPart == 2 )
+    {
+      bTestNormalMC = false;
+    }
+    
+    if (bTestNormalMC)
+    {
+#endif
+
+    //  Uni-directional prediction
+    for ( Int iRefList = 0; iRefList < iNumPredDir; iRefList++ )
+    {
+      RefPicList  eRefPicList = ( iRefList ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
+      
+      for ( Int iRefIdxTemp = 0; iRefIdxTemp < pcCU->getSlice()->getNumRefIdx(eRefPicList); iRefIdxTemp++ )
+      {
+        uiBitsTemp = uiMbBits[iRefList];
+        if ( pcCU->getSlice()->getNumRefIdx(eRefPicList) > 1 )
+        {
+          uiBitsTemp += iRefIdxTemp+1;
+          if ( iRefIdxTemp == pcCU->getSlice()->getNumRefIdx(eRefPicList)-1 ) uiBitsTemp--;
+        }
+#if ZERO_MVD_EST
+        xEstimateMvPredAMVP( pcCU, pcOrgYuv, iPartIdx, eRefPicList, iRefIdxTemp, cMvPred[iRefList][iRefIdxTemp], false, &biPDistTemp, &uiZeroMvdDistTemp);
+#else
+        xEstimateMvPredAMVP( pcCU, pcOrgYuv, iPartIdx, eRefPicList, iRefIdxTemp, cMvPred[iRefList][iRefIdxTemp], false, &biPDistTemp);
+#endif
+        aaiMvpIdx[iRefList][iRefIdxTemp] = pcCU->getMVPIdx(eRefPicList, uiPartAddr);
+        aaiMvpNum[iRefList][iRefIdxTemp] = pcCU->getMVPNum(eRefPicList, uiPartAddr);
+        
+        if(pcCU->getSlice()->getMvdL1ZeroFlag() && iRefList==1 && biPDistTemp < bestBiPDist)
+        {
+          bestBiPDist = biPDistTemp;
+          bestBiPMvpL1 = aaiMvpIdx[iRefList][iRefIdxTemp];
+          bestBiPRefIdxL1 = iRefIdxTemp;
+        }
+
+        uiBitsTemp += m_auiMVPIdxCost[aaiMvpIdx[iRefList][iRefIdxTemp]][AMVP_MAX_NUM_CANDS];
+#if ZERO_MVD_EST
+        if ((iRefList != 1 || !pcCU->getSlice()->getNoBackPredFlag()) &&
+            (pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) <= 0 || pcCU->getSlice()->getRefIdxOfLC(eRefPicList, iRefIdxTemp)>=0))
+        {
+          uiZeroMvdBitsTemp = uiBitsTemp;
+          uiZeroMvdBitsTemp += 2; //zero mvd bits
+
+          m_pcRdCost->getMotionCost( 1, 0 );
+          uiZeroMvdCostTemp = uiZeroMvdDistTemp + m_pcRdCost->getCost(uiZeroMvdBitsTemp);
+
+          if (uiZeroMvdCostTemp < uiZeroMvdCost)
+          {
+            uiZeroMvdCost = uiZeroMvdCostTemp;
+            iZeroMvdDir = iRefList + 1;
+            aiZeroMvdRefIdx[iRefList] = iRefIdxTemp;
+            aiZeroMvdMvpIdx[iRefList] = aaiMvpIdx[iRefList][iRefIdxTemp];
+            auiZeroMvdBits[iRefList] = uiZeroMvdBitsTemp;
+          }          
+        }
+#endif
+        
+#if GPB_SIMPLE_UNI
+        if ( pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0)
+        {
+          if ( iRefList && ( pcCU->getSlice()->getNoBackPredFlag() || (pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0 && !pcCU->getSlice()->getNoBackPredFlag() && pcCU->getSlice()->getRefIdxOfL0FromRefIdxOfL1(iRefIdxTemp)>=0 ) ) )
+            {
+              if ( pcCU->getSlice()->getNoBackPredFlag() )
+              {
+                cMvTemp[1][iRefIdxTemp] = cMvTemp[0][iRefIdxTemp];
+                uiCostTemp = uiCostTempL0[iRefIdxTemp];
+                /*first subtract the bit-rate part of the cost of the other list*/
+                uiCostTemp -= m_pcRdCost->getCost( uiBitsTempL0[iRefIdxTemp] );
+              }
+              else
+              {
+                cMvTemp[1][iRefIdxTemp] = cMvTemp[0][pcCU->getSlice()->getRefIdxOfL0FromRefIdxOfL1(iRefIdxTemp)]; 
+                uiCostTemp = uiCostTempL0[pcCU->getSlice()->getRefIdxOfL0FromRefIdxOfL1(iRefIdxTemp)];
+                /*first subtract the bit-rate part of the cost of the other list*/
+                uiCostTemp -= m_pcRdCost->getCost( uiBitsTempL0[pcCU->getSlice()->getRefIdxOfL0FromRefIdxOfL1(iRefIdxTemp)] );
+              }
+              /*correct the bit-rate part of the current ref*/
+              m_pcRdCost->setPredictor  ( cMvPred[iRefList][iRefIdxTemp] );
+              uiBitsTemp += m_pcRdCost->getBits( cMvTemp[1][iRefIdxTemp].getHor(), cMvTemp[1][iRefIdxTemp].getVer() );
+              /*calculate the correct cost*/
+              uiCostTemp += m_pcRdCost->getCost( uiBitsTemp );
+            }
+            else
+            {
+              xMotionEstimation ( pcCU, pcOrgYuv, iPartIdx, eRefPicList, &cMvPred[iRefList][iRefIdxTemp], iRefIdxTemp, cMvTemp[iRefList][iRefIdxTemp], uiBitsTemp, uiCostTemp );
+            }
+        }
+        else
+        {
+          if (iRefList && pcCU->getSlice()->getNoBackPredFlag())
+          {
+            uiCostTemp = MAX_UINT;
+            cMvTemp[1][iRefIdxTemp] = cMvTemp[0][iRefIdxTemp];
+          }
+          else
+          { 
+            xMotionEstimation ( pcCU, pcOrgYuv, iPartIdx, eRefPicList, &cMvPred[iRefList][iRefIdxTemp], iRefIdxTemp, cMvTemp[iRefList][iRefIdxTemp], uiBitsTemp, uiCostTemp );
+          }        
+        }
+#else
+        xMotionEstimation ( pcCU, pcOrgYuv, iPartIdx, eRefPicList, &cMvPred[iRefList][iRefIdxTemp], iRefIdxTemp, cMvTemp[iRefList][iRefIdxTemp], uiBitsTemp, uiCostTemp );
+#endif
+        xCopyAMVPInfo(pcCU->getCUMvField(eRefPicList)->getAMVPInfo(), &aacAMVPInfo[iRefList][iRefIdxTemp]); // must always be done ( also when AMVP_MODE = AM_NONE )
+#if !SPS_AMVP_CLEANUP
+        if ( pcCU->getAMVPMode(uiPartAddr) == AM_EXPL )
+        {          
+#endif
+        xCheckBestMVP(pcCU, eRefPicList, cMvTemp[iRefList][iRefIdxTemp], cMvPred[iRefList][iRefIdxTemp], aaiMvpIdx[iRefList][iRefIdxTemp], uiBitsTemp, uiCostTemp);
+#if !SPS_AMVP_CLEANUP
+        }
+#endif
+
+        if(pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0 && !pcCU->getSlice()->getNoBackPredFlag())
+        {
+          if(iRefList==REF_PIC_LIST_0)
+          {
+            uiCostTempL0[iRefIdxTemp] = uiCostTemp;
+            uiBitsTempL0[iRefIdxTemp] = uiBitsTemp;
+            if(pcCU->getSlice()->getRefIdxOfLC(REF_PIC_LIST_0, iRefIdxTemp)<0)
+            {
+              uiCostTemp = MAX_UINT;
+            }
+          }
+          else
+          {
+            if(pcCU->getSlice()->getRefIdxOfLC(REF_PIC_LIST_1, iRefIdxTemp)<0)
+            {
+              uiCostTemp = MAX_UINT;
+            }           
+          }
+        }
+
+        if ( ( iRefList == 0 && uiCostTemp < uiCost[iRefList] ) ||
+            ( iRefList == 1 &&  pcCU->getSlice()->getNoBackPredFlag() && iRefIdxTemp == iRefIdx[0] ) ||
+            ( iRefList == 1 && (pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0) && (iRefIdxTemp==0 || iRefIdxTemp == iRefIdx[0]) && !pcCU->getSlice()->getNoBackPredFlag() && (iRefIdxTemp == pcCU->getSlice()->getRefIdxOfL0FromRefIdxOfL1(iRefIdxTemp)) ) ||
+            ( iRefList == 1 && !pcCU->getSlice()->getNoBackPredFlag() && uiCostTemp < uiCost[iRefList] ) )
+          {
+            uiCost[iRefList] = uiCostTemp;
+            uiBits[iRefList] = uiBitsTemp; // storing for bi-prediction
+            
+            // set motion
+            cMv[iRefList]     = cMvTemp[iRefList][iRefIdxTemp];
+            iRefIdx[iRefList] = iRefIdxTemp;
+            pcCU->getCUMvField(eRefPicList)->setAllMv( cMv[iRefList], ePartSize, uiPartAddr, 0, iPartIdx );
+            pcCU->getCUMvField(eRefPicList)->setAllRefIdx( iRefIdx[iRefList], ePartSize, uiPartAddr, 0, iPartIdx );
+
+            if(!pcCU->getSlice()->getMvdL1ZeroFlag())
+            {
+              // storing list 1 prediction signal for iterative bi-directional prediction
+              if ( eRefPicList == REF_PIC_LIST_1 )
+              {
+                TComYuv*  pcYuvPred = &m_acYuvPred[iRefList];
+                motionCompensation ( pcCU, pcYuvPred, eRefPicList, iPartIdx );
+              }
+              if ( (pcCU->getSlice()->getNoBackPredFlag() || (pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0 && pcCU->getSlice()->getRefIdxOfL0FromRefIdxOfL1(0)==0 )) && eRefPicList == REF_PIC_LIST_0 )
+              {
+                TComYuv*  pcYuvPred = &m_acYuvPred[iRefList];
+                motionCompensation ( pcCU, pcYuvPred, eRefPicList, iPartIdx );
+              }
+            }
+          }
+      }
+    }
+    //  Bi-directional prediction
+    if ( (pcCU->getSlice()->isInterB()) && (pcCU->isBipredRestriction(iPartIdx) == false) )
+    {
+      
+      cMvBi[0] = cMv[0];            cMvBi[1] = cMv[1];
+      iRefIdxBi[0] = iRefIdx[0];    iRefIdxBi[1] = iRefIdx[1];
+      
+      ::memcpy(cMvPredBi, cMvPred, sizeof(cMvPred));
+      ::memcpy(aaiMvpIdxBi, aaiMvpIdx, sizeof(aaiMvpIdx));
+      
+      UInt uiMotBits[2];
+
+      if(pcCU->getSlice()->getMvdL1ZeroFlag())
+      {
+        xCopyAMVPInfo(&aacAMVPInfo[1][bestBiPRefIdxL1], pcCU->getCUMvField(REF_PIC_LIST_1)->getAMVPInfo());
+        pcCU->setMVPIdxSubParts( bestBiPMvpL1, REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+        aaiMvpIdxBi[1][bestBiPRefIdxL1] = bestBiPMvpL1;
+        cMvPredBi[1][bestBiPRefIdxL1]   = pcCU->getCUMvField(REF_PIC_LIST_1)->getAMVPInfo()->m_acMvCand[bestBiPMvpL1];
+
+        cMvBi[1] = cMvPredBi[1][bestBiPRefIdxL1];
+        iRefIdxBi[1] = bestBiPRefIdxL1;
+        pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMv( cMvBi[1], ePartSize, uiPartAddr, 0, iPartIdx );
+        pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllRefIdx( iRefIdxBi[1], ePartSize, uiPartAddr, 0, iPartIdx );
+        TComYuv* pcYuvPred = &m_acYuvPred[1];
+        motionCompensation( pcCU, pcYuvPred, REF_PIC_LIST_1, iPartIdx );
+
+        uiMotBits[0] = uiBits[0] - uiMbBits[0];
+        uiMotBits[1] = uiMbBits[1];
+
+        if ( pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_1) > 1 )
+        {
+          uiMotBits[1] += bestBiPRefIdxL1+1;
+          if ( bestBiPRefIdxL1 == pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_1)-1 ) uiMotBits[1]--;
+        }
+
+        uiMotBits[1] += m_auiMVPIdxCost[aaiMvpIdxBi[1][bestBiPRefIdxL1]][AMVP_MAX_NUM_CANDS];
+
+        uiBits[2] = uiMbBits[2] + uiMotBits[0] + uiMotBits[1];
+
+        cMvTemp[1][bestBiPRefIdxL1] = cMvBi[1];
+      }
+      else
+      {
+        uiMotBits[0] = uiBits[0] - uiMbBits[0];
+        uiMotBits[1] = uiBits[1] - uiMbBits[1];
+        uiBits[2] = uiMbBits[2] + uiMotBits[0] + uiMotBits[1];
+      }
+
+      // 4-times iteration (default)
+      Int iNumIter = 4;
+      
+      // fast encoder setting: only one iteration
+      if ( m_pcEncCfg->getUseFastEnc() || pcCU->getSlice()->getMvdL1ZeroFlag())
+      {
+        iNumIter = 1;
+      }
+      
+      for ( Int iIter = 0; iIter < iNumIter; iIter++ )
+      {
+        
+        Int         iRefList    = iIter % 2;
+        if ( m_pcEncCfg->getUseFastEnc() && (pcCU->getSlice()->getNoBackPredFlag() || (pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0 && pcCU->getSlice()->getRefIdxOfL0FromRefIdxOfL1(0)==0 )) )
+        {
+          iRefList = 1;
+        }
+        RefPicList  eRefPicList = ( iRefList ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
+
+        if(pcCU->getSlice()->getMvdL1ZeroFlag())
+        {
+          iRefList = 0;
+          eRefPicList = REF_PIC_LIST_0;
+        }
+
+        Bool bChanged = false;
+        
+        iRefStart = 0;
+        iRefEnd   = pcCU->getSlice()->getNumRefIdx(eRefPicList)-1;
+        
+        for ( Int iRefIdxTemp = iRefStart; iRefIdxTemp <= iRefEnd; iRefIdxTemp++ )
+        {
+          uiBitsTemp = uiMbBits[2] + uiMotBits[1-iRefList];
+          if ( pcCU->getSlice()->getNumRefIdx(eRefPicList) > 1 )
+          {
+            uiBitsTemp += iRefIdxTemp+1;
+            if ( iRefIdxTemp == pcCU->getSlice()->getNumRefIdx(eRefPicList)-1 ) uiBitsTemp--;
+          }
+          uiBitsTemp += m_auiMVPIdxCost[aaiMvpIdxBi[iRefList][iRefIdxTemp]][AMVP_MAX_NUM_CANDS];
+          // call ME
+          xMotionEstimation ( pcCU, pcOrgYuv, iPartIdx, eRefPicList, &cMvPredBi[iRefList][iRefIdxTemp], iRefIdxTemp, cMvTemp[iRefList][iRefIdxTemp], uiBitsTemp, uiCostTemp, true );
+#if !SPS_AMVP_CLEANUP
+          if ( pcCU->getAMVPMode(uiPartAddr) == AM_EXPL )
+          {
+#endif
+          xCopyAMVPInfo(&aacAMVPInfo[iRefList][iRefIdxTemp], pcCU->getCUMvField(eRefPicList)->getAMVPInfo());
+          xCheckBestMVP(pcCU, eRefPicList, cMvTemp[iRefList][iRefIdxTemp], cMvPredBi[iRefList][iRefIdxTemp], aaiMvpIdxBi[iRefList][iRefIdxTemp], uiBitsTemp, uiCostTemp);
+#if !SPS_AMVP_CLEANUP
+          }
+#endif
+
+          if ( uiCostTemp < uiCostBi )
+          {
+            bChanged = true;
+            
+            cMvBi[iRefList]     = cMvTemp[iRefList][iRefIdxTemp];
+            iRefIdxBi[iRefList] = iRefIdxTemp;
+            
+            uiCostBi            = uiCostTemp;
+            uiMotBits[iRefList] = uiBitsTemp - uiMbBits[2] - uiMotBits[1-iRefList];
+            uiBits[2]           = uiBitsTemp;
+            
+            if(iNumIter!=1)
+            {
+              //  Set motion
+              pcCU->getCUMvField( eRefPicList )->setAllMv( cMvBi[iRefList], ePartSize, uiPartAddr, 0, iPartIdx );
+              pcCU->getCUMvField( eRefPicList )->setAllRefIdx( iRefIdxBi[iRefList], ePartSize, uiPartAddr, 0, iPartIdx );
+
+              TComYuv* pcYuvPred = &m_acYuvPred[iRefList];
+              motionCompensation( pcCU, pcYuvPred, eRefPicList, iPartIdx );
+            }
+          }
+        } // for loop-iRefIdxTemp
+        
+        if ( !bChanged )
+        {
+#if !SPS_AMVP_CLEANUP
+          if ( uiCostBi <= uiCost[0] && uiCostBi <= uiCost[1] && pcCU->getAMVPMode(uiPartAddr) == AM_EXPL )
+#else
+          if ( uiCostBi <= uiCost[0] && uiCostBi <= uiCost[1] )
+#endif
+          {
+            xCopyAMVPInfo(&aacAMVPInfo[0][iRefIdxBi[0]], pcCU->getCUMvField(REF_PIC_LIST_0)->getAMVPInfo());
+            xCheckBestMVP(pcCU, REF_PIC_LIST_0, cMvBi[0], cMvPredBi[0][iRefIdxBi[0]], aaiMvpIdxBi[0][iRefIdxBi[0]], uiBits[2], uiCostBi);
+            if(!pcCU->getSlice()->getMvdL1ZeroFlag())
+            {
+              xCopyAMVPInfo(&aacAMVPInfo[1][iRefIdxBi[1]], pcCU->getCUMvField(REF_PIC_LIST_1)->getAMVPInfo());
+              xCheckBestMVP(pcCU, REF_PIC_LIST_1, cMvBi[1], cMvPredBi[1][iRefIdxBi[1]], aaiMvpIdxBi[1][iRefIdxBi[1]], uiBits[2], uiCostBi);
+            }
+          }
+          break;
+        }
+      } // for loop-iter
+    } // if (B_SLICE)
+#if ZERO_MVD_EST
+    if ( (pcCU->getSlice()->isInterB()) && (pcCU->isBipredRestriction(iPartIdx) == false) )
+    {
+      m_pcRdCost->getMotionCost( 1, 0 );
+
+      for ( Int iL0RefIdxTemp = 0; iL0RefIdxTemp <= pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_0)-1; iL0RefIdxTemp++ )
+      for ( Int iL1RefIdxTemp = 0; iL1RefIdxTemp <= pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_1)-1; iL1RefIdxTemp++ )
+      {
+        UInt uiRefIdxBitsTemp = 0;
+        if ( pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_0) > 1 )
+        {
+          uiRefIdxBitsTemp += iL0RefIdxTemp+1;
+          if ( iL0RefIdxTemp == pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_0)-1 ) uiRefIdxBitsTemp--;
+        }
+        if ( pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_1) > 1 )
+        {
+          uiRefIdxBitsTemp += iL1RefIdxTemp+1;
+          if ( iL1RefIdxTemp == pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_1)-1 ) uiRefIdxBitsTemp--;
+        }
+
+        Int iL0MVPIdx = 0;
+        Int iL1MVPIdx = 0;
+
+        for (iL0MVPIdx = 0; iL0MVPIdx < aaiMvpNum[0][iL0RefIdxTemp]; iL0MVPIdx++)
+        {
+          for (iL1MVPIdx = 0; iL1MVPIdx < aaiMvpNum[1][iL1RefIdxTemp]; iL1MVPIdx++)
+          {
+            uiZeroMvdBitsTemp = uiRefIdxBitsTemp;
+            uiZeroMvdBitsTemp += uiMbBits[2];
+            uiZeroMvdBitsTemp += m_auiMVPIdxCost[iL0MVPIdx][aaiMvpNum[0][iL0RefIdxTemp]] + m_auiMVPIdxCost[iL1MVPIdx][aaiMvpNum[1][iL1RefIdxTemp]];
+            uiZeroMvdBitsTemp += 4; //zero mvd for both directions
+            pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( aacAMVPInfo[0][iL0RefIdxTemp].m_acMvCand[iL0MVPIdx], iL0RefIdxTemp, ePartSize, uiPartAddr, iPartIdx, 0 );
+            pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( aacAMVPInfo[1][iL1RefIdxTemp].m_acMvCand[iL1MVPIdx], iL1RefIdxTemp, ePartSize, uiPartAddr, iPartIdx, 0 );
+  
+            xGetInterPredictionError( pcCU, pcOrgYuv, iPartIdx, uiZeroMvdDistTemp, m_pcEncCfg->getUseHADME() );
+            uiZeroMvdCostTemp = uiZeroMvdDistTemp + m_pcRdCost->getCost( uiZeroMvdBitsTemp );
+            if (uiZeroMvdCostTemp < uiZeroMvdCost)
+            {
+              uiZeroMvdCost = uiZeroMvdCostTemp;
+              iZeroMvdDir = 3;
+              aiZeroMvdMvpIdx[0] = iL0MVPIdx;
+              aiZeroMvdMvpIdx[1] = iL1MVPIdx;
+              aiZeroMvdRefIdx[0] = iL0RefIdxTemp;
+              aiZeroMvdRefIdx[1] = iL1RefIdxTemp;
+              auiZeroMvdBits[2] = uiZeroMvdBitsTemp;
+            }
+          }
+        }
+      }
+    }
+#endif
+
+#if AMP_MRG
+    } //end if bTestNormalMC
+#endif
+    //  Clear Motion Field
+    pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvField( TComMvField(), ePartSize, uiPartAddr, 0, iPartIdx );
+    pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvField( TComMvField(), ePartSize, uiPartAddr, 0, iPartIdx );
+    pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvd    ( cMvZero,       ePartSize, uiPartAddr, 0, iPartIdx );
+    pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvd    ( cMvZero,       ePartSize, uiPartAddr, 0, iPartIdx );
+
+    pcCU->setMVPIdxSubParts( -1, REF_PIC_LIST_0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+    pcCU->setMVPNumSubParts( -1, REF_PIC_LIST_0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+    pcCU->setMVPIdxSubParts( -1, REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+    pcCU->setMVPNumSubParts( -1, REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+    
+    UInt uiMEBits = 0;
+    // Set Motion Field_
+    if ( pcCU->getSlice()->getNoBackPredFlag() || (pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0 && pcCU->getSlice()->getRefIdxOfL0FromRefIdxOfL1(0)==0 ) )
+    {
+      uiCost[1] = MAX_UINT;
+    }
+#if AMP_MRG
+    if (bTestNormalMC)
+    {
+#endif
+#if ZERO_MVD_EST
+    if (uiZeroMvdCost <= uiCostBi && uiZeroMvdCost <= uiCost[0] && uiZeroMvdCost <= uiCost[1])
+    {
+      if (iZeroMvdDir == 3)
+      {
+        uiLastMode = 2;
+
+        pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvField( aacAMVPInfo[0][aiZeroMvdRefIdx[0]].m_acMvCand[aiZeroMvdMvpIdx[0]], aiZeroMvdRefIdx[0], ePartSize, uiPartAddr, iPartIdx, 0 );
+        pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvField( aacAMVPInfo[1][aiZeroMvdRefIdx[1]].m_acMvCand[aiZeroMvdMvpIdx[1]], aiZeroMvdRefIdx[1], ePartSize, uiPartAddr, iPartIdx, 0 );
+  
+        pcCU->setInterDirSubParts( 3, uiPartAddr, iPartIdx, pcCU->getDepth(0) );
+        
+        pcCU->setMVPIdxSubParts( aiZeroMvdMvpIdx[0], REF_PIC_LIST_0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+        pcCU->setMVPNumSubParts( aaiMvpNum[0][aiZeroMvdRefIdx[0]], REF_PIC_LIST_0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+        pcCU->setMVPIdxSubParts( aiZeroMvdMvpIdx[1], REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+        pcCU->setMVPNumSubParts( aaiMvpNum[1][aiZeroMvdRefIdx[1]], REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+        uiMEBits = auiZeroMvdBits[2];
+      }
+      else if (iZeroMvdDir == 1)
+      {        
+        uiLastMode = 0;
+
+        pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvField( aacAMVPInfo[0][aiZeroMvdRefIdx[0]].m_acMvCand[aiZeroMvdMvpIdx[0]], aiZeroMvdRefIdx[0], ePartSize, uiPartAddr, iPartIdx, 0 );
+
+        pcCU->setInterDirSubParts( 1, uiPartAddr, iPartIdx, pcCU->getDepth(0) );
+        
+        pcCU->setMVPIdxSubParts( aiZeroMvdMvpIdx[0], REF_PIC_LIST_0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+        pcCU->setMVPNumSubParts( aaiMvpNum[0][aiZeroMvdRefIdx[0]], REF_PIC_LIST_0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+        uiMEBits = auiZeroMvdBits[0];
+      }
+      else if (iZeroMvdDir == 2)
+      {
+        uiLastMode = 1;
+
+        pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvField( aacAMVPInfo[1][aiZeroMvdRefIdx[1]].m_acMvCand[aiZeroMvdMvpIdx[1]], aiZeroMvdRefIdx[1], ePartSize, uiPartAddr, iPartIdx, 0 );
+
+        pcCU->setInterDirSubParts( 2, uiPartAddr, iPartIdx, pcCU->getDepth(0) );
+        
+        pcCU->setMVPIdxSubParts( aiZeroMvdMvpIdx[1], REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+        pcCU->setMVPNumSubParts( aaiMvpNum[1][aiZeroMvdRefIdx[1]], REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+        uiMEBits = auiZeroMvdBits[1];
+      }
+      else
+      {
+        assert(0);
+      }
+    }
+    else
+#endif
+    if ( uiCostBi <= uiCost[0] && uiCostBi <= uiCost[1])
+    {
+      uiLastMode = 2;
+      {
+            pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMv( cMvBi[0], ePartSize, uiPartAddr, 0, iPartIdx );
+            pcCU->getCUMvField(REF_PIC_LIST_0)->setAllRefIdx( iRefIdxBi[0], ePartSize, uiPartAddr, 0, iPartIdx );
+            pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMv( cMvBi[1], ePartSize, uiPartAddr, 0, iPartIdx );
+            pcCU->getCUMvField(REF_PIC_LIST_1)->setAllRefIdx( iRefIdxBi[1], ePartSize, uiPartAddr, 0, iPartIdx );
+      }
+      {
+        TempMv = cMvBi[0] - cMvPredBi[0][iRefIdxBi[0]];
+            pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
+      }
+      {
+        TempMv = cMvBi[1] - cMvPredBi[1][iRefIdxBi[1]];
+            pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
+      }
+      
+      pcCU->setInterDirSubParts( 3, uiPartAddr, iPartIdx, pcCU->getDepth(0) );
+      
+      pcCU->setMVPIdxSubParts( aaiMvpIdxBi[0][iRefIdxBi[0]], REF_PIC_LIST_0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+      pcCU->setMVPNumSubParts( aaiMvpNum[0][iRefIdxBi[0]], REF_PIC_LIST_0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+      pcCU->setMVPIdxSubParts( aaiMvpIdxBi[1][iRefIdxBi[1]], REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+      pcCU->setMVPNumSubParts( aaiMvpNum[1][iRefIdxBi[1]], REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+
+      uiMEBits = uiBits[2];
+    }
+    else if ( uiCost[0] <= uiCost[1] )
+    {
+      uiLastMode = 0;
+          pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMv( cMv[0], ePartSize, uiPartAddr, 0, iPartIdx );
+          pcCU->getCUMvField(REF_PIC_LIST_0)->setAllRefIdx( iRefIdx[0], ePartSize, uiPartAddr, 0, iPartIdx );
+      {
+        TempMv = cMv[0] - cMvPred[0][iRefIdx[0]];
+            pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
+      }
+      pcCU->setInterDirSubParts( 1, uiPartAddr, iPartIdx, pcCU->getDepth(0) );
+      
+      pcCU->setMVPIdxSubParts( aaiMvpIdx[0][iRefIdx[0]], REF_PIC_LIST_0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+      pcCU->setMVPNumSubParts( aaiMvpNum[0][iRefIdx[0]], REF_PIC_LIST_0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+
+      uiMEBits = uiBits[0];
+    }
+    else
+    {
+      uiLastMode = 1;
+          pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMv( cMv[1], ePartSize, uiPartAddr, 0, iPartIdx );
+          pcCU->getCUMvField(REF_PIC_LIST_1)->setAllRefIdx( iRefIdx[1], ePartSize, uiPartAddr, 0, iPartIdx );
+      {
+        TempMv = cMv[1] - cMvPred[1][iRefIdx[1]];
+            pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
+      }
+      pcCU->setInterDirSubParts( 2, uiPartAddr, iPartIdx, pcCU->getDepth(0) );
+      
+      pcCU->setMVPIdxSubParts( aaiMvpIdx[1][iRefIdx[1]], REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+      pcCU->setMVPNumSubParts( aaiMvpNum[1][iRefIdx[1]], REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+
+      uiMEBits = uiBits[1];
+    }
+#if AMP_MRG
+    } // end if bTestNormalMC
+#endif
+
+    if ( pcCU->getPartitionSize( uiPartAddr ) != SIZE_2Nx2N )
+    {
+      UInt uiMRGInterDir = 0;     
+      TComMvField cMRGMvField[2];
+      UInt uiMRGIndex = 0;
+
+      UInt uiMEInterDir = 0;
+      TComMvField cMEMvField[2];
+
+      m_pcRdCost->getMotionCost( 1, 0 );
+#if AMP_MRG
+      // calculate ME cost
+      UInt uiMEError = MAX_UINT;
+      UInt uiMECost = MAX_UINT;
+
+      if (bTestNormalMC)
+      {
+        xGetInterPredictionError( pcCU, pcOrgYuv, iPartIdx, uiMEError, m_pcEncCfg->getUseHADME() );
+        uiMECost = uiMEError + m_pcRdCost->getCost( uiMEBits );
+      }
+#else
+      // calculate ME cost
+      UInt uiMEError = MAX_UINT;
+      xGetInterPredictionError( pcCU, pcOrgYuv, iPartIdx, uiMEError, m_pcEncCfg->getUseHADME() );
+      UInt uiMECost = uiMEError + m_pcRdCost->getCost( uiMEBits );
+#endif 
+      // 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] );
+
+      // find Merge result
+      UInt uiMRGCost = MAX_UINT;
+      xMergeEstimation( pcCU, pcOrgYuv, iPartIdx, uiMRGInterDir, cMRGMvField, uiMRGIndex, uiMRGCost, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand);
+      if ( uiMRGCost < uiMECost )
+      {
+        // set Merge result
+        pcCU->setMergeFlagSubParts ( true,          uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
+        pcCU->setMergeIndexSubParts( uiMRGIndex,    uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
+        pcCU->setInterDirSubParts  ( uiMRGInterDir, uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
+        {
+          pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( cMRGMvField[0], ePartSize, uiPartAddr, 0, iPartIdx );
+          pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMRGMvField[1], ePartSize, uiPartAddr, 0, iPartIdx );
+        }
+
+        pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvd    ( cMvZero,            ePartSize, uiPartAddr, 0, iPartIdx );
+        pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvd    ( cMvZero,            ePartSize, uiPartAddr, 0, iPartIdx );
+
+        pcCU->setMVPIdxSubParts( -1, REF_PIC_LIST_0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+        pcCU->setMVPNumSubParts( -1, REF_PIC_LIST_0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+        pcCU->setMVPIdxSubParts( -1, REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+        pcCU->setMVPNumSubParts( -1, REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+      }
+      else
+      {
+        // set ME result
+        pcCU->setMergeFlagSubParts( false,        uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
+        pcCU->setInterDirSubParts ( uiMEInterDir, uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
+        {
+          pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( cMEMvField[0], ePartSize, uiPartAddr, 0, iPartIdx );
+          pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMEMvField[1], ePartSize, uiPartAddr, 0, iPartIdx );
+        }
+      }
+    }
+
+    //  MC
+    motionCompensation ( pcCU, rpcPredYuv, REF_PIC_LIST_X, iPartIdx );
+    
+  } //  end of for ( Int iPartIdx = 0; iPartIdx < iNumPart; iPartIdx++ )
+
+  setWpScalingDistParam( pcCU, -1, REF_PIC_LIST_X );
+
+  return;
+}
+
+// AMVP
+#if ZERO_MVD_EST
+Void TEncSearch::xEstimateMvPredAMVP( TComDataCU* pcCU, TComYuv* pcOrgYuv, UInt uiPartIdx, RefPicList eRefPicList, Int iRefIdx, TComMv& rcMvPred, Bool bFilled, UInt* puiDistBiP, UInt* puiDist  )
+#else
+Void TEncSearch::xEstimateMvPredAMVP( TComDataCU* pcCU, TComYuv* pcOrgYuv, UInt uiPartIdx, RefPicList eRefPicList, Int iRefIdx, TComMv& rcMvPred, Bool bFilled, UInt* puiDistBiP )
+#endif
+{
+  AMVPInfo* pcAMVPInfo = pcCU->getCUMvField(eRefPicList)->getAMVPInfo();
+  
+  TComMv  cBestMv;
+  Int     iBestIdx = 0;
+  TComMv  cZeroMv;
+  TComMv  cMvPred;
+  UInt    uiBestCost = MAX_INT;
+  UInt    uiPartAddr = 0;
+  Int     iRoiWidth, iRoiHeight;
+  Int     i;
+  
+  pcCU->getPartIndexAndSize( uiPartIdx, uiPartAddr, iRoiWidth, iRoiHeight );
+  // Fill the MV Candidates
+  if (!bFilled)
+  {
+    pcCU->fillMvpCand( uiPartIdx, uiPartAddr, eRefPicList, iRefIdx, pcAMVPInfo );
+  }
+  
+  // initialize Mvp index & Mvp
+  iBestIdx = 0;
+  cBestMv  = pcAMVPInfo->m_acMvCand[0];
+#if !ZERO_MVD_EST
+#if !SPS_AMVP_CLEANUP
+  if( pcCU->getAMVPMode(uiPartAddr) == AM_NONE || (pcAMVPInfo->iN <= 1 && pcCU->getAMVPMode(uiPartAddr) == AM_EXPL) )
+#else
+  if (pcAMVPInfo->iN <= 1)
+#endif
+  {
+    rcMvPred = cBestMv;
+    
+    pcCU->setMVPIdxSubParts( iBestIdx, eRefPicList, uiPartAddr, uiPartIdx, pcCU->getDepth(uiPartAddr));
+    pcCU->setMVPNumSubParts( pcAMVPInfo->iN, eRefPicList, uiPartAddr, uiPartIdx, pcCU->getDepth(uiPartAddr));
+
+    if(pcCU->getSlice()->getMvdL1ZeroFlag() && eRefPicList==REF_PIC_LIST_1)
+    {
+#if ZERO_MVD_EST
+      (*puiDistBiP) = xGetTemplateCost( pcCU, uiPartIdx, uiPartAddr, pcOrgYuv, &m_cYuvPredTemp, rcMvPred, 0, AMVP_MAX_NUM_CANDS, eRefPicList, iRefIdx, iRoiWidth, iRoiHeight, uiDist );
+#else
+      (*puiDistBiP) = xGetTemplateCost( pcCU, uiPartIdx, uiPartAddr, pcOrgYuv, &m_cYuvPredTemp, rcMvPred, 0, AMVP_MAX_NUM_CANDS, eRefPicList, iRefIdx, iRoiWidth, iRoiHeight);
+#endif
+    }
+    return;
+  }
+#endif  
+#if !SPS_AMVP_CLEANUP
+  if (pcCU->getAMVPMode(uiPartAddr) == AM_EXPL && bFilled)
+#else
+  if (bFilled)
+#endif
+  {
+    assert(pcCU->getMVPIdx(eRefPicList,uiPartAddr) >= 0);
+    rcMvPred = pcAMVPInfo->m_acMvCand[pcCU->getMVPIdx(eRefPicList,uiPartAddr)];
+    return;
+  }
+  
+#if !SPS_AMVP_CLEANUP
+  if (pcCU->getAMVPMode(uiPartAddr) == AM_EXPL)
+  {
+#endif
+  m_cYuvPredTemp.clear();
+#if ZERO_MVD_EST
+  UInt uiDist;
+#endif
+  //-- Check Minimum Cost.
+  for ( i = 0 ; i < pcAMVPInfo->iN; i++)
+  {
+    UInt uiTmpCost;
+#if ZERO_MVD_EST
+    uiTmpCost = xGetTemplateCost( pcCU, uiPartIdx, uiPartAddr, pcOrgYuv, &m_cYuvPredTemp, pcAMVPInfo->m_acMvCand[i], i, AMVP_MAX_NUM_CANDS, eRefPicList, iRefIdx, iRoiWidth, iRoiHeight, uiDist );
+#else
+    uiTmpCost = xGetTemplateCost( pcCU, uiPartIdx, uiPartAddr, pcOrgYuv, &m_cYuvPredTemp, pcAMVPInfo->m_acMvCand[i], i, AMVP_MAX_NUM_CANDS, eRefPicList, iRefIdx, iRoiWidth, iRoiHeight);
+#endif      
+    if ( uiBestCost > uiTmpCost )
+    {
+      uiBestCost = uiTmpCost;
+      cBestMv   = pcAMVPInfo->m_acMvCand[i];
+      iBestIdx  = i;
+      (*puiDistBiP) = uiTmpCost;
+#if ZERO_MVD_EST
+      (*puiDist) = uiDist;
+#endif
+    }
+  }
+
+  m_cYuvPredTemp.clear();
+#if !SPS_AMVP_CLEANUP
+  }
+#endif
+  
+  // Setting Best MVP
+  rcMvPred = cBestMv;
+  pcCU->setMVPIdxSubParts( iBestIdx, eRefPicList, uiPartAddr, uiPartIdx, pcCU->getDepth(uiPartAddr));
+  pcCU->setMVPNumSubParts( pcAMVPInfo->iN, eRefPicList, uiPartAddr, uiPartIdx, pcCU->getDepth(uiPartAddr));
+  return;
+}
+
+UInt TEncSearch::xGetMvpIdxBits(Int iIdx, Int iNum)
+{
+  assert(iIdx >= 0 && iNum >= 0 && iIdx < iNum);
+  
+  if (iNum == 1)
+    return 0;
+  
+  UInt uiLength = 1;
+  Int iTemp = iIdx;
+  if ( iTemp == 0 )
+  {
+    return uiLength;
+  }
+  
+  Bool bCodeLast = ( iNum-1 > iTemp );
+  
+  uiLength += (iTemp-1);
+  
+  if( bCodeLast )
+  {
+    uiLength++;
+  }
+  
+  return uiLength;
+}
+
+Void TEncSearch::xGetBlkBits( PartSize eCUMode, Bool bPSlice, Int iPartIdx, UInt uiLastMode, UInt uiBlkBit[3])
+{
+  if ( eCUMode == SIZE_2Nx2N )
+  {
+    uiBlkBit[0] = (! bPSlice) ? 3 : 1;
+    uiBlkBit[1] = 3;
+    uiBlkBit[2] = 5;
+  }
+  else if ( (eCUMode == SIZE_2NxN || eCUMode == SIZE_2NxnU) || eCUMode == SIZE_2NxnD )
+  {
+    UInt aauiMbBits[2][3][3] = { { {0,0,3}, {0,0,0}, {0,0,0} } , { {5,7,7}, {7,5,7}, {9-3,9-3,9-3} } };
+    if ( bPSlice )
+    {
+      uiBlkBit[0] = 3;
+      uiBlkBit[1] = 0;
+      uiBlkBit[2] = 0;
+    }
+    else
+    {
+      ::memcpy( uiBlkBit, aauiMbBits[iPartIdx][uiLastMode], 3*sizeof(UInt) );
+    }
+  }
+  else if ( (eCUMode == SIZE_Nx2N || eCUMode == SIZE_nLx2N) || eCUMode == SIZE_nRx2N )
+  {
+    UInt aauiMbBits[2][3][3] = { { {0,2,3}, {0,0,0}, {0,0,0} } , { {5,7,7}, {7-2,7-2,9-2}, {9-3,9-3,9-3} } };
+    if ( bPSlice )
+    {
+      uiBlkBit[0] = 3;
+      uiBlkBit[1] = 0;
+      uiBlkBit[2] = 0;
+    }
+    else
+    {
+      ::memcpy( uiBlkBit, aauiMbBits[iPartIdx][uiLastMode], 3*sizeof(UInt) );
+    }
+  }
+  else if ( eCUMode == SIZE_NxN )
+  {
+    uiBlkBit[0] = (! bPSlice) ? 3 : 1;
+    uiBlkBit[1] = 3;
+    uiBlkBit[2] = 5;
+  }
+  else
+  {
+    printf("Wrong!\n");
+    assert( 0 );
+  }
+}
+
+Void TEncSearch::xCopyAMVPInfo (AMVPInfo* pSrc, AMVPInfo* pDst)
+{
+  pDst->iN = pSrc->iN;
+  for (Int i = 0; i < pSrc->iN; i++)
+  {
+    pDst->m_acMvCand[i] = pSrc->m_acMvCand[i];
+  }
+}
+
+Void TEncSearch::xCheckBestMVP ( TComDataCU* pcCU, RefPicList eRefPicList, TComMv cMv, TComMv& rcMvPred, Int& riMVPIdx, UInt& ruiBits, UInt& ruiCost )
+{
+  AMVPInfo* pcAMVPInfo = pcCU->getCUMvField(eRefPicList)->getAMVPInfo();
+  
+  assert(pcAMVPInfo->m_acMvCand[riMVPIdx] == rcMvPred);
+  
+  if (pcAMVPInfo->iN < 2) return;
+  
+  m_pcRdCost->getMotionCost( 1, 0 );
+  m_pcRdCost->setCostScale ( 0    );
+  
+  Int iBestMVPIdx = riMVPIdx;
+  
+  m_pcRdCost->setPredictor( rcMvPred );
+  Int iOrgMvBits  = m_pcRdCost->getBits(cMv.getHor(), cMv.getVer());
+  iOrgMvBits += m_auiMVPIdxCost[riMVPIdx][AMVP_MAX_NUM_CANDS];
+  Int iBestMvBits = iOrgMvBits;
+  
+  for (Int iMVPIdx = 0; iMVPIdx < pcAMVPInfo->iN; iMVPIdx++)
+  {
+    if (iMVPIdx == riMVPIdx) continue;
+    
+    m_pcRdCost->setPredictor( pcAMVPInfo->m_acMvCand[iMVPIdx] );
+    
+    Int iMvBits = m_pcRdCost->getBits(cMv.getHor(), cMv.getVer());
+    iMvBits += m_auiMVPIdxCost[iMVPIdx][AMVP_MAX_NUM_CANDS];
+    
+    if (iMvBits < iBestMvBits)
+    {
+      iBestMvBits = iMvBits;
+      iBestMVPIdx = iMVPIdx;
+    }
+  }
+  
+  if (iBestMVPIdx != riMVPIdx)  //if changed
+  {
+    rcMvPred = pcAMVPInfo->m_acMvCand[iBestMVPIdx];
+    
+    riMVPIdx = iBestMVPIdx;
+    UInt uiOrgBits = ruiBits;
+    ruiBits = uiOrgBits - iOrgMvBits + iBestMvBits;
+    ruiCost = (ruiCost - m_pcRdCost->getCost( uiOrgBits ))  + m_pcRdCost->getCost( ruiBits );
+  }
+}
+
+UInt TEncSearch::xGetTemplateCost( TComDataCU* pcCU,
+                                  UInt        uiPartIdx,
+                                  UInt      uiPartAddr,
+                                  TComYuv*    pcOrgYuv,
+                                  TComYuv*    pcTemplateCand,
+                                  TComMv      cMvCand,
+                                  Int         iMVPIdx,
+                                  Int     iMVPNum,
+                                  RefPicList  eRefPicList,
+                                  Int         iRefIdx,
+                                  Int         iSizeX,
+                                  Int         iSizeY
+                               #if ZERO_MVD_EST
+                                , UInt&       ruiDist
+                               #endif
+                                  )
+{
+  UInt uiCost  = MAX_INT;
+  
+  TComPicYuv* pcPicYuvRef = pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPicYuvRec();
+  
+  pcCU->clipMv( cMvCand );
+
+  // prediction pattern
+  if ( pcCU->getSlice()->getPPS()->getUseWP() && pcCU->getSlice()->getSliceType()==P_SLICE )
+  {
+    xPredInterLumaBlk( pcCU, pcPicYuvRef, uiPartAddr, &cMvCand, iSizeX, iSizeY, pcTemplateCand, true );
+  }
+  else
+  {
+    xPredInterLumaBlk( pcCU, pcPicYuvRef, uiPartAddr, &cMvCand, iSizeX, iSizeY, pcTemplateCand, false );
+  }
+
+  if ( pcCU->getSlice()->getPPS()->getUseWP() && pcCU->getSlice()->getSliceType()==P_SLICE )
+  {
+    xWeightedPredictionUni( pcCU, pcTemplateCand, uiPartAddr, iSizeX, iSizeY, eRefPicList, pcTemplateCand, uiPartIdx, iRefIdx );
+  }
+
+  // calc distortion
+#if ZERO_MVD_EST
+  m_pcRdCost->getMotionCost( 1, 0 );
+  DistParam cDistParam;
+  m_pcRdCost->setDistParam( cDistParam, 
+                            pcOrgYuv->getLumaAddr(uiPartAddr), pcOrgYuv->getStride(), 
+                            pcTemplateCand->getLumaAddr(uiPartAddr), pcTemplateCand->getStride(), 
+#if NS_HAD
+                            iSizeX, iSizeY, m_pcEncCfg->getUseHADME(), m_pcEncCfg->getUseNSQT() );
+#else
+                            iSizeX, iSizeY, m_pcEncCfg->getUseHADME() );
+#endif
+  ruiDist = cDistParam.DistFunc( &cDistParam );
+  uiCost = ruiDist + m_pcRdCost->getCost( m_auiMVPIdxCost[iMVPIdx][iMVPNum] );
+#else
+#if WEIGHTED_CHROMA_DISTORTION
+  uiCost = m_pcRdCost->getDistPart( pcTemplateCand->getLumaAddr(uiPartAddr), pcTemplateCand->getStride(), pcOrgYuv->getLumaAddr(uiPartAddr), pcOrgYuv->getStride(), iSizeX, iSizeY, false, DF_SAD );
+#else
+  uiCost = m_pcRdCost->getDistPart( pcTemplateCand->getLumaAddr(uiPartAddr), pcTemplateCand->getStride(), pcOrgYuv->getLumaAddr(uiPartAddr), pcOrgYuv->getStride(), iSizeX, iSizeY, DF_SAD );
+#endif
+  uiCost = (UInt) m_pcRdCost->calcRdCost( m_auiMVPIdxCost[iMVPIdx][iMVPNum], uiCost, false, DF_SAD );
+#endif
+  return uiCost;
+}
+
+Void TEncSearch::xMotionEstimation( TComDataCU* pcCU, TComYuv* pcYuvOrg, Int iPartIdx, RefPicList eRefPicList, TComMv* pcMvPred, Int iRefIdxPred, TComMv& rcMv, UInt& ruiBits, UInt& ruiCost, Bool bBi  )
+{
+  UInt          uiPartAddr;
+  Int           iRoiWidth;
+  Int           iRoiHeight;
+  
+  TComMv        cMvHalf, cMvQter;
+  TComMv        cMvSrchRngLT;
+  TComMv        cMvSrchRngRB;
+  
+  TComYuv*      pcYuv = pcYuvOrg;
+  m_iSearchRange = m_aaiAdaptSR[eRefPicList][iRefIdxPred];
+  
+  Int           iSrchRng      = ( bBi ? m_bipredSearchRange : m_iSearchRange );
+  TComPattern*  pcPatternKey  = pcCU->getPattern        ();
+  
+  Double        fWeight       = 1.0;
+  
+  pcCU->getPartIndexAndSize( iPartIdx, uiPartAddr, iRoiWidth, iRoiHeight );
+  
+  if ( bBi )
+  {
+    TComYuv*  pcYuvOther = &m_acYuvPred[1-(Int)eRefPicList];
+    pcYuv                = &m_cYuvPredTemp;
+    
+    pcYuvOrg->copyPartToPartYuv( pcYuv, uiPartAddr, iRoiWidth, iRoiHeight );
+    
+    pcYuv->removeHighFreq( pcYuvOther, uiPartAddr, iRoiWidth, iRoiHeight );
+    
+    fWeight = 0.5;
+  }
+  
+  //  Search key pattern initialization
+  pcPatternKey->initPattern( pcYuv->getLumaAddr( uiPartAddr ),
+                            pcYuv->getCbAddr  ( uiPartAddr ),
+                            pcYuv->getCrAddr  ( uiPartAddr ),
+                            iRoiWidth,
+                            iRoiHeight,
+                            pcYuv->getStride(),
+                            0, 0, 0, 0 );
+  
+  Pel*        piRefY      = pcCU->getSlice()->getRefPic( eRefPicList, iRefIdxPred )->getPicYuvRec()->getLumaAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() + uiPartAddr );
+  Int         iRefStride  = pcCU->getSlice()->getRefPic( eRefPicList, iRefIdxPred )->getPicYuvRec()->getStride();
+  
+  TComMv      cMvPred = *pcMvPred;
+  
+  if ( bBi )  xSetSearchRange   ( pcCU, rcMv   , iSrchRng, cMvSrchRngLT, cMvSrchRngRB );
+  else        xSetSearchRange   ( pcCU, cMvPred, iSrchRng, cMvSrchRngLT, cMvSrchRngRB );
+  
+  m_pcRdCost->getMotionCost ( 1, 0 );
+  
+  m_pcRdCost->setPredictor  ( *pcMvPred );
+  m_pcRdCost->setCostScale  ( 2 );
+
+  setWpScalingDistParam( pcCU, iRefIdxPred, eRefPicList );
+  //  Do integer search
+#if REF_IDX_ME_AROUND_ZEROMV
+  if( pcCU->getSlice()->getRefPic(eRefPicList, iRefIdxPred )->getIsILR())  //ILR reference pic
+  {
+    xPatternSearchILR  ( pcCU, pcPatternKey, piRefY, iRefStride, rcMv, ruiCost );
+  }
+  else  //non ILR reference pic
+  {
+  if ( !m_iFastSearch || bBi )
+  {
+    xPatternSearch      ( pcPatternKey, piRefY, iRefStride, &cMvSrchRngLT, &cMvSrchRngRB, rcMv, ruiCost );
+  }
+  else
+  {
+    rcMv = *pcMvPred;
+    xPatternSearchFast  ( pcCU, pcPatternKey, piRefY, iRefStride, &cMvSrchRngLT, &cMvSrchRngRB, rcMv, ruiCost );
+    }
+  }
+#else
+  if ( !m_iFastSearch || bBi )
+  {
+    xPatternSearch      ( pcPatternKey, piRefY, iRefStride, &cMvSrchRngLT, &cMvSrchRngRB, rcMv, ruiCost );
+  }
+  else
+  {
+    rcMv = *pcMvPred;
+    xPatternSearchFast  ( pcCU, pcPatternKey, piRefY, iRefStride, &cMvSrchRngLT, &cMvSrchRngRB, rcMv, ruiCost );
+  }
+#endif
+  
+  m_pcRdCost->getMotionCost( 1, 0 );
+  m_pcRdCost->setCostScale ( 1 );
+  
+  {
+    xPatternSearchFracDIF( pcCU, pcPatternKey, piRefY, iRefStride, &rcMv, cMvHalf, cMvQter, ruiCost
+                          ,bBi
+                          );
+  }
+  
+  
+  
+  m_pcRdCost->setCostScale( 0 );
+  rcMv <<= 2;
+  rcMv += (cMvHalf <<= 1);
+  rcMv +=  cMvQter;
+  
+  UInt uiMvBits = m_pcRdCost->getBits( rcMv.getHor(), rcMv.getVer() );
+  
+  ruiBits      += uiMvBits;
+  ruiCost       = (UInt)( floor( fWeight * ( (Double)ruiCost - (Double)m_pcRdCost->getCost( uiMvBits ) ) ) + (Double)m_pcRdCost->getCost( ruiBits ) );
+}
+
+
+Void TEncSearch::xSetSearchRange ( TComDataCU* pcCU, TComMv& cMvPred, Int iSrchRng, TComMv& rcMvSrchRngLT, TComMv& rcMvSrchRngRB )
+{
+  Int  iMvShift = 2;
+  TComMv cTmpMvPred = cMvPred;
+  pcCU->clipMv( cTmpMvPred );
+
+  rcMvSrchRngLT.setHor( cTmpMvPred.getHor() - (iSrchRng << iMvShift) );
+  rcMvSrchRngLT.setVer( cTmpMvPred.getVer() - (iSrchRng << iMvShift) );
+  
+  rcMvSrchRngRB.setHor( cTmpMvPred.getHor() + (iSrchRng << iMvShift) );
+  rcMvSrchRngRB.setVer( cTmpMvPred.getVer() + (iSrchRng << iMvShift) );
+  pcCU->clipMv        ( rcMvSrchRngLT );
+  pcCU->clipMv        ( rcMvSrchRngRB );
+  
+  rcMvSrchRngLT >>= iMvShift;
+  rcMvSrchRngRB >>= iMvShift;
+}
+
+Void TEncSearch::xPatternSearch( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, TComMv* pcMvSrchRngLT, TComMv* pcMvSrchRngRB, TComMv& rcMv, UInt& ruiSAD )
+{
+  Int   iSrchRngHorLeft   = pcMvSrchRngLT->getHor();
+  Int   iSrchRngHorRight  = pcMvSrchRngRB->getHor();
+  Int   iSrchRngVerTop    = pcMvSrchRngLT->getVer();
+  Int   iSrchRngVerBottom = pcMvSrchRngRB->getVer();
+  
+  UInt  uiSad;
+  UInt  uiSadBest         = MAX_UINT;
+  Int   iBestX = 0;
+  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_cDistParam.iRows > 8 )
+    {
+      m_cDistParam.iSubShift = 1;
+    }
+  }
+  
+  piRefY += (iSrchRngVerTop * iRefStride);
+  for ( Int y = iSrchRngVerTop; y <= iSrchRngVerBottom; y++ )
+  {
+    for ( Int x = iSrchRngHorLeft; x <= iSrchRngHorRight; x++ )
+    {
+      //  find min. distortion position
+      piRefSrch = piRefY + x;
+      m_cDistParam.pCur = piRefSrch;
+
+      setDistParamComp(0);
+
+      uiSad = m_cDistParam.DistFunc( &m_cDistParam );
+      
+      // motion cost
+      uiSad += m_pcRdCost->getCost( x, y );
+      
+      if ( uiSad < uiSadBest )
+      {
+        uiSadBest = uiSad;
+        iBestX    = x;
+        iBestY    = y;
+      }
+    }
+    piRefY += iRefStride;
+  }
+  
+  rcMv.set( iBestX, iBestY );
+  
+  ruiSAD = uiSadBest - m_pcRdCost->getCost( iBestX, iBestY );
+  return;
+}
+
+Void TEncSearch::xPatternSearchFast( TComDataCU* pcCU, TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, TComMv* pcMvSrchRngLT, TComMv* pcMvSrchRngRB, TComMv& rcMv, UInt& ruiSAD )
+{
+  pcCU->getMvPredLeft       ( m_acMvPredictors[0] );
+  pcCU->getMvPredAbove      ( m_acMvPredictors[1] );
+  pcCU->getMvPredAboveRight ( m_acMvPredictors[2] );
+  
+  switch ( m_iFastSearch )
+  {
+    case 1:
+      xTZSearch( pcCU, pcPatternKey, piRefY, iRefStride, pcMvSrchRngLT, pcMvSrchRngRB, rcMv, ruiSAD );
+      break;
+      
+    default:
+      break;
+  }
+}
+
+#if REF_IDX_ME_AROUND_ZEROMV
+//ILR integer pixel motion estimation search
+//pcCU is CU pointer
+//pcPatterney contains target PU infor
+//piRefY is the PU at the same position as the source PU, but in the reference pic
+//iRefStride is the reference stride
+//rcMv output best integer MV
+//ruiSAD outputs the SAD of best integer MV
+Void TEncSearch::xPatternSearchILR( TComDataCU* pcCU, TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, TComMv& rcMv, UInt& ruiSAD )
+{
+  Int      candMvX[5] = {0, -1, 1,  0, 0};
+  Int      candMvY[5] = {0,  0, 0, -1, 1};
+  Int      numCand    = 1;
+  Int      iBestX = 0;
+  Int      iBestY = 0;
+  Int      uiSadBest = MAX_UINT;
+  UInt     uiSad;
+
+  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_cDistParam.iRows > 8 )
+    {
+      m_cDistParam.iSubShift = 1;
+    }
+  }
+
+  for(Int candId = 0; candId < numCand; candId++)
+  {
+    piRefSrch         = piRefY + (candMvY[candId] * iRefStride) + candMvX[candId];
+    m_cDistParam.pCur = piRefSrch;
+
+    setDistParamComp(0);
+    
+    uiSad = m_cDistParam.DistFunc( &m_cDistParam );  //SAD
+
+    //motion cost
+    uiSad += m_pcRdCost->getCost( candMvX[candId], candMvY[candId] );  //SAD rdCost
+
+    if(uiSad < uiSadBest)
+    {
+      uiSadBest = uiSad;
+      iBestX    = candMvX[candId];
+      iBestY    = candMvY[candId];
+    }
+  }
+
+  rcMv.set( iBestX, iBestY );
+
+  ruiSAD = uiSadBest - m_pcRdCost->getCost( iBestX, iBestY );
+  return;
+}
+#endif
+Void TEncSearch::xTZSearch( TComDataCU* pcCU, TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, TComMv* pcMvSrchRngLT, TComMv* pcMvSrchRngRB, TComMv& rcMv, UInt& ruiSAD )
+{
+  Int   iSrchRngHorLeft   = pcMvSrchRngLT->getHor();
+  Int   iSrchRngHorRight  = pcMvSrchRngRB->getHor();
+  Int   iSrchRngVerTop    = pcMvSrchRngLT->getVer();
+  Int   iSrchRngVerBottom = pcMvSrchRngRB->getVer();
+  
+  TZ_SEARCH_CONFIGURATION
+  
+  UInt uiSearchRange = m_iSearchRange;
+  pcCU->clipMv( rcMv );
+  rcMv >>= 2;
+  // init TZSearchStruct
+  IntTZSearchStruct cStruct;
+  cStruct.iYStride    = iRefStride;
+  cStruct.piRefY      = piRefY;
+  cStruct.uiBestSad   = MAX_UINT;
+  
+  // set rcMv (Median predictor) as start point and as best point
+  xTZSearchHelp( pcPatternKey, cStruct, rcMv.getHor(), rcMv.getVer(), 0, 0 );
+  
+  // test whether one of PRED_A, PRED_B, PRED_C MV is better start point than Median predictor
+  if ( bTestOtherPredictedMV )
+  {
+    for ( UInt index = 0; index < 3; index++ )
+    {
+      TComMv cMv = m_acMvPredictors[index];
+      pcCU->clipMv( cMv );
+      cMv >>= 2;
+      xTZSearchHelp( pcPatternKey, cStruct, cMv.getHor(), cMv.getVer(), 0, 0 );
+    }
+  }
+  
+  // test whether zero Mv is better start point than Median predictor
+  if ( bTestZeroVector )
+  {
+    xTZSearchHelp( pcPatternKey, cStruct, 0, 0, 0, 0 );
+  }
+  
+  // start search
+  Int  iDist = 0;
+  Int  iStartX = cStruct.iBestX;
+  Int  iStartY = cStruct.iBestY;
+  
+  // first search
+  for ( iDist = 1; iDist <= (Int)uiSearchRange; iDist*=2 )
+  {
+    if ( bFirstSearchDiamond == 1 )
+    {
+      xTZ8PointDiamondSearch ( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, iStartX, iStartY, iDist );
+    }
+    else
+    {
+      xTZ8PointSquareSearch  ( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, iStartX, iStartY, iDist );
+    }
+    
+    if ( bFirstSearchStop && ( cStruct.uiBestRound >= uiFirstSearchRounds ) ) // stop criterion
+    {
+      break;
+    }
+  }
+  
+  // test whether zero Mv is a better start point than Median predictor
+  if ( bTestZeroVectorStart && ((cStruct.iBestX != 0) || (cStruct.iBestY != 0)) )
+  {
+    xTZSearchHelp( pcPatternKey, cStruct, 0, 0, 0, 0 );
+    if ( (cStruct.iBestX == 0) && (cStruct.iBestY == 0) )
+    {
+      // test its neighborhood
+      for ( iDist = 1; iDist <= (Int)uiSearchRange; iDist*=2 )
+      {
+        xTZ8PointDiamondSearch( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, 0, 0, iDist );
+        if ( bTestZeroVectorStop && (cStruct.uiBestRound > 0) ) // stop criterion
+        {
+          break;
+        }
+      }
+    }
+  }
+  
+  // calculate only 2 missing points instead 8 points if cStruct.uiBestDistance == 1
+  if ( cStruct.uiBestDistance == 1 )
+  {
+    cStruct.uiBestDistance = 0;
+    xTZ2PointSearch( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB );
+  }
+  
+  // raster search if distance is too big
+  if ( bEnableRasterSearch && ( ((Int)(cStruct.uiBestDistance) > iRaster) || bAlwaysRasterSearch ) )
+  {
+    cStruct.uiBestDistance = iRaster;
+    for ( iStartY = iSrchRngVerTop; iStartY <= iSrchRngVerBottom; iStartY += iRaster )
+    {
+      for ( iStartX = iSrchRngHorLeft; iStartX <= iSrchRngHorRight; iStartX += iRaster )
+      {
+        xTZSearchHelp( pcPatternKey, cStruct, iStartX, iStartY, 0, iRaster );
+      }
+    }
+  }
+  
+  // raster refinement
+  if ( bRasterRefinementEnable && cStruct.uiBestDistance > 0 )
+  {
+    while ( cStruct.uiBestDistance > 0 )
+    {
+      iStartX = cStruct.iBestX;
+      iStartY = cStruct.iBestY;
+      if ( cStruct.uiBestDistance > 1 )
+      {
+        iDist = cStruct.uiBestDistance >>= 1;
+        if ( bRasterRefinementDiamond == 1 )
+        {
+          xTZ8PointDiamondSearch ( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, iStartX, iStartY, iDist );
+        }
+        else
+        {
+          xTZ8PointSquareSearch  ( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, iStartX, iStartY, iDist );
+        }
+      }
+      
+      // calculate only 2 missing points instead 8 points if cStruct.uiBestDistance == 1
+      if ( cStruct.uiBestDistance == 1 )
+      {
+        cStruct.uiBestDistance = 0;
+        if ( cStruct.ucPointNr != 0 )
+        {
+          xTZ2PointSearch( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB );
+        }
+      }
+    }
+  }
+  
+  // start refinement
+  if ( bStarRefinementEnable && cStruct.uiBestDistance > 0 )
+  {
+    while ( cStruct.uiBestDistance > 0 )
+    {
+      iStartX = cStruct.iBestX;
+      iStartY = cStruct.iBestY;
+      cStruct.uiBestDistance = 0;
+      cStruct.ucPointNr = 0;
+      for ( iDist = 1; iDist < (Int)uiSearchRange + 1; iDist*=2 )
+      {
+        if ( bStarRefinementDiamond == 1 )
+        {
+          xTZ8PointDiamondSearch ( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, iStartX, iStartY, iDist );
+        }
+        else
+        {
+          xTZ8PointSquareSearch  ( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, iStartX, iStartY, iDist );
+        }
+        if ( bStarRefinementStop && (cStruct.uiBestRound >= uiStarRefinementRounds) ) // stop criterion
+        {
+          break;
+        }
+      }
+      
+      // calculate only 2 missing points instead 8 points if cStrukt.uiBestDistance == 1
+      if ( cStruct.uiBestDistance == 1 )
+      {
+        cStruct.uiBestDistance = 0;
+        if ( cStruct.ucPointNr != 0 )
+        {
+          xTZ2PointSearch( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB );
+        }
+      }
+    }
+  }
+  
+  // write out best match
+  rcMv.set( cStruct.iBestX, cStruct.iBestY );
+  ruiSAD = cStruct.uiBestSad - m_pcRdCost->getCost( cStruct.iBestX, cStruct.iBestY );
+}
+
+Void TEncSearch::xPatternSearchFracDIF(TComDataCU* pcCU,
+                                       TComPattern* pcPatternKey,
+                                       Pel* piRefY,
+                                       Int iRefStride,
+                                       TComMv* pcMvInt,
+                                       TComMv& rcMvHalf,
+                                       TComMv& rcMvQter,
+                                       UInt& ruiCost
+                                       ,Bool biPred
+                                       )
+{
+  //  Reference pattern initialization (integer scale)
+  TComPattern cPatternRoi;
+  Int         iOffset    = pcMvInt->getHor() + pcMvInt->getVer() * iRefStride;
+  cPatternRoi.initPattern( piRefY +  iOffset,
+                          NULL,
+                          NULL,
+                          pcPatternKey->getROIYWidth(),
+                          pcPatternKey->getROIYHeight(),
+                          iRefStride,
+                          0, 0, 0, 0 );
+  
+  //  Half-pel refinement
+  xExtDIFUpSamplingH ( &cPatternRoi, biPred );
+  
+  rcMvHalf = *pcMvInt;   rcMvHalf <<= 1;    // for mv-cost
+  TComMv baseRefMv(0, 0);
+  ruiCost = xPatternRefinement( pcPatternKey, baseRefMv, 2, rcMvHalf   );
+  
+  m_pcRdCost->setCostScale( 0 );
+  
+  xExtDIFUpSamplingQ ( &cPatternRoi, rcMvHalf, biPred );
+  baseRefMv = rcMvHalf;
+  baseRefMv <<= 1;
+  
+  rcMvQter = *pcMvInt;   rcMvQter <<= 1;    // for mv-cost
+  rcMvQter += rcMvHalf;  rcMvQter <<= 1;
+  ruiCost = xPatternRefinement( pcPatternKey, baseRefMv, 1, rcMvQter );
+}
+
+/** encode residual and calculate rate-distortion for a CU block
+ * \param pcCU
+ * \param pcYuvOrg
+ * \param pcYuvPred
+ * \param rpcYuvResi
+ * \param rpcYuvResiBest
+ * \param rpcYuvRec
+ * \param bSkipRes
+ * \returns Void
+ */
+Void TEncSearch::encodeResAndCalcRdInterCU( TComDataCU* pcCU, TComYuv* pcYuvOrg, TComYuv* pcYuvPred, TComYuv*& rpcYuvResi, TComYuv*& rpcYuvResiBest, TComYuv*& rpcYuvRec, Bool bSkipRes )
+{
+  if ( pcCU->isIntra(0) )
+  {
+    return;
+  }
+  
+  Bool      bHighPass    = pcCU->getSlice()->getDepth() ? true : false;
+  UInt      uiBits       = 0, uiBitsBest = 0;
+  UInt      uiDistortion = 0, uiDistortionBest = 0;
+  
+  UInt      uiWidth      = pcCU->getWidth ( 0 );
+  UInt      uiHeight     = pcCU->getHeight( 0 );
+  
+  //  No residual coding : SKIP mode
+  if ( bSkipRes )
+  {
+#if SKIP_FLAG
+    pcCU->setSkipFlagSubParts( true, 0, pcCU->getDepth(0) );
+#endif
+
+    rpcYuvResi->clear();
+    
+    pcYuvPred->copyToPartYuv( rpcYuvRec, 0 );
+    
+#if WEIGHTED_CHROMA_DISTORTION
+    uiDistortion = m_pcRdCost->getDistPart( rpcYuvRec->getLumaAddr(), rpcYuvRec->getStride(),  pcYuvOrg->getLumaAddr(), pcYuvOrg->getStride(),  uiWidth,      uiHeight      )
+    + m_pcRdCost->getDistPart( rpcYuvRec->getCbAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCbAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1, true )
+    + m_pcRdCost->getDistPart( rpcYuvRec->getCrAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCrAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1, true );
+#else
+    uiDistortion = m_pcRdCost->getDistPart( rpcYuvRec->getLumaAddr(), rpcYuvRec->getStride(),  pcYuvOrg->getLumaAddr(), pcYuvOrg->getStride(),  uiWidth,      uiHeight      )
+    + m_pcRdCost->getDistPart( rpcYuvRec->getCbAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCbAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1 )
+    + m_pcRdCost->getDistPart( rpcYuvRec->getCrAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCrAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1 );
+#endif
+
+    if( m_bUseSBACRD )
+      m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_CURR_BEST]);
+    
+    m_pcEntropyCoder->resetBits();
+    if (pcCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
+    {
+      m_pcEntropyCoder->encodeCUTransquantBypassFlag(pcCU, 0, true);
+    }
+    m_pcEntropyCoder->encodeSkipFlag(pcCU, 0, true);
+    m_pcEntropyCoder->encodeMergeIndex( pcCU, 0, 0, true );
+    
+    uiBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+    pcCU->getTotalBits()       = uiBits;
+    pcCU->getTotalDistortion() = uiDistortion;
+    pcCU->getTotalCost()       = m_pcRdCost->calcRdCost( uiBits, uiDistortion );
+    
+    if( m_bUseSBACRD )
+      m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_TEMP_BEST]);
+    
+    pcCU->setCbfSubParts( 0, 0, 0, 0, pcCU->getDepth( 0 ) );
+    pcCU->setTrIdxSubParts( 0, 0, pcCU->getDepth(0) );
+    
+    return;
+  }
+  
+  //  Residual coding.
+  Int    qp, qpBest = 0, qpMin, qpMax;
+  Double  dCost, dCostBest = MAX_DOUBLE;
+  
+  UInt uiTrLevel = 0;
+  if( (pcCU->getWidth(0) > pcCU->getSlice()->getSPS()->getMaxTrSize()) )
+  {
+    while( pcCU->getWidth(0) > (pcCU->getSlice()->getSPS()->getMaxTrSize()<<uiTrLevel) ) uiTrLevel++;
+  }
+  UInt uiMaxTrMode = pcCU->getSlice()->getSPS()->getMaxTrDepth() + uiTrLevel;
+  
+  while((uiWidth>>uiMaxTrMode) < (g_uiMaxCUWidth>>g_uiMaxCUDepth)) uiMaxTrMode--;
+  
+  qpMin =  bHighPass ? Clip3( -pcCU->getSlice()->getSPS()->getQpBDOffsetY(), MAX_QP, pcCU->getQP(0) - m_iMaxDeltaQP ) : pcCU->getQP( 0 );
+  qpMax =  bHighPass ? Clip3( -pcCU->getSlice()->getSPS()->getQpBDOffsetY(), MAX_QP, pcCU->getQP(0) + m_iMaxDeltaQP ) : pcCU->getQP( 0 );
+
+  rpcYuvResi->subtract( pcYuvOrg, pcYuvPred, 0, uiWidth );
+
+  for ( qp = qpMin; qp <= qpMax; qp++ )
+  {
+    dCost = 0.;
+    uiBits = 0;
+    uiDistortion = 0;
+    if( m_bUseSBACRD )
+    {
+      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ pcCU->getDepth( 0 ) ][ CI_CURR_BEST ] );
+    }
+    
+    UInt uiZeroDistortion = 0;
+#if IBDI_DISTORTION
+    xEstimateResidualQT( pcCU, 0, 0, 0, pcYuvOrg, pcYuvPred, rpcYuvResi,  pcCU->getDepth(0), dCost, uiBits, uiDistortion, &uiZeroDistortion );
+#else
+    xEstimateResidualQT( pcCU, 0, 0, 0, rpcYuvResi,  pcCU->getDepth(0), dCost, uiBits, uiDistortion, &uiZeroDistortion );
+#endif
+    
+#if TU_ZERO_CBF_RDO
+    m_pcEntropyCoder->resetBits();
+    m_pcEntropyCoder->encodeQtRootCbfZero( pcCU, 0 );
+    UInt zeroResiBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+    double dZeroCost = m_pcRdCost->calcRdCost( zeroResiBits, uiZeroDistortion );
+#else
+    double dZeroCost = m_pcRdCost->calcRdCost( 0, uiZeroDistortion );
+#endif
+    if(pcCU->isLosslessCoded( 0 ))
+    {  
+      dZeroCost = dCost + 1;
+    }
+    if ( dZeroCost < dCost )
+    {
+      dCost        = dZeroCost;
+      uiBits       = 0;
+      uiDistortion = uiZeroDistortion;
+      
+      const UInt uiQPartNum = pcCU->getPic()->getNumPartInCU() >> (pcCU->getDepth(0) << 1);
+      ::memset( pcCU->getTransformIdx()      , 0, uiQPartNum * sizeof(UChar) );
+      ::memset( pcCU->getCbf( TEXT_LUMA )    , 0, uiQPartNum * sizeof(UChar) );
+      ::memset( pcCU->getCbf( TEXT_CHROMA_U ), 0, uiQPartNum * sizeof(UChar) );
+      ::memset( pcCU->getCbf( TEXT_CHROMA_V ), 0, uiQPartNum * sizeof(UChar) );
+      ::memset( pcCU->getCoeffY()            , 0, uiWidth * uiHeight * sizeof( TCoeff )      );
+      ::memset( pcCU->getCoeffCb()           , 0, uiWidth * uiHeight * sizeof( TCoeff ) >> 2 );
+      ::memset( pcCU->getCoeffCr()           , 0, uiWidth * uiHeight * sizeof( TCoeff ) >> 2 );
+#if INTER_TRANSFORMSKIP
+      pcCU->setTransformSkipSubParts ( 0, 0, 0, 0, pcCU->getDepth(0) );
+#endif
+    }
+    else
+    {
+      xSetResidualQTData( pcCU, 0, 0, 0, NULL, pcCU->getDepth(0), false );
+    }
+    
+    if( m_bUseSBACRD )
+    {
+      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_CURR_BEST] );
+    }
+#if 0 // check
+    {
+      m_pcEntropyCoder->resetBits();
+      m_pcEntropyCoder->encodeCoeff( pcCU, 0, pcCU->getDepth(0), pcCU->getWidth(0), pcCU->getHeight(0) );
+      const UInt uiBitsForCoeff = m_pcEntropyCoder->getNumberOfWrittenBits();
+      if( m_bUseSBACRD )
+      {
+        m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_CURR_BEST] );
+      }
+      if( uiBitsForCoeff != uiBits )
+        assert( 0 );
+    }
+#endif
+    uiBits = 0;
+    {
+      TComYuv *pDummy = NULL;
+      xAddSymbolBitsInter( pcCU, 0, 0, uiBits, pDummy, NULL, pDummy );
+    }
+    
+    
+    Double dExactCost = m_pcRdCost->calcRdCost( uiBits, uiDistortion );
+    dCost = dExactCost;
+    
+    if ( dCost < dCostBest )
+    {
+      if ( !pcCU->getQtRootCbf( 0 ) )
+      {
+        rpcYuvResiBest->clear();
+      }
+      else
+      {
+        xSetResidualQTData( pcCU, 0, 0, 0, rpcYuvResiBest, pcCU->getDepth(0), true );
+      }
+      
+      if( qpMin != qpMax && qp != qpMax )
+      {
+        const UInt uiQPartNum = pcCU->getPic()->getNumPartInCU() >> (pcCU->getDepth(0) << 1);
+        ::memcpy( m_puhQTTempTrIdx, pcCU->getTransformIdx(),        uiQPartNum * sizeof(UChar) );
+        ::memcpy( m_puhQTTempCbf[0], pcCU->getCbf( TEXT_LUMA ),     uiQPartNum * sizeof(UChar) );
+        ::memcpy( m_puhQTTempCbf[1], pcCU->getCbf( TEXT_CHROMA_U ), uiQPartNum * sizeof(UChar) );
+        ::memcpy( m_puhQTTempCbf[2], pcCU->getCbf( TEXT_CHROMA_V ), uiQPartNum * sizeof(UChar) );
+        ::memcpy( m_pcQTTempCoeffY,  pcCU->getCoeffY(),  uiWidth * uiHeight * sizeof( TCoeff )      );
+        ::memcpy( m_pcQTTempCoeffCb, pcCU->getCoeffCb(), uiWidth * uiHeight * sizeof( TCoeff ) >> 2 );
+        ::memcpy( m_pcQTTempCoeffCr, pcCU->getCoeffCr(), uiWidth * uiHeight * sizeof( TCoeff ) >> 2 );
+#if ADAPTIVE_QP_SELECTION
+        ::memcpy( m_pcQTTempArlCoeffY,  pcCU->getArlCoeffY(),  uiWidth * uiHeight * sizeof( Int )      );
+        ::memcpy( m_pcQTTempArlCoeffCb, pcCU->getArlCoeffCb(), uiWidth * uiHeight * sizeof( Int ) >> 2 );
+        ::memcpy( m_pcQTTempArlCoeffCr, pcCU->getArlCoeffCr(), uiWidth * uiHeight * sizeof( Int ) >> 2 );
+#endif
+#if INTER_TRANSFORMSKIP
+        ::memcpy( m_puhQTTempTransformSkipFlag[0], pcCU->getTransformSkip(TEXT_LUMA),     uiQPartNum * sizeof( UChar ) );
+        ::memcpy( m_puhQTTempTransformSkipFlag[1], pcCU->getTransformSkip(TEXT_CHROMA_U), uiQPartNum * sizeof( UChar ) );
+        ::memcpy( m_puhQTTempTransformSkipFlag[2], pcCU->getTransformSkip(TEXT_CHROMA_V), uiQPartNum * sizeof( UChar ) );
+#endif
+      }
+      uiBitsBest       = uiBits;
+      uiDistortionBest = uiDistortion;
+      dCostBest        = dCost;
+      qpBest           = qp;
+      if( m_bUseSBACRD )
+      {
+        m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ pcCU->getDepth( 0 ) ][ CI_TEMP_BEST ] );
+      }
+    }
+  }
+  
+  assert ( dCostBest != MAX_DOUBLE );
+  
+  if( qpMin != qpMax && qpBest != qpMax )
+  {
+    if( m_bUseSBACRD )
+    {
+      assert( 0 ); // check
+      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ pcCU->getDepth( 0 ) ][ CI_TEMP_BEST ] );
+    }
+    // copy best cbf and trIdx to pcCU
+    const UInt uiQPartNum = pcCU->getPic()->getNumPartInCU() >> (pcCU->getDepth(0) << 1);
+    ::memcpy( pcCU->getTransformIdx(),       m_puhQTTempTrIdx,  uiQPartNum * sizeof(UChar) );
+    ::memcpy( pcCU->getCbf( TEXT_LUMA ),     m_puhQTTempCbf[0], uiQPartNum * sizeof(UChar) );
+    ::memcpy( pcCU->getCbf( TEXT_CHROMA_U ), m_puhQTTempCbf[1], uiQPartNum * sizeof(UChar) );
+    ::memcpy( pcCU->getCbf( TEXT_CHROMA_V ), m_puhQTTempCbf[2], uiQPartNum * sizeof(UChar) );
+    ::memcpy( pcCU->getCoeffY(),  m_pcQTTempCoeffY,  uiWidth * uiHeight * sizeof( TCoeff )      );
+    ::memcpy( pcCU->getCoeffCb(), m_pcQTTempCoeffCb, uiWidth * uiHeight * sizeof( TCoeff ) >> 2 );
+    ::memcpy( pcCU->getCoeffCr(), m_pcQTTempCoeffCr, uiWidth * uiHeight * sizeof( TCoeff ) >> 2 );
+#if ADAPTIVE_QP_SELECTION
+    ::memcpy( pcCU->getArlCoeffY(),  m_pcQTTempArlCoeffY,  uiWidth * uiHeight * sizeof( Int )      );
+    ::memcpy( pcCU->getArlCoeffCb(), m_pcQTTempArlCoeffCb, uiWidth * uiHeight * sizeof( Int ) >> 2 );
+    ::memcpy( pcCU->getArlCoeffCr(), m_pcQTTempArlCoeffCr, uiWidth * uiHeight * sizeof( Int ) >> 2 );
+#endif
+#if INTER_TRANSFORMSKIP
+    ::memcpy( pcCU->getTransformSkip(TEXT_LUMA),     m_puhQTTempTransformSkipFlag[0], uiQPartNum * sizeof( UChar ) );
+    ::memcpy( pcCU->getTransformSkip(TEXT_CHROMA_U), m_puhQTTempTransformSkipFlag[1], uiQPartNum * sizeof( UChar ) );
+    ::memcpy( pcCU->getTransformSkip(TEXT_CHROMA_V), m_puhQTTempTransformSkipFlag[2], uiQPartNum * sizeof( UChar ) );
+#endif
+  }
+  rpcYuvRec->addClip ( pcYuvPred, rpcYuvResiBest, 0, uiWidth );
+  
+  // update with clipped distortion and cost (qp estimation loop uses unclipped values)
+#if WEIGHTED_CHROMA_DISTORTION
+  uiDistortionBest = m_pcRdCost->getDistPart( rpcYuvRec->getLumaAddr(), rpcYuvRec->getStride(),  pcYuvOrg->getLumaAddr(), pcYuvOrg->getStride(),  uiWidth,      uiHeight      )
+  + m_pcRdCost->getDistPart( rpcYuvRec->getCbAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCbAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1, true )
+  + m_pcRdCost->getDistPart( rpcYuvRec->getCrAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCrAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1, true );
+#else
+  uiDistortionBest = m_pcRdCost->getDistPart( rpcYuvRec->getLumaAddr(), rpcYuvRec->getStride(),  pcYuvOrg->getLumaAddr(), pcYuvOrg->getStride(),  uiWidth,      uiHeight      )
+  + m_pcRdCost->getDistPart( rpcYuvRec->getCbAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCbAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1 )
+  + m_pcRdCost->getDistPart( rpcYuvRec->getCrAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCrAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1 );
+#endif
+  dCostBest = m_pcRdCost->calcRdCost( uiBitsBest, uiDistortionBest );
+  
+  pcCU->getTotalBits()       = uiBitsBest;
+  pcCU->getTotalDistortion() = uiDistortionBest;
+  pcCU->getTotalCost()       = dCostBest;
+  
+  if ( pcCU->isSkipped(0) )
+  {
+    pcCU->setCbfSubParts( 0, 0, 0, 0, pcCU->getDepth( 0 ) );
+  }
+  
+  pcCU->setQPSubParts( qpBest, 0, pcCU->getDepth(0) );
+}
+
+#if IBDI_DISTORTION
+Void TEncSearch::xEstimateResidualQT( TComDataCU* pcCU, UInt uiQuadrant, UInt uiAbsPartIdx, UInt absTUPartIdx, TComYuv* pcOrg, TComYuv* pcPred, TComYuv* pcResi, const UInt uiDepth, Double &rdCost, UInt &ruiBits, UInt &ruiDist, UInt *puiZeroDist )
+#else
+Void TEncSearch::xEstimateResidualQT( TComDataCU* pcCU, UInt uiQuadrant, UInt uiAbsPartIdx, UInt absTUPartIdx, TComYuv* pcResi, const UInt uiDepth, Double &rdCost, UInt &ruiBits, UInt &ruiDist, UInt *puiZeroDist )
+#endif
+{
+  const UInt uiTrMode = uiDepth - pcCU->getDepth( 0 );
+  
+  assert( pcCU->getDepth( 0 ) == pcCU->getDepth( uiAbsPartIdx ) );
+  const UInt uiLog2TrSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiDepth]+2;
+  
+  UInt SplitFlag = ((pcCU->getSlice()->getSPS()->getQuadtreeTUMaxDepthInter() == 1) && pcCU->getPredictionMode(uiAbsPartIdx) == MODE_INTER && ( pcCU->getPartitionSize(uiAbsPartIdx) != SIZE_2Nx2N ));
+  Bool bCheckFull;
+  if ( SplitFlag && uiDepth == pcCU->getDepth(uiAbsPartIdx) && ( uiLog2TrSize >  pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) ) )
+     bCheckFull = false;
+  else
+     bCheckFull =  ( uiLog2TrSize <= pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() );
+
+  const Bool bCheckSplit  = ( uiLog2TrSize >  pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) );
+  
+  assert( bCheckFull || bCheckSplit );
+  
+  Bool  bCodeChroma   = true;
+  UInt  uiTrModeC     = uiTrMode;
+  UInt  uiLog2TrSizeC = uiLog2TrSize-1;
+  if( uiLog2TrSize == 2 )
+  {
+    uiLog2TrSizeC++;
+    uiTrModeC    --;
+    UInt  uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrModeC ) << 1 );
+    bCodeChroma   = ( ( uiAbsPartIdx % uiQPDiv ) == 0 );
+  }
+  
+  const UInt uiSetCbf = 1 << uiTrMode;
+  // code full block
+  Double dSingleCost = MAX_DOUBLE;
+  UInt uiSingleBits = 0;
+  UInt uiSingleDist = 0;
+  UInt uiAbsSumY = 0, uiAbsSumU = 0, uiAbsSumV = 0;
+#if INTER_TRANSFORMSKIP
+  UInt uiBestTransformMode[3] = {0};
+#endif
+
+  if( m_bUseSBACRD )
+  {
+    m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
+  }
+  
+  if( bCheckFull )
+  {
+    const UInt uiNumCoeffPerAbsPartIdxIncrement = pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() >> ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 );
+    const UInt uiQTTempAccessLayer = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+    TCoeff *pcCoeffCurrY = m_ppcQTTempCoeffY [uiQTTempAccessLayer] +  uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx;
+    TCoeff *pcCoeffCurrU = m_ppcQTTempCoeffCb[uiQTTempAccessLayer] + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
+    TCoeff *pcCoeffCurrV = m_ppcQTTempCoeffCr[uiQTTempAccessLayer] + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
+#if ADAPTIVE_QP_SELECTION    
+    Int *pcArlCoeffCurrY = m_ppcQTTempArlCoeffY [uiQTTempAccessLayer] +  uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx;
+    Int *pcArlCoeffCurrU = m_ppcQTTempArlCoeffCb[uiQTTempAccessLayer] + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
+    Int *pcArlCoeffCurrV = m_ppcQTTempArlCoeffCr[uiQTTempAccessLayer] + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);   
+#endif
+    
+    Int trWidth = 0, trHeight = 0, trWidthC = 0, trHeightC = 0;
+    UInt absTUPartIdxC = uiAbsPartIdx;
+
+    trWidth  = trHeight  = 1 << uiLog2TrSize;
+    trWidthC = trHeightC = 1 <<uiLog2TrSizeC;
+#if !REMOVE_NSQT
+    pcCU->getNSQTSize ( uiTrMode, uiAbsPartIdx, trWidth, trHeight );
+    pcCU->getNSQTSize ( uiTrModeC, uiAbsPartIdx, trWidthC, trHeightC );
+
+    if( bCodeChroma && pcCU->useNonSquareTrans( uiTrMode, uiAbsPartIdx ) && !( uiLog2TrSizeC  == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() && uiTrModeC == 1 ) )
+    {  
+      absTUPartIdxC = pcCU->getNSAddrChroma( uiLog2TrSizeC, uiTrModeC, uiQuadrant, absTUPartIdx );
+    }
+#endif
+    pcCU->setTrIdxSubParts( uiDepth - pcCU->getDepth( 0 ), uiAbsPartIdx, uiDepth );
+#if INTER_TRANSFORMSKIP
+    Double minCostY = MAX_DOUBLE;
+    Double minCostU = MAX_DOUBLE;
+    Double minCostV = MAX_DOUBLE;
+#if PPS_TS_FLAG
+    Bool checkTransformSkipY  = pcCU->getSlice()->getPPS()->getUseTransformSkip() && trWidth == 4 && trHeight == 4;
+    Bool checkTransformSkipUV = pcCU->getSlice()->getPPS()->getUseTransformSkip() && trWidthC == 4 && trHeightC == 4;
+#else
+    Bool checkTransformSkipY  = pcCU->getSlice()->getSPS()->getUseTransformSkip() && trWidth == 4 && trHeight == 4;
+    Bool checkTransformSkipUV = pcCU->getSlice()->getSPS()->getUseTransformSkip() && trWidthC == 4 && trHeightC == 4;
+#endif
+
+    checkTransformSkipY         &= (!pcCU->isLosslessCoded(0));
+    checkTransformSkipUV        &= (!pcCU->isLosslessCoded(0));
+
+    pcCU->setTransformSkipSubParts ( 0, TEXT_LUMA, uiAbsPartIdx, uiDepth ); 
+    if( bCodeChroma )
+    {
+      pcCU->setTransformSkipSubParts ( 0, TEXT_CHROMA_U, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC ); 
+      pcCU->setTransformSkipSubParts ( 0, TEXT_CHROMA_V, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC ); 
+    }
+#endif
+
+    if (m_pcEncCfg->getUseRDOQ())
+    {
+      m_pcEntropyCoder->estimateBit(m_pcTrQuant->m_pcEstBitsSbac, trWidth, trHeight, TEXT_LUMA );        
+    }
+
+    m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_LUMA, pcCU->getSlice()->getSPS()->getQpBDOffsetY(), 0 );
+
+#if RDOQ_CHROMA_LAMBDA 
+    m_pcTrQuant->selectLambda(TEXT_LUMA);  
+#endif
+    m_pcTrQuant->transformNxN( pcCU, pcResi->getLumaAddr( absTUPartIdx ), pcResi->getStride (), pcCoeffCurrY, 
+#if ADAPTIVE_QP_SELECTION
+                                 pcArlCoeffCurrY, 
+#endif      
+                                 trWidth,   trHeight,    uiAbsSumY, TEXT_LUMA,     uiAbsPartIdx );
+    
+    pcCU->setCbfSubParts( uiAbsSumY ? uiSetCbf : 0, TEXT_LUMA, uiAbsPartIdx, uiDepth );
+    
+    if( bCodeChroma )
+    {
+      if (m_pcEncCfg->getUseRDOQ())
+      {
+        m_pcEntropyCoder->estimateBit(m_pcTrQuant->m_pcEstBitsSbac, trWidthC, trHeightC, TEXT_CHROMA );          
+      }
+
+#if CHROMA_QP_EXTENSION
+      Int curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCbQpOffset() + pcCU->getSlice()->getSliceQpDeltaCb();
+      m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
+#else
+      m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), pcCU->getSlice()->getPPS()->getChromaCbQpOffset() );
+#endif
+
+#if RDOQ_CHROMA_LAMBDA 
+      m_pcTrQuant->selectLambda(TEXT_CHROMA); 
+#endif
+
+      m_pcTrQuant->transformNxN( pcCU, pcResi->getCbAddr(absTUPartIdxC), pcResi->getCStride(), pcCoeffCurrU, 
+#if ADAPTIVE_QP_SELECTION
+                                 pcArlCoeffCurrU, 
+#endif        
+                                 trWidthC, trHeightC, uiAbsSumU, TEXT_CHROMA_U, uiAbsPartIdx );
+
+#if CHROMA_QP_EXTENSION
+      curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCrQpOffset() + pcCU->getSlice()->getSliceQpDeltaCr();
+      m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
+#else
+      m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), pcCU->getSlice()->getPPS()->getChromaCrQpOffset() );
+#endif
+      m_pcTrQuant->transformNxN( pcCU, pcResi->getCrAddr(absTUPartIdxC), pcResi->getCStride(), pcCoeffCurrV, 
+#if ADAPTIVE_QP_SELECTION
+                                 pcArlCoeffCurrV, 
+#endif        
+                                 trWidthC, trHeightC, uiAbsSumV, TEXT_CHROMA_V, uiAbsPartIdx );
+
+      pcCU->setCbfSubParts( uiAbsSumU ? uiSetCbf : 0, TEXT_CHROMA_U, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC );
+      pcCU->setCbfSubParts( uiAbsSumV ? uiSetCbf : 0, TEXT_CHROMA_V, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC );
+    }
+    
+    m_pcEntropyCoder->resetBits();
+    
+    {
+      m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
+    }
+    
+    m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrY, uiAbsPartIdx,  trWidth,  trHeight,    uiDepth, TEXT_LUMA );
+    const UInt uiSingleBitsY = m_pcEntropyCoder->getNumberOfWrittenBits();
+    
+    UInt uiSingleBitsU = 0;
+    UInt uiSingleBitsV = 0;
+    if( bCodeChroma )
+    {
+      {
+        m_pcEntropyCoder->encodeQtCbf   ( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrMode );
+      }
+      m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrU, uiAbsPartIdx, trWidthC, trHeightC, uiDepth, TEXT_CHROMA_U );
+      uiSingleBitsU = m_pcEntropyCoder->getNumberOfWrittenBits() - uiSingleBitsY;
+      
+      {
+        m_pcEntropyCoder->encodeQtCbf   ( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrMode );
+      }
+      m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrV, uiAbsPartIdx, trWidthC, trHeightC, uiDepth, TEXT_CHROMA_V );
+      uiSingleBitsV = m_pcEntropyCoder->getNumberOfWrittenBits() - ( uiSingleBitsY + uiSingleBitsU );
+    }
+    
+    const UInt uiNumSamplesLuma = 1 << (uiLog2TrSize<<1);
+    const UInt uiNumSamplesChro = 1 << (uiLog2TrSizeC<<1);
+    
+    ::memset( m_pTempPel, 0, sizeof( Pel ) * uiNumSamplesLuma ); // not necessary needed for inside of recursion (only at the beginning)
+    
+#if IBDI_DISTORTION
+    UInt uiDistY = m_pcRdCost->getDistPart( pcPred->getLumaAddr( absTUPartIdx ), pcPred->getStride(), pcOrg->getLumaAddr( absTUPartIdx), pcOrg->getStride(), trWidth, trHeight);
+#else
+    UInt uiDistY = m_pcRdCost->getDistPart( m_pTempPel, trWidth, pcResi->getLumaAddr( absTUPartIdx ), pcResi->getStride(), trWidth, trHeight ); // initialized with zero residual destortion
+#endif
+    if ( puiZeroDist )
+    {
+      *puiZeroDist += uiDistY;
+    }
+    if( uiAbsSumY )
+    {
+      Pel *pcResiCurrY = m_pcQTTempTComYuv[ uiQTTempAccessLayer ].getLumaAddr( absTUPartIdx );
+
+      m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_LUMA, pcCU->getSlice()->getSPS()->getQpBDOffsetY(), 0 );
+
+      Int scalingListType = 3 + g_eTTable[(Int)TEXT_LUMA];
+      assert(scalingListType < 6);     
+      m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_LUMA,REG_DCT, pcResiCurrY, m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(),  pcCoeffCurrY, trWidth, trHeight, scalingListType );//this is for inter mode only
+      
+      const UInt uiNonzeroDistY = m_pcRdCost->getDistPart( m_pcQTTempTComYuv[uiQTTempAccessLayer].getLumaAddr( absTUPartIdx ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(),
+      pcResi->getLumaAddr( absTUPartIdx ), pcResi->getStride(), trWidth,trHeight );
+      if (pcCU->isLosslessCoded(0)) 
+      {
+        uiDistY = uiNonzeroDistY;
+      }
+      else
+      {
+        const Double singleCostY = m_pcRdCost->calcRdCost( uiSingleBitsY, uiNonzeroDistY );
+#if TU_ZERO_CBF_RDO
+        m_pcEntropyCoder->resetBits();
+        m_pcEntropyCoder->encodeQtCbfZero( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
+        const UInt uiNullBitsY   = m_pcEntropyCoder->getNumberOfWrittenBits();
+        const Double nullCostY   = m_pcRdCost->calcRdCost( uiNullBitsY, uiDistY );
+#else
+        const Double nullCostY   = m_pcRdCost->calcRdCost( 0, uiDistY );
+#endif
+        if( nullCostY < singleCostY )  
+        {    
+          uiAbsSumY = 0;
+          ::memset( pcCoeffCurrY, 0, sizeof( TCoeff ) * uiNumSamplesLuma );
+#if INTER_TRANSFORMSKIP
+          if( checkTransformSkipY )
+          {
+            minCostY = nullCostY;
+          }
+#endif
+        }
+        else
+        {
+          uiDistY = uiNonzeroDistY;
+#if INTER_TRANSFORMSKIP
+          if( checkTransformSkipY )
+          {
+            minCostY = singleCostY;
+          }
+#endif
+        }
+      }
+    }
+#if INTER_TRANSFORMSKIP
+    else if( checkTransformSkipY )
+    {
+#if TU_ZERO_CBF_RDO
+      m_pcEntropyCoder->resetBits();
+      m_pcEntropyCoder->encodeQtCbfZero( pcCU, uiAbsPartIdx, TEXT_LUMA, uiTrMode );
+      const UInt uiNullBitsY = m_pcEntropyCoder->getNumberOfWrittenBits();
+      minCostY = m_pcRdCost->calcRdCost( uiNullBitsY, uiDistY );
+#else
+      minCostY = m_pcRdCost->calcRdCost( 0, uiDistY );
+#endif
+    }
+#endif
+
+    if( !uiAbsSumY )
+    {
+      Pel *pcPtr =  m_pcQTTempTComYuv[uiQTTempAccessLayer].getLumaAddr( absTUPartIdx );
+      const UInt uiStride = m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride();
+      for( UInt uiY = 0; uiY < trHeight; ++uiY )
+      {
+        ::memset( pcPtr, 0, sizeof( Pel ) * trWidth );
+        pcPtr += uiStride;
+      } 
+    }
+    
+    UInt uiDistU = 0;
+    UInt uiDistV = 0;
+    if( bCodeChroma )
+    {
+#if IBDI_DISTORTION
+      uiDistU = m_pcRdCost->getDistPart( pcPred->getCbAddr( absTUPartIdxC ), pcPred->getCStride(), pcOrg->getCbAddr( absTUPartIdxC ), pcOrg->getCStride(), trWidthC, trHeightC
+#if WEIGHTED_CHROMA_DISTORTION
+                                          , true
+#endif
+                                          );
+#else
+      uiDistU = m_pcRdCost->getDistPart( m_pTempPel, trWidthC, pcResi->getCbAddr( absTUPartIdxC ), pcResi->getCStride(), trWidthC, trHeightC
+#if WEIGHTED_CHROMA_DISTORTION
+                                          , true
+#endif
+                                          ); // initialized with zero residual destortion
+#endif
+      if ( puiZeroDist )
+      {
+        *puiZeroDist += uiDistU;
+      }
+      if( uiAbsSumU )
+      {
+        Pel *pcResiCurrU = m_pcQTTempTComYuv[uiQTTempAccessLayer].getCbAddr( absTUPartIdxC );
+
+#if CHROMA_QP_EXTENSION
+        Int curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCbQpOffset() + pcCU->getSlice()->getSliceQpDeltaCb();
+        m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
+#else
+        m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), pcCU->getSlice()->getPPS()->getChromaCbQpOffset() );
+#endif
+
+        Int scalingListType = 3 + g_eTTable[(Int)TEXT_CHROMA_U];
+        assert(scalingListType < 6);
+        m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_CHROMA,REG_DCT, pcResiCurrU, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(), pcCoeffCurrU, trWidthC, trHeightC, scalingListType  );
+        
+        const UInt uiNonzeroDistU = m_pcRdCost->getDistPart( m_pcQTTempTComYuv[uiQTTempAccessLayer].getCbAddr( absTUPartIdxC), m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(),
+          pcResi->getCbAddr( absTUPartIdxC), pcResi->getCStride(), trWidthC, trHeightC
+#if WEIGHTED_CHROMA_DISTORTION
+          , true
+#endif
+          );
+
+        if(pcCU->isLosslessCoded(0))  
+        {
+          uiDistU = uiNonzeroDistU;
+        }
+        else
+        {
+          const Double dSingleCostU = m_pcRdCost->calcRdCost( uiSingleBitsU, uiNonzeroDistU );
+#if TU_ZERO_CBF_RDO
+          m_pcEntropyCoder->resetBits();
+          m_pcEntropyCoder->encodeQtCbfZero( pcCU, uiAbsPartIdx, TEXT_CHROMA_U,     uiTrMode );
+          const UInt uiNullBitsU    = m_pcEntropyCoder->getNumberOfWrittenBits();
+          const Double dNullCostU   = m_pcRdCost->calcRdCost( uiNullBitsU, uiDistU );
+#else
+          const Double dNullCostU   = m_pcRdCost->calcRdCost( 0, uiDistU );
+#endif
+          if( dNullCostU < dSingleCostU )
+          {
+            uiAbsSumU = 0;
+            ::memset( pcCoeffCurrU, 0, sizeof( TCoeff ) * uiNumSamplesChro );
+#if INTER_TRANSFORMSKIP
+            if( checkTransformSkipUV )
+            {
+              minCostU = dNullCostU;
+            }
+#endif
+          }
+          else
+          {
+            uiDistU = uiNonzeroDistU;
+#if INTER_TRANSFORMSKIP
+            if( checkTransformSkipUV )
+            {
+              minCostU = dSingleCostU;
+            }
+#endif
+          }
+        }
+      }
+#if INTER_TRANSFORMSKIP
+      else if( checkTransformSkipUV )
+      {
+#if TU_ZERO_CBF_RDO
+        m_pcEntropyCoder->resetBits();
+        m_pcEntropyCoder->encodeQtCbfZero( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrModeC );
+        const UInt uiNullBitsU = m_pcEntropyCoder->getNumberOfWrittenBits();
+        minCostU = m_pcRdCost->calcRdCost( uiNullBitsU, uiDistU );
+#else
+        minCostU = m_pcRdCost->calcRdCost( 0, uiDistU );
+#endif
+      }
+#endif
+      if( !uiAbsSumU )
+      {
+        Pel *pcPtr =  m_pcQTTempTComYuv[uiQTTempAccessLayer].getCbAddr( absTUPartIdxC );
+          const UInt uiStride = m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride();
+        for( UInt uiY = 0; uiY < trHeightC; ++uiY )
+        {
+          ::memset( pcPtr, 0, sizeof(Pel) * trWidthC );
+          pcPtr += uiStride;
+        }
+      }
+      
+#if IBDI_DISTORTION
+      uiDistV = m_pcRdCost->getDistPart( pcPred->getCrAddr( absTUPartIdxC ), pcPred->getCStride(), pcOrg->getCrAddr( absTUPartIdxC ), pcOrg->getCStride(), trWidthC, trHeightC
+#if WEIGHTED_CHROMA_DISTORTION
+                                          , true
+#endif
+                                          );
+#else
+      uiDistV = m_pcRdCost->getDistPart( m_pTempPel, trWidthC, pcResi->getCrAddr( absTUPartIdxC), pcResi->getCStride(), trWidthC, trHeightC
+#if WEIGHTED_CHROMA_DISTORTION
+                                          , true
+#endif
+                                          ); // initialized with zero residual destortion
+#endif
+      if ( puiZeroDist )
+      {
+        *puiZeroDist += uiDistV;
+      }
+      if( uiAbsSumV )
+      {
+        Pel *pcResiCurrV = m_pcQTTempTComYuv[uiQTTempAccessLayer].getCrAddr( absTUPartIdxC );
+        if( !uiAbsSumU )
+        {
+#if CHROMA_QP_EXTENSION
+          Int curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCrQpOffset() + pcCU->getSlice()->getSliceQpDeltaCr();
+          m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
+#else
+          m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), pcCU->getSlice()->getPPS()->getChromaCrQpOffset() );
+#endif
+        }
+        Int scalingListType = 3 + g_eTTable[(Int)TEXT_CHROMA_V];
+        assert(scalingListType < 6);
+        m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_CHROMA,REG_DCT, pcResiCurrV, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(), pcCoeffCurrV, trWidthC, trHeightC, scalingListType );
+        
+        const UInt uiNonzeroDistV = m_pcRdCost->getDistPart( m_pcQTTempTComYuv[uiQTTempAccessLayer].getCrAddr( absTUPartIdxC ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(),
+          pcResi->getCrAddr( absTUPartIdxC ), pcResi->getCStride(), trWidthC, trHeightC
+#if WEIGHTED_CHROMA_DISTORTION
+                                                   , true
+#endif
+                                                   );
+        if (pcCU->isLosslessCoded(0)) 
+        {
+          uiDistV = uiNonzeroDistV;
+        }
+        else
+        {
+          const Double dSingleCostV = m_pcRdCost->calcRdCost( uiSingleBitsV, uiNonzeroDistV );
+#if TU_ZERO_CBF_RDO
+          m_pcEntropyCoder->resetBits();
+          m_pcEntropyCoder->encodeQtCbfZero( pcCU, uiAbsPartIdx, TEXT_CHROMA_V,     uiTrMode );
+          const UInt uiNullBitsV    = m_pcEntropyCoder->getNumberOfWrittenBits();
+          const Double dNullCostV   = m_pcRdCost->calcRdCost( uiNullBitsV, uiDistV );
+#else
+          const Double dNullCostV   = m_pcRdCost->calcRdCost( 0, uiDistV );
+#endif
+          if( dNullCostV < dSingleCostV )
+          {
+            uiAbsSumV = 0;
+            ::memset( pcCoeffCurrV, 0, sizeof( TCoeff ) * uiNumSamplesChro );
+#if INTER_TRANSFORMSKIP
+            if( checkTransformSkipUV )
+            {
+              minCostV = dNullCostV;
+            }
+#endif
+          }
+          else
+          {
+            uiDistV = uiNonzeroDistV;
+#if INTER_TRANSFORMSKIP
+            if( checkTransformSkipUV )
+            {
+              minCostV = dSingleCostV;
+            }
+#endif
+          }
+        }
+      }
+#if INTER_TRANSFORMSKIP
+      else if( checkTransformSkipUV )
+      {
+#if TU_ZERO_CBF_RDO
+        m_pcEntropyCoder->resetBits();
+        m_pcEntropyCoder->encodeQtCbfZero( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrModeC );
+        const UInt uiNullBitsV = m_pcEntropyCoder->getNumberOfWrittenBits();
+        minCostV = m_pcRdCost->calcRdCost( uiNullBitsV, uiDistV );
+#else
+        minCostV = m_pcRdCost->calcRdCost( 0, uiDistV );
+#endif
+      }
+#endif
+      if( !uiAbsSumV )
+      {
+        Pel *pcPtr =  m_pcQTTempTComYuv[uiQTTempAccessLayer].getCrAddr( absTUPartIdxC );
+        const UInt uiStride = m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride();
+        for( UInt uiY = 0; uiY < trHeightC; ++uiY )
+        {   
+          ::memset( pcPtr, 0, sizeof(Pel) * trWidthC );
+          pcPtr += uiStride;
+        }
+      }
+    }
+    pcCU->setCbfSubParts( uiAbsSumY ? uiSetCbf : 0, TEXT_LUMA, uiAbsPartIdx, uiDepth );
+    if( bCodeChroma )
+    {
+      pcCU->setCbfSubParts( uiAbsSumU ? uiSetCbf : 0, TEXT_CHROMA_U, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC );
+      pcCU->setCbfSubParts( uiAbsSumV ? uiSetCbf : 0, TEXT_CHROMA_V, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC );
+    }
+
+#if INTER_TRANSFORMSKIP
+    if( checkTransformSkipY )
+    {
+      UInt uiNonzeroDistY, uiAbsSumTransformSkipY;
+      Double dSingleCostY;
+
+      Pel *pcResiCurrY = m_pcQTTempTComYuv[ uiQTTempAccessLayer ].getLumaAddr( absTUPartIdx );
+      UInt resiYStride = m_pcQTTempTComYuv[ uiQTTempAccessLayer ].getStride();
+
+      TCoeff bestCoeffY[32*32];
+      memcpy( bestCoeffY, pcCoeffCurrY, sizeof(TCoeff) * uiNumSamplesLuma );
+      
+#if ADAPTIVE_QP_SELECTION
+      TCoeff bestArlCoeffY[32*32];
+      memcpy( bestArlCoeffY, pcArlCoeffCurrY, sizeof(TCoeff) * uiNumSamplesLuma );
+#endif
+
+      Pel bestResiY[32*32];
+      for ( Int i = 0; i < trHeight; ++i )
+      {
+        memcpy( &bestResiY[i*trWidth], pcResiCurrY+i*resiYStride, sizeof(Pel) * trWidth );
+      }
+
+      if( m_bUseSBACRD )
+      {
+        m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
+      }
+
+      pcCU->setTransformSkipSubParts ( 1, TEXT_LUMA, uiAbsPartIdx, uiDepth );
+
+      if (m_pcEncCfg->getUseRDOQ())
+      {
+        m_pcEntropyCoder->estimateBit( m_pcTrQuant->m_pcEstBitsSbac, trWidth, trHeight, TEXT_LUMA );        
+      }
+
+      m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_LUMA, pcCU->getSlice()->getSPS()->getQpBDOffsetY(), 0 );
+
+#if RDOQ_CHROMA_LAMBDA 
+      m_pcTrQuant->selectLambda(TEXT_LUMA);
+#endif
+      m_pcTrQuant->transformNxN( pcCU, pcResi->getLumaAddr( absTUPartIdx ), pcResi->getStride (), pcCoeffCurrY, 
+#if ADAPTIVE_QP_SELECTION
+        pcArlCoeffCurrY, 
+#endif      
+        trWidth,   trHeight,    uiAbsSumTransformSkipY, TEXT_LUMA, uiAbsPartIdx, true );
+      pcCU->setCbfSubParts( uiAbsSumTransformSkipY ? uiSetCbf : 0, TEXT_LUMA, uiAbsPartIdx, uiDepth );
+
+      if( uiAbsSumTransformSkipY != 0 )
+      {
+        m_pcEntropyCoder->resetBits();
+        m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA, uiTrMode );
+        m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrY, uiAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_LUMA );
+        const UInt uiTsSingleBitsY = m_pcEntropyCoder->getNumberOfWrittenBits();
+
+        m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_LUMA, pcCU->getSlice()->getSPS()->getQpBDOffsetY(), 0 );
+
+        Int scalingListType = 3 + g_eTTable[(Int)TEXT_LUMA];
+        assert(scalingListType < 6);     
+
+        m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_LUMA,REG_DCT, pcResiCurrY, m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(),  pcCoeffCurrY, trWidth, trHeight, scalingListType, true );
+
+        uiNonzeroDistY = m_pcRdCost->getDistPart( m_pcQTTempTComYuv[uiQTTempAccessLayer].getLumaAddr( absTUPartIdx ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(),
+          pcResi->getLumaAddr( absTUPartIdx ), pcResi->getStride(), trWidth, trHeight );
+
+        dSingleCostY = m_pcRdCost->calcRdCost( uiTsSingleBitsY, uiNonzeroDistY );
+      }
+
+      if( !uiAbsSumTransformSkipY || minCostY < dSingleCostY )
+      {
+        pcCU->setTransformSkipSubParts ( 0, TEXT_LUMA, uiAbsPartIdx, uiDepth );
+        memcpy( pcCoeffCurrY, bestCoeffY, sizeof(TCoeff) * uiNumSamplesLuma );
+#if ADAPTIVE_QP_SELECTION
+        memcpy( pcArlCoeffCurrY, bestArlCoeffY, sizeof(TCoeff) * uiNumSamplesLuma );
+#endif
+        for( Int i = 0; i < trHeight; ++i )
+        {
+          memcpy( pcResiCurrY+i*resiYStride, &bestResiY[i*trWidth], sizeof(Pel) * trWidth );
+        }
+      }
+      else
+      {
+        uiDistY = uiNonzeroDistY;
+        uiAbsSumY = uiAbsSumTransformSkipY;
+        uiBestTransformMode[0] = 1;
+      }
+
+      pcCU->setCbfSubParts( uiAbsSumY ? uiSetCbf : 0, TEXT_LUMA, uiAbsPartIdx, uiDepth );
+    }
+
+    if( bCodeChroma && checkTransformSkipUV  )
+    {
+      UInt uiNonzeroDistU, uiNonzeroDistV, uiAbsSumTransformSkipU, uiAbsSumTransformSkipV;
+      Double dSingleCostU, dSingleCostV;
+
+      Pel *pcResiCurrU = m_pcQTTempTComYuv[uiQTTempAccessLayer].getCbAddr( absTUPartIdxC );
+      Pel *pcResiCurrV = m_pcQTTempTComYuv[uiQTTempAccessLayer].getCrAddr( absTUPartIdxC );
+      UInt resiCStride = m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride();
+
+      TCoeff bestCoeffU[32*32], bestCoeffV[32*32];
+      memcpy( bestCoeffU, pcCoeffCurrU, sizeof(TCoeff) * uiNumSamplesChro );
+      memcpy( bestCoeffV, pcCoeffCurrV, sizeof(TCoeff) * uiNumSamplesChro );
+
+#if ADAPTIVE_QP_SELECTION
+      TCoeff bestArlCoeffU[32*32], bestArlCoeffV[32*32];
+      memcpy( bestArlCoeffU, pcArlCoeffCurrU, sizeof(TCoeff) * uiNumSamplesChro );
+      memcpy( bestArlCoeffV, pcArlCoeffCurrV, sizeof(TCoeff) * uiNumSamplesChro );
+#endif
+
+      Pel bestResiU[32*32], bestResiV[32*32];
+      for (Int i = 0; i < trHeightC; ++i )
+      {
+        memcpy( &bestResiU[i*trWidthC], pcResiCurrU+i*resiCStride, sizeof(Pel) * trWidthC );
+        memcpy( &bestResiV[i*trWidthC], pcResiCurrV+i*resiCStride, sizeof(Pel) * trWidthC );
+      }
+
+      if( m_bUseSBACRD )
+      {
+        m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
+      }
+
+      pcCU->setTransformSkipSubParts ( 1, TEXT_CHROMA_U, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC ); 
+      pcCU->setTransformSkipSubParts ( 1, TEXT_CHROMA_V, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC );
+
+      if (m_pcEncCfg->getUseRDOQ())
+      {
+        m_pcEntropyCoder->estimateBit(m_pcTrQuant->m_pcEstBitsSbac, trWidthC, trHeightC, TEXT_CHROMA );          
+      }
+
+#if CHROMA_QP_EXTENSION
+      Int curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCbQpOffset() + pcCU->getSlice()->getSliceQpDeltaCb();
+      m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
+#else
+      m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), pcCU->getSlice()->getPPS()->getChromaCbQpOffset() );
+#endif
+
+#if RDOQ_CHROMA_LAMBDA 
+      m_pcTrQuant->selectLambda(TEXT_CHROMA); 
+#endif
+
+      m_pcTrQuant->transformNxN( pcCU, pcResi->getCbAddr(absTUPartIdxC), pcResi->getCStride(), pcCoeffCurrU, 
+#if ADAPTIVE_QP_SELECTION
+        pcArlCoeffCurrU, 
+#endif        
+        trWidthC, trHeightC, uiAbsSumTransformSkipU, TEXT_CHROMA_U, uiAbsPartIdx, true );
+#if CHROMA_QP_EXTENSION
+      curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCrQpOffset() + pcCU->getSlice()->getSliceQpDeltaCr();
+      m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
+#else
+      m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), pcCU->getSlice()->getPPS()->getChromaCrQpOffset() );
+#endif
+      m_pcTrQuant->transformNxN( pcCU, pcResi->getCrAddr(absTUPartIdxC), pcResi->getCStride(), pcCoeffCurrV, 
+#if ADAPTIVE_QP_SELECTION
+        pcArlCoeffCurrV, 
+#endif        
+        trWidthC, trHeightC, uiAbsSumTransformSkipV, TEXT_CHROMA_V, uiAbsPartIdx, true );
+
+      pcCU->setCbfSubParts( uiAbsSumTransformSkipU ? uiSetCbf : 0, TEXT_CHROMA_U, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC );
+      pcCU->setCbfSubParts( uiAbsSumTransformSkipV ? uiSetCbf : 0, TEXT_CHROMA_V, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC );
+
+      m_pcEntropyCoder->resetBits();
+      uiSingleBitsU = 0;
+      uiSingleBitsV = 0;
+
+      if( uiAbsSumTransformSkipU )
+      {
+        m_pcEntropyCoder->encodeQtCbf   ( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrMode );
+        m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrU, uiAbsPartIdx, trWidthC, trHeightC, uiDepth, TEXT_CHROMA_U );
+        uiSingleBitsU = m_pcEntropyCoder->getNumberOfWrittenBits();    
+
+#if CHROMA_QP_EXTENSION
+        curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCbQpOffset() + pcCU->getSlice()->getSliceQpDeltaCb();
+        m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
+#else
+        m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), pcCU->getSlice()->getPPS()->getChromaCbQpOffset() );
+#endif
+
+        Int scalingListType = 3 + g_eTTable[(Int)TEXT_CHROMA_U];
+        assert(scalingListType < 6);
+
+        m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_CHROMA,REG_DCT, pcResiCurrU, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(), pcCoeffCurrU, trWidthC, trHeightC, scalingListType, true  );
+
+        uiNonzeroDistU = m_pcRdCost->getDistPart( m_pcQTTempTComYuv[uiQTTempAccessLayer].getCbAddr( absTUPartIdxC), m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(),
+          pcResi->getCbAddr( absTUPartIdxC), pcResi->getCStride(), trWidthC, trHeightC
+#if WEIGHTED_CHROMA_DISTORTION
+          , true
+#endif
+          );
+
+        dSingleCostU = m_pcRdCost->calcRdCost( uiSingleBitsU, uiNonzeroDistU );
+      }
+
+      if( !uiAbsSumTransformSkipU || minCostU < dSingleCostU )
+      {
+        pcCU->setTransformSkipSubParts ( 0, TEXT_CHROMA_U, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC ); 
+
+        memcpy( pcCoeffCurrU, bestCoeffU, sizeof (TCoeff) * uiNumSamplesChro );
+#if ADAPTIVE_QP_SELECTION
+        memcpy( pcArlCoeffCurrU, bestArlCoeffU, sizeof (TCoeff) * uiNumSamplesChro );
+#endif
+        for( Int i = 0; i < trHeightC; ++i )
+        {
+          memcpy( pcResiCurrU+i*resiCStride, &bestResiU[i*trWidthC], sizeof(Pel) * trWidthC );
+        }
+      }
+      else
+      {
+        uiDistU = uiNonzeroDistU;
+        uiAbsSumU = uiAbsSumTransformSkipU;
+        uiBestTransformMode[1] = 1;
+      }
+
+      if( uiAbsSumTransformSkipV )
+      {
+        m_pcEntropyCoder->encodeQtCbf   ( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrMode );
+        m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrV, uiAbsPartIdx, trWidthC, trHeightC, uiDepth, TEXT_CHROMA_V );
+        uiSingleBitsV = m_pcEntropyCoder->getNumberOfWrittenBits() - uiSingleBitsU;
+
+#if CHROMA_QP_EXTENSION
+        curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCrQpOffset() + pcCU->getSlice()->getSliceQpDeltaCr();
+        m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
+#else
+        m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), pcCU->getSlice()->getPPS()->getChromaCrQpOffset() );
+#endif
+
+        Int scalingListType = 3 + g_eTTable[(Int)TEXT_CHROMA_V];
+        assert(scalingListType < 6);
+
+        m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_CHROMA,REG_DCT, pcResiCurrV, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(), pcCoeffCurrV, trWidthC, trHeightC, scalingListType, true );
+
+        uiNonzeroDistV = m_pcRdCost->getDistPart( m_pcQTTempTComYuv[uiQTTempAccessLayer].getCrAddr( absTUPartIdxC ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(),
+          pcResi->getCrAddr( absTUPartIdxC ), pcResi->getCStride(), trWidthC, trHeightC
+#if WEIGHTED_CHROMA_DISTORTION
+          , true
+#endif
+          );
+
+        dSingleCostV = m_pcRdCost->calcRdCost( uiSingleBitsV, uiNonzeroDistV );
+      }
+
+      if( !uiAbsSumTransformSkipV || minCostV < dSingleCostV )
+      {
+        pcCU->setTransformSkipSubParts ( 0, TEXT_CHROMA_V, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC ); 
+
+        memcpy( pcCoeffCurrV, bestCoeffV, sizeof(TCoeff) * uiNumSamplesChro );
+#if ADAPTIVE_QP_SELECTION
+        memcpy( pcArlCoeffCurrV, bestArlCoeffV, sizeof(TCoeff) * uiNumSamplesChro );
+#endif
+        for( Int i = 0; i < trHeightC; ++i )
+        {
+          memcpy( pcResiCurrV+i*resiCStride, &bestResiV[i*trWidthC], sizeof(Pel) * trWidthC );
+        }
+      }
+      else
+      {
+        uiDistV = uiNonzeroDistV;
+        uiAbsSumV = uiAbsSumTransformSkipV;
+        uiBestTransformMode[2] = 1;
+      }
+
+      pcCU->setCbfSubParts( uiAbsSumU ? uiSetCbf : 0, TEXT_CHROMA_U, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC );
+      pcCU->setCbfSubParts( uiAbsSumV ? uiSetCbf : 0, TEXT_CHROMA_V, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC );
+    }
+#endif
+
+    if( m_bUseSBACRD )
+    {
+      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
+    }
+
+    m_pcEntropyCoder->resetBits();
+
+    {
+      if( uiLog2TrSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
+      {
+#if TRANS_SPLIT_FLAG_CTX_REDUCTION
+        m_pcEntropyCoder->encodeTransformSubdivFlag( 0, 5 - uiLog2TrSize );
+#else
+        m_pcEntropyCoder->encodeTransformSubdivFlag( 0, uiDepth );
+#endif
+      }
+    }
+
+    {
+      if( bCodeChroma )
+      {
+        m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrMode );
+        m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrMode );
+      }
+
+      m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
+    }
+
+    m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrY, uiAbsPartIdx, trWidth, trHeight,    uiDepth, TEXT_LUMA );
+
+    if( bCodeChroma )
+    {
+      m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrU, uiAbsPartIdx, trWidthC, trHeightC, uiDepth, TEXT_CHROMA_U );
+      m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrV, uiAbsPartIdx, trWidthC, trHeightC, uiDepth, TEXT_CHROMA_V );
+    }
+
+    uiSingleBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+
+    uiSingleDist = uiDistY + uiDistU + uiDistV;
+    dSingleCost = m_pcRdCost->calcRdCost( uiSingleBits, uiSingleDist );
+  }  
+  
+  // code sub-blocks
+  if( bCheckSplit )
+  {
+    if( m_bUseSBACRD && bCheckFull )
+    {
+      m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_TEST ] );
+      m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
+    }
+    UInt uiSubdivDist = 0;
+    UInt uiSubdivBits = 0;
+    Double dSubdivCost = 0.0;
+    
+    const UInt uiQPartNumSubdiv = pcCU->getPic()->getNumPartInCU() >> ((uiDepth + 1 ) << 1);
+    for( UInt ui = 0; ui < 4; ++ui )
+    {
+#if REMOVE_NSQT
+      UInt nsAddr = uiAbsPartIdx + ui * uiQPartNumSubdiv;
+#else
+      UInt nsAddr = 0;
+      nsAddr = pcCU->getNSAbsPartIdx( uiLog2TrSize - 1, uiAbsPartIdx + ui * uiQPartNumSubdiv, absTUPartIdx, ui, uiTrMode + 1 );
+#endif
+#if IBDI_DISTORTION
+      xEstimateResidualQT( pcCU, ui, uiAbsPartIdx + ui * uiQPartNumSubdiv, nsAddr, pcOrg, pcPred, pcResi, uiDepth + 1, dSubdivCost, uiSubdivBits, uiSubdivDist, bCheckFull ? NULL : puiZeroDist );
+#else
+      xEstimateResidualQT( pcCU, ui, uiAbsPartIdx + ui * uiQPartNumSubdiv, nsAddr, pcResi, uiDepth + 1, dSubdivCost, uiSubdivBits, uiSubdivDist, bCheckFull ? NULL : puiZeroDist );
+#endif
+    }
+    
+    UInt uiYCbf = 0;
+    UInt uiUCbf = 0;
+    UInt uiVCbf = 0;
+    for( UInt ui = 0; ui < 4; ++ui )
+    {
+      uiYCbf |= pcCU->getCbf( uiAbsPartIdx + ui * uiQPartNumSubdiv, TEXT_LUMA,     uiTrMode + 1 );
+      uiUCbf |= pcCU->getCbf( uiAbsPartIdx + ui * uiQPartNumSubdiv, TEXT_CHROMA_U, uiTrMode + 1 );
+      uiVCbf |= pcCU->getCbf( uiAbsPartIdx + ui * uiQPartNumSubdiv, TEXT_CHROMA_V, uiTrMode + 1 );
+    }
+    for( UInt ui = 0; ui < 4 * uiQPartNumSubdiv; ++ui )
+    {
+      pcCU->getCbf( TEXT_LUMA     )[uiAbsPartIdx + ui] |= uiYCbf << uiTrMode;
+      pcCU->getCbf( TEXT_CHROMA_U )[uiAbsPartIdx + ui] |= uiUCbf << uiTrMode;
+      pcCU->getCbf( TEXT_CHROMA_V )[uiAbsPartIdx + ui] |= uiVCbf << uiTrMode;
+    }
+    
+    if( m_bUseSBACRD )
+    {
+      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
+    }
+    m_pcEntropyCoder->resetBits();
+    
+    {
+      xEncodeResidualQT( pcCU, uiAbsPartIdx, uiDepth, true,  TEXT_LUMA );
+      xEncodeResidualQT( pcCU, uiAbsPartIdx, uiDepth, false, TEXT_LUMA );
+      xEncodeResidualQT( pcCU, uiAbsPartIdx, uiDepth, false, TEXT_CHROMA_U );
+      xEncodeResidualQT( pcCU, uiAbsPartIdx, uiDepth, false, TEXT_CHROMA_V );
+    }
+    
+    uiSubdivBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+    dSubdivCost  = m_pcRdCost->calcRdCost( uiSubdivBits, uiSubdivDist );
+    
+    if( uiYCbf || uiUCbf || uiVCbf || !bCheckFull )
+    {
+      if( dSubdivCost < dSingleCost )
+      {
+        rdCost += dSubdivCost;
+        ruiBits += uiSubdivBits;
+        ruiDist += uiSubdivDist;
+        return;
+      }
+    }
+#if INTER_TRANSFORMSKIP
+    pcCU->setTransformSkipSubParts ( uiBestTransformMode[0], TEXT_LUMA, uiAbsPartIdx, uiDepth ); 
+    if(bCodeChroma)
+    {
+      pcCU->setTransformSkipSubParts ( uiBestTransformMode[1], TEXT_CHROMA_U, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC ); 
+      pcCU->setTransformSkipSubParts ( uiBestTransformMode[2], TEXT_CHROMA_V, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC ); 
+    }
+#endif
+    assert( bCheckFull );
+    if( m_bUseSBACRD )
+    {
+      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_TEST ] );
+    }
+  }
+  rdCost += dSingleCost;
+  ruiBits += uiSingleBits;
+  ruiDist += uiSingleDist;
+  
+  pcCU->setTrIdxSubParts( uiTrMode, uiAbsPartIdx, uiDepth );
+  
+  pcCU->setCbfSubParts( uiAbsSumY ? uiSetCbf : 0, TEXT_LUMA, uiAbsPartIdx, uiDepth );
+  if( bCodeChroma )
+  {
+    pcCU->setCbfSubParts( uiAbsSumU ? uiSetCbf : 0, TEXT_CHROMA_U, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC );
+    pcCU->setCbfSubParts( uiAbsSumV ? uiSetCbf : 0, TEXT_CHROMA_V, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC );
+  }
+}
+
+Void TEncSearch::xEncodeResidualQT( TComDataCU* pcCU, UInt uiAbsPartIdx, const UInt uiDepth, Bool bSubdivAndCbf, TextType eType )
+{
+  assert( pcCU->getDepth( 0 ) == pcCU->getDepth( uiAbsPartIdx ) );
+  const UInt uiCurrTrMode = uiDepth - pcCU->getDepth( 0 );
+  const UInt uiTrMode = pcCU->getTransformIdx( uiAbsPartIdx );
+  
+  const Bool bSubdiv = uiCurrTrMode != uiTrMode;
+  
+  const UInt uiLog2TrSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiDepth]+2;
+
+  {
+    if( bSubdivAndCbf && uiLog2TrSize <= pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() && uiLog2TrSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
+    {
+#if TRANS_SPLIT_FLAG_CTX_REDUCTION
+      m_pcEntropyCoder->encodeTransformSubdivFlag( bSubdiv, 5 - uiLog2TrSize );
+#else
+      m_pcEntropyCoder->encodeTransformSubdivFlag( bSubdiv, uiDepth );
+#endif
+    }
+  }
+
+  {
+#if INTRA_BL
+    assert( !pcCU->isIntra(uiAbsPartIdx) );
+#else
+    assert( pcCU->getPredictionMode(uiAbsPartIdx) != MODE_INTRA );
+#endif
+    if( bSubdivAndCbf )
+    {
+      const Bool bFirstCbfOfCU = uiCurrTrMode == 0;
+      if( bFirstCbfOfCU || uiLog2TrSize > 2 )
+      {
+        if( bFirstCbfOfCU || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiCurrTrMode - 1 ) )
+        {
+          m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiCurrTrMode );
+        }
+        if( bFirstCbfOfCU || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiCurrTrMode - 1 ) )
+        {
+          m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiCurrTrMode );
+        }
+      }
+      else if( uiLog2TrSize == 2 )
+      {
+        assert( pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiCurrTrMode ) == pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiCurrTrMode - 1 ) );
+        assert( pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiCurrTrMode ) == pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiCurrTrMode - 1 ) );
+      }
+    }
+  }
+  
+  if( !bSubdiv )
+  {
+    const UInt uiNumCoeffPerAbsPartIdxIncrement = pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() >> ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 );
+    //assert( 16 == uiNumCoeffPerAbsPartIdxIncrement ); // check
+    const UInt uiQTTempAccessLayer = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+    TCoeff *pcCoeffCurrY = m_ppcQTTempCoeffY [uiQTTempAccessLayer] +  uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx;
+    TCoeff *pcCoeffCurrU = m_ppcQTTempCoeffCb[uiQTTempAccessLayer] + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
+    TCoeff *pcCoeffCurrV = m_ppcQTTempCoeffCr[uiQTTempAccessLayer] + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
+    
+    Bool  bCodeChroma   = true;
+    UInt  uiTrModeC     = uiTrMode;
+    UInt  uiLog2TrSizeC = uiLog2TrSize-1;
+    if( uiLog2TrSize == 2 )
+    {
+      uiLog2TrSizeC++;
+      uiTrModeC    --;
+      UInt  uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrModeC ) << 1 );
+      bCodeChroma   = ( ( uiAbsPartIdx % uiQPDiv ) == 0 );
+    }
+    
+    if( bSubdivAndCbf )
+    {
+      {
+        m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
+      }
+    }
+    else
+    {
+      if( eType == TEXT_LUMA     && pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA,     uiTrMode ) )
+      {
+        Int trWidth  = 1 << uiLog2TrSize;
+        Int trHeight = 1 << uiLog2TrSize;
+#if !REMOVE_NSQT
+        pcCU->getNSQTSize( uiTrMode, uiAbsPartIdx, trWidth, trHeight );
+#endif
+        m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrY, uiAbsPartIdx, trWidth, trHeight,    uiDepth, TEXT_LUMA );
+      }
+      if( bCodeChroma )
+      {
+        Int trWidth  = 1 << uiLog2TrSizeC;
+        Int trHeight = 1 << uiLog2TrSizeC;
+#if !REMOVE_NSQT
+        pcCU->getNSQTSize( uiTrMode, uiAbsPartIdx, trWidth, trHeight );
+#endif
+        if( eType == TEXT_CHROMA_U && pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrMode ) )
+        {
+          m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrU, uiAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_CHROMA_U );
+        }
+        if( eType == TEXT_CHROMA_V && pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrMode ) )
+        {
+          m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrV, uiAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_CHROMA_V );
+        }
+      }
+    }
+  }
+  else
+  {
+    if( bSubdivAndCbf || pcCU->getCbf( uiAbsPartIdx, eType, uiCurrTrMode ) )
+    {
+      const UInt uiQPartNumSubdiv = pcCU->getPic()->getNumPartInCU() >> ((uiDepth + 1 ) << 1);
+      for( UInt ui = 0; ui < 4; ++ui )
+      {
+        xEncodeResidualQT( pcCU, uiAbsPartIdx + ui * uiQPartNumSubdiv, uiDepth + 1, bSubdivAndCbf, eType );
+      }
+    }
+  }
+}
+
+Void TEncSearch::xSetResidualQTData( TComDataCU* pcCU, UInt uiQuadrant, UInt uiAbsPartIdx, UInt absTUPartIdx, TComYuv* pcResi, UInt uiDepth, Bool bSpatial )
+{
+  assert( pcCU->getDepth( 0 ) == pcCU->getDepth( uiAbsPartIdx ) );
+  const UInt uiCurrTrMode = uiDepth - pcCU->getDepth( 0 );
+  const UInt uiTrMode = pcCU->getTransformIdx( uiAbsPartIdx );
+
+  if( uiCurrTrMode == uiTrMode )
+  {
+    const UInt uiLog2TrSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiDepth]+2;
+    const UInt uiQTTempAccessLayer = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+
+    Bool  bCodeChroma   = true;
+    UInt  uiTrModeC     = uiTrMode;
+    UInt  uiLog2TrSizeC = uiLog2TrSize-1;
+    if( uiLog2TrSize == 2 )
+    {
+      uiLog2TrSizeC++;
+      uiTrModeC    --;
+      UInt  uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrModeC ) << 1 );
+      bCodeChroma   = ( ( uiAbsPartIdx % uiQPDiv ) == 0 );
+    }
+
+    if( bSpatial )
+    {      
+      Int trWidth  = 1 << uiLog2TrSize;
+      Int trHeight = 1 << uiLog2TrSize;
+#if !REMOVE_NSQT
+      pcCU->getNSQTSize( uiTrMode, uiAbsPartIdx, trWidth, trHeight );
+#endif
+      m_pcQTTempTComYuv[uiQTTempAccessLayer].copyPartToPartLuma    ( pcResi, absTUPartIdx, trWidth , trHeight );
+
+      if( bCodeChroma )
+      {
+#if !REMOVE_NSQT
+        Int trWidthC  = 1 << uiLog2TrSizeC;
+        Int trHeightC = 1 << uiLog2TrSizeC;
+        UInt absTUPartIdxC = absTUPartIdx;
+        pcCU->getNSQTSize( uiTrModeC, uiAbsPartIdx, trWidthC, trHeightC );
+
+        if( pcCU->useNonSquareTrans( uiTrModeC, uiAbsPartIdx ) && !( uiLog2TrSizeC  == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() && uiTrModeC == 1 ) )
+        {          
+          absTUPartIdxC = pcCU->getNSAddrChroma( uiLog2TrSizeC, uiTrModeC, uiQuadrant, absTUPartIdx );
+          m_pcQTTempTComYuv[uiQTTempAccessLayer].copyPartToPartChroma( pcResi, absTUPartIdxC, trWidthC, trHeightC );
+        }
+        else
+#endif
+        {
+          m_pcQTTempTComYuv[uiQTTempAccessLayer].copyPartToPartChroma( pcResi, uiAbsPartIdx, 1 << uiLog2TrSizeC, 1 << uiLog2TrSizeC );
+        }
+      }
+    }
+    else
+    {
+      UInt    uiNumCoeffPerAbsPartIdxIncrement = pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() >> ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 );
+      UInt    uiNumCoeffY = ( 1 << ( uiLog2TrSize << 1 ) );
+      TCoeff* pcCoeffSrcY = m_ppcQTTempCoeffY [uiQTTempAccessLayer] +  uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx;
+      TCoeff* pcCoeffDstY = pcCU->getCoeffY() + uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx;
+      ::memcpy( pcCoeffDstY, pcCoeffSrcY, sizeof( TCoeff ) * uiNumCoeffY );
+#if ADAPTIVE_QP_SELECTION
+      Int* pcArlCoeffSrcY = m_ppcQTTempArlCoeffY [uiQTTempAccessLayer] +  uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx;
+      Int* pcArlCoeffDstY = pcCU->getArlCoeffY() + uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx;
+      ::memcpy( pcArlCoeffDstY, pcArlCoeffSrcY, sizeof( Int ) * uiNumCoeffY );
+#endif
+      if( bCodeChroma )
+      {
+        UInt    uiNumCoeffC = ( 1 << ( uiLog2TrSizeC << 1 ) );
+        TCoeff* pcCoeffSrcU = m_ppcQTTempCoeffCb[uiQTTempAccessLayer] + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
+        TCoeff* pcCoeffSrcV = m_ppcQTTempCoeffCr[uiQTTempAccessLayer] + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
+        TCoeff* pcCoeffDstU = pcCU->getCoeffCb() + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
+        TCoeff* pcCoeffDstV = pcCU->getCoeffCr() + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
+        ::memcpy( pcCoeffDstU, pcCoeffSrcU, sizeof( TCoeff ) * uiNumCoeffC );
+        ::memcpy( pcCoeffDstV, pcCoeffSrcV, sizeof( TCoeff ) * uiNumCoeffC );
+#if ADAPTIVE_QP_SELECTION
+        Int* pcArlCoeffSrcU = m_ppcQTTempArlCoeffCb[uiQTTempAccessLayer] + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
+        Int* pcArlCoeffSrcV = m_ppcQTTempArlCoeffCr[uiQTTempAccessLayer] + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
+        Int* pcArlCoeffDstU = pcCU->getArlCoeffCb() + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
+        Int* pcArlCoeffDstV = pcCU->getArlCoeffCr() + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
+        ::memcpy( pcArlCoeffDstU, pcArlCoeffSrcU, sizeof( Int ) * uiNumCoeffC );
+        ::memcpy( pcArlCoeffDstV, pcArlCoeffSrcV, sizeof( Int ) * uiNumCoeffC );
+#endif
+      }
+    }
+  }
+  else
+  {
+    const UInt uiQPartNumSubdiv = pcCU->getPic()->getNumPartInCU() >> ((uiDepth + 1 ) << 1);
+#if !REMOVE_NSQT
+    const UInt uiLog2TrSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiDepth] + 2;
+#endif
+    for( UInt ui = 0; ui < 4; ++ui )
+    {
+#if REMOVE_NSQT
+      UInt nsAddr = uiAbsPartIdx + ui * uiQPartNumSubdiv;
+#else
+      UInt nsAddr = 0;
+      nsAddr = pcCU->getNSAbsPartIdx( uiLog2TrSize-1, uiAbsPartIdx + ui * uiQPartNumSubdiv, absTUPartIdx, ui, uiCurrTrMode + 1);
+#endif
+      xSetResidualQTData( pcCU, ui, uiAbsPartIdx + ui * uiQPartNumSubdiv, nsAddr, pcResi, uiDepth + 1, bSpatial );
+    }
+  }
+}
+
+UInt TEncSearch::xModeBitsIntra( TComDataCU* pcCU, UInt uiMode, UInt uiPU, UInt uiPartOffset, UInt uiDepth, UInt uiInitTrDepth )
+{
+  if( m_bUseSBACRD )
+  {
+    // Reload only contexts required for coding intra mode information
+    m_pcRDGoOnSbacCoder->loadIntraDirModeLuma( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
+  }
+  
+  pcCU->setLumaIntraDirSubParts ( uiMode, uiPartOffset, uiDepth + uiInitTrDepth );
+  
+  m_pcEntropyCoder->resetBits();
+  m_pcEntropyCoder->encodeIntraDirModeLuma ( pcCU, uiPartOffset);
+  
+  return m_pcEntropyCoder->getNumberOfWrittenBits();
+}
+
+UInt TEncSearch::xUpdateCandList( UInt uiMode, Double uiCost, UInt uiFastCandNum, UInt * CandModeList, Double * CandCostList )
+{
+  UInt i;
+  UInt shift=0;
+  
+  while ( shift<uiFastCandNum && uiCost<CandCostList[ uiFastCandNum-1-shift ] ) shift++;
+  
+  if( shift!=0 )
+  {
+    for(i=1; i<shift; i++)
+    {
+      CandModeList[ uiFastCandNum-i ] = CandModeList[ uiFastCandNum-1-i ];
+      CandCostList[ uiFastCandNum-i ] = CandCostList[ uiFastCandNum-1-i ];
+    }
+    CandModeList[ uiFastCandNum-shift ] = uiMode;
+    CandCostList[ uiFastCandNum-shift ] = uiCost;
+    return 1;
+  }
+  
+  return 0;
+}
+
+/** add inter-prediction syntax elements for a CU block
+ * \param pcCU
+ * \param uiQp
+ * \param uiTrMode
+ * \param ruiBits
+ * \param rpcYuvRec
+ * \param pcYuvPred
+ * \param rpcYuvResi
+ * \returns Void
+ */
+Void  TEncSearch::xAddSymbolBitsInter( TComDataCU* pcCU, UInt uiQp, UInt uiTrMode, UInt& ruiBits, TComYuv*& rpcYuvRec, TComYuv*pcYuvPred, TComYuv*& rpcYuvResi )
+{
+#if SKIP_FLAG
+  if(pcCU->getMergeFlag( 0 ) && pcCU->getPartitionSize( 0 ) == SIZE_2Nx2N && !pcCU->getQtRootCbf( 0 ))
+#else
+  if ( pcCU->isSkipped( 0 ) )
+#endif
+  {
+#if SKIP_FLAG
+    pcCU->setSkipFlagSubParts( true, 0, pcCU->getDepth(0) );
+#endif
+
+    m_pcEntropyCoder->resetBits();
+    if(pcCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
+    {
+      m_pcEntropyCoder->encodeCUTransquantBypassFlag(pcCU, 0, true);
+    }
+    m_pcEntropyCoder->encodeSkipFlag(pcCU, 0, true);
+    m_pcEntropyCoder->encodeMergeIndex(pcCU, 0, 0, true);
+    ruiBits += m_pcEntropyCoder->getNumberOfWrittenBits();
+  }
+  else
+  {
+    m_pcEntropyCoder->resetBits();
+    if(pcCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
+    {
+      m_pcEntropyCoder->encodeCUTransquantBypassFlag(pcCU, 0, true);
+    }
+    m_pcEntropyCoder->encodeSkipFlag ( pcCU, 0, true );
+    m_pcEntropyCoder->encodePredMode( pcCU, 0, true );
+    m_pcEntropyCoder->encodePartSize( pcCU, 0, pcCU->getDepth(0), true );
+    m_pcEntropyCoder->encodePredInfo( pcCU, 0, true );
+    Bool bDummy = false;
+    m_pcEntropyCoder->encodeCoeff   ( pcCU, 0, pcCU->getDepth(0), pcCU->getWidth(0), pcCU->getHeight(0), bDummy );
+    
+    ruiBits += m_pcEntropyCoder->getNumberOfWrittenBits();
+  }
+}
+
+/**
+ * \brief Generate half-sample interpolated block
+ *
+ * \param pattern Reference picture ROI
+ * \param biPred    Flag indicating whether block is for biprediction
+ */
+Void TEncSearch::xExtDIFUpSamplingH( TComPattern* pattern, Bool biPred )
+{
+  Int width      = pattern->getROIYWidth();
+  Int height     = pattern->getROIYHeight();
+  Int srcStride  = pattern->getPatternLStride();
+  
+  Int intStride = m_filteredBlockTmp[0].getStride();
+  Int dstStride = m_filteredBlock[0][0].getStride();
+  Short *intPtr;
+  Short *dstPtr;
+  Int filterSize = NTAPS_LUMA;
+  Int halfFilterSize = (filterSize>>1);
+  Pel *srcPtr = pattern->getROIY() - halfFilterSize*srcStride - 1;
+  
+  m_if.filterHorLuma(srcPtr, srcStride, m_filteredBlockTmp[0].getLumaAddr(), intStride, width+1, height+filterSize, 0, false);
+  m_if.filterHorLuma(srcPtr, srcStride, m_filteredBlockTmp[2].getLumaAddr(), intStride, width+1, height+filterSize, 2, false);
+  
+  intPtr = m_filteredBlockTmp[0].getLumaAddr() + halfFilterSize * intStride + 1;  
+  dstPtr = m_filteredBlock[0][0].getLumaAddr();
+  m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width+0, height+0, 0, false, true);
+  
+  intPtr = m_filteredBlockTmp[0].getLumaAddr() + (halfFilterSize-1) * intStride + 1;  
+  dstPtr = m_filteredBlock[2][0].getLumaAddr();
+  m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width+0, height+1, 2, false, true);
+  
+  intPtr = m_filteredBlockTmp[2].getLumaAddr() + halfFilterSize * intStride;
+  dstPtr = m_filteredBlock[0][2].getLumaAddr();
+  m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width+1, height+0, 0, false, true);
+  
+  intPtr = m_filteredBlockTmp[2].getLumaAddr() + (halfFilterSize-1) * intStride;
+  dstPtr = m_filteredBlock[2][2].getLumaAddr();
+  m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width+1, height+1, 2, false, true);
+}
+
+/**
+ * \brief Generate quarter-sample interpolated blocks
+ *
+ * \param pattern    Reference picture ROI
+ * \param halfPelRef Half-pel mv
+ * \param biPred     Flag indicating whether block is for biprediction
+ */
+Void TEncSearch::xExtDIFUpSamplingQ( TComPattern* pattern, TComMv halfPelRef, Bool biPred )
+{
+  Int width      = pattern->getROIYWidth();
+  Int height     = pattern->getROIYHeight();
+  Int srcStride  = pattern->getPatternLStride();
+  
+  Pel *srcPtr;
+  Int intStride = m_filteredBlockTmp[0].getStride();
+  Int dstStride = m_filteredBlock[0][0].getStride();
+  Short *intPtr;
+  Short *dstPtr;
+  Int filterSize = NTAPS_LUMA;
+  
+  Int halfFilterSize = (filterSize>>1);
+
+  Int extHeight = (halfPelRef.getVer() == 0) ? height + filterSize : height + filterSize-1;
+  
+  // Horizontal filter 1/4
+  srcPtr = pattern->getROIY() - halfFilterSize * srcStride - 1;
+  intPtr = m_filteredBlockTmp[1].getLumaAddr();
+  if (halfPelRef.getVer() > 0)
+  {
+    srcPtr += srcStride;
+  }
+  if (halfPelRef.getHor() >= 0)
+  {
+    srcPtr += 1;
+  }
+  m_if.filterHorLuma(srcPtr, srcStride, intPtr, intStride, width, extHeight, 1, false);
+  
+  // Horizontal filter 3/4
+  srcPtr = pattern->getROIY() - halfFilterSize*srcStride - 1;
+  intPtr = m_filteredBlockTmp[3].getLumaAddr();
+  if (halfPelRef.getVer() > 0)
+  {
+    srcPtr += srcStride;
+  }
+  if (halfPelRef.getHor() > 0)
+  {
+    srcPtr += 1;
+  }
+  m_if.filterHorLuma(srcPtr, srcStride, intPtr, intStride, width, extHeight, 3, false);        
+  
+  // Generate @ 1,1
+  intPtr = m_filteredBlockTmp[1].getLumaAddr() + (halfFilterSize-1) * intStride;
+  dstPtr = m_filteredBlock[1][1].getLumaAddr();
+  if (halfPelRef.getVer() == 0)
+  {
+    intPtr += intStride;
+  }
+  m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 1, false, true);
+  
+  // Generate @ 3,1
+  intPtr = m_filteredBlockTmp[1].getLumaAddr() + (halfFilterSize-1) * intStride;
+  dstPtr = m_filteredBlock[3][1].getLumaAddr();
+  m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 3, false, true);
+  
+  if (halfPelRef.getVer() != 0)
+  {
+    // Generate @ 2,1
+    intPtr = m_filteredBlockTmp[1].getLumaAddr() + (halfFilterSize-1) * intStride;
+    dstPtr = m_filteredBlock[2][1].getLumaAddr();
+    if (halfPelRef.getVer() == 0)
+    {
+      intPtr += intStride;
+    }
+    m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 2, false, true);
+    
+    // Generate @ 2,3
+    intPtr = m_filteredBlockTmp[3].getLumaAddr() + (halfFilterSize-1) * intStride;
+    dstPtr = m_filteredBlock[2][3].getLumaAddr();
+    if (halfPelRef.getVer() == 0)
+    {
+      intPtr += intStride;
+    }
+    m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 2, false, true);
+  }
+  else
+  {
+    // Generate @ 0,1
+    intPtr = m_filteredBlockTmp[1].getLumaAddr() + halfFilterSize * intStride;
+    dstPtr = m_filteredBlock[0][1].getLumaAddr();
+    m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 0, false, true);
+    
+    // Generate @ 0,3
+    intPtr = m_filteredBlockTmp[3].getLumaAddr() + halfFilterSize * intStride;
+    dstPtr = m_filteredBlock[0][3].getLumaAddr();
+    m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 0, false, true);
+  }
+  
+  if (halfPelRef.getHor() != 0)
+  {
+    // Generate @ 1,2
+    intPtr = m_filteredBlockTmp[2].getLumaAddr() + (halfFilterSize-1) * intStride;
+    dstPtr = m_filteredBlock[1][2].getLumaAddr();
+    if (halfPelRef.getHor() > 0)
+    {
+      intPtr += 1;
+    }
+    if (halfPelRef.getVer() >= 0)
+    {
+      intPtr += intStride;
+    }
+    m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 1, false, true);
+    
+    // Generate @ 3,2
+    intPtr = m_filteredBlockTmp[2].getLumaAddr() + (halfFilterSize-1) * intStride;
+    dstPtr = m_filteredBlock[3][2].getLumaAddr();
+    if (halfPelRef.getHor() > 0)
+    {
+      intPtr += 1;
+    }
+    if (halfPelRef.getVer() > 0)
+    {
+      intPtr += intStride;
+    }
+    m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 3, false, true);  
+  }
+  else
+  {
+    // Generate @ 1,0
+    intPtr = m_filteredBlockTmp[0].getLumaAddr() + (halfFilterSize-1) * intStride + 1;
+    dstPtr = m_filteredBlock[1][0].getLumaAddr();
+    if (halfPelRef.getVer() >= 0)
+    {
+      intPtr += intStride;
+    }
+    m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 1, false, true);
+    
+    // Generate @ 3,0
+    intPtr = m_filteredBlockTmp[0].getLumaAddr() + (halfFilterSize-1) * intStride + 1;
+    dstPtr = m_filteredBlock[3][0].getLumaAddr();
+    if (halfPelRef.getVer() > 0)
+    {
+      intPtr += intStride;
+    }
+    m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 3, false, true);
+  }
+  
+  // Generate @ 1,3
+  intPtr = m_filteredBlockTmp[3].getLumaAddr() + (halfFilterSize-1) * intStride;
+  dstPtr = m_filteredBlock[1][3].getLumaAddr();
+  if (halfPelRef.getVer() == 0)
+  {
+    intPtr += intStride;
+  }
+  m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 1, false, true);
+  
+  // Generate @ 3,3
+  intPtr = m_filteredBlockTmp[3].getLumaAddr() + (halfFilterSize-1) * intStride;
+  dstPtr = m_filteredBlock[3][3].getLumaAddr();
+  m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 3, false, true);
+}
+
+/** set wp tables
+ * \param TComDataCU* pcCU
+ * \param iRefIdx
+ * \param eRefPicListCur
+ * \returns Void
+ */
+Void  TEncSearch::setWpScalingDistParam( TComDataCU* pcCU, Int iRefIdx, RefPicList eRefPicListCur )
+{
+  if ( iRefIdx<0 )
+  {
+    m_cDistParam.bApplyWeight = false;
+    return;
+  }
+
+  TComSlice       *pcSlice  = pcCU->getSlice();
+  TComPPS         *pps      = pcCU->getSlice()->getPPS();
+  wpScalingParam  *wp0 , *wp1;
+  m_cDistParam.bApplyWeight = ( pcSlice->getSliceType()==P_SLICE && pps->getUseWP() ) || ( pcSlice->getSliceType()==B_SLICE && pps->getWPBiPred() ) ;
+  if ( !m_cDistParam.bApplyWeight ) return;
+
+  Int iRefIdx0 = ( eRefPicListCur == REF_PIC_LIST_0 ) ? iRefIdx : (-1);
+  Int iRefIdx1 = ( eRefPicListCur == REF_PIC_LIST_1 ) ? iRefIdx : (-1);
+
+  getWpScaling( pcCU, iRefIdx0, iRefIdx1, wp0 , wp1 );
+
+  if ( iRefIdx0 < 0 ) wp0 = NULL;
+  if ( iRefIdx1 < 0 ) wp1 = NULL;
+
+  m_cDistParam.wpCur  = NULL;
+
+  if ( eRefPicListCur == REF_PIC_LIST_0 )
+  {
+    m_cDistParam.wpCur = wp0;
+  }
+  else
+  {
+    m_cDistParam.wpCur = wp1;
+  }
+}
+
+//! \}
Index: /trunk/source/Lib/TLibEncoder/TEncSearch.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncSearch.h	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/TEncSearch.h	(revision 2)
@@ -0,0 +1,500 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncSearch.h
+    \brief    encoder search class (header)
+*/
+
+#ifndef __TENCSEARCH__
+#define __TENCSEARCH__
+
+// Include files
+#include "TLibCommon/TComYuv.h"
+#include "TLibCommon/TComMotionInfo.h"
+#include "TLibCommon/TComPattern.h"
+#include "TLibCommon/TComPrediction.h"
+#include "TLibCommon/TComTrQuant.h"
+#include "TLibCommon/TComPic.h"
+#include "TEncEntropy.h"
+#include "TEncSbac.h"
+#include "TEncCfg.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+class TEncCu;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// encoder search class
+class TEncSearch : public TComPrediction
+{
+private:
+  TCoeff**        m_ppcQTTempCoeffY;
+  TCoeff**        m_ppcQTTempCoeffCb;
+  TCoeff**        m_ppcQTTempCoeffCr;
+  TCoeff*         m_pcQTTempCoeffY;
+  TCoeff*         m_pcQTTempCoeffCb;
+  TCoeff*         m_pcQTTempCoeffCr;
+#if ADAPTIVE_QP_SELECTION
+  Int**           m_ppcQTTempArlCoeffY;
+  Int**           m_ppcQTTempArlCoeffCb;
+  Int**           m_ppcQTTempArlCoeffCr;
+  Int*            m_pcQTTempArlCoeffY;
+  Int*            m_pcQTTempArlCoeffCb;
+  Int*            m_pcQTTempArlCoeffCr;
+#endif
+  UChar*          m_puhQTTempTrIdx;
+  UChar*          m_puhQTTempCbf[3];
+  
+  TComYuv*        m_pcQTTempTComYuv;
+  TComYuv         m_tmpYuvPred; // To be used in xGetInterPredictionError() to avoid constant memory allocation/deallocation
+  Pel*            m_pSharedPredTransformSkip[3];
+  TCoeff*         m_pcQTTempTUCoeffY;
+  TCoeff*         m_pcQTTempTUCoeffCb;
+  TCoeff*         m_pcQTTempTUCoeffCr;
+  UChar*          m_puhQTTempTransformSkipFlag[3];
+  TComYuv         m_pcQTTempTransformSkipTComYuv;
+#if ADAPTIVE_QP_SELECTION
+  Int*            m_ppcQTTempTUArlCoeffY;
+  Int*            m_ppcQTTempTUArlCoeffCb;
+  Int*            m_ppcQTTempTUArlCoeffCr;
+#endif
+protected:
+  // interface to option
+  TEncCfg*        m_pcEncCfg;
+
+#if SVC_EXTENSION
+  TEncTop**       m_ppcTEncTop;
+#endif
+#if INTRA_BL
+  TComPicYuv*     m_pcPicYuvRecBase;       ///< reconstructed base layer
+#endif
+  
+  // interface to classes
+  TComTrQuant*    m_pcTrQuant;
+  TComRdCost*     m_pcRdCost;
+  TEncEntropy*    m_pcEntropyCoder;
+  
+  // ME parameters
+  Int             m_iSearchRange;
+  Int             m_bipredSearchRange; // Search range for bi-prediction
+  Int             m_iFastSearch;
+  Int             m_aaiAdaptSR[2][33];
+  TComMv          m_cSrchRngLT;
+  TComMv          m_cSrchRngRB;
+  TComMv          m_acMvPredictors[3];
+  
+  // RD computation
+  TEncSbac***     m_pppcRDSbacCoder;
+  TEncSbac*       m_pcRDGoOnSbacCoder;
+  Bool            m_bUseSBACRD;
+  DistParam       m_cDistParam;
+  
+  // Misc.
+  Pel*            m_pTempPel;
+  const UInt*     m_puiDFilter;
+  Int             m_iMaxDeltaQP;
+  
+  // AMVP cost computation
+  // UInt            m_auiMVPIdxCost[AMVP_MAX_NUM_CANDS+1][AMVP_MAX_NUM_CANDS];
+  UInt            m_auiMVPIdxCost[AMVP_MAX_NUM_CANDS+1][AMVP_MAX_NUM_CANDS+1]; //th array bounds
+  
+public:
+  TEncSearch();
+  virtual ~TEncSearch();
+  
+  Void init(  TEncCfg*      pcEncCfg,
+            TComTrQuant*  pcTrQuant,
+            Int           iSearchRange,
+            Int           bipredSearchRange,
+            Int           iFastSearch,
+            Int           iMaxDeltaQP,
+            TEncEntropy*  pcEntropyCoder,
+            TComRdCost*   pcRdCost,
+            TEncSbac***   pppcRDSbacCoder,
+            TEncSbac*     pcRDGoOnSbacCoder );
+  
+protected:
+  
+  /// sub-function for motion vector refinement used in fractional-pel accuracy
+  UInt  xPatternRefinement( TComPattern* pcPatternKey,
+                           TComMv baseRefMv,
+                           Int iFrac, TComMv& rcMvFrac );
+  
+  typedef struct
+  {
+    Pel*  piRefY;
+    Int   iYStride;
+    Int   iBestX;
+    Int   iBestY;
+    UInt  uiBestRound;
+    UInt  uiBestDistance;
+    UInt  uiBestSad;
+    UChar ucPointNr;
+  } IntTZSearchStruct;
+  
+  // 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 );
+  
+  Void xGetInterPredictionError( TComDataCU* pcCU, TComYuv* pcYuvOrg, Int iPartIdx, UInt& ruiSAD, Bool Hadamard );
+
+public:
+  Void  preestChromaPredMode    ( TComDataCU* pcCU, 
+                                  TComYuv*    pcOrgYuv, 
+                                  TComYuv*    pcPredYuv );
+  Void  estIntraPredQT          ( TComDataCU* pcCU, 
+                                  TComYuv*    pcOrgYuv, 
+                                  TComYuv*    pcPredYuv, 
+                                  TComYuv*    pcResiYuv, 
+                                  TComYuv*    pcRecoYuv,
+                                  UInt&       ruiDistC,
+                                  Bool        bLumaOnly );
+  Void  estIntraPredChromaQT    ( TComDataCU* pcCU, 
+                                  TComYuv*    pcOrgYuv, 
+                                  TComYuv*    pcPredYuv, 
+                                  TComYuv*    pcResiYuv, 
+                                  TComYuv*    pcRecoYuv,
+                                  UInt        uiPreCalcDistC );
+  
+#if INTRA_BL
+  Void setBaseRecPic            ( TComPicYuv* pcPicYuvRecBase ) { m_pcPicYuvRecBase = pcPicYuvRecBase; }  
+  TComPicYuv* getBaseRecPic     ()                              { return m_pcPicYuvRecBase; }
+  Void  estIntraBLPredQT        ( TComDataCU* pcCU, 
+                                  TComYuv*    pcOrgYuv, 
+                                  TComYuv*    pcPredYuv, 
+                                  TComYuv*    pcResiYuv, 
+                                  TComYuv*    pcRecoYuv );
+#endif
+  
+  /// encoder estimation - inter prediction (non-skip)
+  Void predInterSearch          ( TComDataCU* pcCU,
+                                  TComYuv*    pcOrgYuv,
+                                  TComYuv*&   rpcPredYuv,
+                                  TComYuv*&   rpcResiYuv,
+                                  TComYuv*&   rpcRecoYuv,
+                                  Bool        bUseRes = false
+#if AMP_MRG
+                                 ,Bool        bUseMRG = false
+#endif
+                                );
+  
+  /// encode residual and compute rd-cost for inter mode
+  Void encodeResAndCalcRdInterCU( TComDataCU* pcCU,
+                                  TComYuv*    pcYuvOrg,
+                                  TComYuv*    pcYuvPred,
+                                  TComYuv*&   rpcYuvResi,
+                                  TComYuv*&   rpcYuvResiBest,
+                                  TComYuv*&   rpcYuvRec,
+                                  Bool        bSkipRes );
+  
+  /// set ME search range
+  Void setAdaptiveSearchRange   ( Int iDir, Int iRefIdx, Int iSearchRange) { m_aaiAdaptSR[iDir][iRefIdx] = iSearchRange; }
+  
+  Void xEncPCM    (TComDataCU* pcCU, UInt uiAbsPartIdx, Pel* piOrg, Pel* piPCM, Pel* piPred, Pel* piResi, Pel* piReco, UInt uiStride, UInt uiWidth, UInt uiHeight, TextType eText);
+  Void IPCMSearch (TComDataCU* pcCU, TComYuv* pcOrgYuv, TComYuv*& rpcPredYuv, TComYuv*& rpcResiYuv, TComYuv*& rpcRecoYuv );
+protected:
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // Intra search
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Void  xEncSubdivCbfQT           ( TComDataCU*  pcCU,
+                                    UInt         uiTrDepth,
+                                    UInt         uiAbsPartIdx,
+                                    Bool         bLuma,
+                                    Bool         bChroma );
+
+  Void  xEncCoeffQT               ( TComDataCU*  pcCU,
+                                    UInt         uiTrDepth,
+                                    UInt         uiAbsPartIdx,
+                                    TextType     eTextType,
+                                    Bool         bRealCoeff );
+  Void  xEncIntraHeader           ( TComDataCU*  pcCU,
+                                    UInt         uiTrDepth,
+                                    UInt         uiAbsPartIdx,
+                                    Bool         bLuma,
+                                    Bool         bChroma );
+  UInt  xGetIntraBitsQT           ( TComDataCU*  pcCU,
+                                    UInt         uiTrDepth,
+                                    UInt         uiAbsPartIdx,
+                                    Bool         bLuma,
+                                    Bool         bChroma,
+                                    Bool         bRealCoeff );
+  UInt  xGetIntraBitsQTChroma    ( TComDataCU*   pcCU,
+                                   UInt          uiTrDepth,
+                                   UInt          uiAbsPartIdx,
+                                   UInt          uiChromaId,
+                                   Bool          bRealCoeff );
+  
+  Void  xIntraCodingLumaBlk       ( TComDataCU*  pcCU,
+                                    UInt         uiTrDepth,
+                                    UInt         uiAbsPartIdx,
+                                    TComYuv*     pcOrgYuv, 
+                                    TComYuv*     pcPredYuv, 
+                                    TComYuv*     pcResiYuv, 
+                                    UInt&        ruiDist,
+                                    Int         default0Save1Load2 = 0);
+  Void  xIntraCodingChromaBlk     ( TComDataCU*  pcCU,
+                                    UInt         uiTrDepth,
+                                    UInt         uiAbsPartIdx,
+                                    TComYuv*     pcOrgYuv, 
+                                    TComYuv*     pcPredYuv, 
+                                    TComYuv*     pcResiYuv, 
+                                    UInt&        ruiDist,
+                                    UInt         uiChromaId,
+                                    Int          default0Save1Load2 = 0 );
+
+  Void  xRecurIntraCodingQT       ( TComDataCU*  pcCU, 
+                                    UInt         uiTrDepth,
+                                    UInt         uiAbsPartIdx, 
+                                    Bool         bLumaOnly,
+                                    TComYuv*     pcOrgYuv, 
+                                    TComYuv*     pcPredYuv, 
+                                    TComYuv*     pcResiYuv, 
+                                    UInt&        ruiDistY,
+                                    UInt&        ruiDistC,
+#if HHI_RQT_INTRA_SPEEDUP
+                                   Bool         bCheckFirst,
+#endif
+                                   Double&      dRDCost );
+  
+  Void  xSetIntraResultQT         ( TComDataCU*  pcCU,
+                                    UInt         uiTrDepth,
+                                    UInt         uiAbsPartIdx,
+                                    Bool         bLumaOnly,
+                                    TComYuv*     pcRecoYuv );
+  
+  Void  xRecurIntraChromaCodingQT ( TComDataCU*  pcCU, 
+                                    UInt         uiTrDepth,
+                                    UInt         uiAbsPartIdx, 
+                                    TComYuv*     pcOrgYuv, 
+                                    TComYuv*     pcPredYuv, 
+                                    TComYuv*     pcResiYuv, 
+                                    UInt&        ruiDist );
+  Void  xSetIntraResultChromaQT   ( TComDataCU*  pcCU,
+                                    UInt         uiTrDepth,
+                                    UInt         uiAbsPartIdx,
+                                    TComYuv*     pcRecoYuv );
+  
+  Void  xStoreIntraResultQT       ( TComDataCU*  pcCU,
+                                    UInt         uiTrDepth,
+                                    UInt         uiAbsPartIdx,
+                                    Bool         bLumaOnly );
+  Void  xLoadIntraResultQT        ( TComDataCU*  pcCU,
+                                    UInt         uiTrDepth,
+                                    UInt         uiAbsPartIdx,
+                                    Bool         bLumaOnly );
+  Void xStoreIntraResultChromaQT  ( TComDataCU*  pcCU,
+                                    UInt         uiTrDepth,
+                                    UInt         uiAbsPartIdx,
+                                    UInt         stateU0V1Both2 );
+  Void xLoadIntraResultChromaQT   ( TComDataCU*  pcCU,
+                                    UInt         uiTrDepth,
+                                    UInt         uiAbsPartIdx,
+                                    UInt         stateU0V1Both2 );
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // Inter search (AMP)
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Void xEstimateMvPredAMVP        ( TComDataCU* pcCU,
+                                    TComYuv*    pcOrgYuv,
+                                    UInt        uiPartIdx,
+                                    RefPicList  eRefPicList,
+                                    Int         iRefIdx,
+                                    TComMv&     rcMvPred,
+                                    Bool        bFilled = false
+                                  , UInt*       puiDistBiP = NULL
+                                  #if ZERO_MVD_EST
+                                  , UInt*       puiDist = NULL
+                                  #endif
+                                     );
+  
+  Void xCheckBestMVP              ( TComDataCU* pcCU,
+                                    RefPicList  eRefPicList,
+                                    TComMv      cMv,
+                                    TComMv&     rcMvPred,
+                                    Int&        riMVPIdx,
+                                    UInt&       ruiBits,
+                                    UInt&       ruiCost );
+  
+  UInt xGetTemplateCost           ( TComDataCU* pcCU,
+                                    UInt        uiPartIdx,
+                                    UInt        uiPartAddr,
+                                    TComYuv*    pcOrgYuv,
+                                    TComYuv*    pcTemplateCand,
+                                    TComMv      cMvCand,
+                                    Int         iMVPIdx,
+                                    Int         iMVPNum,
+                                    RefPicList  eRefPicList,
+                                    Int         iRefIdx,
+                                    Int         iSizeX,
+                                    Int         iSizeY
+                                  #if ZERO_MVD_EST
+                                  , UInt&       ruiDist
+                                  #endif
+                                   );
+  
+  
+  Void xCopyAMVPInfo              ( AMVPInfo*   pSrc, AMVPInfo* pDst );
+  UInt xGetMvpIdxBits             ( Int iIdx, Int iNum );
+  Void xGetBlkBits                ( PartSize  eCUMode, Bool bPSlice, Int iPartIdx,  UInt uiLastMode, UInt uiBlkBit[3]);
+  
+  Void xMergeEstimation           ( TComDataCU*     pcCU,
+                                    TComYuv*        pcYuvOrg,
+                                    Int             iPartIdx,
+                                    UInt&           uiInterDir,
+                                    TComMvField*    pacMvField,
+                                    UInt&           uiMergeIndex,
+                                    UInt&           ruiCost
+                                  , TComMvField* cMvFieldNeighbours,  
+                                    UChar* uhInterDirNeighbours,
+                                    Int& numValidMergeCand
+                                   );
+
+  Void xRestrictBipredMergeCand   ( TComDataCU*     pcCU,
+                                    UInt            puIdx,
+                                    TComMvField*    mvFieldNeighbours, 
+                                    UChar*          interDirNeighbours, 
+                                    Int             numValidMergeCand );
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // motion estimation
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Void xMotionEstimation          ( TComDataCU*   pcCU,
+                                    TComYuv*      pcYuvOrg,
+                                    Int           iPartIdx,
+                                    RefPicList    eRefPicList,
+                                    TComMv*       pcMvPred,
+                                    Int           iRefIdxPred,
+                                    TComMv&       rcMv,
+                                    UInt&         ruiBits,
+                                    UInt&         ruiCost,
+                                    Bool          bBi = false  );
+  
+  Void xTZSearch                  ( TComDataCU*   pcCU,
+                                    TComPattern*  pcPatternKey,
+                                    Pel*          piRefY,
+                                    Int           iRefStride,
+                                    TComMv*       pcMvSrchRngLT,
+                                    TComMv*       pcMvSrchRngRB,
+                                    TComMv&       rcMv,
+                                    UInt&         ruiSAD );
+  
+  Void xSetSearchRange            ( TComDataCU*   pcCU,
+                                    TComMv&       cMvPred,
+                                    Int           iSrchRng,
+                                    TComMv&       rcMvSrchRngLT,
+                                    TComMv&       rcMvSrchRngRB );
+  
+  Void xPatternSearchFast         ( TComDataCU*   pcCU,
+                                    TComPattern*  pcPatternKey,
+                                    Pel*          piRefY,
+                                    Int           iRefStride,
+                                    TComMv*       pcMvSrchRngLT,
+                                    TComMv*       pcMvSrchRngRB,
+                                    TComMv&       rcMv,
+                                    UInt&         ruiSAD );
+  
+  Void xPatternSearch             ( TComPattern*  pcPatternKey,
+                                    Pel*          piRefY,
+                                    Int           iRefStride,
+                                    TComMv*       pcMvSrchRngLT,
+                                    TComMv*       pcMvSrchRngRB,
+                                    TComMv&       rcMv,
+                                    UInt&         ruiSAD );
+  
+  Void xPatternSearchFracDIF      ( TComDataCU*   pcCU,
+                                    TComPattern*  pcPatternKey,
+                                    Pel*          piRefY,
+                                    Int           iRefStride,
+                                    TComMv*       pcMvInt,
+                                    TComMv&       rcMvHalf,
+                                    TComMv&       rcMvQter,
+                                    UInt&         ruiCost 
+                                   ,Bool biPred
+                                   );
+#if REF_IDX_ME_AROUND_ZEROMV
+  Void xPatternSearchILR         ( TComDataCU*    pcCU,
+                                   TComPattern*   pcPatternKey,
+                                   Pel*           piRefY, 
+                                   Int            iRefStride, 
+                                   TComMv&        rcMv, 
+                                   UInt&          ruiSAD );
+#endif
+  
+  Void xExtDIFUpSamplingH( TComPattern* pcPattern, Bool biPred  );
+  Void xExtDIFUpSamplingQ( TComPattern* pcPatternKey, TComMv halfPelRef, Bool biPred );
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // T & Q & Q-1 & T-1
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Void xEncodeResidualQT( TComDataCU* pcCU, UInt uiAbsPartIdx, const UInt uiDepth, Bool bSubdivAndCbf, TextType eType );
+#if IBDI_DISTORTION
+  Void xEstimateResidualQT( TComDataCU* pcCU, UInt uiQuadrant, UInt uiAbsPartIdx, UInt absTUPartIdx,TComYuv* pcOrg, TComYuv* pcPred, TComYuv* pcResi, const UInt uiDepth, Double &rdCost, UInt &ruiBits, UInt &ruiDist, UInt *puiZeroDist );
+#else
+  Void xEstimateResidualQT( TComDataCU* pcCU, UInt uiQuadrant, UInt uiAbsPartIdx, UInt absTUPartIdx,TComYuv* pcResi, const UInt uiDepth, Double &rdCost, UInt &ruiBits, UInt &ruiDist, UInt *puiZeroDist );
+#endif
+  Void xSetResidualQTData( TComDataCU* pcCU, UInt uiQuadrant, UInt uiAbsPartIdx,UInt absTUPartIdx, TComYuv* pcResi, UInt uiDepth, Bool bSpatial );
+  
+  UInt  xModeBitsIntra ( TComDataCU* pcCU, UInt uiMode, UInt uiPU, UInt uiPartOffset, UInt uiDepth, UInt uiInitTrDepth );
+  UInt  xUpdateCandList( UInt uiMode, Double uiCost, UInt uiFastCandNum, UInt * CandModeList, Double * CandCostList );
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // compute symbol bits
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Void xAddSymbolBitsInter        ( TComDataCU*   pcCU,
+                                   UInt          uiQp,
+                                   UInt          uiTrMode,
+                                   UInt&         ruiBits,
+                                   TComYuv*&     rpcYuvRec,
+                                   TComYuv*      pcYuvPred,
+                                   TComYuv*&     rpcYuvResi );
+  
+  Void  setWpScalingDistParam( TComDataCU* pcCU, Int iRefIdx, RefPicList eRefPicListCur );
+  inline  Void  setDistParamComp( UInt uiComp )  { m_cDistParam.uiComp = uiComp; }
+  
+};// END CLASS DEFINITION TEncSearch
+
+//! \}
+
+#endif // __TENCSEARCH__
Index: /trunk/source/Lib/TLibEncoder/TEncSlice.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 2)
@@ -0,0 +1,1797 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncSlice.cpp
+    \brief    slice encoder class
+*/
+
+#include "TEncTop.h"
+#include "TEncSlice.h"
+#include <math.h>
+
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TEncSlice::TEncSlice()
+{
+  m_apcPicYuvPred = NULL;
+  m_apcPicYuvResi = NULL;
+  
+  m_pdRdPicLambda = NULL;
+  m_pdRdPicQp     = NULL;
+  m_piRdPicQp     = NULL;
+  m_pcBufferSbacCoders    = NULL;
+  m_pcBufferBinCoderCABACs  = NULL;
+  m_pcBufferLowLatSbacCoders    = NULL;
+  m_pcBufferLowLatBinCoderCABACs  = NULL;
+}
+
+TEncSlice::~TEncSlice()
+{
+#if DEPENDENT_SLICES
+  for (std::vector<TEncSbac*>::iterator i = CTXMem.begin(); i != CTXMem.end(); i++)
+  {
+    delete (*i);
+  }
+#endif
+}
+
+#if DEPENDENT_SLICES
+Void TEncSlice::initCtxMem(  UInt i )                
+{   
+  for (std::vector<TEncSbac*>::iterator j = CTXMem.begin(); j != CTXMem.end(); j++)
+  {
+    delete (*j);
+  }
+  CTXMem.clear(); 
+  CTXMem.resize(i); 
+}
+#endif
+
+Void TEncSlice::create( Int iWidth, Int iHeight, UInt iMaxCUWidth, UInt iMaxCUHeight, UChar uhTotalDepth )
+{
+  // create prediction picture
+  if ( m_apcPicYuvPred == NULL )
+  {
+    m_apcPicYuvPred  = new TComPicYuv;
+    m_apcPicYuvPred->create( iWidth, iHeight, iMaxCUWidth, iMaxCUHeight, uhTotalDepth );
+  }
+  
+  // create residual picture
+  if( m_apcPicYuvResi == NULL )
+  {
+    m_apcPicYuvResi  = new TComPicYuv;
+    m_apcPicYuvResi->create( iWidth, iHeight, iMaxCUWidth, iMaxCUHeight, uhTotalDepth );
+  }
+}
+
+Void TEncSlice::destroy()
+{
+  // destroy prediction picture
+  if ( m_apcPicYuvPred )
+  {
+    m_apcPicYuvPred->destroy();
+    delete m_apcPicYuvPred;
+    m_apcPicYuvPred  = NULL;
+  }
+  
+  // destroy residual picture
+  if ( m_apcPicYuvResi )
+  {
+    m_apcPicYuvResi->destroy();
+    delete m_apcPicYuvResi;
+    m_apcPicYuvResi  = NULL;
+  }
+  
+  // free lambda and QP arrays
+  if ( m_pdRdPicLambda ) { xFree( m_pdRdPicLambda ); m_pdRdPicLambda = NULL; }
+  if ( m_pdRdPicQp     ) { xFree( m_pdRdPicQp     ); m_pdRdPicQp     = NULL; }
+  if ( m_piRdPicQp     ) { xFree( m_piRdPicQp     ); m_piRdPicQp     = NULL; }
+
+  if ( m_pcBufferSbacCoders )
+  {
+    delete[] m_pcBufferSbacCoders;
+  }
+  if ( m_pcBufferBinCoderCABACs )
+  {
+    delete[] m_pcBufferBinCoderCABACs;
+  }
+  if ( m_pcBufferLowLatSbacCoders )
+    delete[] m_pcBufferLowLatSbacCoders;
+  if ( m_pcBufferLowLatBinCoderCABACs )
+    delete[] m_pcBufferLowLatBinCoderCABACs;
+}
+
+Void TEncSlice::init( TEncTop* pcEncTop )
+{
+  m_pcCfg             = pcEncTop;
+  m_pcListPic         = pcEncTop->getListPic();
+#if SVC_EXTENSION
+  m_ppcTEncTop        = pcEncTop->getLayerEnc();
+#endif  
+  m_pcGOPEncoder      = pcEncTop->getGOPEncoder();
+  m_pcCuEncoder       = pcEncTop->getCuEncoder();
+  m_pcPredSearch      = pcEncTop->getPredSearch();
+  
+  m_pcEntropyCoder    = pcEncTop->getEntropyCoder();
+  m_pcCavlcCoder      = pcEncTop->getCavlcCoder();
+  m_pcSbacCoder       = pcEncTop->getSbacCoder();
+  m_pcBinCABAC        = pcEncTop->getBinCABAC();
+  m_pcTrQuant         = pcEncTop->getTrQuant();
+  
+  m_pcBitCounter      = pcEncTop->getBitCounter();
+  m_pcRdCost          = pcEncTop->getRdCost();
+  m_pppcRDSbacCoder   = pcEncTop->getRDSbacCoder();
+  m_pcRDGoOnSbacCoder = pcEncTop->getRDGoOnSbacCoder();
+  
+  // create lambda and QP arrays
+  m_pdRdPicLambda     = (Double*)xMalloc( Double, m_pcCfg->getDeltaQpRD() * 2 + 1 );
+  m_pdRdPicQp         = (Double*)xMalloc( Double, m_pcCfg->getDeltaQpRD() * 2 + 1 );
+  m_piRdPicQp         = (Int*   )xMalloc( Int,    m_pcCfg->getDeltaQpRD() * 2 + 1 );
+  m_pcRateCtrl        = pcEncTop->getRateCtrl();
+}
+
+/**
+ - non-referenced frame marking
+ - QP computation based on temporal structure
+ - lambda computation based on QP
+ - set temporal layer ID and the parameter sets
+ .
+ \param pcPic         picture class
+ \param iPOCLast      POC of last picture
+ \param uiPOCCurr     current POC
+ \param iNumPicRcvd   number of received pictures
+ \param iTimeOffset   POC offset for hierarchical structure
+ \param iDepth        temporal layer depth
+ \param rpcSlice      slice header class
+ \param pSPS          SPS associated with the slice
+ \param pPPS          PPS associated with the slice
+ */
+Void TEncSlice::initEncSlice( TComPic* pcPic, Int iPOCLast, UInt uiPOCCurr, Int iNumPicRcvd, Int iGOPid, TComSlice*& rpcSlice, TComSPS* pSPS, TComPPS *pPPS )
+{
+  Double dQP;
+  Double dLambda;
+  
+  rpcSlice = pcPic->getSlice(0);
+  rpcSlice->setSPS( pSPS );
+  rpcSlice->setPPS( pPPS );
+  rpcSlice->setSliceBits(0);
+  rpcSlice->setPic( pcPic );
+  rpcSlice->initSlice();
+  rpcSlice->setPicOutputFlag( true );
+  rpcSlice->setPOC( uiPOCCurr );
+  
+#if SVC_EXTENSION
+  rpcSlice->setLayerId( pcPic->getLayerId());
+#endif
+
+  // depth computation based on GOP size
+  int iDepth;
+  {
+    Int i, j;
+    Int iPOC = rpcSlice->getPOC()%m_pcCfg->getGOPSize();
+    if ( iPOC == 0 )
+    {
+      iDepth = 0;
+    }
+    else
+    {
+      Int iStep = m_pcCfg->getGOPSize();
+      iDepth    = 0;
+      for( i=iStep>>1; i>=1; i>>=1 )
+      {
+        for ( j=i; j<m_pcCfg->getGOPSize(); j+=iStep )
+        {
+          if ( j == iPOC )
+          {
+            i=0;
+            break;
+          }
+        }
+        iStep>>=1;
+        iDepth++;
+      }
+    }
+  }
+  
+  // slice type
+  SliceType eSliceType;
+  
+  eSliceType=B_SLICE;
+  eSliceType = (iPOCLast == 0 || uiPOCCurr % m_pcCfg->getIntraPeriod() == 0 || m_pcGOPEncoder->getGOPSize() == 0) ? I_SLICE : eSliceType;
+  
+  rpcSlice->setSliceType    ( eSliceType );
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  // Non-referenced frame marking
+  // ------------------------------------------------------------------------------------------------------------------
+  
+#if TEMPORAL_LAYER_NON_REFERENCE
+  if(iPOCLast == 0)
+  {
+    rpcSlice->setTemporalLayerNonReferenceFlag(false);
+  }
+  else
+  {
+    rpcSlice->setTemporalLayerNonReferenceFlag(!m_pcCfg->getGOPEntry(iGOPid).m_refPic);
+  }
+  rpcSlice->setReferenced(true);
+#else
+  rpcSlice->setReferenced(m_pcCfg->getGOPEntry(iGOPid).m_refPic);
+#endif
+#if !REMOVE_NAL_REF_FLAG
+  rpcSlice->setNalRefFlag(m_pcCfg->getGOPEntry(iGOPid).m_refPic);
+#endif
+#if !TEMPORAL_LAYER_NON_REFERENCE
+  if(eSliceType==I_SLICE)
+  {
+    rpcSlice->setReferenced(true);
+  }
+#endif
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  // QP setting
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  dQP = m_pcCfg->getQP();
+  if(eSliceType!=I_SLICE)
+  {
+    if (!(( m_pcCfg->getMaxDeltaQP() == 0 ) && (dQP == -rpcSlice->getSPS()->getQpBDOffsetY() ) && (rpcSlice->getSPS()->getUseLossless()))) 
+    {
+      dQP += m_pcCfg->getGOPEntry(iGOPid).m_QPOffset;
+    }
+  }
+  
+  // modify QP
+  Int* pdQPs = m_pcCfg->getdQPs();
+  if ( pdQPs )
+  {
+    dQP += pdQPs[ rpcSlice->getPOC() ];
+  }
+  if ( m_pcCfg->getUseRateCtrl())
+  {
+    dQP = m_pcRateCtrl->getFrameQP(rpcSlice->isReferenced(), rpcSlice->getPOC());
+  }
+  // ------------------------------------------------------------------------------------------------------------------
+  // Lambda computation
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  Int iQP;
+  Double dOrigQP = dQP;
+
+  // pre-compute lambda and QP values for all possible QP candidates
+  for ( Int iDQpIdx = 0; iDQpIdx < 2 * m_pcCfg->getDeltaQpRD() + 1; iDQpIdx++ )
+  {
+    // compute QP value
+    dQP = dOrigQP + ((iDQpIdx+1)>>1)*(iDQpIdx%2 ? -1 : 1);
+    
+    // compute lambda value
+    Int    NumberBFrames = ( m_pcCfg->getGOPSize() - 1 );
+    Int    SHIFT_QP = 12;
+    Double dLambda_scale = 1.0 - Clip3( 0.0, 0.5, 0.05*(Double)NumberBFrames );
+#if FULL_NBIT
+    Int    bitdepth_luma_qp_scale = 6 * (g_uiBitDepth - 8);
+#else
+    Int    bitdepth_luma_qp_scale = 0;
+#endif
+    Double qp_temp = (Double) dQP + bitdepth_luma_qp_scale - SHIFT_QP;
+#if FULL_NBIT
+    Double qp_temp_orig = (Double) dQP - SHIFT_QP;
+#endif
+    // Case #1: I or P-slices (key-frame)
+    Double dQPFactor = m_pcCfg->getGOPEntry(iGOPid).m_QPFactor;
+    if ( eSliceType==I_SLICE )
+    {
+      dQPFactor=0.57*dLambda_scale;
+    }
+    dLambda = dQPFactor*pow( 2.0, qp_temp/3.0 );
+
+    if ( iDepth>0 )
+    {
+#if FULL_NBIT
+        dLambda *= Clip3( 2.00, 4.00, (qp_temp_orig / 6.0) ); // (j == B_SLICE && p_cur_frm->layer != 0 )
+#else
+        dLambda *= Clip3( 2.00, 4.00, (qp_temp / 6.0) ); // (j == B_SLICE && p_cur_frm->layer != 0 )
+#endif
+    }
+    
+    // if hadamard is used in ME process
+    if ( !m_pcCfg->getUseHADME() )
+    {
+      dLambda *= 0.95;
+    }
+    
+    iQP = max( -pSPS->getQpBDOffsetY(), min( MAX_QP, (Int) floor( dQP + 0.5 ) ) );
+
+    m_pdRdPicLambda[iDQpIdx] = dLambda;
+    m_pdRdPicQp    [iDQpIdx] = dQP;
+    m_piRdPicQp    [iDQpIdx] = iQP;
+  }
+  
+  // obtain dQP = 0 case
+  dLambda = m_pdRdPicLambda[0];
+  dQP     = m_pdRdPicQp    [0];
+  iQP     = m_piRdPicQp    [0];
+  
+  if( rpcSlice->getSliceType( ) != I_SLICE )
+  {
+    dLambda *= m_pcCfg->getLambdaModifier( m_pcCfg->getGOPEntry(iGOPid).m_temporalId );
+  }
+
+  // store lambda
+  m_pcRdCost ->setLambda( dLambda );
+#if WEIGHTED_CHROMA_DISTORTION
+// for RDO
+  // in RdCost there is only one lambda because the luma and chroma bits are not separated, instead we weight the distortion of chroma.
+  Double weight = 1.0;
+  if(iQP >= 0)
+  {
+    weight = pow( 2.0, (iQP-g_aucChromaScale[iQP])/3.0 );  // takes into account of the chroma qp mapping without chroma qp Offset
+  }
+  m_pcRdCost ->setChromaDistortionWeight( weight );     
+#endif
+
+#if RDOQ_CHROMA_LAMBDA 
+// for RDOQ
+  m_pcTrQuant->setLambda( dLambda, dLambda / weight );    
+#else
+  m_pcTrQuant->setLambda( dLambda );
+#endif
+
+#if ALF_CHROMA_LAMBDA || SAO_CHROMA_LAMBDA
+// For ALF or SAO
+  rpcSlice   ->setLambda( dLambda, dLambda / weight );  
+#else
+  rpcSlice   ->setLambda( dLambda );
+#endif
+  
+#if HB_LAMBDA_FOR_LDC
+  // restore original slice type
+  eSliceType = (iPOCLast == 0 || uiPOCCurr % m_pcCfg->getIntraPeriod() == 0 || m_pcGOPEncoder->getGOPSize() == 0) ? I_SLICE : eSliceType;
+#if REF_IDX_FRAMEWORK
+  if(m_pcCfg->getLayerId() > 0)
+  {
+    eSliceType=B_SLICE;
+  }
+#endif
+  rpcSlice->setSliceType        ( eSliceType );
+#endif
+  
+#if RECALCULATE_QP_ACCORDING_LAMBDA
+  if (m_pcCfg->getUseRecalculateQPAccordingToLambda())
+  {
+    dQP = xGetQPValueAccordingToLambda( dLambda );
+    iQP = max( -pSPS->getQpBDOffsetY(), min( MAX_QP, (Int) floor( dQP + 0.5 ) ) );    
+  }
+#endif
+
+  rpcSlice->setSliceQp          ( iQP );
+#if ADAPTIVE_QP_SELECTION
+  rpcSlice->setSliceQpBase      ( iQP );
+#endif
+  rpcSlice->setSliceQpDelta     ( 0 );
+#if CHROMA_QP_EXTENSION
+  rpcSlice->setSliceQpDeltaCb   ( 0 );
+  rpcSlice->setSliceQpDeltaCr   ( 0 );
+#endif
+  rpcSlice->setNumRefIdx(REF_PIC_LIST_0,m_pcCfg->getGOPEntry(iGOPid).m_numRefPicsActive);
+  rpcSlice->setNumRefIdx(REF_PIC_LIST_1,m_pcCfg->getGOPEntry(iGOPid).m_numRefPicsActive);
+  
+  if (rpcSlice->getPPS()->getDeblockingFilterControlPresentFlag())
+  {
+    rpcSlice->getPPS()->setDeblockingFilterOverrideEnabledFlag( !m_pcCfg->getLoopFilterOffsetInPPS() );
+    rpcSlice->setDeblockingFilterOverrideFlag( !m_pcCfg->getLoopFilterOffsetInPPS() );
+    rpcSlice->getPPS()->setPicDisableDeblockingFilterFlag( m_pcCfg->getLoopFilterDisable() );
+    rpcSlice->setDeblockingFilterDisable( m_pcCfg->getLoopFilterDisable() );
+    if ( !rpcSlice->getDeblockingFilterDisable())
+    {
+      rpcSlice->getPPS()->setDeblockingFilterBetaOffsetDiv2( m_pcCfg->getLoopFilterBetaOffset() );
+      rpcSlice->getPPS()->setDeblockingFilterTcOffsetDiv2( m_pcCfg->getLoopFilterTcOffset() );
+      rpcSlice->setDeblockingFilterBetaOffsetDiv2( m_pcCfg->getLoopFilterBetaOffset() );
+      rpcSlice->setDeblockingFilterTcOffsetDiv2( m_pcCfg->getLoopFilterTcOffset() );
+    }
+  }
+
+  rpcSlice->setDepth            ( iDepth );
+  
+  pcPic->setTLayer( m_pcCfg->getGOPEntry(iGOPid).m_temporalId );
+  if(eSliceType==I_SLICE)
+  {
+    pcPic->setTLayer(0);
+  }
+  rpcSlice->setTLayer( pcPic->getTLayer() );
+
+  assert( m_apcPicYuvPred );
+  assert( m_apcPicYuvResi );
+  
+  pcPic->setPicYuvPred( m_apcPicYuvPred );
+  pcPic->setPicYuvResi( m_apcPicYuvResi );
+  rpcSlice->setSliceMode            ( m_pcCfg->getSliceMode()            );
+  rpcSlice->setSliceArgument        ( m_pcCfg->getSliceArgument()        );
+  rpcSlice->setDependentSliceMode     ( m_pcCfg->getDependentSliceMode()     );
+  rpcSlice->setDependentSliceArgument ( m_pcCfg->getDependentSliceArgument() );
+  rpcSlice->setMaxNumMergeCand        ( m_pcCfg->getMaxNumMergeCand()        );
+  xStoreWPparam( pPPS->getUseWP(), pPPS->getWPBiPred() );
+}
+
+
+/**
+ - lambda re-computation based on rate control QP
+ */
+Void TEncSlice::xLamdaRecalculation(Int changeQP, Int idGOP, Int depth, SliceType eSliceType, TComSPS* pcSPS, TComSlice* pcSlice)
+{
+  Int qp;
+  Double recalQP= (Double)changeQP;
+  Double origQP = (Double)recalQP;
+  Double lambda;
+
+  // pre-compute lambda and QP values for all possible QP candidates
+  for ( Int deltqQpIdx = 0; deltqQpIdx < 2 * m_pcCfg->getDeltaQpRD() + 1; deltqQpIdx++ )
+  {
+    // compute QP value
+    recalQP = origQP + ((deltqQpIdx+1)>>1)*(deltqQpIdx%2 ? -1 : 1);
+
+    // compute lambda value
+    Int    NumberBFrames = ( m_pcCfg->getGOPSize() - 1 );
+    Int    SHIFT_QP = 12;
+    Double dLambda_scale = 1.0 - Clip3( 0.0, 0.5, 0.05*(Double)NumberBFrames );
+#if FULL_NBIT
+    Int    bitdepth_luma_qp_scale = 6 * (g_uiBitDepth - 8);
+#else
+    Int    bitdepth_luma_qp_scale = 0;
+#endif
+    Double qp_temp = (Double) recalQP + bitdepth_luma_qp_scale - SHIFT_QP;
+#if FULL_NBIT
+    Double qp_temp_orig = (Double) recalQP - SHIFT_QP;
+#endif
+    // Case #1: I or P-slices (key-frame)
+    Double dQPFactor = m_pcCfg->getGOPEntry(idGOP).m_QPFactor;
+    if ( eSliceType==I_SLICE )
+    {
+      dQPFactor=0.57*dLambda_scale;
+    }
+    lambda = dQPFactor*pow( 2.0, qp_temp/3.0 );
+
+    if ( depth>0 )
+    {
+#if FULL_NBIT
+      lambda *= Clip3( 2.00, 4.00, (qp_temp_orig / 6.0) ); // (j == B_SLICE && p_cur_frm->layer != 0 )
+#else
+      lambda *= Clip3( 2.00, 4.00, (qp_temp / 6.0) ); // (j == B_SLICE && p_cur_frm->layer != 0 )
+#endif
+    }
+
+    // if hadamard is used in ME process
+    if ( !m_pcCfg->getUseHADME() )
+    {
+      lambda *= 0.95;
+    }
+
+    qp = max( -pcSPS->getQpBDOffsetY(), min( MAX_QP, (Int) floor( recalQP + 0.5 ) ) );
+
+    m_pdRdPicLambda[deltqQpIdx] = lambda;
+    m_pdRdPicQp    [deltqQpIdx] = recalQP;
+    m_piRdPicQp    [deltqQpIdx] = qp;
+  }
+
+  // obtain dQP = 0 case
+  lambda  = m_pdRdPicLambda[0];
+  recalQP = m_pdRdPicQp    [0];
+  qp      = m_piRdPicQp    [0];
+
+  if( pcSlice->getSliceType( ) != I_SLICE )
+  {
+    lambda *= m_pcCfg->getLambdaModifier( depth );
+  }
+
+  // store lambda
+  m_pcRdCost ->setLambda( lambda );
+#if WEIGHTED_CHROMA_DISTORTION
+  // for RDO
+  // in RdCost there is only one lambda because the luma and chroma bits are not separated, instead we weight the distortion of chroma.
+  Double weight = 1.0;
+  if(qp >= 0)
+  {
+    weight = pow( 2.0, (qp-g_aucChromaScale[qp])/3.0 );  // takes into account of the chroma qp mapping without chroma qp Offset
+  }
+  m_pcRdCost ->setChromaDistortionWeight( weight );     
+#endif
+
+#if RDOQ_CHROMA_LAMBDA 
+  // for RDOQ
+  m_pcTrQuant->setLambda( lambda, lambda / weight );    
+#else
+  m_pcTrQuant->setLambda( lambda );
+#endif
+
+#if ALF_CHROMA_LAMBDA || SAO_CHROMA_LAMBDA
+  // For ALF or SAO
+  pcSlice   ->setLambda( lambda, lambda / weight );  
+#else
+  pcSlice   ->setLambda( lambda );
+#endif
+}
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+Void TEncSlice::setSearchRange( TComSlice* pcSlice )
+{
+  Int iCurrPOC = pcSlice->getPOC();
+  Int iRefPOC;
+  Int iGOPSize = m_pcCfg->getGOPSize();
+  Int iOffset = (iGOPSize >> 1);
+  Int iMaxSR = m_pcCfg->getSearchRange();
+  Int iNumPredDir = pcSlice->isInterP() ? 1 : 2;
+ 
+  for (Int iDir = 0; iDir <= iNumPredDir; iDir++)
+  {
+    //RefPicList e = (RefPicList)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);
+    }
+  }
+}
+
+/**
+ - multi-loop slice encoding for different slice QP
+ .
+ \param rpcPic    picture class
+ */
+Void TEncSlice::precompressSlice( TComPic*& rpcPic )
+{
+  // if deltaQP RD is not used, simply return
+  if ( m_pcCfg->getDeltaQpRD() == 0 )
+  {
+    return;
+  }
+  
+  TComSlice* pcSlice        = rpcPic->getSlice(getSliceIdx());
+  Double     dPicRdCostBest = MAX_DOUBLE;
+  UInt       uiQpIdxBest = 0;
+  
+  Double dFrameLambda;
+#if FULL_NBIT
+  Int    SHIFT_QP = 12 + 6 * (g_uiBitDepth - 8);
+#else
+  Int    SHIFT_QP = 12;
+#endif
+  
+  // set frame lambda
+  if (m_pcCfg->getGOPSize() > 1)
+  {
+    dFrameLambda = 0.68 * pow (2, (m_piRdPicQp[0]  - SHIFT_QP) / 3.0) * (pcSlice->isInterB()? 2 : 1);
+  }
+  else
+  {
+    dFrameLambda = 0.68 * pow (2, (m_piRdPicQp[0] - SHIFT_QP) / 3.0);
+  }
+  m_pcRdCost      ->setFrameLambda(dFrameLambda);
+  
+  // for each QP candidate
+  for ( UInt uiQpIdx = 0; uiQpIdx < 2 * m_pcCfg->getDeltaQpRD() + 1; uiQpIdx++ )
+  {
+    pcSlice       ->setSliceQp             ( m_piRdPicQp    [uiQpIdx] );
+#if ADAPTIVE_QP_SELECTION
+    pcSlice       ->setSliceQpBase         ( m_piRdPicQp    [uiQpIdx] );
+#endif
+    m_pcRdCost    ->setLambda              ( m_pdRdPicLambda[uiQpIdx] );
+#if WEIGHTED_CHROMA_DISTORTION
+    // for RDO
+    // in RdCost there is only one lambda because the luma and chroma bits are not separated, instead we weight the distortion of chroma.
+    int iQP = m_piRdPicQp    [uiQpIdx];
+    Double weight = 1.0;
+    if(iQP >= 0)
+    {
+      weight = pow( 2.0, (iQP-g_aucChromaScale[iQP])/3.0 );  // takes into account of the chroma qp mapping without chroma qp Offset
+    }
+    m_pcRdCost    ->setChromaDistortionWeight( weight );     
+#endif
+
+#if RDOQ_CHROMA_LAMBDA 
+    // for RDOQ
+    m_pcTrQuant   ->setLambda( m_pdRdPicLambda[uiQpIdx], m_pdRdPicLambda[uiQpIdx] / weight );
+#else
+    m_pcTrQuant   ->setLambda              ( m_pdRdPicLambda[uiQpIdx] );
+#endif
+#if ALF_CHROMA_LAMBDA || SAO_CHROMA_LAMBDA
+    // For ALF or SAO
+    pcSlice       ->setLambda              ( m_pdRdPicLambda[uiQpIdx], m_pdRdPicLambda[uiQpIdx] / weight ); 
+#else
+    pcSlice       ->setLambda              ( m_pdRdPicLambda[uiQpIdx] );
+#endif
+    
+    // try compress
+    compressSlice   ( rpcPic );
+    
+    Double dPicRdCost;
+    UInt64 uiPicDist        = m_uiPicDist;
+    UInt64 uiALFBits        = 0;
+    
+    m_pcGOPEncoder->preLoopFilterPicAll( rpcPic, uiPicDist, uiALFBits );
+    
+    // compute RD cost and choose the best
+    dPicRdCost = m_pcRdCost->calcRdCost64( m_uiPicTotalBits + uiALFBits, uiPicDist, true, DF_SSE_FRAME);
+    
+    if ( dPicRdCost < dPicRdCostBest )
+    {
+      uiQpIdxBest    = uiQpIdx;
+      dPicRdCostBest = dPicRdCost;
+    }
+  }
+  
+  // set best values
+  pcSlice       ->setSliceQp             ( m_piRdPicQp    [uiQpIdxBest] );
+#if ADAPTIVE_QP_SELECTION
+  pcSlice       ->setSliceQpBase         ( m_piRdPicQp    [uiQpIdxBest] );
+#endif
+  m_pcRdCost    ->setLambda              ( m_pdRdPicLambda[uiQpIdxBest] );
+#if WEIGHTED_CHROMA_DISTORTION
+  // in RdCost there is only one lambda because the luma and chroma bits are not separated, instead we weight the distortion of chroma.
+  int iQP = m_piRdPicQp    [uiQpIdxBest];
+  Double weight = 1.0;
+  if(iQP >= 0)
+  {
+    weight = pow( 2.0, (iQP-g_aucChromaScale[iQP])/3.0 );  // takes into account of the chroma qp mapping without chroma qp Offset
+  }
+  m_pcRdCost ->setChromaDistortionWeight( weight );     
+#endif
+
+#if RDOQ_CHROMA_LAMBDA 
+  // for RDOQ 
+  m_pcTrQuant   ->setLambda( m_pdRdPicLambda[uiQpIdxBest], m_pdRdPicLambda[uiQpIdxBest] / weight ); 
+#else
+  m_pcTrQuant   ->setLambda              ( m_pdRdPicLambda[uiQpIdxBest] );
+#endif
+#if ALF_CHROMA_LAMBDA || SAO_CHROMA_LAMBDA
+  // For ALF or SAO
+  pcSlice       ->setLambda              ( m_pdRdPicLambda[uiQpIdxBest], m_pdRdPicLambda[uiQpIdxBest] / weight ); 
+#else
+  pcSlice       ->setLambda              ( m_pdRdPicLambda[uiQpIdxBest] );
+#endif
+}
+
+/** \param rpcPic   picture class
+ */
+Void TEncSlice::compressSlice( TComPic*& rpcPic )
+{
+  UInt  uiCUAddr;
+  UInt   uiStartCUAddr;
+  UInt   uiBoundingCUAddr;
+  rpcPic->getSlice(getSliceIdx())->setDependentSliceCounter(0);
+  TEncBinCABAC* pppcRDSbacCoder = NULL;
+  TComSlice* pcSlice            = rpcPic->getSlice(getSliceIdx());
+  xDetermineStartAndBoundingCUAddr ( uiStartCUAddr, uiBoundingCUAddr, rpcPic, false );
+  
+  // initialize cost values
+  m_uiPicTotalBits  = 0;
+  m_dPicRdCost      = 0;
+  m_uiPicDist       = 0;
+  
+  // set entropy coder
+  if( m_pcCfg->getUseSBACRD() )
+  {
+    m_pcSbacCoder->init( m_pcBinCABAC );
+    m_pcEntropyCoder->setEntropyCoder   ( m_pcSbacCoder, pcSlice );
+    m_pcEntropyCoder->resetEntropy      ();
+    m_pppcRDSbacCoder[0][CI_CURR_BEST]->load(m_pcSbacCoder);
+    pppcRDSbacCoder = (TEncBinCABAC *) m_pppcRDSbacCoder[0][CI_CURR_BEST]->getEncBinIf();
+    pppcRDSbacCoder->setBinCountingEnableFlag( false );
+    pppcRDSbacCoder->setBinsCoded( 0 );
+  }
+  else
+  {
+    m_pcEntropyCoder->setEntropyCoder ( m_pcCavlcCoder, pcSlice );
+    m_pcEntropyCoder->resetEntropy      ();
+    m_pcEntropyCoder->setBitstream    ( m_pcBitCounter );
+  }
+  
+  //------------------------------------------------------------------------------
+  //  Weighted Prediction parameters estimation.
+  //------------------------------------------------------------------------------
+  // calculate AC/DC values for current picture
+  if( pcSlice->getPPS()->getUseWP() || pcSlice->getPPS()->getWPBiPred() )
+  {
+    xCalcACDCParamSlice(pcSlice);
+  }
+
+  Bool bWp_explicit = (pcSlice->getSliceType()==P_SLICE && pcSlice->getPPS()->getUseWP()) || (pcSlice->getSliceType()==B_SLICE && pcSlice->getPPS()->getWPBiPred());
+
+  if ( bWp_explicit )
+  {
+    //------------------------------------------------------------------------------
+    //  Weighted Prediction implemented at Slice level. SliceMode=2 is not supported yet.
+    //------------------------------------------------------------------------------
+    if ( pcSlice->getSliceMode()==2 || pcSlice->getDependentSliceMode()==2 )
+    {
+      printf("Weighted Prediction is not supported with slice mode determined by max number of bins.\n"); exit(0);
+    }
+
+    xEstimateWPParamSlice( pcSlice );
+    pcSlice->initWpScaling();
+
+    // check WP on/off
+    xCheckWPEnable( pcSlice );
+  }
+
+#if ADAPTIVE_QP_SELECTION
+  if( m_pcCfg->getUseAdaptQpSelect() )
+  {
+    m_pcTrQuant->clearSliceARLCnt();
+    if(pcSlice->getSliceType()!=I_SLICE)
+    {
+      Int qpBase = pcSlice->getSliceQpBase();
+      pcSlice->setSliceQp(qpBase + m_pcTrQuant->getQpDelta(qpBase));
+    }
+  }
+#endif
+  TEncTop* pcEncTop = (TEncTop*) m_pcCfg;
+  TEncSbac**** ppppcRDSbacCoders    = pcEncTop->getRDSbacCoders();
+  TComBitCounter* pcBitCounters     = pcEncTop->getBitCounters();
+  Int  iNumSubstreams = 1;
+  UInt uiTilesAcross  = 0;
+
+  if( m_pcCfg->getUseSBACRD() )
+  {
+    iNumSubstreams = pcSlice->getPPS()->getNumSubstreams();
+    uiTilesAcross = rpcPic->getPicSym()->getNumColumnsMinus1()+1;
+    delete[] m_pcBufferSbacCoders;
+    delete[] m_pcBufferBinCoderCABACs;
+    m_pcBufferSbacCoders     = new TEncSbac    [uiTilesAcross];
+    m_pcBufferBinCoderCABACs = new TEncBinCABAC[uiTilesAcross];
+    for (int ui = 0; ui < uiTilesAcross; ui++)
+    {
+      m_pcBufferSbacCoders[ui].init( &m_pcBufferBinCoderCABACs[ui] );
+    }
+    for (UInt ui = 0; ui < uiTilesAcross; ui++)
+    {
+      m_pcBufferSbacCoders[ui].load(m_pppcRDSbacCoder[0][CI_CURR_BEST]);  //init. state
+    }
+
+    for ( UInt ui = 0 ; ui < iNumSubstreams ; ui++ ) //init all sbac coders for RD optimization
+    {
+      ppppcRDSbacCoders[ui][0][CI_CURR_BEST]->load(m_pppcRDSbacCoder[0][CI_CURR_BEST]);
+    }
+  }
+  //if( m_pcCfg->getUseSBACRD() )
+  {
+    delete[] m_pcBufferLowLatSbacCoders;
+    delete[] m_pcBufferLowLatBinCoderCABACs;
+    m_pcBufferLowLatSbacCoders     = new TEncSbac    [uiTilesAcross];
+    m_pcBufferLowLatBinCoderCABACs = new TEncBinCABAC[uiTilesAcross];
+    for (int ui = 0; ui < uiTilesAcross; ui++)
+    {
+      m_pcBufferLowLatSbacCoders[ui].init( &m_pcBufferLowLatBinCoderCABACs[ui] );
+    }
+    for (UInt ui = 0; ui < uiTilesAcross; ui++)
+      m_pcBufferLowLatSbacCoders[ui].load(m_pppcRDSbacCoder[0][CI_CURR_BEST]);  //init. state
+  }
+  UInt uiWidthInLCUs  = rpcPic->getPicSym()->getFrameWidthInCU();
+  //UInt uiHeightInLCUs = rpcPic->getPicSym()->getFrameHeightInCU();
+  UInt uiCol=0, uiLin=0, uiSubStrm=0;
+  UInt uiTileCol      = 0;
+  UInt uiTileStartLCU = 0;
+  UInt uiTileLCUX     = 0;
+
+#if INTRA_BL
+  m_pcCuEncoder->setBaseRecPic( rpcPic->getLayerId() > 0 ? rpcPic->getFullPelBaseRec() : NULL);
+#endif
+
+
+#if DEPENDENT_SLICES
+  Bool bAllowDependence = false;
+#if TILES_WPP_ENTROPYSLICES_FLAGS
+  if( pcSlice->getPPS()->getDependentSliceEnabledFlag()&&(!pcSlice->getPPS()->getEntropySliceEnabledFlag()) )
+#else
+  if( pcSlice->getPPS()->getDependentSliceEnabledFlag()&&(!pcSlice->getPPS()->getCabacIndependentFlag()) )
+#endif
+  {
+    bAllowDependence = true;
+  }
+  if( bAllowDependence )
+  {
+    if(pcSlice->getDependentSliceCurStartCUAddr()!= pcSlice->getSliceCurStartCUAddr())
+    {
+      if( m_pcCfg->getWaveFrontsynchro() )
+      {
+        m_pcBufferSbacCoders[uiTileCol].loadContexts( CTXMem[1] );
+      }
+      m_pppcRDSbacCoder[0][CI_CURR_BEST]->loadContexts( CTXMem[0] );
+      if (pcSlice->getPPS()->getNumSubstreams() > 1)
+      {
+        Int iNumSubstreamsPerTile = iNumSubstreams/rpcPic->getPicSym()->getNumTiles();
+        uiCUAddr = rpcPic->getPicSym()->getCUOrderMap( uiStartCUAddr /rpcPic->getNumPartInCU()); 
+        uiLin     = uiCUAddr / uiWidthInLCUs;
+        uiSubStrm = rpcPic->getPicSym()->getTileIdxMap(rpcPic->getPicSym()->getCUOrderMap(uiCUAddr))*iNumSubstreamsPerTile
+          + uiLin%iNumSubstreamsPerTile;
+      }
+      ppppcRDSbacCoders[uiSubStrm][0][CI_CURR_BEST]->loadContexts( CTXMem[0] );
+    }
+    else
+    {
+      if(m_pcCfg->getWaveFrontsynchro())
+      {
+        CTXMem[1]->loadContexts(m_pcSbacCoder);
+      }
+      CTXMem[0]->loadContexts(m_pcSbacCoder);
+    }
+  }
+#endif
+  // for every CU in slice
+  UInt uiEncCUOrder;
+  uiCUAddr = rpcPic->getPicSym()->getCUOrderMap( uiStartCUAddr /rpcPic->getNumPartInCU()); 
+  for( uiEncCUOrder = uiStartCUAddr/rpcPic->getNumPartInCU();
+       uiEncCUOrder < (uiBoundingCUAddr+(rpcPic->getNumPartInCU()-1))/rpcPic->getNumPartInCU();
+       uiCUAddr = rpcPic->getPicSym()->getCUOrderMap(++uiEncCUOrder) )
+  {
+    // initialize CU encoder
+    TComDataCU*& pcCU = rpcPic->getCU( uiCUAddr );
+    pcCU->initCU( rpcPic, uiCUAddr );
+#if SVC_EXTENSION
+    pcCU->setLayerId(m_pcCfg->getLayerId());
+#endif
+
+    if(m_pcCfg->getUseRateCtrl())
+    {
+      if(m_pcRateCtrl->calculateUnitQP())
+      {
+        xLamdaRecalculation(m_pcRateCtrl->getUnitQP(), m_pcRateCtrl->getGOPId(), pcSlice->getDepth(), pcSlice->getSliceType(), pcSlice->getSPS(), pcSlice );
+      }
+    }
+    // inherit from TR if necessary, select substream to use.
+    if( m_pcCfg->getUseSBACRD() )
+    {
+      uiTileCol = rpcPic->getPicSym()->getTileIdxMap(uiCUAddr) % (rpcPic->getPicSym()->getNumColumnsMinus1()+1); // what column of tiles are we in?
+      uiTileStartLCU = rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(uiCUAddr))->getFirstCUAddr();
+      uiTileLCUX = uiTileStartLCU % uiWidthInLCUs;
+      //UInt uiSliceStartLCU = pcSlice->getSliceCurStartCUAddr();
+      uiCol     = uiCUAddr % uiWidthInLCUs;
+      uiLin     = uiCUAddr / uiWidthInLCUs;
+      if (pcSlice->getPPS()->getNumSubstreams() > 1)
+      {
+        // independent tiles => substreams are "per tile".  iNumSubstreams has already been multiplied.
+        Int iNumSubstreamsPerTile = iNumSubstreams/rpcPic->getPicSym()->getNumTiles();
+        uiSubStrm = rpcPic->getPicSym()->getTileIdxMap(uiCUAddr)*iNumSubstreamsPerTile
+                      + uiLin%iNumSubstreamsPerTile;
+      }
+      else
+      {
+        // dependent tiles => substreams are "per frame".
+        uiSubStrm = uiLin % iNumSubstreams;
+      }
+#if DEPENDENT_SLICES
+      if ( ((pcSlice->getPPS()->getNumSubstreams() > 1) || bAllowDependence ) && (uiCol == uiTileLCUX) && m_pcCfg->getWaveFrontsynchro())
+#else
+      if ( pcSlice->getPPS()->getNumSubstreams() > 1 && (uiCol == uiTileLCUX) )
+#endif
+      {
+        // We'll sync if the TR is available.
+        TComDataCU *pcCUUp = pcCU->getCUAbove();
+        UInt uiWidthInCU = rpcPic->getFrameWidthInCU();
+        UInt uiMaxParts = 1<<(pcSlice->getSPS()->getMaxCUDepth()<<1);
+        TComDataCU *pcCUTR = NULL;
+        if ( pcCUUp && ((uiCUAddr%uiWidthInCU+1) < uiWidthInCU)  )
+        {
+          pcCUTR = rpcPic->getCU( uiCUAddr - uiWidthInCU + 1 );
+        }
+        if ( ((pcCUTR==NULL) || (pcCUTR->getSlice()==NULL) || 
+             (pcCUTR->getSCUAddr()+uiMaxParts-1 < pcSlice->getSliceCurStartCUAddr()) ||
+             ((rpcPic->getPicSym()->getTileIdxMap( pcCUTR->getAddr() ) != rpcPic->getPicSym()->getTileIdxMap(uiCUAddr)))
+             )||
+             ((pcCUTR==NULL) || (pcCUTR->getSlice()==NULL) || 
+             (pcCUTR->getSCUAddr()+uiMaxParts-1 < pcSlice->getDependentSliceCurStartCUAddr()) ||
+             ((rpcPic->getPicSym()->getTileIdxMap( pcCUTR->getAddr() ) != rpcPic->getPicSym()->getTileIdxMap(uiCUAddr)))
+             )
+           )
+        {
+#if DEPENDENT_SLICES
+          if ( (uiCUAddr != 0) && (pcCUTR->getSCUAddr()+uiMaxParts-1 >= pcSlice->getSliceCurStartCUAddr())  && bAllowDependence)
+          {
+            ppppcRDSbacCoders[uiSubStrm][0][CI_CURR_BEST]->loadContexts( &m_pcBufferSbacCoders[uiTileCol] );
+          }
+#endif
+          // TR not available.
+        }
+        else
+        {
+          // TR is available, we use it.
+          ppppcRDSbacCoders[uiSubStrm][0][CI_CURR_BEST]->loadContexts( &m_pcBufferSbacCoders[uiTileCol] );
+        }
+      }
+      m_pppcRDSbacCoder[0][CI_CURR_BEST]->load( ppppcRDSbacCoders[uiSubStrm][0][CI_CURR_BEST] ); //this load is used to simplify the code
+    }
+
+    // reset the entropy coder
+    if( uiCUAddr == rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(uiCUAddr))->getFirstCUAddr() &&                                   // must be first CU of tile
+        uiCUAddr!=0 &&                                                                                                                                    // cannot be first CU of picture
+#if DEPENDENT_SLICES
+        uiCUAddr!=rpcPic->getPicSym()->getPicSCUAddr(rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getDependentSliceCurStartCUAddr())/rpcPic->getNumPartInCU() &&
+#endif
+        uiCUAddr!=rpcPic->getPicSym()->getPicSCUAddr(rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getSliceCurStartCUAddr())/rpcPic->getNumPartInCU())     // cannot be first CU of slice
+    {
+      SliceType sliceType = pcSlice->getSliceType();
+      if (!pcSlice->isIntra() && pcSlice->getPPS()->getCabacInitPresentFlag() && pcSlice->getPPS()->getEncCABACTableIdx()!=I_SLICE)
+      {
+        sliceType = (SliceType) pcSlice->getPPS()->getEncCABACTableIdx();
+      }
+      m_pcEntropyCoder->updateContextTables ( sliceType, pcSlice->getSliceQp(), false );
+      m_pcEntropyCoder->setEntropyCoder     ( m_pppcRDSbacCoder[0][CI_CURR_BEST], pcSlice );
+      m_pcEntropyCoder->updateContextTables ( sliceType, pcSlice->getSliceQp() );
+      m_pcEntropyCoder->setEntropyCoder     ( m_pcSbacCoder, pcSlice );
+    }
+    // if RD based on SBAC is used
+    if( m_pcCfg->getUseSBACRD() )
+    {
+      // set go-on entropy coder
+      m_pcEntropyCoder->setEntropyCoder ( m_pcRDGoOnSbacCoder, pcSlice );
+      m_pcEntropyCoder->setBitstream( &pcBitCounters[uiSubStrm] );
+      
+      ((TEncBinCABAC*)m_pcRDGoOnSbacCoder->getEncBinIf())->setBinCountingEnableFlag(true);
+      // run CU encoder
+      m_pcCuEncoder->compressCU( pcCU );
+      
+      // restore entropy coder to an initial stage
+      m_pcEntropyCoder->setEntropyCoder ( m_pppcRDSbacCoder[0][CI_CURR_BEST], pcSlice );
+      m_pcEntropyCoder->setBitstream( &pcBitCounters[uiSubStrm] );
+      m_pcCuEncoder->setBitCounter( &pcBitCounters[uiSubStrm] );
+      m_pcBitCounter = &pcBitCounters[uiSubStrm];
+      pppcRDSbacCoder->setBinCountingEnableFlag( true );
+      m_pcBitCounter->resetBits();
+      pppcRDSbacCoder->setBinsCoded( 0 );
+      m_pcCuEncoder->encodeCU( pcCU );
+
+      pppcRDSbacCoder->setBinCountingEnableFlag( false );
+      if (m_pcCfg->getSliceMode()==AD_HOC_SLICES_FIXED_NUMBER_OF_BYTES_IN_SLICE && ( ( pcSlice->getSliceBits() + m_pcEntropyCoder->getNumberOfWrittenBits() ) ) > m_pcCfg->getSliceArgument()<<3)
+      {
+        pcSlice->setNextSlice( true );
+        break;
+      }
+      if (m_pcCfg->getDependentSliceMode()==SHARP_MULTIPLE_CONSTRAINT_BASED_DEPENDENT_SLICE && pcSlice->getDependentSliceCounter()+pppcRDSbacCoder->getBinsCoded() > m_pcCfg->getDependentSliceArgument()&&pcSlice->getSliceCurEndCUAddr()!=pcSlice->getDependentSliceCurEndCUAddr())
+      {
+        pcSlice->setNextDependentSlice( true );
+        break;
+      }
+      if( m_pcCfg->getUseSBACRD() )
+      {
+         ppppcRDSbacCoders[uiSubStrm][0][CI_CURR_BEST]->load( m_pppcRDSbacCoder[0][CI_CURR_BEST] );
+       
+         //Store probabilties of second LCU in line into buffer
+#if DEPENDENT_SLICES
+         if ( ( uiCol == uiTileLCUX+1) && (bAllowDependence || (pcSlice->getPPS()->getNumSubstreams() > 1)) && m_pcCfg->getWaveFrontsynchro())
+#else
+        if (pcSlice->getPPS()->getNumSubstreams() > 1 && uiCol == uiTileLCUX+1)
+#endif
+        {
+          m_pcBufferSbacCoders[uiTileCol].loadContexts(ppppcRDSbacCoders[uiSubStrm][0][CI_CURR_BEST]);
+        }
+      }
+    }
+    // other case: encodeCU is not called
+    else
+    {
+      m_pcCuEncoder->compressCU( pcCU );
+      m_pcCuEncoder->encodeCU( pcCU );
+      if (m_pcCfg->getSliceMode()==AD_HOC_SLICES_FIXED_NUMBER_OF_BYTES_IN_SLICE && ( ( pcSlice->getSliceBits()+ m_pcEntropyCoder->getNumberOfWrittenBits() ) ) > m_pcCfg->getSliceArgument()<<3)
+      {
+        pcSlice->setNextSlice( true );
+        break;
+      }
+      if (m_pcCfg->getDependentSliceMode()==SHARP_MULTIPLE_CONSTRAINT_BASED_DEPENDENT_SLICE && pcSlice->getDependentSliceCounter()+ m_pcEntropyCoder->getNumberOfWrittenBits()> m_pcCfg->getDependentSliceArgument()&&pcSlice->getSliceCurEndCUAddr()!=pcSlice->getDependentSliceCurEndCUAddr())
+      {
+        pcSlice->setNextDependentSlice( true );
+        break;
+      }
+    }
+    
+    m_uiPicTotalBits += pcCU->getTotalBits();
+    m_dPicRdCost     += pcCU->getTotalCost();
+    m_uiPicDist      += pcCU->getTotalDistortion();
+    if(m_pcCfg->getUseRateCtrl())
+    {
+      m_pcRateCtrl->updateLCUData(pcCU, pcCU->getTotalBits(), pcCU->getQP(0));
+      m_pcRateCtrl->updataRCUnitStatus();
+    }
+  }
+#if DEPENDENT_SLICES
+  if ((pcSlice->getPPS()->getNumSubstreams() > 1) && !bAllowDependence)
+#else
+  if (pcSlice->getPPS()->getNumSubstreams() > 1)
+#endif
+  {
+    pcSlice->setNextSlice( true );
+  }
+#if DEPENDENT_SLICES
+  if( bAllowDependence )
+  {
+    if (m_pcCfg->getWaveFrontsynchro())
+    {
+      CTXMem[1]->loadContexts( &m_pcBufferSbacCoders[uiTileCol] );//ctx 2.LCU
+    }
+     CTXMem[0]->loadContexts( m_pppcRDSbacCoder[0][CI_CURR_BEST] );//ctx end of dep.slice
+  }
+#endif
+  xRestoreWPparam( pcSlice );
+  if(m_pcCfg->getUseRateCtrl())
+  {
+    m_pcRateCtrl->updateFrameData(m_uiPicTotalBits);
+  }
+}
+
+/**
+ \param  rpcPic        picture class
+ \retval rpcBitstream  bitstream class
+ */
+Void TEncSlice::encodeSlice   ( TComPic*& rpcPic, TComOutputBitstream* pcBitstream, TComOutputBitstream* pcSubstreams )
+{
+  UInt       uiCUAddr;
+  UInt       uiStartCUAddr;
+  UInt       uiBoundingCUAddr;
+  TComSlice* pcSlice = rpcPic->getSlice(getSliceIdx());
+
+  uiStartCUAddr=pcSlice->getDependentSliceCurStartCUAddr();
+  uiBoundingCUAddr=pcSlice->getDependentSliceCurEndCUAddr();
+  // choose entropy coder
+  {
+    m_pcSbacCoder->init( (TEncBinIf*)m_pcBinCABAC );
+    m_pcEntropyCoder->setEntropyCoder ( m_pcSbacCoder, pcSlice );
+  }
+  
+  m_pcCuEncoder->setBitCounter( NULL );
+  m_pcBitCounter = NULL;
+  // Appropriate substream bitstream is switched later.
+  // for every CU
+#if ENC_DEC_TRACE
+  g_bJustDoIt = g_bEncDecTraceEnable;
+#endif
+  DTRACE_CABAC_VL( g_nSymbolCounter++ );
+  DTRACE_CABAC_T( "\tPOC: " );
+  DTRACE_CABAC_V( rpcPic->getPOC() );
+  DTRACE_CABAC_T( "\n" );
+#if ENC_DEC_TRACE
+  g_bJustDoIt = g_bEncDecTraceDisable;
+#endif
+
+  TEncTop* pcEncTop = (TEncTop*) m_pcCfg;
+  TEncSbac* pcSbacCoders = pcEncTop->getSbacCoders(); //coder for each substream
+  Int iNumSubstreams = pcSlice->getPPS()->getNumSubstreams();
+  UInt uiBitsOriginallyInSubstreams = 0;
+  {
+    UInt uiTilesAcross = rpcPic->getPicSym()->getNumColumnsMinus1()+1;
+    for (UInt ui = 0; ui < uiTilesAcross; ui++)
+    {
+      m_pcBufferSbacCoders[ui].load(m_pcSbacCoder); //init. state
+    }
+    
+    for (Int iSubstrmIdx=0; iSubstrmIdx < iNumSubstreams; iSubstrmIdx++)
+    {
+      uiBitsOriginallyInSubstreams += pcSubstreams[iSubstrmIdx].getNumberOfWrittenBits();
+    }
+
+    for (UInt ui = 0; ui < uiTilesAcross; ui++)
+    {
+      m_pcBufferLowLatSbacCoders[ui].load(m_pcSbacCoder);  //init. state
+    }
+  }
+
+  UInt uiWidthInLCUs  = rpcPic->getPicSym()->getFrameWidthInCU();
+  UInt uiCol=0, uiLin=0, uiSubStrm=0;
+  UInt uiTileCol      = 0;
+  UInt uiTileStartLCU = 0;
+  UInt uiTileLCUX     = 0;
+#if DEPENDENT_SLICES
+  Bool bAllowDependence = false;
+#if TILES_WPP_ENTROPYSLICES_FLAGS
+  if( pcSlice->getPPS()->getDependentSliceEnabledFlag()&&(!pcSlice->getPPS()->getEntropySliceEnabledFlag()) )
+#else
+  if( pcSlice->getPPS()->getDependentSliceEnabledFlag()&&(!pcSlice->getPPS()->getCabacIndependentFlag()) )
+#endif
+  {
+    bAllowDependence = true;
+  }
+  if( bAllowDependence )
+  {
+    if(pcSlice->isNextSlice())
+    {
+      if(m_pcCfg->getWaveFrontsynchro())
+      {
+        CTXMem[1]->loadContexts(m_pcSbacCoder);
+      }
+      CTXMem[0]->loadContexts(m_pcSbacCoder);
+    }
+    else
+    {
+      if(m_pcCfg->getWaveFrontsynchro())
+      {
+        m_pcBufferSbacCoders[uiTileCol].loadContexts( CTXMem[1] );
+      }
+      if(pcSlice->getPPS()->getNumSubstreams() > 1)
+      {
+        Int iNumSubstreamsPerTile = iNumSubstreams/rpcPic->getPicSym()->getNumTiles();
+        uiCUAddr = rpcPic->getPicSym()->getCUOrderMap( uiStartCUAddr /rpcPic->getNumPartInCU());
+        uiLin     = uiCUAddr / uiWidthInLCUs;
+        uiSubStrm = rpcPic->getPicSym()->getTileIdxMap(rpcPic->getPicSym()->getCUOrderMap( uiCUAddr))*iNumSubstreamsPerTile
+          + uiLin%iNumSubstreamsPerTile;
+      }
+      pcSbacCoders[uiSubStrm].loadContexts( CTXMem[0] );
+    }
+  }
+#endif
+
+  UInt uiEncCUOrder;
+  uiCUAddr = rpcPic->getPicSym()->getCUOrderMap( uiStartCUAddr /rpcPic->getNumPartInCU());  /*for tiles, uiStartCUAddr is NOT the real raster scan address, it is actually
+                                                                                              an encoding order index, so we need to convert the index (uiStartCUAddr)
+                                                                                              into the real raster scan address (uiCUAddr) via the CUOrderMap*/
+  for( uiEncCUOrder = uiStartCUAddr /rpcPic->getNumPartInCU();
+       uiEncCUOrder < (uiBoundingCUAddr+rpcPic->getNumPartInCU()-1)/rpcPic->getNumPartInCU();
+       uiCUAddr = rpcPic->getPicSym()->getCUOrderMap(++uiEncCUOrder) )
+  {
+    if( m_pcCfg->getUseSBACRD() )
+    {
+      uiTileCol = rpcPic->getPicSym()->getTileIdxMap(uiCUAddr) % (rpcPic->getPicSym()->getNumColumnsMinus1()+1); // what column of tiles are we in?
+      uiTileStartLCU = rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(uiCUAddr))->getFirstCUAddr();
+      uiTileLCUX = uiTileStartLCU % uiWidthInLCUs;
+      //UInt uiSliceStartLCU = pcSlice->getSliceCurStartCUAddr();
+      uiCol     = uiCUAddr % uiWidthInLCUs;
+      uiLin     = uiCUAddr / uiWidthInLCUs;
+      if (pcSlice->getPPS()->getNumSubstreams() > 1)
+      {
+        // independent tiles => substreams are "per tile".  iNumSubstreams has already been multiplied.
+        Int iNumSubstreamsPerTile = iNumSubstreams/rpcPic->getPicSym()->getNumTiles();
+        uiSubStrm = rpcPic->getPicSym()->getTileIdxMap(uiCUAddr)*iNumSubstreamsPerTile
+                      + uiLin%iNumSubstreamsPerTile;
+      }
+      else
+      {
+        // dependent tiles => substreams are "per frame".
+        uiSubStrm = uiLin % iNumSubstreams;
+      }
+
+      m_pcEntropyCoder->setBitstream( &pcSubstreams[uiSubStrm] );
+      // Synchronize cabac probabilities with upper-right LCU if it's available and we're at the start of a line.
+#if DEPENDENT_SLICES
+      if (((pcSlice->getPPS()->getNumSubstreams() > 1) || bAllowDependence) && (uiCol == uiTileLCUX) && m_pcCfg->getWaveFrontsynchro())
+#else
+      if (pcSlice->getPPS()->getNumSubstreams() > 1 && (uiCol == uiTileLCUX))
+#endif
+      {
+        // We'll sync if the TR is available.
+        TComDataCU *pcCUUp = rpcPic->getCU( uiCUAddr )->getCUAbove();
+        UInt uiWidthInCU = rpcPic->getFrameWidthInCU();
+        UInt uiMaxParts = 1<<(pcSlice->getSPS()->getMaxCUDepth()<<1);
+        TComDataCU *pcCUTR = NULL;
+        if ( pcCUUp && ((uiCUAddr%uiWidthInCU+1) < uiWidthInCU)  )
+        {
+          pcCUTR = rpcPic->getCU( uiCUAddr - uiWidthInCU + 1 );
+        }
+        if ( (true/*bEnforceSliceRestriction*/ &&
+             ((pcCUTR==NULL) || (pcCUTR->getSlice()==NULL) || 
+             (pcCUTR->getSCUAddr()+uiMaxParts-1 < pcSlice->getSliceCurStartCUAddr()) ||
+             ((rpcPic->getPicSym()->getTileIdxMap( pcCUTR->getAddr() ) != rpcPic->getPicSym()->getTileIdxMap(uiCUAddr)))
+             ))||
+             (true/*bEnforceDependentSliceRestriction*/ &&
+             ((pcCUTR==NULL) || (pcCUTR->getSlice()==NULL) || 
+             (pcCUTR->getSCUAddr()+uiMaxParts-1 < pcSlice->getDependentSliceCurStartCUAddr()) ||
+             ((rpcPic->getPicSym()->getTileIdxMap( pcCUTR->getAddr() ) != rpcPic->getPicSym()->getTileIdxMap(uiCUAddr)))
+             ))
+           )
+        {
+#if DEPENDENT_SLICES
+          if ( (uiCUAddr != 0) && ( pcCUTR->getSCUAddr()+uiMaxParts-1 >= pcSlice->getSliceCurStartCUAddr() ) && bAllowDependence)
+          {
+            pcSbacCoders[uiSubStrm].loadContexts( &m_pcBufferSbacCoders[uiTileCol] );
+          }
+#endif
+          // TR not available.
+        }
+        else
+        {
+          // TR is available, we use it.
+          pcSbacCoders[uiSubStrm].loadContexts( &m_pcBufferSbacCoders[uiTileCol] );
+        }
+      }
+      m_pcSbacCoder->load(&pcSbacCoders[uiSubStrm]);  //this load is used to simplify the code (avoid to change all the call to m_pcSbacCoder)
+    }
+    // reset the entropy coder
+    if( uiCUAddr == rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(uiCUAddr))->getFirstCUAddr() &&                                   // must be first CU of tile
+        uiCUAddr!=0 &&                                                                                                                                    // cannot be first CU of picture
+#if DEPENDENT_SLICES
+        uiCUAddr!=rpcPic->getPicSym()->getPicSCUAddr(rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getDependentSliceCurStartCUAddr())/rpcPic->getNumPartInCU() &&
+#endif
+        uiCUAddr!=rpcPic->getPicSym()->getPicSCUAddr(rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getSliceCurStartCUAddr())/rpcPic->getNumPartInCU())     // cannot be first CU of slice
+    {
+      {
+        // We're crossing into another tile, tiles are independent.
+        // When tiles are independent, we have "substreams per tile".  Each substream has already been terminated, and we no longer
+        // have to perform it here.
+        if (pcSlice->getPPS()->getNumSubstreams() > 1)
+        {
+          ; // do nothing.
+        }
+        else
+        {
+          SliceType sliceType  = pcSlice->getSliceType();
+          if (!pcSlice->isIntra() && pcSlice->getPPS()->getCabacInitPresentFlag() && pcSlice->getPPS()->getEncCABACTableIdx()!=I_SLICE)
+          {
+            sliceType = (SliceType) pcSlice->getPPS()->getEncCABACTableIdx();
+          }
+          m_pcEntropyCoder->updateContextTables( sliceType, pcSlice->getSliceQp() );
+#if BYTE_ALIGNMENT
+          // Byte-alignment in slice_data() when new tile
+          pcSubstreams[uiSubStrm].writeByteAlignment();
+#else
+          pcSubstreams[uiSubStrm].write( 1, 1 );
+          pcSubstreams[uiSubStrm].writeAlignZero();
+#endif
+        }
+      }
+      {
+          UInt uiCounter = 0;
+          vector<uint8_t>& rbsp   = pcSubstreams[uiSubStrm].getFIFO();
+          for (vector<uint8_t>::iterator it = rbsp.begin(); it != rbsp.end();)
+          {
+            /* 1) find the next emulated 00 00 {00,01,02,03}
+             * 2a) if not found, write all remaining bytes out, stop.
+             * 2b) otherwise, write all non-emulated bytes out
+             * 3) insert emulation_prevention_three_byte
+             */
+            vector<uint8_t>::iterator found = it;
+            do
+            {
+              /* NB, end()-1, prevents finding a trailing two byte sequence */
+              found = search_n(found, rbsp.end()-1, 2, 0);
+              found++;
+              /* if not found, found == end, otherwise found = second zero byte */
+              if (found == rbsp.end())
+              {
+                break;
+              }
+              if (*(++found) <= 3)
+              {
+                break;
+              }
+            } while (true);
+            it = found;
+            if (found != rbsp.end())
+            {
+              it++;
+              uiCounter++;
+            }
+          }
+        
+        UInt uiAccumulatedSubstreamLength = 0;
+        for (Int iSubstrmIdx=0; iSubstrmIdx < iNumSubstreams; iSubstrmIdx++)
+        {
+          uiAccumulatedSubstreamLength += pcSubstreams[iSubstrmIdx].getNumberOfWrittenBits();
+        }
+        // add bits coded in previous dependent slices + bits coded so far
+        // add number of emulation prevention byte count in the tile
+        pcSlice->addTileLocation( ((pcSlice->getTileOffstForMultES() + uiAccumulatedSubstreamLength - uiBitsOriginallyInSubstreams) >> 3) + uiCounter );
+      }
+    }
+
+    TComDataCU*& pcCU = rpcPic->getCU( uiCUAddr );    
+#if !SAO_LUM_CHROMA_ONOFF_FLAGS
+    if ( pcSlice->getSPS()->getUseSAO() && pcSlice->getSaoEnabledFlag() )
+#else
+    if ( pcSlice->getSPS()->getUseSAO() && (pcSlice->getSaoEnabledFlag()||pcSlice->getSaoEnabledFlagChroma()) )
+#endif
+    {
+#if REMOVE_APS
+      SAOParam *saoParam = pcSlice->getPic()->getPicSym()->getSaoParam();
+#else
+      SAOParam *saoParam = pcSlice->getAPS()->getSaoParam();
+#endif
+      Int iNumCuInWidth     = saoParam->numCuInWidth;
+      Int iCUAddrInSlice    = uiCUAddr - rpcPic->getPicSym()->getCUOrderMap(pcSlice->getSliceCurStartCUAddr()/rpcPic->getNumPartInCU());
+      Int iCUAddrUpInSlice  = iCUAddrInSlice - iNumCuInWidth;
+      Int rx = uiCUAddr % iNumCuInWidth;
+      Int ry = uiCUAddr / iNumCuInWidth;
+      Int allowMergeLeft = 1;
+      Int allowMergeUp   = 1;
+      if (rx!=0)
+      {
+        if (rpcPic->getPicSym()->getTileIdxMap(uiCUAddr-1) != rpcPic->getPicSym()->getTileIdxMap(uiCUAddr))
+        {
+          allowMergeLeft = 0;
+        }
+      }
+      if (ry!=0)
+      {
+        if (rpcPic->getPicSym()->getTileIdxMap(uiCUAddr-iNumCuInWidth) != rpcPic->getPicSym()->getTileIdxMap(uiCUAddr))
+        {
+          allowMergeUp = 0;
+        }
+      }
+      Int addr = pcCU->getAddr();
+#if SAO_SINGLE_MERGE
+      allowMergeLeft = allowMergeLeft && (rx>0) && (iCUAddrInSlice!=0);
+      allowMergeUp = allowMergeUp && (ry>0) && (iCUAddrUpInSlice>=0);
+#if SAO_TYPE_SHARING
+      if( saoParam->bSaoFlag[0] || saoParam->bSaoFlag[1] )
+#else
+      if( saoParam->bSaoFlag[0] || saoParam->bSaoFlag[1] || saoParam->bSaoFlag[2])
+#endif
+      {
+        Int mergeLeft = saoParam->saoLcuParam[0][addr].mergeLeftFlag;
+        Int mergeUp = saoParam->saoLcuParam[0][addr].mergeUpFlag;
+        if (allowMergeLeft)
+        {
+#if SAO_MERGE_ONE_CTX
+          m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMerge(mergeLeft); 
+#else
+          m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMergeLeft(mergeLeft, 0); 
+#endif
+        }
+        else
+        {
+          mergeLeft = 0;
+        }
+        if(mergeLeft == 0)
+        {
+          if (allowMergeUp)
+          {
+#if SAO_MERGE_ONE_CTX
+            m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMerge(mergeUp);
+#else
+            m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMergeUp(mergeUp);
+#endif
+          }
+          else
+          {
+            mergeUp = 0;
+          }
+          if(mergeUp == 0)
+          {
+            for (Int compIdx=0;compIdx<3;compIdx++)
+            {
+#if SAO_TYPE_SHARING
+            if( (compIdx == 0 && saoParam->bSaoFlag[0]) || (compIdx > 0 && saoParam->bSaoFlag[1]))
+#else
+            if( saoParam->bSaoFlag[compIdx])
+#endif
+              {
+#if SAO_TYPE_SHARING
+                m_pcEntropyCoder->encodeSaoOffset(&saoParam->saoLcuParam[compIdx][addr], compIdx);
+#else
+                m_pcEntropyCoder->encodeSaoOffset(&saoParam->saoLcuParam[compIdx][addr]);
+#endif
+              }
+            }
+          }
+        }
+      }
+#else
+      m_pcEntropyCoder->encodeSaoUnitInterleaving(0, saoParam->bSaoFlag[0], rx, ry, &(saoParam->saoLcuParam[0][addr]), iCUAddrInSlice, iCUAddrUpInSlice, allowMergeLeft, allowMergeUp);
+      m_pcEntropyCoder->encodeSaoUnitInterleaving(1, saoParam->bSaoFlag[1], rx, ry, &(saoParam->saoLcuParam[1][addr]), iCUAddrInSlice, iCUAddrUpInSlice, allowMergeLeft, allowMergeUp);
+      m_pcEntropyCoder->encodeSaoUnitInterleaving(2, saoParam->bSaoFlag[2], rx, ry, &(saoParam->saoLcuParam[2][addr]), iCUAddrInSlice, iCUAddrUpInSlice, allowMergeLeft, allowMergeUp);
+#endif
+    }
+#if ENC_DEC_TRACE
+    g_bJustDoIt = g_bEncDecTraceEnable;
+#endif
+#if !REMOVE_ALF
+    if( pcSlice->getSPS()->getUseALF())
+    {
+      for(Int compIdx=0; compIdx< 3; compIdx++)
+      {
+        if(pcSlice->getAlfEnabledFlag(compIdx))
+        {
+          m_pcEntropyCoder->encodeAlfCtrlFlag(compIdx, pcCU->getAlfLCUEnabled(compIdx)?1:0);
+        }
+      }
+    }
+#endif
+    if ( (m_pcCfg->getSliceMode()!=0 || m_pcCfg->getDependentSliceMode()!=0) &&
+      uiCUAddr == rpcPic->getPicSym()->getCUOrderMap((uiBoundingCUAddr+rpcPic->getNumPartInCU()-1)/rpcPic->getNumPartInCU()-1) )
+    {
+      m_pcCuEncoder->encodeCU( pcCU, true );
+    }
+    else
+    {
+      m_pcCuEncoder->encodeCU( pcCU );
+    }
+#if ENC_DEC_TRACE
+    g_bJustDoIt = g_bEncDecTraceDisable;
+#endif    
+    if( m_pcCfg->getUseSBACRD() )
+    {
+       pcSbacCoders[uiSubStrm].load(m_pcSbacCoder);   //load back status of the entropy coder after encoding the LCU into relevant bitstream entropy coder
+       
+
+       //Store probabilties of second LCU in line into buffer
+#if DEPENDENT_SLICES
+       if ( (bAllowDependence || (pcSlice->getPPS()->getNumSubstreams() > 1)) && (uiCol == uiTileLCUX+1) && m_pcCfg->getWaveFrontsynchro())
+#else
+      if (pcSlice->getPPS()->getNumSubstreams() > 1 && (uiCol == uiTileLCUX+1))
+#endif
+      {
+        m_pcBufferSbacCoders[uiTileCol].loadContexts( &pcSbacCoders[uiSubStrm] );
+      }
+    }
+  }
+#if DEPENDENT_SLICES
+  if( bAllowDependence )
+  {
+    if (m_pcCfg->getWaveFrontsynchro())
+    {
+      CTXMem[1]->loadContexts( &m_pcBufferSbacCoders[uiTileCol] );//ctx 2.LCU
+    }
+    CTXMem[0]->loadContexts( m_pcSbacCoder );//ctx end of dep.slice
+  }
+#endif
+#if ADAPTIVE_QP_SELECTION
+  if( m_pcCfg->getUseAdaptQpSelect() )
+  {
+    m_pcTrQuant->storeSliceQpNext(pcSlice);
+  }
+#endif
+  if (pcSlice->getPPS()->getCabacInitPresentFlag())
+  {
+    if  (pcSlice->getPPS()->getDependentSliceEnabledFlag())
+    {
+      pcSlice->getPPS()->setEncCABACTableIdx( pcSlice->getSliceType() );
+    }
+    else
+    {
+      m_pcEntropyCoder->determineCabacInitIdx();
+    }
+  }
+}
+
+/** Determines the starting and bounding LCU address of current slice / dependent slice
+ * \param bEncodeSlice Identifies if the calling function is compressSlice() [false] or encodeSlice() [true]
+ * \returns Updates uiStartCUAddr, uiBoundingCUAddr with appropriate LCU address
+ */
+Void TEncSlice::xDetermineStartAndBoundingCUAddr  ( UInt& uiStartCUAddr, UInt& uiBoundingCUAddr, TComPic*& rpcPic, Bool bEncodeSlice )
+{
+  TComSlice* pcSlice = rpcPic->getSlice(getSliceIdx());
+  UInt uiStartCUAddrSlice, uiBoundingCUAddrSlice;
+  UInt tileIdxIncrement;
+  UInt tileIdx;
+  UInt tileWidthInLcu;
+  UInt tileHeightInLcu;
+  UInt tileTotalCount;
+
+  uiStartCUAddrSlice        = pcSlice->getSliceCurStartCUAddr();
+  UInt uiNumberOfCUsInFrame = rpcPic->getNumCUsInFrame();
+  uiBoundingCUAddrSlice     = uiNumberOfCUsInFrame;
+  if (bEncodeSlice) 
+  {
+    UInt uiCUAddrIncrement;
+    switch (m_pcCfg->getSliceMode())
+    {
+    case AD_HOC_SLICES_FIXED_NUMBER_OF_LCU_IN_SLICE:
+      uiCUAddrIncrement        = m_pcCfg->getSliceArgument();
+      uiBoundingCUAddrSlice    = ((uiStartCUAddrSlice + uiCUAddrIncrement) < uiNumberOfCUsInFrame*rpcPic->getNumPartInCU()) ? (uiStartCUAddrSlice + uiCUAddrIncrement) : uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
+      break;
+    case AD_HOC_SLICES_FIXED_NUMBER_OF_BYTES_IN_SLICE:
+      uiCUAddrIncrement        = rpcPic->getNumCUsInFrame();
+      uiBoundingCUAddrSlice    = pcSlice->getSliceCurEndCUAddr();
+      break;
+    case AD_HOC_SLICES_FIXED_NUMBER_OF_TILES_IN_SLICE:
+      tileIdx                = rpcPic->getPicSym()->getTileIdxMap(
+        rpcPic->getPicSym()->getCUOrderMap(uiStartCUAddrSlice/rpcPic->getNumPartInCU())
+        );
+      uiCUAddrIncrement        = 0;
+      tileTotalCount         = (rpcPic->getPicSym()->getNumColumnsMinus1()+1) * (rpcPic->getPicSym()->getNumRowsMinus1()+1);
+
+      for(tileIdxIncrement = 0; tileIdxIncrement < m_pcCfg->getSliceArgument(); tileIdxIncrement++)
+      {
+        if((tileIdx + tileIdxIncrement) < tileTotalCount)
+        {
+          tileWidthInLcu   = rpcPic->getPicSym()->getTComTile(tileIdx + tileIdxIncrement)->getTileWidth();
+          tileHeightInLcu  = rpcPic->getPicSym()->getTComTile(tileIdx + tileIdxIncrement)->getTileHeight();
+#if REMOVE_FGS
+          uiCUAddrIncrement += (tileWidthInLcu * tileHeightInLcu * rpcPic->getNumPartInCU());
+#else
+          uiCUAddrIncrement += (tileWidthInLcu * tileHeightInLcu * rpcPic->getNumPartInCU()) >> (m_pcCfg->getSliceGranularity() << 1);
+#endif
+        }
+      }
+
+      uiBoundingCUAddrSlice    = ((uiStartCUAddrSlice + uiCUAddrIncrement) < uiNumberOfCUsInFrame*rpcPic->getNumPartInCU()) ? (uiStartCUAddrSlice + uiCUAddrIncrement) : uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
+      break;
+    default:
+      uiCUAddrIncrement        = rpcPic->getNumCUsInFrame();
+      uiBoundingCUAddrSlice    = uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
+      break;
+    } 
+    pcSlice->setSliceCurEndCUAddr( uiBoundingCUAddrSlice );
+  }
+  else
+  {
+    UInt uiCUAddrIncrement     ;
+    switch (m_pcCfg->getSliceMode())
+    {
+    case AD_HOC_SLICES_FIXED_NUMBER_OF_LCU_IN_SLICE:
+      uiCUAddrIncrement        = m_pcCfg->getSliceArgument();
+      uiBoundingCUAddrSlice    = ((uiStartCUAddrSlice + uiCUAddrIncrement) < uiNumberOfCUsInFrame*rpcPic->getNumPartInCU()) ? (uiStartCUAddrSlice + uiCUAddrIncrement) : uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
+      break;
+    case AD_HOC_SLICES_FIXED_NUMBER_OF_TILES_IN_SLICE:
+      tileIdx                = rpcPic->getPicSym()->getTileIdxMap(
+        rpcPic->getPicSym()->getCUOrderMap(uiStartCUAddrSlice/rpcPic->getNumPartInCU())
+        );
+      uiCUAddrIncrement        = 0;
+      tileTotalCount         = (rpcPic->getPicSym()->getNumColumnsMinus1()+1) * (rpcPic->getPicSym()->getNumRowsMinus1()+1);
+
+      for(tileIdxIncrement = 0; tileIdxIncrement < m_pcCfg->getSliceArgument(); tileIdxIncrement++)
+      {
+        if((tileIdx + tileIdxIncrement) < tileTotalCount)
+        {
+          tileWidthInLcu   = rpcPic->getPicSym()->getTComTile(tileIdx + tileIdxIncrement)->getTileWidth();
+          tileHeightInLcu  = rpcPic->getPicSym()->getTComTile(tileIdx + tileIdxIncrement)->getTileHeight();
+#if REMOVE_FGS
+          uiCUAddrIncrement += (tileWidthInLcu * tileHeightInLcu * rpcPic->getNumPartInCU());
+#else
+          uiCUAddrIncrement += (tileWidthInLcu * tileHeightInLcu * rpcPic->getNumPartInCU()) >> (m_pcCfg->getSliceGranularity() << 1);
+#endif
+        }
+      }
+
+      uiBoundingCUAddrSlice    = ((uiStartCUAddrSlice + uiCUAddrIncrement) < uiNumberOfCUsInFrame*rpcPic->getNumPartInCU()) ? (uiStartCUAddrSlice + uiCUAddrIncrement) : uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
+      break;
+    default:
+      uiCUAddrIncrement        = rpcPic->getNumCUsInFrame();
+      uiBoundingCUAddrSlice    = uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
+      break;
+    } 
+    // set the slice end address to the end of the SCU row if the slice does not start at the beginning of an SCU row
+    if (pcSlice->getPPS()->getNumSubstreams() > 1 && (uiStartCUAddrSlice % (rpcPic->getFrameWidthInCU()*rpcPic->getNumPartInCU()) != 0))
+    {
+      uiBoundingCUAddrSlice = uiStartCUAddrSlice - (uiStartCUAddrSlice % (rpcPic->getFrameWidthInCU()*rpcPic->getNumPartInCU())) + (rpcPic->getFrameWidthInCU()*rpcPic->getNumPartInCU());
+    }
+    pcSlice->setSliceCurEndCUAddr( uiBoundingCUAddrSlice );
+  }
+
+  Bool tileBoundary = false;
+  if ((m_pcCfg->getSliceMode() == AD_HOC_SLICES_FIXED_NUMBER_OF_LCU_IN_SLICE || m_pcCfg->getSliceMode() == AD_HOC_SLICES_FIXED_NUMBER_OF_BYTES_IN_SLICE) && 
+      (m_pcCfg->getNumRowsMinus1() > 0 || m_pcCfg->getNumColumnsMinus1() > 0))
+  {
+    UInt lcuEncAddr = (uiStartCUAddrSlice+rpcPic->getNumPartInCU()-1)/rpcPic->getNumPartInCU();
+    UInt lcuAddr = rpcPic->getPicSym()->getCUOrderMap(lcuEncAddr);
+    UInt startTileIdx = rpcPic->getPicSym()->getTileIdxMap(lcuAddr);
+    UInt tileBoundingCUAddrSlice = 0;
+    while (lcuEncAddr < uiNumberOfCUsInFrame && rpcPic->getPicSym()->getTileIdxMap(lcuAddr) == startTileIdx)
+    {
+      lcuEncAddr++;
+      lcuAddr = rpcPic->getPicSym()->getCUOrderMap(lcuEncAddr);
+    }
+    tileBoundingCUAddrSlice = lcuEncAddr*rpcPic->getNumPartInCU();
+    
+    if (tileBoundingCUAddrSlice < uiBoundingCUAddrSlice)
+    {
+      uiBoundingCUAddrSlice = tileBoundingCUAddrSlice;
+      pcSlice->setSliceCurEndCUAddr( uiBoundingCUAddrSlice );
+      tileBoundary = true;
+    }
+  }
+
+  // Dependent slice
+  UInt uiStartCUAddrDependentSlice, uiBoundingCUAddrDependentSlice;
+  uiStartCUAddrDependentSlice    = pcSlice->getDependentSliceCurStartCUAddr();
+  uiBoundingCUAddrDependentSlice = uiNumberOfCUsInFrame;
+  if (bEncodeSlice) 
+  {
+    UInt uiCUAddrIncrement;
+    switch (m_pcCfg->getDependentSliceMode())
+    {
+    case SHARP_FIXED_NUMBER_OF_LCU_IN_DEPENDENT_SLICE:
+      uiCUAddrIncrement               = m_pcCfg->getDependentSliceArgument();
+      uiBoundingCUAddrDependentSlice    = ((uiStartCUAddrDependentSlice + uiCUAddrIncrement) < uiNumberOfCUsInFrame*rpcPic->getNumPartInCU() ) ? (uiStartCUAddrDependentSlice + uiCUAddrIncrement) : uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
+      break;
+    case SHARP_MULTIPLE_CONSTRAINT_BASED_DEPENDENT_SLICE:
+      uiCUAddrIncrement               = rpcPic->getNumCUsInFrame();
+      uiBoundingCUAddrDependentSlice    = pcSlice->getDependentSliceCurEndCUAddr();
+      break;
+#if DEPENDENT_SLICES
+    case FIXED_NUMBER_OF_TILES_IN_DEPENDENT_SLICE:
+      tileIdx                = rpcPic->getPicSym()->getTileIdxMap(
+        rpcPic->getPicSym()->getCUOrderMap(pcSlice->getDependentSliceCurStartCUAddr()/rpcPic->getNumPartInCU())
+        );
+      uiCUAddrIncrement        = 0;
+      tileTotalCount         = (rpcPic->getPicSym()->getNumColumnsMinus1()+1) * (rpcPic->getPicSym()->getNumRowsMinus1()+1);
+
+      for(tileIdxIncrement = 0; tileIdxIncrement < m_pcCfg->getDependentSliceArgument(); tileIdxIncrement++)
+      {
+        if((tileIdx + tileIdxIncrement) < tileTotalCount)
+        {
+          tileWidthInLcu   = rpcPic->getPicSym()->getTComTile(tileIdx + tileIdxIncrement)->getTileWidth();
+          tileHeightInLcu  = rpcPic->getPicSym()->getTComTile(tileIdx + tileIdxIncrement)->getTileHeight();
+#if REMOVE_FGS
+          uiCUAddrIncrement += (tileWidthInLcu * tileHeightInLcu * rpcPic->getNumPartInCU());
+#else
+          uiCUAddrIncrement += (tileWidthInLcu * tileHeightInLcu * rpcPic->getNumPartInCU()) >> (m_pcCfg->getSliceGranularity() << 1);
+#endif
+        }
+      }
+      uiBoundingCUAddrDependentSlice    = ((uiStartCUAddrDependentSlice + uiCUAddrIncrement) < uiNumberOfCUsInFrame*rpcPic->getNumPartInCU() ) ? (uiStartCUAddrDependentSlice + uiCUAddrIncrement) : uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
+      break;
+#endif
+    default:
+      uiCUAddrIncrement               = rpcPic->getNumCUsInFrame();
+      uiBoundingCUAddrDependentSlice    = uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
+      break;
+    } 
+    pcSlice->setDependentSliceCurEndCUAddr( uiBoundingCUAddrDependentSlice );
+  }
+  else
+  {
+    UInt uiCUAddrIncrement;
+    switch (m_pcCfg->getDependentSliceMode())
+    {
+    case SHARP_FIXED_NUMBER_OF_LCU_IN_DEPENDENT_SLICE:
+      uiCUAddrIncrement               = m_pcCfg->getDependentSliceArgument();
+      uiBoundingCUAddrDependentSlice    = ((uiStartCUAddrDependentSlice + uiCUAddrIncrement) < uiNumberOfCUsInFrame*rpcPic->getNumPartInCU() ) ? (uiStartCUAddrDependentSlice + uiCUAddrIncrement) : uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
+      break;
+#if DEPENDENT_SLICES
+    case FIXED_NUMBER_OF_TILES_IN_DEPENDENT_SLICE:
+      tileIdx                = rpcPic->getPicSym()->getTileIdxMap(
+        rpcPic->getPicSym()->getCUOrderMap(pcSlice->getDependentSliceCurStartCUAddr()/rpcPic->getNumPartInCU())
+        );
+      uiCUAddrIncrement        = 0;
+      tileTotalCount         = (rpcPic->getPicSym()->getNumColumnsMinus1()+1) * (rpcPic->getPicSym()->getNumRowsMinus1()+1);
+
+      for(tileIdxIncrement = 0; tileIdxIncrement < m_pcCfg->getDependentSliceArgument(); tileIdxIncrement++)
+      {
+        if((tileIdx + tileIdxIncrement) < tileTotalCount)
+        {
+          tileWidthInLcu   = rpcPic->getPicSym()->getTComTile(tileIdx + tileIdxIncrement)->getTileWidth();
+          tileHeightInLcu  = rpcPic->getPicSym()->getTComTile(tileIdx + tileIdxIncrement)->getTileHeight();
+#if REMOVE_FGS
+          uiCUAddrIncrement += (tileWidthInLcu * tileHeightInLcu * rpcPic->getNumPartInCU());
+#else
+          uiCUAddrIncrement += (tileWidthInLcu * tileHeightInLcu * rpcPic->getNumPartInCU()) >> (m_pcCfg->getSliceGranularity() << 1);
+#endif
+        }
+      }
+      uiBoundingCUAddrDependentSlice    = ((uiStartCUAddrDependentSlice + uiCUAddrIncrement) < uiNumberOfCUsInFrame*rpcPic->getNumPartInCU() ) ? (uiStartCUAddrDependentSlice + uiCUAddrIncrement) : uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
+      break;
+#endif
+    default:
+      uiCUAddrIncrement               = rpcPic->getNumCUsInFrame();
+      uiBoundingCUAddrDependentSlice    = uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
+      break;
+    } 
+    pcSlice->setDependentSliceCurEndCUAddr( uiBoundingCUAddrDependentSlice );
+  }
+  if(uiBoundingCUAddrDependentSlice>uiBoundingCUAddrSlice)
+  {
+    uiBoundingCUAddrDependentSlice = uiBoundingCUAddrSlice;
+    pcSlice->setDependentSliceCurEndCUAddr(uiBoundingCUAddrSlice);
+  }
+  //calculate real dependent slice start address
+  UInt uiInternalAddress = rpcPic->getPicSym()->getPicSCUAddr(pcSlice->getDependentSliceCurStartCUAddr()) % rpcPic->getNumPartInCU();
+  UInt uiExternalAddress = rpcPic->getPicSym()->getPicSCUAddr(pcSlice->getDependentSliceCurStartCUAddr()) / rpcPic->getNumPartInCU();
+  UInt uiPosX = ( uiExternalAddress % rpcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
+  UInt uiPosY = ( uiExternalAddress / rpcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
+  UInt uiWidth = pcSlice->getSPS()->getPicWidthInLumaSamples();
+  UInt uiHeight = pcSlice->getSPS()->getPicHeightInLumaSamples();
+  while((uiPosX>=uiWidth||uiPosY>=uiHeight)&&!(uiPosX>=uiWidth&&uiPosY>=uiHeight))
+  {
+    uiInternalAddress++;
+    if(uiInternalAddress>=rpcPic->getNumPartInCU())
+    {
+      uiInternalAddress=0;
+      uiExternalAddress = rpcPic->getPicSym()->getCUOrderMap(rpcPic->getPicSym()->getInverseCUOrderMap(uiExternalAddress)+1);
+    }
+    uiPosX = ( uiExternalAddress % rpcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
+    uiPosY = ( uiExternalAddress / rpcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
+  }
+  UInt uiRealStartAddress = rpcPic->getPicSym()->getPicSCUEncOrder(uiExternalAddress*rpcPic->getNumPartInCU()+uiInternalAddress);
+  
+  pcSlice->setDependentSliceCurStartCUAddr(uiRealStartAddress);
+  uiStartCUAddrDependentSlice=uiRealStartAddress;
+  
+  //calculate real slice start address
+  uiInternalAddress = rpcPic->getPicSym()->getPicSCUAddr(pcSlice->getSliceCurStartCUAddr()) % rpcPic->getNumPartInCU();
+  uiExternalAddress = rpcPic->getPicSym()->getPicSCUAddr(pcSlice->getSliceCurStartCUAddr()) / rpcPic->getNumPartInCU();
+  uiPosX = ( uiExternalAddress % rpcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
+  uiPosY = ( uiExternalAddress / rpcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
+  uiWidth = pcSlice->getSPS()->getPicWidthInLumaSamples();
+  uiHeight = pcSlice->getSPS()->getPicHeightInLumaSamples();
+  while((uiPosX>=uiWidth||uiPosY>=uiHeight)&&!(uiPosX>=uiWidth&&uiPosY>=uiHeight))
+  {
+    uiInternalAddress++;
+    if(uiInternalAddress>=rpcPic->getNumPartInCU())
+    {
+      uiInternalAddress=0;
+      uiExternalAddress = rpcPic->getPicSym()->getCUOrderMap(rpcPic->getPicSym()->getInverseCUOrderMap(uiExternalAddress)+1);
+    }
+    uiPosX = ( uiExternalAddress % rpcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
+    uiPosY = ( uiExternalAddress / rpcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
+  }
+  uiRealStartAddress = rpcPic->getPicSym()->getPicSCUEncOrder(uiExternalAddress*rpcPic->getNumPartInCU()+uiInternalAddress);
+  
+  pcSlice->setSliceCurStartCUAddr(uiRealStartAddress);
+  uiStartCUAddrSlice=uiRealStartAddress;
+  
+  // Make a joint decision based on reconstruction and dependent slice bounds
+  uiStartCUAddr    = max(uiStartCUAddrSlice   , uiStartCUAddrDependentSlice   );
+  uiBoundingCUAddr = min(uiBoundingCUAddrSlice, uiBoundingCUAddrDependentSlice);
+
+
+  if (!bEncodeSlice)
+  {
+    // For fixed number of LCU within an entropy and reconstruction slice we already know whether we will encounter end of entropy and/or reconstruction slice
+    // first. Set the flags accordingly.
+    if ( (m_pcCfg->getSliceMode()==AD_HOC_SLICES_FIXED_NUMBER_OF_LCU_IN_SLICE && m_pcCfg->getDependentSliceMode()==SHARP_FIXED_NUMBER_OF_LCU_IN_DEPENDENT_SLICE)
+      || (m_pcCfg->getSliceMode()==0 && m_pcCfg->getDependentSliceMode()==SHARP_FIXED_NUMBER_OF_LCU_IN_DEPENDENT_SLICE)
+      || (m_pcCfg->getSliceMode()==AD_HOC_SLICES_FIXED_NUMBER_OF_LCU_IN_SLICE && m_pcCfg->getDependentSliceMode()==0) 
+      || (m_pcCfg->getSliceMode()==AD_HOC_SLICES_FIXED_NUMBER_OF_TILES_IN_SLICE && m_pcCfg->getDependentSliceMode()==SHARP_FIXED_NUMBER_OF_LCU_IN_DEPENDENT_SLICE)
+      || (m_pcCfg->getSliceMode()==AD_HOC_SLICES_FIXED_NUMBER_OF_TILES_IN_SLICE && m_pcCfg->getDependentSliceMode()==0) 
+#if DEPENDENT_SLICES
+      || (m_pcCfg->getDependentSliceMode()==FIXED_NUMBER_OF_TILES_IN_DEPENDENT_SLICE && m_pcCfg->getSliceMode()==0)
+#endif
+      || tileBoundary
+)
+    {
+      if (uiBoundingCUAddrSlice < uiBoundingCUAddrDependentSlice)
+      {
+        pcSlice->setNextSlice       ( true );
+        pcSlice->setNextDependentSlice( false );
+      }
+      else if (uiBoundingCUAddrSlice > uiBoundingCUAddrDependentSlice)
+      {
+        pcSlice->setNextSlice       ( false );
+        pcSlice->setNextDependentSlice( true );
+      }
+      else
+      {
+        pcSlice->setNextSlice       ( true );
+        pcSlice->setNextDependentSlice( true );
+      }
+    }
+    else
+    {
+      pcSlice->setNextSlice       ( false );
+      pcSlice->setNextDependentSlice( false );
+    }
+  }
+}
+
+#if RECALCULATE_QP_ACCORDING_LAMBDA
+Double TEncSlice::xGetQPValueAccordingToLambda ( Double lambda )
+{
+  return 4.2005*log(lambda) + 13.7122;
+}
+#endif
+
+//! \}
Index: /trunk/source/Lib/TLibEncoder/TEncSlice.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncSlice.h	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/TEncSlice.h	(revision 2)
@@ -0,0 +1,149 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncSlice.h
+    \brief    slice encoder class (header)
+*/
+
+#ifndef __TENCSLICE__
+#define __TENCSLICE__
+
+// Include files
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComList.h"
+#include "TLibCommon/TComPic.h"
+#include "TLibCommon/TComPicYuv.h"
+#include "TEncCu.h"
+#include "WeightPredAnalysis.h"
+#include "TEncRateCtrl.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+class TEncTop;
+class TEncGOP;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// slice encoder class
+class TEncSlice
+  : public WeightPredAnalysis
+{
+private:
+  // encoder configuration
+  TEncCfg*                m_pcCfg;                              ///< encoder configuration class
+  
+#if SVC_EXTENSION
+  TEncTop**               m_ppcTEncTop;
+#endif  
+
+  // pictures
+  TComList<TComPic*>*     m_pcListPic;                          ///< list of pictures
+  TComPicYuv*             m_apcPicYuvPred;                      ///< prediction picture buffer
+  TComPicYuv*             m_apcPicYuvResi;                      ///< residual picture buffer
+  
+  // processing units
+  TEncGOP*                m_pcGOPEncoder;                       ///< GOP encoder
+  TEncCu*                 m_pcCuEncoder;                        ///< CU encoder
+  
+  // encoder search
+  TEncSearch*             m_pcPredSearch;                       ///< encoder search class
+  
+  // coding tools
+  TEncEntropy*            m_pcEntropyCoder;                     ///< entropy encoder
+  TEncCavlc*              m_pcCavlcCoder;                       ///< CAVLC encoder
+  TEncSbac*               m_pcSbacCoder;                        ///< SBAC encoder
+  TEncBinCABAC*           m_pcBinCABAC;                         ///< Bin encoder CABAC
+  TComTrQuant*            m_pcTrQuant;                          ///< transform & quantization
+  
+  // RD optimization
+  TComBitCounter*         m_pcBitCounter;                       ///< bit counter
+  TComRdCost*             m_pcRdCost;                           ///< RD cost computation
+  TEncSbac***             m_pppcRDSbacCoder;                    ///< storage for SBAC-based RD optimization
+  TEncSbac*               m_pcRDGoOnSbacCoder;                  ///< go-on SBAC encoder
+  UInt64                  m_uiPicTotalBits;                     ///< total bits for the picture
+  UInt64                  m_uiPicDist;                          ///< total distortion for the picture
+  Double                  m_dPicRdCost;                         ///< picture-level RD cost
+  Double*                 m_pdRdPicLambda;                      ///< array of lambda candidates
+  Double*                 m_pdRdPicQp;                          ///< array of picture QP candidates (double-type for lambda)
+  Int*                    m_piRdPicQp;                          ///< array of picture QP candidates (int-type)
+  TEncBinCABAC*           m_pcBufferBinCoderCABACs;       ///< line of bin coder CABAC
+  TEncSbac*               m_pcBufferSbacCoders;                 ///< line to store temporary contexts
+  TEncBinCABAC*           m_pcBufferLowLatBinCoderCABACs;       ///< dependent tiles: line of bin coder CABAC
+  TEncSbac*               m_pcBufferLowLatSbacCoders;           ///< dependent tiles: line to store temporary contexts
+  TEncRateCtrl*           m_pcRateCtrl;                         ///< Rate control manager
+  UInt                    m_uiSliceIdx;
+#if DEPENDENT_SLICES
+  std::vector<TEncSbac*> CTXMem;
+#endif
+public:
+  TEncSlice();
+  virtual ~TEncSlice();
+  
+  Void    create              ( Int iWidth, Int iHeight, UInt iMaxCUWidth, UInt iMaxCUHeight, UChar uhTotalDepth );
+  Void    destroy             ();
+  Void    init                ( TEncTop* pcEncTop );
+  
+  /// preparation of slice encoding (reference marking, QP and lambda)
+  Void    initEncSlice        ( TComPic*  pcPic, Int iPOCLast, UInt uiPOCCurr, Int iNumPicRcvd,
+                                Int iGOPid,   TComSlice*& rpcSlice, TComSPS* pSPS, TComPPS *pPPS );
+  Void    xLamdaRecalculation ( Int changeQP, Int idGOP, Int depth, SliceType eSliceType, TComSPS* pcSPS, TComSlice* pcSlice);
+  // compress and encode slice
+  Void    precompressSlice    ( TComPic*& rpcPic                                );      ///< precompress slice for multi-loop opt.
+  Void    compressSlice       ( TComPic*& rpcPic                                );      ///< analysis stage of slice
+  Void    encodeSlice         ( TComPic*& rpcPic, TComOutputBitstream* rpcBitstream, TComOutputBitstream* pcSubstreams  );
+  
+  // misc. functions
+  Void    setSearchRange      ( TComSlice* pcSlice  );                                  ///< set ME range adaptively
+  UInt64  getTotalBits        ()  { return m_uiPicTotalBits; }
+  
+  TEncCu*        getCUEncoder() { return m_pcCuEncoder; }                        ///< CU encoder
+  Void    xDetermineStartAndBoundingCUAddr  ( UInt& uiStartCUAddr, UInt& uiBoundingCUAddr, TComPic*& rpcPic, Bool bEncodeSlice );
+  UInt    getSliceIdx()         { return m_uiSliceIdx;                    }
+  Void    setSliceIdx(UInt i)   { m_uiSliceIdx = i;                       }
+#if DEPENDENT_SLICES
+  Void      initCtxMem( UInt i );
+  Void      setCtxMem( TEncSbac* sb, int b )   { CTXMem[b] = sb; }
+#endif
+
+#if RECALCULATE_QP_ACCORDING_LAMBDA
+private:
+  Double  xGetQPValueAccordingToLambda ( Double lambda );
+#endif
+};
+
+//! \}
+
+#endif // __TENCSLICE__
Index: /trunk/source/Lib/TLibEncoder/TEncTop.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncTop.cpp	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/TEncTop.cpp	(revision 2)
@@ -0,0 +1,1177 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncTop.cpp
+    \brief    encoder class
+*/
+
+#include "TLibCommon/CommonDef.h"
+#include "TEncTop.h"
+#include "TEncPic.h"
+#if FAST_BIT_EST
+#include "TLibCommon/ContextModel.h"
+#endif
+
+//! \ingroup TLibEncoder
+//! \{
+#if SVC_EXTENSION  
+Int TEncTop::m_iSPSIdCnt = 0;
+Int TEncTop::m_iPPSIdCnt = 0;
+#endif
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TEncTop::TEncTop()
+{
+  m_iPOCLast          = -1;
+  m_iNumPicRcvd       =  0;
+  m_uiNumAllPicCoded  =  0;
+  m_pppcRDSbacCoder   =  NULL;
+  m_pppcBinCoderCABAC =  NULL;
+  m_cRDGoOnSbacCoder.init( &m_cRDGoOnBinCoderCABAC );
+#if ENC_DEC_TRACE
+  g_hTrace = fopen( "TraceEnc.txt", "wb" );
+  g_bJustDoIt = g_bEncDecTraceDisable;
+  g_nSymbolCounter = 0;
+#endif
+
+  m_iMaxRefPicNum     = 0;
+
+#if FAST_BIT_EST
+  ContextModel::buildNextStateTable();
+#endif
+
+  m_pcSbacCoders           = NULL;
+  m_pcBinCoderCABACs       = NULL;
+  m_ppppcRDSbacCoders      = NULL;
+  m_ppppcBinCodersCABAC    = NULL;
+  m_pcRDGoOnSbacCoders     = NULL;
+  m_pcRDGoOnBinCodersCABAC = NULL;
+  m_pcBitCounters          = NULL;
+  m_pcRdCosts              = NULL;
+#if REF_IDX_FRAMEWORK
+  memset(m_cIlpPic, 0, sizeof(m_cIlpPic));
+#endif
+}
+
+TEncTop::~TEncTop()
+{
+#if ENC_DEC_TRACE
+  fclose( g_hTrace );
+#endif
+}
+
+Void TEncTop::create ()
+{
+#if !SVC_EXTENSION
+  // initialize global variables
+  initROM();
+#endif
+
+  // create processing unit classes
+#if SVC_EXTENSION
+  m_cGOPEncoder.        create( getSourceWidth(), getSourceHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight, m_layerId );
+#else
+  m_cGOPEncoder.        create( getSourceWidth(), getSourceHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight );
+#endif
+  m_cSliceEncoder.      create( getSourceWidth(), getSourceHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+  m_cCuEncoder.         create( g_uiMaxCUDepth, g_uiMaxCUWidth, g_uiMaxCUHeight );
+  if (m_bUseSAO)
+  {
+#if SAO_LCU_BOUNDARY
+    m_cEncSAO.setSaoLcuBoundary(getSaoLcuBoundary());
+#endif
+    m_cEncSAO.setSaoLcuBasedOptimization(getSaoLcuBasedOptimization());
+    m_cEncSAO.setMaxNumOffsetsPerPic(getMaxNumOffsetsPerPic());
+    m_cEncSAO.create( getSourceWidth(), getSourceHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+    m_cEncSAO.createEncBuffer();
+  }
+#if ADAPTIVE_QP_SELECTION
+  if (m_bUseAdaptQpSelect)
+  {
+    m_cTrQuant.initSliceQpDelta();
+  }
+#endif
+#if !REMOVE_ALF
+  m_cAdaptiveLoopFilter.create( getSourceWidth(), getSourceHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+#endif
+  m_cLoopFilter.        create( g_uiMaxCUDepth );
+  
+#if !REMOVE_ALF
+  if(m_bUseALF)
+  {
+    m_cAdaptiveLoopFilter.setALFLowLatencyEncoding( m_alfLowLatencyEncoding );
+    m_cAdaptiveLoopFilter.setGOPSize( getGOPSize() );
+    m_cAdaptiveLoopFilter.createAlfGlobalBuffers();
+  }
+#endif
+  
+#if !REMOVE_APS
+#if REMOVE_ALF
+  if(m_bUseSAO)
+#else
+  if(m_bUseSAO || m_bUseALF)
+#endif
+  {
+    m_vAPS.reserve(MAX_NUM_SUPPORTED_APS);
+  }
+#endif
+  m_cRateCtrl.create(getIntraPeriod(), getGOPSize(), getFrameRate(), getTargetBitrate(), getQP(), getNumLCUInUnit(), getSourceWidth(), getSourceHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight);
+  // if SBAC-based RD optimization is used
+  if( m_bUseSBACRD )
+  {
+    m_pppcRDSbacCoder = new TEncSbac** [g_uiMaxCUDepth+1];
+#if FAST_BIT_EST
+    m_pppcBinCoderCABAC = new TEncBinCABACCounter** [g_uiMaxCUDepth+1];
+#else
+    m_pppcBinCoderCABAC = new TEncBinCABAC** [g_uiMaxCUDepth+1];
+#endif
+    
+    for ( Int iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
+    {
+      m_pppcRDSbacCoder[iDepth] = new TEncSbac* [CI_NUM];
+#if FAST_BIT_EST
+      m_pppcBinCoderCABAC[iDepth] = new TEncBinCABACCounter* [CI_NUM];
+#else
+      m_pppcBinCoderCABAC[iDepth] = new TEncBinCABAC* [CI_NUM];
+#endif
+      
+      for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
+      {
+        m_pppcRDSbacCoder[iDepth][iCIIdx] = new TEncSbac;
+#if FAST_BIT_EST
+        m_pppcBinCoderCABAC [iDepth][iCIIdx] = new TEncBinCABACCounter;
+#else
+        m_pppcBinCoderCABAC [iDepth][iCIIdx] = new TEncBinCABAC;
+#endif
+        m_pppcRDSbacCoder   [iDepth][iCIIdx]->init( m_pppcBinCoderCABAC [iDepth][iCIIdx] );
+      }
+    }
+  }
+}
+
+/**
+ - Allocate coders required for wavefront for the nominated number of substreams.
+ .
+ \param iNumSubstreams Determines how much information to allocate.
+ */
+Void TEncTop::createWPPCoders(Int iNumSubstreams)
+{
+  if (m_pcSbacCoders != NULL)
+  {
+    return; // already generated.
+  }
+
+  m_iNumSubstreams         = iNumSubstreams;
+  m_pcSbacCoders           = new TEncSbac       [iNumSubstreams];
+  m_pcBinCoderCABACs       = new TEncBinCABAC   [iNumSubstreams];
+  m_pcRDGoOnSbacCoders     = new TEncSbac       [iNumSubstreams];
+  m_pcRDGoOnBinCodersCABAC = new TEncBinCABAC   [iNumSubstreams];
+  m_pcBitCounters          = new TComBitCounter [iNumSubstreams];
+  m_pcRdCosts              = new TComRdCost     [iNumSubstreams];
+
+  for ( UInt ui = 0 ; ui < iNumSubstreams; ui++ )
+  {
+    m_pcRDGoOnSbacCoders[ui].init( &m_pcRDGoOnBinCodersCABAC[ui] );
+    m_pcSbacCoders[ui].init( &m_pcBinCoderCABACs[ui] );
+  }
+  if( m_bUseSBACRD )
+  {
+    m_ppppcRDSbacCoders      = new TEncSbac***    [iNumSubstreams];
+    m_ppppcBinCodersCABAC    = new TEncBinCABAC***[iNumSubstreams];
+    for ( UInt ui = 0 ; ui < iNumSubstreams ; ui++ )
+    {
+      m_ppppcRDSbacCoders[ui]  = new TEncSbac** [g_uiMaxCUDepth+1];
+      m_ppppcBinCodersCABAC[ui]= new TEncBinCABAC** [g_uiMaxCUDepth+1];
+      
+      for ( Int iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
+      {
+        m_ppppcRDSbacCoders[ui][iDepth]  = new TEncSbac*     [CI_NUM];
+        m_ppppcBinCodersCABAC[ui][iDepth]= new TEncBinCABAC* [CI_NUM];
+
+        for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
+        {
+          m_ppppcRDSbacCoders  [ui][iDepth][iCIIdx] = new TEncSbac;
+          m_ppppcBinCodersCABAC[ui][iDepth][iCIIdx] = new TEncBinCABAC;
+          m_ppppcRDSbacCoders  [ui][iDepth][iCIIdx]->init( m_ppppcBinCodersCABAC[ui][iDepth][iCIIdx] );
+        }
+      }
+    }
+  }
+}
+
+Void TEncTop::destroy ()
+{
+#if !REMOVE_ALF
+  if(m_bUseALF)
+  {
+    m_cAdaptiveLoopFilter.destroyAlfGlobalBuffers();
+  }
+#endif
+#if !REMOVE_APS
+  for(Int i=0; i< m_vAPS.size(); i++)
+  {
+    TComAPS& cAPS = m_vAPS[i];
+    m_cGOPEncoder.freeAPS(&cAPS, &m_cSPS);
+  }
+#endif
+  // destroy processing unit classes
+  m_cGOPEncoder.        destroy();
+  m_cSliceEncoder.      destroy();
+  m_cCuEncoder.         destroy();
+  if (m_cSPS.getUseSAO())
+  {
+    m_cEncSAO.destroy();
+    m_cEncSAO.destroyEncBuffer();
+  }
+#if !REMOVE_ALF
+  m_cAdaptiveLoopFilter.destroy();
+#endif
+  m_cLoopFilter.        destroy();
+  m_cRateCtrl.          destroy();
+  // SBAC RD
+  if( m_bUseSBACRD )
+  {
+    Int iDepth;
+    for ( iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
+    {
+      for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
+      {
+        delete m_pppcRDSbacCoder[iDepth][iCIIdx];
+        delete m_pppcBinCoderCABAC[iDepth][iCIIdx];
+      }
+    }
+    
+    for ( iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
+    {
+      delete [] m_pppcRDSbacCoder[iDepth];
+      delete [] m_pppcBinCoderCABAC[iDepth];
+    }
+    
+    delete [] m_pppcRDSbacCoder;
+    delete [] m_pppcBinCoderCABAC;
+
+    for ( UInt ui = 0; ui < m_iNumSubstreams; ui++ )
+    {
+      for ( iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
+      {
+        for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
+        {
+          delete m_ppppcRDSbacCoders  [ui][iDepth][iCIIdx];
+          delete m_ppppcBinCodersCABAC[ui][iDepth][iCIIdx];
+        }
+      }
+
+      for ( iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
+      {
+        delete [] m_ppppcRDSbacCoders  [ui][iDepth];
+        delete [] m_ppppcBinCodersCABAC[ui][iDepth];
+      }
+      delete[] m_ppppcRDSbacCoders  [ui];
+      delete[] m_ppppcBinCodersCABAC[ui];
+    }
+    delete[] m_ppppcRDSbacCoders;
+    delete[] m_ppppcBinCodersCABAC;
+  }
+  delete[] m_pcSbacCoders;
+  delete[] m_pcBinCoderCABACs;
+  delete[] m_pcRDGoOnSbacCoders;  
+  delete[] m_pcRDGoOnBinCodersCABAC;
+  delete[] m_pcBitCounters;
+  delete[] m_pcRdCosts;
+  
+#if !SVC_EXTENSION
+  // destroy ROM
+  destroyROM();
+#endif
+#if REF_IDX_FRAMEWORK
+  for(Int i=0; i<MAX_NUM_REF; i++)
+  {
+    if(m_cIlpPic[i])
+    {
+      //m_cIlpPic[i]->setPicYuvRec(NULL);
+      m_cIlpPic[i]->destroy();
+      delete m_cIlpPic[i];
+      m_cIlpPic[i] = NULL;
+    }
+  }    
+#endif
+  return;
+}
+
+Void TEncTop::init()
+{
+  UInt *aTable4=NULL, *aTable8=NULL;
+  UInt* aTableLastPosVlcIndex=NULL; 
+  
+  // initialize SPS
+  xInitSPS();
+  
+  // initialize PPS
+  m_cPPS.setSPS(&m_cSPS);
+  xInitPPS();
+  xInitRPS();
+
+  xInitPPSforTiles();
+
+  // initialize processing unit classes
+  m_cGOPEncoder.  init( this );
+  m_cSliceEncoder.init( this );
+  m_cCuEncoder.   init( this );
+  
+  // initialize transform & quantization class
+  m_pcCavlcCoder = getCavlcCoder();
+  
+  m_cTrQuant.init( g_uiMaxCUWidth, g_uiMaxCUHeight, 1 << m_uiQuadtreeTULog2MaxSize,
+                  0,
+                  aTable4, aTable8, 
+                  aTableLastPosVlcIndex, m_bUseRDOQ, true 
+                  ,m_useTransformSkipFast
+#if ADAPTIVE_QP_SELECTION                  
+                  , m_bUseAdaptQpSelect
+#endif
+                  );
+  
+  // initialize encoder search class
+  m_cSearch.init( this, &m_cTrQuant, m_iSearchRange, m_bipredSearchRange, m_iFastSearch, 0, &m_cEntropyCoder, &m_cRdCost, getRDSbacCoder(), getRDGoOnSbacCoder() );
+
+  m_iMaxRefPicNum = 0;
+#if SVC_EXTENSION
+  m_iSPSIdCnt ++;
+  m_iPPSIdCnt ++;
+#endif
+#if REF_IDX_FRAMEWORK
+  xInitILRP();
+#endif
+}
+
+#if REF_IDX_FRAMEWORK
+Void TEncTop::xInitILRP()
+{
+  if(m_layerId>0)
+  {
+    if (m_cIlpPic[0] == NULL)
+    {
+      for (Int j=0; j<1/*MAX_NUM_REF*/; j++)
+      {
+        m_cIlpPic[j] = new  TComPic;
+        //m_cIlpPic[j]->createWithOutYuv(m_iSourceWidth, m_iSourceHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, &m_cSPS, true);
+        m_cIlpPic[j]->create(m_iSourceWidth, m_iSourceHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, &m_cSPS, true);
+#if REF_IDX_ME_AROUND_ZEROMV
+        m_cIlpPic[j]->setIsILR(true);
+#endif
+        for (Int i=0; i<m_cIlpPic[j]->getPicSym()->getNumberOfCUsInFrame(); i++)
+        {
+            m_cIlpPic[j]->getPicSym()->getCU(i)->initCU(m_cIlpPic[j], i);
+        }
+      }
+    }
+  }
+}
+
+Void TEncTop::setILRPic(TComPic *pcPic)
+{
+  if(m_cIlpPic[0])
+  {
+    //m_cIlpPic[0]->setPicYuvRec(pcPic->getFullPelBaseRec());
+    m_cIlpPic[0]->copyUpsampledPictureYuv(pcPic->getFullPelBaseRec(), m_cIlpPic[0]->getPicYuvRec());
+    m_cIlpPic[0]->getSlice(0)->setPOC(pcPic->getPOC());
+    m_cIlpPic[0]->getPicYuvRec()->setBorderExtension(false);
+    m_cIlpPic[0]->getPicYuvRec()->extendPicBorder();
+  }
+}
+#endif
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+Void TEncTop::deletePicBuffer()
+{
+  TComList<TComPic*>::iterator iterPic = m_cListPic.begin();
+  Int iSize = Int( m_cListPic.size() );
+  
+  for ( Int i = 0; i < iSize; i++ )
+  {
+    TComPic* pcPic = *(iterPic++);
+    
+    pcPic->destroy();
+    delete pcPic;
+    pcPic = NULL;
+  }
+}
+
+/**
+ - Application has picture buffer list with size of GOP + 1
+ - Picture buffer list acts like as ring buffer
+ - End of the list has the latest picture
+ .
+ \param   bEos                true if end-of-sequence is reached
+ \param   pcPicYuvOrg         original YUV picture
+ \retval  rcListPicYuvRecOut  list of reconstruction YUV pictures
+ \retval  rcListBitstreamOut  list of output bitstreams
+ \retval  iNumEncoded         number of encoded pictures
+ */
+#if SVC_EXTENSION
+Void TEncTop::encode( TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int iPicIdInGOP )
+{
+  // compress GOP
+  m_cGOPEncoder.compressGOP(iPicIdInGOP, m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut);
+  
+  m_uiNumAllPicCoded ++;
+}
+
+
+Void TEncTop::encodePrep( bool bEos, TComPicYuv* pcPicYuvOrg )
+{
+  TComPic* pcPicCurr = NULL;
+  
+  // get original YUV
+  xGetNewPicBuffer( pcPicCurr );
+  pcPicYuvOrg->copyToPic( pcPicCurr->getPicYuvOrg() );
+  
+  // compute image characteristics
+  if ( getUseAdaptiveQP() )
+  {
+    m_cPreanalyzer.xPreanalyze( dynamic_cast<TEncPic*>( pcPicCurr ) );
+  }
+}
+
+#else
+Void TEncTop::encode( bool bEos, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded )
+{
+  TComPic* pcPicCurr = NULL;
+  
+  // get original YUV
+  xGetNewPicBuffer( pcPicCurr );
+  pcPicYuvOrg->copyToPic( pcPicCurr->getPicYuvOrg() );
+  
+  // compute image characteristics
+  if ( getUseAdaptiveQP() )
+  {
+    m_cPreanalyzer.xPreanalyze( dynamic_cast<TEncPic*>( pcPicCurr ) );
+  }
+  
+  if ( m_iPOCLast != 0 && ( m_iNumPicRcvd != m_iGOPSize && m_iGOPSize ) && !bEos )
+  {
+    iNumEncoded = 0;
+    return;
+  }
+  
+  // compress GOP
+  m_cGOPEncoder.compressGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut);
+  
+  iNumEncoded         = m_iNumPicRcvd;
+  m_iNumPicRcvd       = 0;
+  m_uiNumAllPicCoded += iNumEncoded;
+  
+  if (bEos)
+  {
+#if SVC_EXTENSION
+    m_cGOPEncoder.printOutSummary (m_uiNumAllPicCoded, m_layerId);
+#else
+    m_cGOPEncoder.printOutSummary (m_uiNumAllPicCoded);
+#endif
+  }
+}
+#endif
+
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+/**
+ - Application has picture buffer list with size of GOP + 1
+ - Picture buffer list acts like as ring buffer
+ - End of the list has the latest picture
+ .
+ \retval rpcPic obtained picture buffer
+ */
+Void TEncTop::xGetNewPicBuffer ( TComPic*& rpcPic )
+{
+  TComSlice::sortPicList(m_cListPic);
+  
+  if (m_cListPic.size() >= (UInt)(m_iGOPSize + getMaxDecPicBuffering(MAX_TLAYER-1) + 2) )
+  {
+    TComList<TComPic*>::iterator iterPic  = m_cListPic.begin();
+    Int iSize = Int( m_cListPic.size() );
+    for ( Int i = 0; i < iSize; i++ )
+    {
+      rpcPic = *(iterPic++);
+      if(rpcPic->getSlice(0)->isReferenced() == false)
+      {
+        break;
+      }
+    }
+  }
+  else
+  {
+    if ( getUseAdaptiveQP() )
+    {
+      TEncPic* pcEPic = new TEncPic;
+#if SVC_EXTENSION //Temporal solution, should be modified
+      if(m_layerId > 0)
+      {
+        TEncTop *pcEncTopBase = (TEncTop *)getLayerEnc( m_layerId-1 );
+        if(m_iSourceWidth != pcEncTopBase->getSourceWidth() || m_iSourceHeight != pcEncTopBase->getSourceHeight() )
+        {
+          pcEPic->setSpatialEnhLayerFlag( true );
+        }
+      }
+#endif
+#if SVC_UPSAMPLING
+      pcEPic->create( m_iSourceWidth, m_iSourceHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, m_cPPS.getMaxCuDQPDepth()+1, &m_cSPS );
+#else   
+      pcEPic->create( m_iSourceWidth, m_iSourceHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, m_cPPS.getMaxCuDQPDepth()+1 );
+#endif
+      rpcPic = pcEPic;
+    }
+    else
+    {
+      rpcPic = new TComPic;
+#if SVC_EXTENSION //Temporal solution, should be modified
+      if(m_layerId > 0)
+      {
+        TEncTop *pcEncTopBase = (TEncTop *)getLayerEnc( m_layerId-1 );
+        if(m_iSourceWidth != pcEncTopBase->getSourceWidth() || m_iSourceHeight != pcEncTopBase->getSourceHeight() )
+        {
+          rpcPic->setSpatialEnhLayerFlag( true );
+        }
+      }
+#endif
+#if SVC_UPSAMPLING
+      rpcPic->create( m_iSourceWidth, m_iSourceHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, &m_cSPS );
+#else
+      rpcPic->create( m_iSourceWidth, m_iSourceHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+#endif
+    }
+#if REMOVE_APS
+    if (getUseSAO())
+    {
+      rpcPic->getPicSym()->allocSaoParam(&m_cEncSAO);
+    }
+#endif
+    m_cListPic.pushBack( rpcPic );
+  }
+  rpcPic->setReconMark (false);
+  
+  m_iPOCLast++;
+  m_iNumPicRcvd++;
+  
+  rpcPic->getSlice(0)->setPOC( m_iPOCLast );
+  // mark it should be extended
+  rpcPic->getPicYuvRec()->setBorderExtension(false);
+}
+
+Void TEncTop::xInitSPS()
+{
+#if SVC_EXTENSION
+  m_cSPS.setLayerId(m_layerId);
+#endif
+
+  m_cSPS.setPicWidthInLumaSamples         ( m_iSourceWidth      );
+  m_cSPS.setPicHeightInLumaSamples        ( m_iSourceHeight     );
+  m_cSPS.setPicCroppingFlag( m_croppingMode!= 0 );
+  if (m_croppingMode != 0)
+  {
+    m_cSPS.setPicCropLeftOffset( m_cropLeft );
+    m_cSPS.setPicCropRightOffset( m_cropRight );
+    m_cSPS.setPicCropTopOffset( m_cropTop );
+    m_cSPS.setPicCropBottomOffset( m_cropBottom );
+  }
+  m_cSPS.setMaxCUWidth    ( g_uiMaxCUWidth      );
+  m_cSPS.setMaxCUHeight   ( g_uiMaxCUHeight     );
+  m_cSPS.setMaxCUDepth    ( g_uiMaxCUDepth      );
+  m_cSPS.setMinTrDepth    ( 0                   );
+  m_cSPS.setMaxTrDepth    ( 1                   );
+#if SVC_EXTENSION
+  m_cSPS.setSPSId         ( m_iSPSIdCnt       );
+#endif
+  
+  m_cSPS.setPCMLog2MinSize (m_uiPCMLog2MinSize);
+  m_cSPS.setUsePCM        ( m_usePCM           );
+  m_cSPS.setPCMLog2MaxSize( m_pcmLog2MaxSize  );
+
+#if !REMOVE_ALF
+  m_cSPS.setUseALF        ( m_bUseALF           );
+#endif
+  m_cSPS.setQuadtreeTULog2MaxSize( m_uiQuadtreeTULog2MaxSize );
+  m_cSPS.setQuadtreeTULog2MinSize( m_uiQuadtreeTULog2MinSize );
+  m_cSPS.setQuadtreeTUMaxDepthInter( m_uiQuadtreeTUMaxDepthInter    );
+  m_cSPS.setQuadtreeTUMaxDepthIntra( m_uiQuadtreeTUMaxDepthIntra    );
+  
+  m_cSPS.setTMVPFlagsPresent(false);
+  m_cSPS.setUseLossless   ( m_useLossless  );
+
+#if !REMOVE_LMCHROMA
+  m_cSPS.setUseLMChroma   ( m_bUseLMChroma           );  
+#endif
+#if !PPS_TS_FLAG
+  m_cSPS.setUseTransformSkip ( m_useTransformSkip );
+#endif
+
+  m_cSPS.setMaxTrSize   ( 1 << m_uiQuadtreeTULog2MaxSize );
+  
+  m_cSPS.setUseLComb    ( m_bUseLComb           );
+#if !REMOVE_NSQT
+  m_cSPS.setUseNSQT( m_useNSQT );
+#endif
+  
+  Int i;
+#if !SPS_AMVP_CLEANUP
+#if HHI_AMVP_OFF
+  for ( i = 0; i < g_uiMaxCUDepth; i++ )
+  {
+    m_cSPS.setAMVPMode( i, AM_NONE );
+  }
+#else
+  for ( i = 0; i < g_uiMaxCUDepth; i++ )
+  {
+    m_cSPS.setAMVPMode( i, AM_EXPL );
+  }
+#endif
+#endif
+  
+  for (i = 0; i < g_uiMaxCUDepth-g_uiAddCUDepth; i++ )
+  {
+    m_cSPS.setAMPAcc( i, m_useAMP );
+    //m_cSPS.setAMPAcc( i, 1 );
+  }
+
+  m_cSPS.setUseAMP ( m_useAMP );
+
+  for (i = g_uiMaxCUDepth-g_uiAddCUDepth; i < g_uiMaxCUDepth; i++ )
+  {
+    m_cSPS.setAMPAcc(i, 0);
+  }
+
+  m_cSPS.setBitDepth    ( g_uiBitDepth        );
+  m_cSPS.setBitIncrement( g_uiBitIncrement    );
+  m_cSPS.setQpBDOffsetY ( (Int)(6*(g_uiBitDepth + g_uiBitIncrement - 8)) );
+  m_cSPS.setQpBDOffsetC ( (Int)(6*(g_uiBitDepth + g_uiBitIncrement - 8)) );
+
+#if !MOVE_LOOP_FILTER_SLICES_FLAG
+  m_cSPS.setLFCrossSliceBoundaryFlag( m_bLFCrossSliceBoundaryFlag );
+#endif
+  m_cSPS.setUseSAO( m_bUseSAO );
+
+  m_cSPS.setMaxTLayers( m_maxTempLayer );
+  m_cSPS.setTemporalIdNestingFlag( false );
+  for ( i = 0; i < m_cSPS.getMaxTLayers(); i++ )
+  {
+    m_cSPS.setMaxDecPicBuffering(m_maxDecPicBuffering[i], i);
+    m_cSPS.setNumReorderPics(m_numReorderPics[i], i);
+  }
+  m_cSPS.setPCMBitDepthLuma (g_uiPCMBitDepthLuma);
+  m_cSPS.setPCMBitDepthChroma (g_uiPCMBitDepthChroma);
+  m_cSPS.setPCMFilterDisableFlag  ( m_bPCMFilterDisableFlag );
+
+  m_cSPS.setScalingListFlag ( (m_useScalingListId == 0) ? 0 : 1 );
+
+#if SUPPORT_FOR_VUI
+  m_cSPS.setVuiParametersPresentFlag(getVuiParametersPresentFlag());
+  if (m_cSPS.getVuiParametersPresentFlag())
+  {
+      TComVUI* pcVUI = m_cSPS.getVuiParameters();
+      pcVUI->setAspectRatioInfoPresentFlag(getAspectRatioIdc() != -1);
+      pcVUI->setAspectRatioIdc(getAspectRatioIdc());
+      pcVUI->setSarWidth(getSarWidth());
+      pcVUI->setSarHeight(getSarHeight());
+      pcVUI->setOverscanInfoPresentFlag(getOverscanInfoPresentFlag());
+      pcVUI->setOverscanAppropriateFlag(getOverscanAppropriateFlag());
+      pcVUI->setVideoSignalTypePresentFlag(getVideoSignalTypePresentFlag());
+      pcVUI->setVideoFormat(getVideoFormat());
+      pcVUI->setVideoFullRangeFlag(getVideoFullRangeFlag());
+      pcVUI->setColourDescriptionPresentFlag(getColourDescriptionPresentFlag());
+      pcVUI->setTransferCharacteristics(getTransferCharacteristics());
+      pcVUI->setMatrixCoefficients(getMatrixCoefficients());
+      pcVUI->setChromaLocInfoPresentFlag(getChromaLocInfoPresentFlag());
+      pcVUI->setChromaSampleLocTypeTopField(getChromaSampleLocTypeTopField());
+      pcVUI->setChromaSampleLocTypeBottomField(getChromaSampleLocTypeBottomField());
+      pcVUI->setNeutralChromaIndicationFlag(getNeutralChromaIndicationFlag());
+      pcVUI->setFieldSeqFlag(false);
+      pcVUI->setHrdParametersPresentFlag(false);
+      pcVUI->setBitstreamRestrictionFlag(getBitstreamRestrictionFlag());
+      pcVUI->setTilesFixedStructureFlag(getTilesFixedStructureFlag());
+      pcVUI->setMotionVectorsOverPicBoundariesFlag(getMotionVectorsOverPicBoundariesFlag());
+      pcVUI->setMaxBytesPerPicDenom(getMaxBytesPerPicDenom());
+      pcVUI->setMaxBitsPerMinCuDenom(getMaxBitsPerMinCuDenom());
+      pcVUI->setLog2MaxMvLengthHorizontal(getLog2MaxMvLengthHorizontal());
+      pcVUI->setLog2MaxMvLengthVertical(getLog2MaxMvLengthVertical());
+  }
+#endif
+}
+
+Void TEncTop::xInitPPS()
+{
+  m_cPPS.setConstrainedIntraPred( m_bUseConstrainedIntraPred );
+#if !REMOVE_FGS
+  m_cPPS.setSliceGranularity(m_iSliceGranularity);
+#endif
+  Bool bUseDQP = (getMaxCuDQPDepth() > 0)? true : false;
+
+  Int lowestQP = - m_cSPS.getQpBDOffsetY();
+
+  if(getUseLossless())
+  {
+    if ((getMaxCuDQPDepth() == 0) && (getMaxDeltaQP() == 0 ) && (getQP() == lowestQP) )
+    {
+      bUseDQP = false;
+    }
+    else
+    {
+      bUseDQP = true;
+    }
+  }
+  else
+  {
+    if(bUseDQP == false)
+    {
+      if((getMaxDeltaQP() != 0 )|| getUseAdaptiveQP())
+      {
+        bUseDQP = true;
+      }
+    }
+  }
+
+  if(bUseDQP)
+  {
+    m_cPPS.setUseDQP(true);
+    m_cPPS.setMaxCuDQPDepth( m_iMaxCuDQPDepth );
+    m_cPPS.setMinCuDQPSize( m_cPPS.getSPS()->getMaxCUWidth() >> ( m_cPPS.getMaxCuDQPDepth()) );
+  }
+  else
+  {
+    m_cPPS.setUseDQP(false);
+    m_cPPS.setMaxCuDQPDepth( 0 );
+    m_cPPS.setMinCuDQPSize( m_cPPS.getSPS()->getMaxCUWidth() >> ( m_cPPS.getMaxCuDQPDepth()) );
+  }
+
+  m_cPPS.setChromaCbQpOffset( m_chromaCbQpOffset );
+  m_cPPS.setChromaCrQpOffset( m_chromaCrQpOffset );
+
+  m_cPPS.setNumSubstreams(m_iWaveFrontSubstreams);
+#if TILES_WPP_ENTROPYSLICES_FLAGS
+  m_cPPS.setEntropyCodingSyncEnabledFlag( m_iWaveFrontSynchro > 0 );
+  m_cPPS.setTilesEnabledFlag( (m_iNumColumnsMinus1 > 0 || m_iNumRowsMinus1 > 0) );
+#else
+  m_cPPS.setTilesOrEntropyCodingSyncIdc( m_iWaveFrontSynchro ? 2 : ((m_iNumColumnsMinus1 > 0 || m_iNumRowsMinus1 > 0) ? 1 : 0));
+#endif
+  m_cPPS.setUseWP( m_bUseWeightPred );
+  m_cPPS.setWPBiPred( m_useWeightedBiPred );
+  m_cPPS.setOutputFlagPresentFlag( false );
+  m_cPPS.setSignHideFlag(getSignHideFlag());
+  m_cPPS.setDeblockingFilterControlPresentFlag (m_DeblockingFilterControlPresent );
+  m_cPPS.setLog2ParallelMergeLevelMinus2   (m_log2ParallelMergeLevelMinus2 );
+  m_cPPS.setCabacInitPresentFlag(CABAC_INIT_PRESENT_FLAG);
+#if MOVE_LOOP_FILTER_SLICES_FLAG
+  m_cPPS.setLoopFilterAcrossSlicesEnabledFlag( m_bLFCrossSliceBoundaryFlag );
+#endif
+  Int histogram[8];
+  for(Int i=0; i<8; i++)
+  {
+    histogram[i]=0;
+  }
+  for( Int i = 0; i < getGOPSize(); i++) 
+  {
+    if(getGOPEntry(i).m_numRefPicsActive<8)
+    {
+      histogram[getGOPEntry(i).m_numRefPicsActive]++;
+    }
+  }
+  Int maxHist=-1;
+  Int bestPos=0;
+  for(Int i=0; i<8; i++)
+  {
+    if(histogram[i]>maxHist)
+    {
+      maxHist=histogram[i];
+      bestPos=i;
+    }
+  }
+  m_cPPS.setNumRefIdxL0DefaultActive(bestPos);
+  m_cPPS.setNumRefIdxL1DefaultActive(bestPos);
+  m_cPPS.setTransquantBypassEnableFlag(getTransquantBypassEnableFlag());
+#if PPS_TS_FLAG
+  m_cPPS.setUseTransformSkip( m_useTransformSkip );
+#endif
+#if TILES_WPP_ENTROPYSLICES_FLAGS
+  if (m_iDependentSliceMode)
+  {
+    m_cPPS.setDependentSliceEnabledFlag( true );
+    m_cPPS.setEntropySliceEnabledFlag( m_entropySliceEnabledFlag );
+  }
+#else
+#if DEPENDENT_SLICES
+  m_cPPS.setDependentSliceEnabledFlag( m_iDependentSliceMode );
+  m_cPPS.setCabacIndependentFlag( m_bCabacIndependentFlag ? 1 : 0 );
+#endif
+#endif
+#if DEPENDENT_SLICES
+#if TILES_WPP_ENTROPYSLICES_FLAGS
+  if( m_cPPS.getDependentSliceEnabledFlag()&&(!m_cPPS.getEntropySliceEnabledFlag()) )
+#else
+  if( m_cPPS.getDependentSliceEnabledFlag()&&(!m_cPPS.getCabacIndependentFlag()) )
+#endif
+  {
+#if TILES_WPP_ENTROPYSLICES_FLAGS
+    int NumCtx = m_cPPS.getEntropyCodingSyncEnabledFlag()?2:1;
+#else
+    int NumCtx = (m_cPPS.getTilesOrEntropyCodingSyncIdc() == 2)?2:1;
+#endif
+    m_cSliceEncoder.initCtxMem( NumCtx );
+    for ( UInt st = 0; st < NumCtx; st++ )
+    {
+      TEncSbac* ctx = NULL;
+      ctx = new TEncSbac;
+      ctx->init( &m_cBinCoderCABAC );
+      m_cSliceEncoder.setCtxMem( ctx, st );
+    }
+  }
+#endif
+#if SVC_EXTENSION
+  m_cPPS.setPPSId         ( m_iPPSIdCnt         );
+  m_cPPS.setSPSId         ( m_iSPSIdCnt         );
+#endif
+}
+
+//Function for initializing m_RPSList, a list of TComReferencePictureSet, based on the GOPEntry objects read from the config file.
+Void TEncTop::xInitRPS()
+{
+  TComReferencePictureSet*      rps;
+  
+  m_cSPS.createRPSList(getGOPSize()+m_extraRPSs);
+  TComRPSList* rpsList = m_cSPS.getRPSList();
+
+  for( Int i = 0; i < getGOPSize()+m_extraRPSs; i++) 
+  {
+    GOPEntry ge = getGOPEntry(i);
+    rps = rpsList->getReferencePictureSet(i);
+    rps->setNumberOfPictures(ge.m_numRefPics);
+    rps->setNumRefIdc(ge.m_numRefIdc);
+    Int numNeg = 0;
+    Int numPos = 0;
+    for( Int j = 0; j < ge.m_numRefPics; j++)
+    {
+      rps->setDeltaPOC(j,ge.m_referencePics[j]);
+      rps->setUsed(j,ge.m_usedByCurrPic[j]);
+      if(ge.m_referencePics[j]>0)
+      {
+        numPos++;
+      }
+      else
+      {
+        numNeg++;
+      }
+    }
+    rps->setNumberOfNegativePictures(numNeg);
+    rps->setNumberOfPositivePictures(numPos);
+
+    // handle inter RPS intialization from the config file.
+#if AUTO_INTER_RPS
+    rps->setInterRPSPrediction(ge.m_interRPSPrediction > 0);  // not very clean, converting anything > 0 to true.
+#if J0234_INTER_RPS_SIMPL
+    rps->setDeltaRIdxMinus1(0);                               // index to the Reference RPS is always the previous one.
+    TComReferencePictureSet*     RPSRef = rpsList->getReferencePictureSet(i-1);  // get the reference RPS
+#else
+    rps->setDeltaRIdxMinus1(ge.m_deltaRIdxMinus1);            // index to the Reference RPS
+    TComReferencePictureSet*     RPSRef = rpsList->getReferencePictureSet(i-(ge.m_deltaRIdxMinus1+1));  // get the reference RPS
+#endif
+
+    if (ge.m_interRPSPrediction == 2)  // Automatic generation of the inter RPS idc based on the RIdx provided.
+    {
+#if J0234_INTER_RPS_SIMPL
+      Int deltaRPS = getGOPEntry(i-1).m_POC - ge.m_POC;  // the ref POC - current POC
+#else
+      Int deltaRPS = getGOPEntry(i-(ge.m_deltaRIdxMinus1+1)).m_POC - ge.m_POC;  // the ref POC - current POC
+#endif
+      Int numRefDeltaPOC = RPSRef->getNumberOfPictures();
+
+      rps->setDeltaRPS(deltaRPS);           // set delta RPS
+      rps->setNumRefIdc(numRefDeltaPOC+1);  // set the numRefIdc to the number of pictures in the reference RPS + 1.
+      Int count=0;
+      for (Int j = 0; j <= numRefDeltaPOC; j++ ) // cycle through pics in reference RPS.
+      {
+        Int RefDeltaPOC = (j<numRefDeltaPOC)? RPSRef->getDeltaPOC(j): 0;  // if it is the last decoded picture, set RefDeltaPOC = 0
+        rps->setRefIdc(j, 0);
+        for (Int k = 0; k < rps->getNumberOfPictures(); k++ )  // cycle through pics in current RPS.
+        {
+          if (rps->getDeltaPOC(k) == ( RefDeltaPOC + deltaRPS))  // if the current RPS has a same picture as the reference RPS. 
+          {
+              rps->setRefIdc(j, (rps->getUsed(k)?1:2));
+              count++;
+              break;
+          }
+        }
+      }
+      if (count != rps->getNumberOfPictures())
+      {
+        printf("Warning: Unable fully predict all delta POCs using the reference RPS index given in the config file.  Setting Inter RPS to false for this RPS.\n");
+        rps->setInterRPSPrediction(0);
+      }
+    }
+    else if (ge.m_interRPSPrediction == 1)  // inter RPS idc based on the RefIdc values provided in config file.
+    {
+      rps->setDeltaRPS(ge.m_deltaRPS);
+      rps->setNumRefIdc(ge.m_numRefIdc);
+      for (Int j = 0; j < ge.m_numRefIdc; j++ )
+      {
+        rps->setRefIdc(j, ge.m_refIdc[j]);
+      }
+#if WRITE_BACK
+      // the folowing code overwrite the deltaPOC and Used by current values read from the config file with the ones
+      // computed from the RefIdc.  A warning is printed if they are not identical.
+      numNeg = 0;
+      numPos = 0;
+      TComReferencePictureSet      RPSTemp;  // temporary variable
+
+      for (Int j = 0; j < ge.m_numRefIdc; j++ )
+      {
+        if (ge.m_refIdc[j])
+        {
+          Int deltaPOC = ge.m_deltaRPS + ((j < RPSRef->getNumberOfPictures())? RPSRef->getDeltaPOC(j) : 0);
+          RPSTemp.setDeltaPOC((numNeg+numPos),deltaPOC);
+          RPSTemp.setUsed((numNeg+numPos),ge.m_refIdc[j]==1?1:0);
+          if (deltaPOC<0)
+          {
+            numNeg++;
+          }
+          else
+          {
+            numPos++;
+          }
+        }
+      }
+      if (numNeg != rps->getNumberOfNegativePictures())
+      {
+        printf("Warning: number of negative pictures in RPS is different between intra and inter RPS specified in the config file.\n");
+        rps->setNumberOfNegativePictures(numNeg);
+        rps->setNumberOfPositivePictures(numNeg+numPos);
+      }
+      if (numPos != rps->getNumberOfPositivePictures())
+      {
+        printf("Warning: number of positive pictures in RPS is different between intra and inter RPS specified in the config file.\n");
+        rps->setNumberOfPositivePictures(numPos);
+        rps->setNumberOfPositivePictures(numNeg+numPos);
+      }
+      RPSTemp.setNumberOfPictures(numNeg+numPos);
+      RPSTemp.setNumberOfNegativePictures(numNeg);
+      RPSTemp.sortDeltaPOC();     // sort the created delta POC before comparing
+      // check if Delta POC and Used are the same 
+      // print warning if they are not.
+      for (Int j = 0; j < ge.m_numRefIdc; j++ )
+      {
+        if (RPSTemp.getDeltaPOC(j) != rps->getDeltaPOC(j))
+        {
+          printf("Warning: delta POC is different between intra RPS and inter RPS specified in the config file.\n");
+          rps->setDeltaPOC(j,RPSTemp.getDeltaPOC(j));
+        }
+        if (RPSTemp.getUsed(j) != rps->getUsed(j))
+        {
+          printf("Warning: Used by Current in RPS is different between intra and inter RPS specified in the config file.\n");
+          rps->setUsed(j,RPSTemp.getUsed(j));
+        }
+      }
+#endif
+    }
+#else
+    rps->setInterRPSPrediction(ge.m_interRPSPrediction);
+    if (ge.m_interRPSPrediction)
+    {
+#if J0234_INTER_RPS_SIMPL
+      rps->setDeltaRIdxMinus1(0);
+#else
+      rps->setDeltaRIdxMinus1(ge.m_deltaRIdxMinus1);
+#endif
+      rps->setDeltaRPS(ge.m_deltaRPS);
+      rps->setNumRefIdc(ge.m_numRefIdc);
+      for (Int j = 0; j < ge.m_numRefIdc; j++ )
+      {
+        rps->setRefIdc(j, ge.m_refIdc[j]);
+      }
+#if WRITE_BACK
+      // the folowing code overwrite the deltaPOC and Used by current values read from the config file with the ones
+      // computed from the RefIdc.  This is not necessary if both are identical. Currently there is no check to see if they are identical.
+      numNeg = 0;
+      numPos = 0;
+#if J0234_INTER_RPS_SIMPL
+      TComReferencePictureSet*     RPSRef = m_RPSList.getReferencePictureSet(i-1);
+#else
+      TComReferencePictureSet*     RPSRef = m_RPSList.getReferencePictureSet(i-(ge.m_deltaRIdxMinus1+1));
+#endif
+
+      for (Int j = 0; j < ge.m_numRefIdc; j++ )
+      {
+        if (ge.m_refIdc[j])
+        {
+          Int deltaPOC = ge.m_deltaRPS + ((j < RPSRef->getNumberOfPictures())? RPSRef->getDeltaPOC(j) : 0);
+          rps->setDeltaPOC((numNeg+numPos),deltaPOC);
+          rps->setUsed((numNeg+numPos),ge.m_refIdc[j]==1?1:0);
+          if (deltaPOC<0)
+          {
+            numNeg++;
+          }
+          else
+          {
+            numPos++;
+          }
+        }
+      }
+      rps->setNumberOfNegativePictures(numNeg);
+      rps->setNumberOfPositivePictures(numPos);
+      rps->sortDeltaPOC();
+#endif
+    }
+#endif //INTER_RPS_AUTO
+  }
+  
+}
+
+   // This is a function that 
+   // determines what Reference Picture Set to use 
+   // for a specific slice (with POC = POCCurr)
+Void TEncTop::selectReferencePictureSet(TComSlice* slice, Int POCCurr, Int GOPid,TComList<TComPic*>& listPic )
+{
+  slice->setRPSidx(GOPid);
+
+  for(Int extraNum=m_iGOPSize; extraNum<m_extraRPSs+m_iGOPSize; extraNum++)
+  {    
+    if(m_uiIntraPeriod > 0 && getDecodingRefreshType() > 0)
+    {
+      Int POCIndex = POCCurr%m_uiIntraPeriod;
+      if(POCIndex == 0)
+      {
+        POCIndex = m_uiIntraPeriod;
+      }
+      if(POCIndex == m_GOPList[extraNum].m_POC)
+      {
+        slice->setRPSidx(extraNum);
+      }
+    }
+    else
+    {
+      if(POCCurr==m_GOPList[extraNum].m_POC)
+      {
+        slice->setRPSidx(extraNum);
+      }
+    }
+  }
+
+  slice->setRPS(getSPS()->getRPSList()->getReferencePictureSet(slice->getRPSidx()));
+  slice->getRPS()->setNumberOfPictures(slice->getRPS()->getNumberOfNegativePictures()+slice->getRPS()->getNumberOfPositivePictures());
+
+}
+
+Void  TEncTop::xInitPPSforTiles()
+{
+  m_cPPS.setUniformSpacingFlag( m_iUniformSpacingIdr );
+  m_cPPS.setNumColumnsMinus1( m_iNumColumnsMinus1 );
+  m_cPPS.setNumRowsMinus1( m_iNumRowsMinus1 );
+  if( m_iUniformSpacingIdr == 0 )
+  {
+    m_cPPS.setColumnWidth( m_puiColumnWidth );
+    m_cPPS.setRowHeight( m_puiRowHeight );
+  }
+  m_cPPS.setLoopFilterAcrossTilesEnabledFlag( m_loopFilterAcrossTilesEnabledFlag );
+
+  // # substreams is "per tile" when tiles are independent.
+  if (m_iWaveFrontSynchro
+    )
+  {
+    m_cPPS.setNumSubstreams(m_iWaveFrontSubstreams * (m_iNumColumnsMinus1+1));
+  }
+}
+
+Void  TEncCfg::xCheckGSParameters()
+{
+  Int   iWidthInCU = ( m_iSourceWidth%g_uiMaxCUWidth ) ? m_iSourceWidth/g_uiMaxCUWidth + 1 : m_iSourceWidth/g_uiMaxCUWidth;
+  Int   iHeightInCU = ( m_iSourceHeight%g_uiMaxCUHeight ) ? m_iSourceHeight/g_uiMaxCUHeight + 1 : m_iSourceHeight/g_uiMaxCUHeight;
+  UInt  uiCummulativeColumnWidth = 0;
+  UInt  uiCummulativeRowHeight = 0;
+
+  //check the column relative parameters
+  if( m_iNumColumnsMinus1 >= (1<<(LOG2_MAX_NUM_COLUMNS_MINUS1+1)) )
+  {
+    printf( "The number of columns is larger than the maximum allowed number of columns.\n" );
+    exit( EXIT_FAILURE );
+  }
+
+  if( m_iNumColumnsMinus1 >= iWidthInCU )
+  {
+    printf( "The current picture can not have so many columns.\n" );
+    exit( EXIT_FAILURE );
+  }
+
+  if( m_iNumColumnsMinus1 && m_iUniformSpacingIdr==0 )
+  {
+    for(Int i=0; i<m_iNumColumnsMinus1; i++)
+    {
+      uiCummulativeColumnWidth += m_puiColumnWidth[i];
+    }
+
+    if( uiCummulativeColumnWidth >= iWidthInCU )
+    {
+      printf( "The width of the column is too large.\n" );
+      exit( EXIT_FAILURE );
+    }
+  }
+
+  //check the row relative parameters
+  if( m_iNumRowsMinus1 >= (1<<(LOG2_MAX_NUM_ROWS_MINUS1+1)) )
+  {
+    printf( "The number of rows is larger than the maximum allowed number of rows.\n" );
+    exit( EXIT_FAILURE );
+  }
+
+  if( m_iNumRowsMinus1 >= iHeightInCU )
+  {
+    printf( "The current picture can not have so many rows.\n" );
+    exit( EXIT_FAILURE );
+  }
+
+  if( m_iNumRowsMinus1 && m_iUniformSpacingIdr==0 )
+  {
+    for(Int i=0; i<m_iNumRowsMinus1; i++)
+      uiCummulativeRowHeight += m_puiRowHeight[i];
+
+    if( uiCummulativeRowHeight >= iHeightInCU )
+    {
+      printf( "The height of the row is too large.\n" );
+      exit( EXIT_FAILURE );
+    }
+  }
+}
+//! \}
Index: /trunk/source/Lib/TLibEncoder/TEncTop.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncTop.h	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/TEncTop.h	(revision 2)
@@ -0,0 +1,235 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncTop.h
+    \brief    encoder class (header)
+*/
+
+#ifndef __TENCTOP__
+#define __TENCTOP__
+
+// Include files
+#include "TLibCommon/TComList.h"
+#include "TLibCommon/TComPrediction.h"
+#include "TLibCommon/TComTrQuant.h"
+#include "TLibCommon/AccessUnit.h"
+
+#include "TLibVideoIO/TVideoIOYuv.h"
+
+#include "TEncCfg.h"
+#include "TEncGOP.h"
+#include "TEncSlice.h"
+#include "TEncEntropy.h"
+#include "TEncCavlc.h"
+#include "TEncSbac.h"
+#include "TEncSearch.h"
+#include "TEncAdaptiveLoopFilter.h"
+#include "TEncSampleAdaptiveOffset.h"
+#include "TEncPreanalyzer.h"
+#include "TEncRateCtrl.h"
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// encoder class
+class TEncTop : public TEncCfg
+{
+private:
+  // picture
+  Int                     m_iPOCLast;                     ///< time index (POC)
+  Int                     m_iNumPicRcvd;                  ///< number of received pictures
+  UInt                    m_uiNumAllPicCoded;             ///< number of coded pictures
+  TComList<TComPic*>      m_cListPic;                     ///< dynamic list of pictures
+#if SVC_EXTENSION 
+  static Int              m_iSPSIdCnt;                    ///< next Id number for SPS    
+  static Int              m_iPPSIdCnt;                    ///< next Id number for PPS    
+#endif
+  
+  // encoder search
+  TEncSearch              m_cSearch;                      ///< encoder search class
+  TEncEntropy*            m_pcEntropyCoder;                     ///< entropy encoder 
+  TEncCavlc*              m_pcCavlcCoder;                       ///< CAVLC encoder  
+  // coding tool
+  TComTrQuant             m_cTrQuant;                     ///< transform & quantization class
+  TComLoopFilter          m_cLoopFilter;                  ///< deblocking filter class
+  TEncSampleAdaptiveOffset m_cEncSAO;                     ///< sample adaptive offset class
+#if !REMOVE_ALF
+  TEncAdaptiveLoopFilter  m_cAdaptiveLoopFilter;          ///< adaptive loop filter class
+#endif
+  TEncEntropy             m_cEntropyCoder;                ///< entropy encoder
+  TEncCavlc               m_cCavlcCoder;                  ///< CAVLC encoder
+  TEncSbac                m_cSbacCoder;                   ///< SBAC encoder
+  TEncBinCABAC            m_cBinCoderCABAC;               ///< bin coder CABAC
+  TEncSbac*               m_pcSbacCoders;                 ///< SBAC encoders (to encode substreams )
+  TEncBinCABAC*           m_pcBinCoderCABACs;             ///< bin coders CABAC (one per substream)
+  
+  // processing unit
+  TEncGOP                 m_cGOPEncoder;                  ///< GOP encoder
+  TEncSlice               m_cSliceEncoder;                ///< slice encoder
+  TEncCu                  m_cCuEncoder;                   ///< CU encoder
+  // SPS
+  TComSPS                 m_cSPS;                         ///< SPS
+  TComPPS                 m_cPPS;                         ///< PPS
+#if !REMOVE_APS
+  std::vector<TComAPS>    m_vAPS;  //!< APS container
+#endif
+  // RD cost computation
+  TComBitCounter          m_cBitCounter;                  ///< bit counter for RD optimization
+  TComRdCost              m_cRdCost;                      ///< RD cost computation class
+  TEncSbac***             m_pppcRDSbacCoder;              ///< temporal storage for RD computation
+  TEncSbac                m_cRDGoOnSbacCoder;             ///< going on SBAC model for RD stage
+#if FAST_BIT_EST
+  TEncBinCABACCounter***  m_pppcBinCoderCABAC;            ///< temporal CABAC state storage for RD computation
+  TEncBinCABACCounter     m_cRDGoOnBinCoderCABAC;         ///< going on bin coder CABAC for RD stage
+#else
+  TEncBinCABAC***         m_pppcBinCoderCABAC;            ///< temporal CABAC state storage for RD computation
+  TEncBinCABAC            m_cRDGoOnBinCoderCABAC;         ///< going on bin coder CABAC for RD stage
+#endif
+  Int                     m_iNumSubstreams;                ///< # of top-level elements allocated.
+  TComBitCounter*         m_pcBitCounters;                 ///< bit counters for RD optimization per substream
+  TComRdCost*             m_pcRdCosts;                     ///< RD cost computation class per substream
+  TEncSbac****            m_ppppcRDSbacCoders;             ///< temporal storage for RD computation per substream
+  TEncSbac*               m_pcRDGoOnSbacCoders;            ///< going on SBAC model for RD stage per substream
+  TEncBinCABAC****        m_ppppcBinCodersCABAC;           ///< temporal CABAC state storage for RD computation per substream
+  TEncBinCABAC*           m_pcRDGoOnBinCodersCABAC;        ///< going on bin coder CABAC for RD stage per substream
+
+  // quality control
+  TEncPreanalyzer         m_cPreanalyzer;                 ///< image characteristics analyzer for TM5-step3-like adaptive QP
+
+  TComScalingList         m_scalingList;                 ///< quantization matrix information
+  TEncRateCtrl            m_cRateCtrl;                    ///< Rate control class
+  
+#if SVC_EXTENSION
+  TEncTop**               m_ppcTEncTop;
+  TEncTop*                getLayerEnc(UInt layer)   { return m_ppcTEncTop[layer]; }
+#endif
+#if REF_IDX_FRAMEWORK
+  TComPic*                m_cIlpPic[MAX_NUM_REF];                    ///<  Inter layer Prediction picture =  upsampled picture 
+#endif
+protected:
+  Void  xGetNewPicBuffer  ( TComPic*& rpcPic );           ///< get picture buffer which will be processed
+  Void  xInitSPS          ();                             ///< initialize SPS from encoder options
+  Void  xInitPPS          ();                             ///< initialize PPS from encoder options
+  
+  Void  xInitPPSforTiles  ();
+  Void  xInitRPS          ();                             ///< initialize PPS from encoder options
+#if REF_IDX_FRAMEWORK
+  Void xInitILRP();
+#endif
+public:
+  TEncTop();
+  virtual ~TEncTop();
+  
+  Void      create          ();
+  Void      destroy         ();
+  Void      init            ();
+  Void      deletePicBuffer ();
+
+  Void      createWPPCoders(Int iNumSubstreams);
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // member access functions
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  TComList<TComPic*>*     getListPic            () { return  &m_cListPic;             }
+  TEncSearch*             getPredSearch         () { return  &m_cSearch;              }
+  
+  TComTrQuant*            getTrQuant            () { return  &m_cTrQuant;             }
+  TComLoopFilter*         getLoopFilter         () { return  &m_cLoopFilter;          }
+#if !REMOVE_ALF
+  TEncAdaptiveLoopFilter* getAdaptiveLoopFilter () { return  &m_cAdaptiveLoopFilter;  }
+#endif
+  TEncSampleAdaptiveOffset* getSAO              () { return  &m_cEncSAO;              }
+  TEncGOP*                getGOPEncoder         () { return  &m_cGOPEncoder;          }
+  TEncSlice*              getSliceEncoder       () { return  &m_cSliceEncoder;        }
+  TEncCu*                 getCuEncoder          () { return  &m_cCuEncoder;           }
+  TEncEntropy*            getEntropyCoder       () { return  &m_cEntropyCoder;        }
+  TEncCavlc*              getCavlcCoder         () { return  &m_cCavlcCoder;          }
+  TEncSbac*               getSbacCoder          () { return  &m_cSbacCoder;           }
+  TEncBinCABAC*           getBinCABAC           () { return  &m_cBinCoderCABAC;       }
+  TEncSbac*               getSbacCoders     () { return  m_pcSbacCoders;      }
+  TEncBinCABAC*           getBinCABACs          () { return  m_pcBinCoderCABACs;      }
+  
+  TComBitCounter*         getBitCounter         () { return  &m_cBitCounter;          }
+  TComRdCost*             getRdCost             () { return  &m_cRdCost;              }
+  TEncSbac***             getRDSbacCoder        () { return  m_pppcRDSbacCoder;       }
+  TEncSbac*               getRDGoOnSbacCoder    () { return  &m_cRDGoOnSbacCoder;     }
+  TComBitCounter*         getBitCounters        () { return  m_pcBitCounters;         }
+  TComRdCost*             getRdCosts            () { return  m_pcRdCosts;             }
+  TEncSbac****            getRDSbacCoders       () { return  m_ppppcRDSbacCoders;     }
+  TEncSbac*               getRDGoOnSbacCoders   () { return  m_pcRDGoOnSbacCoders;   }
+  TEncRateCtrl*           getRateCtrl           () { return &m_cRateCtrl;             }
+  TComSPS*                getSPS                () { return  &m_cSPS;                 }
+  TComPPS*                getPPS                () { return  &m_cPPS;                 }
+#if !REMOVE_APS
+  std::vector<TComAPS>&   getAPS                () { return m_vAPS; }
+#endif
+#if SVC_EXTENSION  
+  Void                    setLayerEnc(TEncTop** p) {m_ppcTEncTop = p;}
+  TEncTop**               getLayerEnc()            {return m_ppcTEncTop;}
+#endif
+  Void selectReferencePictureSet(TComSlice* slice, Int POCCurr, Int GOPid,TComList<TComPic*>& listPic );
+  TComScalingList*        getScalingList        () { return  &m_scalingList;         }
+#if SVC_EXTENSION
+  Int                     getPOCLast            () { return m_iPOCLast;               }
+  Int                     getNumPicRcvd         () { return m_iNumPicRcvd;            }
+  Void                    setNumPicRcvd         ( Int num ) { m_iNumPicRcvd = num;      }
+#endif
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // encoder function
+  // -------------------------------------------------------------------------------------------------------------------
+
+  /// encode several number of pictures until end-of-sequence
+#if SVC_EXTENSION
+  Void encode( TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut,
+              std::list<AccessUnit>& accessUnitsOut, Int iPicIdInGOP  );
+
+  Void encodePrep( bool bEos, TComPicYuv* pcPicYuvOrg );
+#else
+  Void encode( bool bEos, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut,
+              std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded );  
+#endif
+#if REF_IDX_FRAMEWORK
+  TComPic** getIlpList() { return m_cIlpPic; }
+  Void setILRPic(TComPic *pcPic);
+#endif
+
+};
+
+//! \}
+
+#endif // __TENCTOP__
Index: /trunk/source/Lib/TLibEncoder/WeightPredAnalysis.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/WeightPredAnalysis.cpp	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/WeightPredAnalysis.cpp	(revision 2)
@@ -0,0 +1,519 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     WeightedPredAnalysis.cpp
+    \brief    encoder class
+*/
+
+#include "../TLibCommon/TypeDef.h"
+#include "../TLibCommon/TComSlice.h"
+#include "../TLibCommon/TComPic.h"
+#include "../TLibCommon/TComPicYuv.h"
+#include "WeightPredAnalysis.h"
+
+#define ABS(a)    ((a) < 0 ? - (a) : (a))
+#define DTHRESH (0.99)
+
+WeightPredAnalysis::WeightPredAnalysis()
+{
+  m_weighted_pred_flag = false;
+  m_weighted_bipred_flag = false;
+  for ( Int iList =0 ; iList<2 ; iList++ )
+  {
+    for ( Int iRefIdx=0 ; iRefIdx<MAX_NUM_REF ; iRefIdx++ ) 
+    {
+      for ( int comp=0 ; comp<3 ;comp++ ) 
+      {
+        wpScalingParam  *pwp   = &(m_wp[iList][iRefIdx][comp]);
+        pwp->bPresentFlag      = false;
+        pwp->uiLog2WeightDenom = 0;
+        pwp->iWeight           = 1;
+        pwp->iOffset           = 0;
+      }
+    }
+  }
+}
+
+/** calculate AC and DC values for current original image
+ * \param TComSlice *slice
+ * \returns Void
+ */
+Bool  WeightPredAnalysis::xCalcACDCParamSlice(TComSlice *slice)
+{
+  //===== calculate AC/DC value =====
+  TComPicYuv*   pPic = slice->getPic()->getPicYuvOrg();
+  Int   iSample  = 0;
+
+  // calculate DC/AC value for Y
+  Pel*  pOrg    = pPic->getLumaAddr();
+  Int64  iOrgDCY = xCalcDCValueSlice(slice, pOrg, &iSample);
+  Int64  iOrgNormDCY = ((iOrgDCY+(iSample>>1)) / iSample);
+  pOrg = pPic->getLumaAddr();
+  Int64  iOrgACY  = xCalcACValueSlice(slice, pOrg, iOrgNormDCY);
+
+  // calculate DC/AC value for Cb
+  pOrg = pPic->getCbAddr();
+  Int64  iOrgDCCb = xCalcDCValueUVSlice(slice, pOrg, &iSample);
+  Int64  iOrgNormDCCb = ((iOrgDCCb+(iSample>>1)) / (iSample));
+  pOrg = pPic->getCbAddr();
+  Int64  iOrgACCb  = xCalcACValueUVSlice(slice, pOrg, iOrgNormDCCb);
+
+  // calculate DC/AC value for Cr
+  pOrg = pPic->getCrAddr();
+  Int64  iOrgDCCr = xCalcDCValueUVSlice(slice, pOrg, &iSample);
+  Int64  iOrgNormDCCr = ((iOrgDCCr+(iSample>>1)) / (iSample));
+  pOrg = pPic->getCrAddr();
+  Int64  iOrgACCr  = xCalcACValueUVSlice(slice, pOrg, iOrgNormDCCr);
+
+  wpACDCParam weightACDCParam[3];
+  weightACDCParam[0].iAC = iOrgACY;
+  weightACDCParam[0].iDC = iOrgNormDCY;
+  weightACDCParam[1].iAC = iOrgACCb;
+  weightACDCParam[1].iDC = iOrgNormDCCb;
+  weightACDCParam[2].iAC = iOrgACCr;
+  weightACDCParam[2].iDC = iOrgNormDCCr;
+
+  slice->setWpAcDcParam(weightACDCParam);
+  return (true);
+}
+
+/** store weighted_pred_flag and weighted_bipred_idc values
+ * \param weighted_pred_flag
+ * \param weighted_bipred_idc
+ * \returns Void
+ */
+Void  WeightPredAnalysis::xStoreWPparam(Bool weighted_pred_flag, Bool weighted_bipred_flag)
+{
+  m_weighted_pred_flag = weighted_pred_flag;
+  m_weighted_bipred_flag = weighted_bipred_flag;
+}
+
+/** restore weighted_pred_flag and weighted_bipred_idc values
+ * \param TComSlice *slice
+ * \returns Void
+ */
+Void  WeightPredAnalysis::xRestoreWPparam(TComSlice *slice)
+{
+  slice->getPPS()->setUseWP(m_weighted_pred_flag);
+  slice->getPPS()->setWPBiPred(m_weighted_bipred_flag);
+}
+
+/** check weighted pred or non-weighted pred
+ * \param TComSlice *slice
+ * \returns Void
+ */
+Void  WeightPredAnalysis::xCheckWPEnable(TComSlice *slice)
+{
+  Int iPresentCnt = 0;
+  for ( Int iList=0 ; iList<2 ; iList++ )
+  {
+    for ( Int iRefIdx=0 ; iRefIdx<MAX_NUM_REF ; iRefIdx++ ) 
+    {
+      for ( Int iComp=0 ; iComp<3 ;iComp++ ) 
+      {
+        wpScalingParam  *pwp = &(m_wp[iList][iRefIdx][iComp]);
+        iPresentCnt += (Int)pwp->bPresentFlag;
+      }
+    }
+  }
+
+  if(iPresentCnt==0)
+  {
+    slice->getPPS()->setUseWP(false);
+    slice->getPPS()->setWPBiPred(false);
+    for ( Int iList=0 ; iList<2 ; iList++ )
+    {
+      for ( Int iRefIdx=0 ; iRefIdx<MAX_NUM_REF ; iRefIdx++ ) 
+      {
+        for ( Int iComp=0 ; iComp<3 ;iComp++ ) 
+        {
+          wpScalingParam  *pwp = &(m_wp[iList][iRefIdx][iComp]);
+          pwp->bPresentFlag      = false;
+          pwp->uiLog2WeightDenom = 0;
+          pwp->iWeight           = 1;
+          pwp->iOffset           = 0;
+        }
+      }
+    }
+    slice->setWpScaling( m_wp );
+  }
+}
+
+/** estimate wp tables for explicit wp
+ * \param TComSlice *slice
+ * \returns Bool
+ */
+Bool  WeightPredAnalysis::xEstimateWPParamSlice(TComSlice *slice)
+{
+  Int iDenom  = 6;
+#if WP_PARAM_RANGE_LIMIT
+  Bool validRangeFlag = false;
+#else
+  Int iRealDenom = iDenom + (g_uiBitDepth+g_uiBitIncrement-8);
+  Int iRealOffset = ((Int)1<<(iRealDenom-1));
+#endif
+
+  if(slice->getNumRefIdx(REF_PIC_LIST_0)>3)
+  {
+    iDenom  = 7;
+#if WP_PARAM_RANGE_LIMIT
+#else
+    iRealDenom = iDenom + (g_uiBitDepth+g_uiBitIncrement-8);
+    iRealOffset = ((Int)1<<(iRealDenom-1));
+#endif
+  }
+
+#if WP_PARAM_RANGE_LIMIT
+  do
+  {
+    validRangeFlag = xUpdatingWPParameters(slice, m_wp, iDenom);
+    if (!validRangeFlag)
+    {
+      iDenom--; // decrement to satisfy the range limitation
+    }
+  } while (validRangeFlag == false);
+#else
+  Int iNumPredDir = slice->isInterP() ? 1 : 2;
+  for ( Int iRefList = 0; iRefList < iNumPredDir; iRefList++ )
+  {
+    RefPicList  eRefPicList = ( iRefList ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
+    for ( Int iRefIdxTemp = 0; iRefIdxTemp < slice->getNumRefIdx(eRefPicList); iRefIdxTemp++ )
+    {
+      wpACDCParam *CurrWeightACDCParam, *RefWeightACDCParam;
+      slice->getWpAcDcParam(CurrWeightACDCParam);
+      slice->getRefPic(eRefPicList, iRefIdxTemp)->getSlice(0)->getWpAcDcParam(RefWeightACDCParam);
+
+      for ( Int iComp = 0; iComp < 3; iComp++ )
+      {
+        // current frame
+        Int64 iCurrDC = CurrWeightACDCParam[iComp].iDC;
+        Int64 iCurrAC = CurrWeightACDCParam[iComp].iAC;
+        // reference frame
+        Int64 iRefDC = RefWeightACDCParam[iComp].iDC;
+        Int64 iRefAC = RefWeightACDCParam[iComp].iAC;
+
+        // calculating iWeight and iOffset params
+        Double dWeight = (iRefAC==0) ? (Double)1.0 : Clip3( -16.0, 15.0, ((Double)iCurrAC / (Double)iRefAC) );
+        Int iWeight = (Int)( 0.5 + dWeight * (Double)(1<<iDenom) );
+        Int iOffset = (Int)( ((iCurrDC<<iDenom) - ((Int64)iWeight * iRefDC) + (Int64)iRealOffset) >> iRealDenom );
+
+        m_wp[iRefList][iRefIdxTemp][iComp].bPresentFlag = true;
+        m_wp[iRefList][iRefIdxTemp][iComp].iWeight = (Int)iWeight;
+        m_wp[iRefList][iRefIdxTemp][iComp].iOffset = (Int)iOffset;
+        m_wp[iRefList][iRefIdxTemp][iComp].uiLog2WeightDenom = (Int)iDenom;
+      }
+    }
+  }
+#endif
+
+  // selecting whether WP is used, or not
+  xSelectWP(slice, m_wp, iDenom);
+  
+  slice->setWpScaling( m_wp );
+
+  return (true);
+}
+
+#if WP_PARAM_RANGE_LIMIT
+/** update wp tables for explicit wp w.r.t ramge limitation
+ * \param TComSlice *slice
+ * \returns Bool
+ */
+Bool WeightPredAnalysis::xUpdatingWPParameters(TComSlice *slice, wpScalingParam weightPredTable[2][MAX_NUM_REF][3], Int log2Denom)
+{
+  Int realLog2Denom = log2Denom + (g_uiBitDepth+g_uiBitIncrement-8);
+  Int realOffset = ((Int)1<<(realLog2Denom-1));
+
+  Int numPredDir = slice->isInterP() ? 1 : 2;
+  for ( Int refList = 0; refList < numPredDir; refList++ )
+  {
+    RefPicList  eRefPicList = ( refList ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
+    for ( Int refIdxTemp = 0; refIdxTemp < slice->getNumRefIdx(eRefPicList); refIdxTemp++ )
+    {
+      wpACDCParam *currWeightACDCParam, *refWeightACDCParam;
+      slice->getWpAcDcParam(currWeightACDCParam);
+      slice->getRefPic(eRefPicList, refIdxTemp)->getSlice(0)->getWpAcDcParam(refWeightACDCParam);
+
+      for ( Int comp = 0; comp < 3; comp++ )
+      {
+        // current frame
+        Int64 currDC = currWeightACDCParam[comp].iDC;
+        Int64 currAC = currWeightACDCParam[comp].iAC;
+        // reference frame
+        Int64 refDC = refWeightACDCParam[comp].iDC;
+        Int64 refAC = refWeightACDCParam[comp].iAC;
+
+        // calculating iWeight and iOffset params
+        Double dWeight = (refAC==0) ? (Double)1.0 : Clip3( -16.0, 15.0, ((Double)currAC / (Double)refAC) );
+        Int weight = (Int)( 0.5 + dWeight * (Double)(1<<log2Denom) );
+        Int offset = (Int)( ((currDC<<log2Denom) - ((Int64)weight * refDC) + (Int64)realOffset) >> realLog2Denom );
+
+        // Chroma offset range limination
+        if(comp)
+        {
+          Int shift = ((1<<(g_uiBitDepth+g_uiBitIncrement-1)));
+          Int pred = ( shift - ( ( shift*weight)>>(log2Denom) ) );
+          Int deltaOffset = Clip3( -512, 511, (offset - pred) );    // signed 10bit
+          offset = Clip3( -128, 127, (deltaOffset + pred) );        // signed 8bit
+        }
+
+        // Weighting factor limitation
+        Int defaultWeight = (1<<log2Denom);
+        Int deltaWeight = (defaultWeight - weight);
+        if(deltaWeight > 127 || deltaWeight < -128)
+          return (false);
+
+        m_wp[refList][refIdxTemp][comp].bPresentFlag = true;
+        m_wp[refList][refIdxTemp][comp].iWeight = (Int)weight;
+        m_wp[refList][refIdxTemp][comp].iOffset = (Int)offset;
+        m_wp[refList][refIdxTemp][comp].uiLog2WeightDenom = (Int)log2Denom;
+      }
+    }
+  }
+  return (true);
+}
+#endif
+
+/** select whether weighted pred enables or not. 
+ * \param TComSlice *slice
+ * \param wpScalingParam
+ * \param iDenom
+ * \returns Bool
+ */
+Bool WeightPredAnalysis::xSelectWP(TComSlice *slice, wpScalingParam weightPredTable[2][MAX_NUM_REF][3], Int iDenom)
+{
+  TComPicYuv*   pPic = slice->getPic()->getPicYuvOrg();
+  Int iWidth  = pPic->getWidth();
+  Int iHeight = pPic->getHeight();
+  Int iDefaultWeight = ((Int)1<<iDenom);
+  Int iNumPredDir = slice->isInterP() ? 1 : 2;
+
+  for ( Int iRefList = 0; iRefList < iNumPredDir; iRefList++ )
+  {
+    Int64 iSADWP = 0, iSADnoWP = 0;
+    RefPicList  eRefPicList = ( iRefList ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
+    for ( Int iRefIdxTemp = 0; iRefIdxTemp < slice->getNumRefIdx(eRefPicList); iRefIdxTemp++ )
+    {
+      Pel*  pOrg    = pPic->getLumaAddr();
+      Pel*  pRef    = slice->getRefPic(eRefPicList, iRefIdxTemp)->getPicYuvRec()->getLumaAddr();
+      Int   iOrgStride = pPic->getStride();
+      Int   iRefStride = slice->getRefPic(eRefPicList, iRefIdxTemp)->getPicYuvRec()->getStride();
+
+      // calculate SAD costs with/without wp for luma
+      iSADWP   = this->xCalcSADvalueWP(pOrg, pRef, iWidth, iHeight, iOrgStride, iRefStride, iDenom, weightPredTable[iRefList][iRefIdxTemp][0].iWeight, weightPredTable[iRefList][iRefIdxTemp][0].iOffset);
+      iSADnoWP = this->xCalcSADvalueWP(pOrg, pRef, iWidth, iHeight, iOrgStride, iRefStride, iDenom, iDefaultWeight, 0);
+
+      pOrg = pPic->getCbAddr();
+      pRef = slice->getRefPic(eRefPicList, iRefIdxTemp)->getPicYuvRec()->getCbAddr();
+      iOrgStride = pPic->getCStride();
+      iRefStride = slice->getRefPic(eRefPicList, iRefIdxTemp)->getPicYuvRec()->getCStride();
+
+      // calculate SAD costs with/without wp for chroma cb
+      iSADWP   += this->xCalcSADvalueWP(pOrg, pRef, iWidth>>1, iHeight>>1, iOrgStride, iRefStride, iDenom, weightPredTable[iRefList][iRefIdxTemp][1].iWeight, weightPredTable[iRefList][iRefIdxTemp][1].iOffset);
+      iSADnoWP += this->xCalcSADvalueWP(pOrg, pRef, iWidth>>1, iHeight>>1, iOrgStride, iRefStride, iDenom, iDefaultWeight, 0);
+
+      pOrg = pPic->getCrAddr();
+      pRef = slice->getRefPic(eRefPicList, iRefIdxTemp)->getPicYuvRec()->getCrAddr();
+
+      // calculate SAD costs with/without wp for chroma cr
+      iSADWP   += this->xCalcSADvalueWP(pOrg, pRef, iWidth>>1, iHeight>>1, iOrgStride, iRefStride, iDenom, weightPredTable[iRefList][iRefIdxTemp][2].iWeight, weightPredTable[iRefList][iRefIdxTemp][2].iOffset);
+      iSADnoWP += this->xCalcSADvalueWP(pOrg, pRef, iWidth>>1, iHeight>>1, iOrgStride, iRefStride, iDenom, iDefaultWeight, 0);
+
+      Double dRatio = ((Double)iSADWP / (Double)iSADnoWP);
+      if(dRatio >= (Double)DTHRESH)
+      {
+        for ( Int iComp = 0; iComp < 3; iComp++ )
+        {
+          weightPredTable[iRefList][iRefIdxTemp][iComp].bPresentFlag = false;
+          weightPredTable[iRefList][iRefIdxTemp][iComp].iOffset = (Int)0;
+          weightPredTable[iRefList][iRefIdxTemp][iComp].iWeight = (Int)iDefaultWeight;
+          weightPredTable[iRefList][iRefIdxTemp][iComp].uiLog2WeightDenom = (Int)iDenom;
+        }
+      }
+    }
+  }
+  return (true);
+}
+
+/** calculate DC value of original image for luma. 
+ * \param TComSlice *slice
+ * \param Pel *pPel
+ * \param Int *iSample
+ * \returns Int64
+ */
+Int64 WeightPredAnalysis::xCalcDCValueSlice(TComSlice *slice, Pel *pPel, Int *iSample)
+{
+  TComPicYuv* pPic = slice->getPic()->getPicYuvOrg();
+  Int iStride = pPic->getStride();
+
+  *iSample = 0;
+  Int iWidth  = pPic->getWidth();
+  Int iHeight = pPic->getHeight();
+  *iSample = iWidth*iHeight;
+  Int64 iDC = xCalcDCValue(pPel, iWidth, iHeight, iStride);
+
+  return (iDC);
+}
+
+/** calculate AC value of original image for luma. 
+ * \param TComSlice *slice
+ * \param Pel *pPel
+ * \param Int iDC
+ * \returns Int64
+ */
+Int64 WeightPredAnalysis::xCalcACValueSlice(TComSlice *slice, Pel *pPel, Int64 iDC)
+{
+  TComPicYuv* pPic = slice->getPic()->getPicYuvOrg();
+  Int iStride = pPic->getStride();
+
+  Int iWidth  = pPic->getWidth();
+  Int iHeight = pPic->getHeight();
+  Int64 iAC = xCalcACValue(pPel, iWidth, iHeight, iStride, iDC);
+
+  return (iAC);
+}
+
+/** calculate DC value of original image for chroma. 
+ * \param TComSlice *slice
+ * \param Pel *pPel
+ * \param Int *iSample
+ * \returns Int64
+ */
+Int64 WeightPredAnalysis::xCalcDCValueUVSlice(TComSlice *slice, Pel *pPel, Int *iSample)
+{
+  TComPicYuv* pPic = slice->getPic()->getPicYuvOrg();
+  Int iCStride = pPic->getCStride();
+
+  *iSample = 0;
+  Int iWidth  = pPic->getWidth()>>1;
+  Int iHeight = pPic->getHeight()>>1;
+  *iSample = iWidth*iHeight;
+  Int64 iDC = xCalcDCValue(pPel, iWidth, iHeight, iCStride);
+
+  return (iDC);
+}
+
+/** calculate AC value of original image for chroma. 
+ * \param TComSlice *slice
+ * \param Pel *pPel
+ * \param Int iDC
+ * \returns Int64
+ */
+Int64 WeightPredAnalysis::xCalcACValueUVSlice(TComSlice *slice, Pel *pPel, Int64 iDC)
+{
+  TComPicYuv* pPic = slice->getPic()->getPicYuvOrg();
+  Int iCStride = pPic->getCStride();
+
+  Int iWidth  = pPic->getWidth()>>1;
+  Int iHeight = pPic->getHeight()>>1;
+  Int64 iAC = xCalcACValue(pPel, iWidth, iHeight, iCStride, iDC);
+
+  return (iAC);
+}
+
+/** calculate DC value. 
+ * \param Pel *pPel
+ * \param Int iWidth
+ * \param Int iHeight
+ * \param Int iStride
+ * \returns Int64
+ */
+Int64 WeightPredAnalysis::xCalcDCValue(Pel *pPel, Int iWidth, Int iHeight, Int iStride)
+{
+  Int x, y;
+  Int64 iDC = 0;
+  for( y = 0; y < iHeight; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+      iDC += (Int)( pPel[x] );
+    }
+    pPel += iStride;
+  }
+  return (iDC);
+}
+
+/** calculate AC value. 
+ * \param Pel *pPel
+ * \param Int iWidth
+ * \param Int iHeight
+ * \param Int iStride
+ * \param Int iDC
+ * \returns Int64
+ */
+Int64 WeightPredAnalysis::xCalcACValue(Pel *pPel, Int iWidth, Int iHeight, Int iStride, Int64 iDC)
+{
+  Int x, y;
+  Int64 iAC = 0;
+  for( y = 0; y < iHeight; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+      iAC += abs( (Int)pPel[x] - (Int)iDC );
+    }
+    pPel += iStride;
+  }
+  return (iAC);
+}
+
+/** calculate SAD values for both WP version and non-WP version. 
+ * \param Pel *pOrgPel
+ * \param Pel *pRefPel
+ * \param Int iWidth
+ * \param Int iHeight
+ * \param Int iOrgStride
+ * \param Int iRefStride
+ * \param Int iDenom
+ * \param Int iWeight
+ * \param Int iOffset
+ * \returns Int64
+ */
+Int64 WeightPredAnalysis::xCalcSADvalueWP(Pel *pOrgPel, Pel *pRefPel, Int iWidth, Int iHeight, Int iOrgStride, Int iRefStride, Int iDenom, Int iWeight, Int iOffset)
+{
+  Int x, y;
+  Int64 iSAD = 0;
+  Int64 iSize   = iWidth*iHeight;
+  Int64 iRealDenom = iDenom + (g_uiBitDepth+g_uiBitIncrement-8);
+  for( y = 0; y < iHeight; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+      iSAD += ABS(( ((Int64)pOrgPel[x]<<(Int64)iDenom) - ( (Int64)pRefPel[x] * (Int64)iWeight + ((Int64)iOffset<<iRealDenom) ) ) );
+    }
+    pOrgPel += iOrgStride;
+    pRefPel += iRefStride;
+  }
+  return (iSAD/iSize);
+}
+
+
Index: /trunk/source/Lib/TLibEncoder/WeightPredAnalysis.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/WeightPredAnalysis.h	(revision 2)
+++ /trunk/source/Lib/TLibEncoder/WeightPredAnalysis.h	(revision 2)
@@ -0,0 +1,78 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     WeightedPredAnalysis.h
+    \brief    encoder class
+*/
+#ifndef __WEIGHTPREDANALYSIS__
+#define __WEIGHTPREDANALYSIS__
+
+#include "../TLibCommon/TypeDef.h"
+#include "../TLibCommon/TComSlice.h"
+#include "TEncCavlc.h"
+
+class  WeightPredAnalysis
+{
+  Bool m_weighted_pred_flag;
+  Bool  m_weighted_bipred_flag;
+  wpScalingParam  m_wp[2][MAX_NUM_REF][3];
+
+  Int64   xCalcDCValueSlice(TComSlice *slice, Pel *pPel,Int *iSample);
+  Int64   xCalcACValueSlice(TComSlice *slice, Pel *pPel, Int64 iDC);
+  Int64   xCalcDCValueUVSlice(TComSlice *slice, Pel *pPel, Int *iSample);
+  Int64   xCalcACValueUVSlice(TComSlice *slice, Pel *pPel, Int64 iDC);
+  Int64   xCalcSADvalueWPSlice(TComSlice *slice, Pel *pOrgPel, Pel *pRefPel, Int iDenom, Int iWeight, Int iOffset);
+
+  Int64   xCalcDCValue(Pel *pPel, Int iWidth, Int iHeight, Int iStride);
+  Int64   xCalcACValue(Pel *pPel, Int iWidth, Int iHeight, Int iStride, Int64 iDC);
+  Int64   xCalcSADvalueWP(Pel *pOrgPel, Pel *pRefPel, Int iWidth, Int iHeight, Int iOrgStride, Int iRefStride, Int iDenom, Int iWeight, Int iOffset);
+  Bool    xSelectWP(TComSlice *slice, wpScalingParam weightPredTable[2][MAX_NUM_REF][3], Int iDenom);
+#if WP_PARAM_RANGE_LIMIT
+  Bool    xUpdatingWPParameters(TComSlice *slice, wpScalingParam weightPredTable[2][MAX_NUM_REF][3], Int log2Denom);
+#endif
+
+public:
+
+  WeightPredAnalysis();
+
+  // WP analysis :
+  Bool  xCalcACDCParamSlice(TComSlice *slice);
+  Bool  xEstimateWPParamSlice(TComSlice *slice);
+  Void  xStoreWPparam(Bool weighted_pred_flag, Bool weighted_bipred_flag);
+  Void  xRestoreWPparam(TComSlice *slice);
+  Void  xCheckWPEnable(TComSlice *slice);
+};
+
+#endif // __WEIGHTPREDANALYSIS__
+
+
Index: /trunk/source/Lib/TLibVideoIO/TVideoIOYuv.cpp
===================================================================
--- /trunk/source/Lib/TLibVideoIO/TVideoIOYuv.cpp	(revision 2)
+++ /trunk/source/Lib/TLibVideoIO/TVideoIOYuv.cpp	(revision 2)
@@ -0,0 +1,479 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TVideoIOYuv.cpp
+    \brief    YUV file I/O class
+*/
+
+#include <cstdlib>
+#include <fcntl.h>
+#include <assert.h>
+#include <sys/stat.h>
+#include <fstream>
+#include <iostream>
+
+#include "TLibCommon/TComRom.h"
+#include "TVideoIOYuv.h"
+
+using namespace std;
+
+/**
+ * Perform division with rounding of all pixels in img by
+ * 2<sup>shiftbits</sup>. All pixels are clipped to [minval, maxval]
+ *
+ * @param img        pointer to image to be transformed
+ * @param stride     distance between vertically adjacent pixels of img.
+ * @param width      width of active area in img.
+ * @param height     height of active area in img.
+ * @param shiftbits  number of rounding bits
+ * @param minval     minimum clipping value
+ * @param maxval     maximum clipping value
+ */
+static void invScalePlane(Pel* img, unsigned int stride, unsigned int width, unsigned int height,
+                       unsigned int shiftbits, Pel minval, Pel maxval)
+{
+  Pel offset = 1 << (shiftbits-1);
+  for (unsigned int y = 0; y < height; y++)
+  {
+    for (unsigned int x = 0; x < width; x++)
+    {
+      Pel val = (img[x] + offset) >> shiftbits;
+      img[x] = Clip3(minval, maxval, val);
+    }
+    img += stride;
+  }
+}
+
+/**
+ * Multiply all pixels in img by 2<sup>shiftbits</sup>.
+ *
+ * @param img        pointer to image to be transformed
+ * @param stride     distance between vertically adjacent pixels of img.
+ * @param width      width of active area in img.
+ * @param height     height of active area in img.
+ * @param shiftbits  number of bits to shift
+ */
+static void scalePlane(Pel* img, unsigned int stride, unsigned int width, unsigned int height,
+                       unsigned int shiftbits)
+{
+  for (unsigned int y = 0; y < height; y++)
+  {
+    for (unsigned int x = 0; x < width; x++)
+    {
+      img[x] <<= shiftbits;
+    }
+    img += stride;
+  }
+}
+
+/**
+ * Scale all pixels in img depending upon sign of shiftbits by a factor of
+ * 2<sup>shiftbits</sup>.
+ *
+ * @param img        pointer to image to be transformed
+ * @param stride  distance between vertically adjacent pixels of img.
+ * @param width   width of active area in img.
+ * @param height  height of active area in img.
+ * @param shiftbits if zero, no operation performed
+ *                  if > 0, multiply by 2<sup>shiftbits</sup>, see scalePlane()
+ *                  if < 0, divide and round by 2<sup>shiftbits</sup> and clip,
+ *                          see invScalePlane().
+ * @param minval  minimum clipping value when dividing.
+ * @param maxval  maximum clipping value when dividing.
+ */
+static void scalePlane(Pel* img, unsigned int stride, unsigned int width, unsigned int height,
+                       int shiftbits, Pel minval, Pel maxval)
+{
+  if (shiftbits == 0)
+  {
+    return;
+  }
+
+  if (shiftbits > 0)
+  {
+    scalePlane(img, stride, width, height, shiftbits);
+  }
+  else
+  {
+    invScalePlane(img, stride, width, height, -shiftbits, minval, maxval);
+  }
+}
+
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/**
+ * Open file for reading/writing Y'CbCr frames.
+ *
+ * Frames read/written have bitdepth fileBitDepth, and are automatically
+ * formatted as 8 or 16 bit word values (see TVideoIOYuv::write()).
+ *
+ * Image data read or written is converted to/from internalBitDepth
+ * (See scalePlane(), TVideoIOYuv::read() and TVideoIOYuv::write() for
+ * further details).
+ *
+ * \param pchFile          file name string
+ * \param bWriteMode       file open mode: true=read, false=write
+ * \param fileBitDepth     bit-depth of input/output file data.
+ * \param internalBitDepth bit-depth to scale image data to/from when reading/writing.
+ */
+Void TVideoIOYuv::open( char* pchFile, Bool bWriteMode, unsigned int fileBitDepth, unsigned int internalBitDepth )
+{
+  m_bitdepthShift = internalBitDepth - fileBitDepth;
+  m_fileBitdepth = fileBitDepth;
+
+  if ( bWriteMode )
+  {
+    m_cHandle.open( pchFile, ios::binary | ios::out );
+    
+    if( m_cHandle.fail() )
+    {
+      printf("\nfailed to write reconstructed YUV file\n");
+      exit(0);
+    }
+  }
+  else
+  {
+    m_cHandle.open( pchFile, ios::binary | ios::in );
+    
+    if( m_cHandle.fail() )
+    {
+      printf("\nfailed to open Input YUV file\n");
+      exit(0);
+    }
+  }
+  
+  return;
+}
+
+Void TVideoIOYuv::close()
+{
+  m_cHandle.close();
+}
+
+Bool TVideoIOYuv::isEof()
+{
+  return m_cHandle.eof();
+}
+
+Bool TVideoIOYuv::isFail()
+{
+  return m_cHandle.fail();
+}
+
+/**
+ * Skip numFrames in input.
+ *
+ * This function correctly handles cases where the input file is not
+ * seekable, by consuming bytes.
+ */
+void TVideoIOYuv::skipFrames(unsigned int numFrames, unsigned int width, unsigned int height)
+{
+  if (!numFrames)
+    return;
+
+  const unsigned int wordsize = m_fileBitdepth > 8 ? 2 : 1;
+  const streamoff framesize = wordsize * width * height * 3 / 2;
+  const streamoff offset = framesize * numFrames;
+
+  /* attempt to seek */
+  if (!!m_cHandle.seekg(offset, ios::cur))
+    return; /* success */
+  m_cHandle.clear();
+
+  /* fall back to consuming the input */
+  char buf[512];
+  const unsigned offset_mod_bufsize = offset % sizeof(buf);
+  for (streamoff i = 0; i < offset - offset_mod_bufsize; i += sizeof(buf))
+  {
+    m_cHandle.read(buf, sizeof(buf));
+  }
+  m_cHandle.read(buf, offset_mod_bufsize);
+}
+
+/**
+ * Read width*height pixels from fd into dst, optionally
+ * padding the left and right edges by edge-extension.  Input may be
+ * either 8bit or 16bit little-endian lsb-aligned words.
+ *
+ * @param dst     destination image
+ * @param fd      input file stream
+ * @param is16bit true if input file carries > 8bit data, false otherwise.
+ * @param stride  distance between vertically adjacent pixels of dst.
+ * @param width   width of active area in dst.
+ * @param height  height of active area in dst.
+ * @param pad_x   length of horizontal padding.
+ * @param pad_y   length of vertical padding.
+ * @return true for success, false in case of error
+ */
+static bool readPlane(Pel* dst, istream& fd, bool is16bit,
+                      unsigned int stride,
+                      unsigned int width, unsigned int height,
+                      unsigned int pad_x, unsigned int pad_y)
+{
+  int read_len = width * (is16bit ? 2 : 1);
+  unsigned char *buf = new unsigned char[read_len];
+  for (int y = 0; y < height; y++)
+  {
+    fd.read(reinterpret_cast<char*>(buf), read_len);
+    if (fd.eof() || fd.fail() )
+    {
+      delete[] buf;
+      return false;
+    }
+
+    if (!is16bit)
+    {
+      for (int x = 0; x < width; x++)
+      {
+        dst[x] = buf[x];
+      }
+    }
+    else
+    {
+      for (int x = 0; x < width; x++)
+      {
+        dst[x] = (buf[2*x+1] << 8) | buf[2*x];
+      }
+    }
+
+    for (int x = width; x < width + pad_x; x++)
+    {
+      dst[x] = dst[width - 1];
+    }
+    dst += stride;
+  }
+  for (int y = height; y < height + pad_y; y++)
+  {
+    for (int x = 0; x < width + pad_x; x++)
+    {
+      dst[x] = (dst - stride)[x];
+    }
+    dst += stride;
+  }
+  delete[] buf;
+  return true;
+}
+
+/**
+ * Write width*height pixels info fd from src.
+ *
+ * @param fd      output file stream
+ * @param src     source image
+ * @param is16bit true if input file carries > 8bit data, false otherwise.
+ * @param stride  distance between vertically adjacent pixels of src.
+ * @param width   width of active area in src.
+ * @param height  height of active area in src.
+ * @return true for success, false in case of error
+ */
+static bool writePlane(ostream& fd, Pel* src, bool is16bit,
+                       unsigned int stride,
+                       unsigned int width, unsigned int height)
+{
+  int write_len = width * (is16bit ? 2 : 1);
+  unsigned char *buf = new unsigned char[write_len];
+  for (int y = 0; y < height; y++)
+  {
+    if (!is16bit) 
+    {
+      for (int x = 0; x < width; x++) 
+      {
+        buf[x] = (unsigned char) src[x];
+      }
+    }
+    else 
+    {
+      for (int x = 0; x < width; x++) 
+      {
+        buf[2*x] = src[x] & 0xff;
+        buf[2*x+1] = (src[x] >> 8) & 0xff;
+      }
+    }
+
+    fd.write(reinterpret_cast<char*>(buf), write_len);
+    if (fd.eof() || fd.fail() )
+    {
+      delete[] buf;
+      return false;
+    }
+    src += stride;
+  }
+  delete[] buf;
+  return true;
+}
+
+/**
+ * Read one Y'CbCr frame, performing any required input scaling to change
+ * from the bitdepth of the input file to the internal bit-depth.
+ *
+ * If a bit-depth reduction is required, and internalBitdepth >= 8, then
+ * the input file is assumed to be ITU-R BT.601/709 compliant, and the
+ * resulting data is clipped to the appropriate legal range, as if the
+ * file had been provided at the lower-bitdepth compliant to Rec601/709.
+ *
+ * @param pPicYuv      input picture YUV buffer class pointer
+ * @param aiPad        source padding size, aiPad[0] = horizontal, aiPad[1] = vertical
+ * @return true for success, false in case of error
+ */
+bool TVideoIOYuv::read ( TComPicYuv*  pPicYuv, Int aiPad[2] )
+{
+  // check end-of-file
+  if ( isEof() ) return false;
+  
+  Int   iStride = pPicYuv->getStride();
+  
+  // compute actual YUV width & height excluding padding size
+  unsigned int pad_h = aiPad[0];
+  unsigned int pad_v = aiPad[1];
+  unsigned int width_full = pPicYuv->getWidth();
+  unsigned int height_full = pPicYuv->getHeight();
+  unsigned int width  = width_full - pad_h;
+  unsigned int height = height_full - pad_v;
+  bool is16bit = m_fileBitdepth > 8;
+
+  int desired_bitdepth = m_fileBitdepth + m_bitdepthShift;
+  Pel minval = 0;
+  Pel maxval = (1 << desired_bitdepth) - 1;
+#if CLIP_TO_709_RANGE
+  if (m_bitdepthShift < 0 && desired_bitdepth >= 8)
+  {
+    /* ITU-R BT.709 compliant clipping for converting say 10b to 8b */
+    minval = 1 << (desired_bitdepth - 8);
+    maxval = (0xff << (desired_bitdepth - 8)) -1;
+  }
+#endif
+  
+  if (! readPlane(pPicYuv->getLumaAddr(), m_cHandle, is16bit, iStride, width, height, pad_h, pad_v))
+    return false;
+  scalePlane(pPicYuv->getLumaAddr(), iStride, width_full, height_full, m_bitdepthShift, minval, maxval);
+
+  iStride >>= 1;
+  width_full >>= 1;
+  height_full >>= 1;
+  width >>= 1;
+  height >>= 1;
+  pad_h >>= 1;
+  pad_v >>= 1;
+
+  if (! readPlane(pPicYuv->getCbAddr(), m_cHandle, is16bit, iStride, width, height, pad_h, pad_v))
+    return false;
+  scalePlane(pPicYuv->getCbAddr(), iStride, width_full, height_full, m_bitdepthShift, minval, maxval);
+
+  if (! readPlane(pPicYuv->getCrAddr(), m_cHandle, is16bit, iStride, width, height, pad_h, pad_v))
+    return false;
+  scalePlane(pPicYuv->getCrAddr(), iStride, width_full, height_full, m_bitdepthShift, minval, maxval);
+
+  return true;
+}
+
+/**
+ * Write one Y'CbCr frame. No bit-depth conversion is performed, pcPicYuv is
+ * assumed to be at TVideoIO::m_fileBitdepth depth.
+ *
+ * @param pPicYuv     input picture YUV buffer class pointer
+ * @param aiPad       source padding size, aiPad[0] = horizontal, aiPad[1] = vertical
+ * @return true for success, false in case of error
+ */
+Bool TVideoIOYuv::write( TComPicYuv* pPicYuv, Int cropLeft, Int cropRight, Int cropTop, Int cropBottom )
+{
+  // compute actual YUV frame size excluding padding size
+  Int   iStride = pPicYuv->getStride();
+  UInt  width  = pPicYuv->getWidth()  - cropLeft - cropRight;
+  UInt  height = pPicYuv->getHeight() - cropTop  - cropBottom;
+  bool is16bit = m_fileBitdepth > 8;
+  TComPicYuv *dstPicYuv = NULL;
+  bool retval = true;
+
+  if (m_bitdepthShift != 0)
+  {
+    dstPicYuv = new TComPicYuv;
+    dstPicYuv->create( pPicYuv->getWidth(), pPicYuv->getHeight(), 1, 1, 0 );
+    pPicYuv->copyToPic(dstPicYuv);
+
+    Pel minval = 0;
+    Pel maxval = (1 << m_fileBitdepth) - 1;
+#if CLIP_TO_709_RANGE
+    if (-m_bitdepthShift < 0 && m_fileBitdepth >= 8)
+    {
+      /* ITU-R BT.709 compliant clipping for converting say 10b to 8b */
+      minval = 1 << (m_fileBitdepth - 8);
+      maxval = (0xff << (m_fileBitdepth - 8)) -1;
+    }
+#endif
+    scalePlane(dstPicYuv->getLumaAddr(), dstPicYuv->getStride(), dstPicYuv->getWidth(), dstPicYuv->getHeight(), -m_bitdepthShift, minval, maxval);
+    scalePlane(dstPicYuv->getCbAddr(), dstPicYuv->getCStride(), dstPicYuv->getWidth()>>1, dstPicYuv->getHeight()>>1, -m_bitdepthShift, minval, maxval);
+    scalePlane(dstPicYuv->getCrAddr(), dstPicYuv->getCStride(), dstPicYuv->getWidth()>>1, dstPicYuv->getHeight()>>1, -m_bitdepthShift, minval, maxval);
+  }
+  else
+  {
+    dstPicYuv = pPicYuv;
+  }
+  // location of upper left pel in a plane
+  Int planeOffset = 0; //cropLeft + cropTop * iStride;
+  
+  if (! writePlane(m_cHandle, dstPicYuv->getLumaAddr() + planeOffset, is16bit, iStride, width, height))
+  {
+    retval=false; 
+    goto exit;
+  }
+
+  width >>= 1;
+  height >>= 1;
+  iStride >>= 1;
+  cropLeft >>= 1;
+  cropRight >>= 1;
+
+  planeOffset = 0; // cropLeft + cropTop * iStride;
+
+  if (! writePlane(m_cHandle, dstPicYuv->getCbAddr() + planeOffset, is16bit, iStride, width, height))
+  {
+    retval=false; 
+    goto exit;
+  }
+  if (! writePlane(m_cHandle, dstPicYuv->getCrAddr() + planeOffset, is16bit, iStride, width, height))
+  {
+    retval=false; 
+    goto exit;
+  }
+  
+exit:
+  if (m_bitdepthShift != 0)
+  {
+    dstPicYuv->destroy();
+    delete dstPicYuv;
+  }  
+  return retval;
+}
+
Index: /trunk/source/Lib/TLibVideoIO/TVideoIOYuv.h
===================================================================
--- /trunk/source/Lib/TLibVideoIO/TVideoIOYuv.h	(revision 2)
+++ /trunk/source/Lib/TLibVideoIO/TVideoIOYuv.h	(revision 2)
@@ -0,0 +1,79 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TVideoIOYuv.h
+    \brief    YUV file I/O class (header)
+*/
+
+#ifndef __TVIDEOIOYUV__
+#define __TVIDEOIOYUV__
+
+#include <stdio.h>
+#include <fstream>
+#include <iostream>
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComPicYuv.h"
+
+using namespace std;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// YUV file I/O class
+class TVideoIOYuv
+{
+private:
+  fstream   m_cHandle;                                      ///< file handle
+  unsigned int m_fileBitdepth; ///< bitdepth of input/output video file
+  int m_bitdepthShift;  ///< number of bits to increase or decrease image by before/after write/read
+  
+public:
+  TVideoIOYuv()           {}
+  virtual ~TVideoIOYuv()  {}
+  
+  Void  open  ( char* pchFile, Bool bWriteMode, unsigned int fileBitDepth, unsigned int internalBitDepth ); ///< open or create file
+  Void  close ();                                           ///< close file
+
+  void skipFrames(unsigned int numFrames, unsigned int width, unsigned int height);
+  
+  bool  read  ( TComPicYuv*   pPicYuv, Int aiPad[2] );     ///< read  one YUV frame with padding parameter
+  Bool  write( TComPicYuv*    pPicYuv, Int cropLeft=0, Int cropRight=0, Int cropTop=0, Int cropBottom=0 );
+  
+  bool  isEof ();                                           ///< check for end-of-file
+  bool  isFail();                                           ///< check for failure
+  
+};
+
+#endif // __TVIDEOIOYUV__
+
Index: /trunk/source/Lib/libmd5/MD5.h
===================================================================
--- /trunk/source/Lib/libmd5/MD5.h	(revision 2)
+++ /trunk/source/Lib/libmd5/MD5.h	(revision 2)
@@ -0,0 +1,96 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#pragma once
+#include "libmd5.h"
+
+//! \ingroup libMD5
+//! \{
+
+class MD5
+{
+public:
+  /**
+   * initialize digest state
+   */
+  MD5()
+  {
+    MD5Init(&m_state);
+  }
+
+  /**
+   * compute digest over buf of length len.
+   * multiple calls may extend the digest over more data.
+   */
+  void update(unsigned char *buf, unsigned len)
+  {
+    MD5Update(&m_state, buf, len);
+  }
+
+  /**
+   * flush any outstanding MD5 data, write the digest into digest.
+   */
+  void finalize(unsigned char digest[16])
+  {
+    MD5Final(digest, &m_state);
+  }
+
+private:
+  context_md5_t m_state;
+};
+
+
+/**
+ * Produce an ascii(hex) representation of picture digest.
+ *
+ * Returns: a statically allocated null-terminated string.  DO NOT FREE.
+ */
+inline const char*
+digestToString(unsigned char digest[3][16], int numChar)
+{
+  const char* hex = "0123456789abcdef";
+  static char string[99];
+  int cnt=0;
+  for(int yuvIdx=0; yuvIdx<3; yuvIdx++)
+  {
+    for (int i = 0; i < numChar; i++)
+    {
+      string[cnt++] = hex[digest[yuvIdx][i] >> 4];
+      string[cnt++] = hex[digest[yuvIdx][i] & 0xf];
+    }
+    string[cnt++] = ',';
+  }
+
+  string[cnt-1] = '\0';
+  return string;
+}
+//! \}
Index: /trunk/source/Lib/libmd5/libmd5.c
===================================================================
--- /trunk/source/Lib/libmd5/libmd5.c	(revision 2)
+++ /trunk/source/Lib/libmd5/libmd5.c	(revision 2)
@@ -0,0 +1,256 @@
+/*
+ * This code implements the MD5 message-digest algorithm.  The algorithm was
+ * written by Ron Rivest.  This code was written by Colin Plumb in 1993, our
+ * understanding is that no copyright is claimed and that this code is in the
+ * public domain.
+ *
+ * Equivalent code is available from RSA Data Security, Inc.
+ * This code has been tested against that, and is functionally equivalent,
+ *
+ * To compute the message digest of a chunk of bytes, declare an MD5Context
+ * structure, pass it to MD5Init, call MD5Update as needed on buffers full of
+ * bytes, and then call MD5Final, which will fill a supplied 16-byte array with
+ * the digest.
+ */
+
+#include <stdint.h>
+#include <string.h>
+#include "libmd5.h"
+
+//! \ingroup libMD5
+//! \{
+
+static void MD5Transform(uint32_t buf[4], uint32_t const in[16]);
+
+#ifndef __BIG_ENDIAN__
+# define byteReverse(buf, len)    /* Nothing */
+#else
+void byteReverse(uint32_t *buf, unsigned len);
+/*
+ * Note: this code is harmless on little-endian machines.
+ */
+void byteReverse(uint32_t *buf, unsigned len)
+{
+  uint32_t t;
+  do {
+    char* bytes = (char *) buf;
+    t = ((unsigned) bytes[3] << 8 | bytes[2]) << 16 |
+        ((unsigned) bytes[1] << 8 | bytes[0]);
+    *buf = t;
+    buf++;
+  } while (--len);
+}
+#endif
+
+/*
+ * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
+ * initialization constants.
+ */
+void MD5Init(context_md5_t *ctx)
+{
+  ctx->buf[0] = 0x67452301;
+  ctx->buf[1] = 0xefcdab89;
+  ctx->buf[2] = 0x98badcfe;
+  ctx->buf[3] = 0x10325476;
+
+  ctx->bits[0] = 0;
+  ctx->bits[1] = 0;
+}
+
+/*
+ * Update context to reflect the concatenation of another buffer full
+ * of bytes.
+ */
+void MD5Update(context_md5_t *ctx, unsigned char *buf, unsigned len)
+{
+  uint32_t t;
+
+  /* Update bitcount */
+
+  t = ctx->bits[0];
+  if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t)
+    ctx->bits[1]++;        /* Carry from low to high */
+  ctx->bits[1] += len >> 29;
+
+  t = (t >> 3) & 0x3f;    /* Bytes already in shsInfo->data */
+
+  /* Handle any leading odd-sized chunks */
+
+  if (t) {
+    unsigned char *p = ctx->in.b8 + t;
+
+    t = 64 - t;
+    if (len < t) {
+      memcpy(p, buf, len);
+      return;
+    }
+    memcpy(p, buf, t);
+    byteReverse(ctx->in.b32, 16);
+    MD5Transform(ctx->buf, ctx->in.b32);
+    buf += t;
+    len -= t;
+  }
+  /* Process data in 64-byte chunks */
+
+  while (len >= 64) {
+    memcpy(ctx->in.b8, buf, 64);
+    byteReverse(ctx->in.b32, 16);
+    MD5Transform(ctx->buf, ctx->in.b32);
+    buf += 64;
+    len -= 64;
+  }
+
+    /* Handle any remaining bytes of data. */
+
+  memcpy(ctx->in.b8, buf, len);
+}
+
+/*
+ * Final wrapup - pad to 64-byte boundary with the bit pattern
+ * 1 0* (64-bit count of bits processed, MSB-first)
+ */
+void MD5Final(unsigned char digest[16], context_md5_t *ctx)
+{
+  unsigned count;
+  unsigned char *p;
+
+  /* Compute number of bytes mod 64 */
+  count = (ctx->bits[0] >> 3) & 0x3F;
+
+  /* Set the first char of padding to 0x80.  This is safe since there is
+     always at least one byte free */
+  p = ctx->in.b8 + count;
+  *p++ = 0x80;
+
+  /* Bytes of padding needed to make 64 bytes */
+  count = 64 - 1 - count;
+
+  /* Pad out to 56 mod 64 */
+  if (count < 8) {
+    /* Two lots of padding:  Pad the first block to 64 bytes */
+    memset(p, 0, count);
+    byteReverse(ctx->in.b32, 16);
+    MD5Transform(ctx->buf, ctx->in.b32);
+
+    /* Now fill the next block with 56 bytes */
+    memset(ctx->in.b8, 0, 56);
+  } else {
+    /* Pad block to 56 bytes */
+    memset(p, 0, count - 8);
+  }
+  byteReverse(ctx->in.b32, 14);
+
+  /* Append length in bits and transform */
+  ctx->in.b32[14] = ctx->bits[0];
+  ctx->in.b32[15] = ctx->bits[1];
+
+  MD5Transform(ctx->buf, ctx->in.b32);
+  byteReverse((uint32_t *) ctx->buf, 4);
+  memcpy(digest, ctx->buf, 16);
+
+  memset(ctx, 0, sizeof(* ctx));    /* In case it's sensitive */
+  /* The original version of this code omitted the asterisk. In
+     effect, only the first part of ctx was wiped with zeros, not
+     the whole thing. Bug found by Derek Jones. Original line: */
+  // memset(ctx, 0, sizeof(ctx));    /* In case it's sensitive */
+}
+
+/* The four core functions - F1 is optimized somewhat */
+
+/* #define F1(x, y, z) (x & y | ~x & z) */
+#define F1(x, y, z) (z ^ (x & (y ^ z)))
+#define F2(x, y, z) F1(z, x, y)
+#define F3(x, y, z) (x ^ y ^ z)
+#define F4(x, y, z) (y ^ (x | ~z))
+
+/* This is the central step in the MD5 algorithm. */
+#define MD5STEP(f, w, x, y, z, data, s) \
+    ( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )
+
+/*
+ * The core of the MD5 algorithm, this alters an existing MD5 hash to
+ * reflect the addition of 16 longwords of new data.  MD5Update blocks
+ * the data and converts bytes into longwords for this routine.
+ */
+static void MD5Transform(uint32_t buf[4], uint32_t const in[16])
+{
+  register uint32_t a, b, c, d;
+
+  a = buf[0];
+  b = buf[1];
+  c = buf[2];
+  d = buf[3];
+
+  MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
+  MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
+  MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
+  MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
+  MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
+  MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
+  MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
+  MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
+  MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
+  MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
+  MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
+  MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
+  MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
+  MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
+  MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
+  MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
+
+  MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
+  MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
+  MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
+  MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
+  MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
+  MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
+  MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
+  MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
+  MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
+  MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
+  MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
+  MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
+  MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
+  MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
+  MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
+  MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
+
+  MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
+  MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
+  MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
+  MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
+  MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
+  MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
+  MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
+  MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
+  MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
+  MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
+  MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
+  MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
+  MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
+  MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
+  MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
+  MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
+
+  MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
+  MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
+  MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
+  MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
+  MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
+  MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
+  MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
+  MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
+  MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
+  MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
+  MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
+  MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
+  MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
+  MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
+  MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
+  MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
+
+  buf[0] += a;
+  buf[1] += b;
+  buf[2] += c;
+  buf[3] += d;
+}
Index: /trunk/source/Lib/libmd5/libmd5.h
===================================================================
--- /trunk/source/Lib/libmd5/libmd5.h	(revision 2)
+++ /trunk/source/Lib/libmd5/libmd5.h	(revision 2)
@@ -0,0 +1,58 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#pragma once
+#include <stdint.h>
+
+//! \ingroup libMD5
+//! \{
+
+typedef struct _context_md5_t {
+  uint32_t buf[4];
+  uint32_t bits[2];
+  union {
+    unsigned char b8[64];
+    uint32_t b32[16];
+  } in;
+} context_md5_t;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+void MD5Init(context_md5_t *ctx);
+void MD5Update(context_md5_t *ctx, unsigned char *buf, unsigned len);
+void MD5Final(unsigned char digest[16], context_md5_t *ctx);
+#ifdef __cplusplus
+}
+#endif
+
+//! \}
