Merge "sdk: Ensure we copy build.prop to platform image directory."
diff --git a/tools/emulator/opengl/Android.mk b/tools/emulator/opengl/Android.mk
new file mode 100644
index 0000000..ba9f93a
--- /dev/null
+++ b/tools/emulator/opengl/Android.mk
@@ -0,0 +1,89 @@
+# This is the top-level build file for the Android HW OpenGL ES emulation
+# in Android.
+#
+# You must define BUILD_EMULATOR_OPENGL to 'true' in your environment to
+# build the following files.
+#
+# Also define BUILD_EMULATOR_OPENGL_DRIVER to 'true' to build the gralloc
+# stuff as well.
+#
+ifeq (true,$(BUILD_EMULATOR_OPENGL))
+
+# Top-level for all modules
+EMUGL_PATH := $(call my-dir)
+
+# Directory containing common headers used by several modules
+# This is always set to a module's LOCAL_C_INCLUDES
+# See the definition of emugl-begin-module in common.mk
+#
+EMUGL_COMMON_INCLUDES := $(EMUGL_PATH)/host/include/libOpenglRender
+
+# Include common definitions used by all the modules included later
+# in this build file. This contains the definition of all useful
+# emugl-xxxx functions.
+#
+include $(EMUGL_PATH)/common.mk
+
+# IMPORTANT: ORDER IS CRUCIAL HERE
+#
+# For the import/export feature to work properly, you must include
+# modules below in correct order. That is, if module B depends on
+# module A, then it must be included after module A below.
+#
+# This ensures that anything exported by module A will be correctly
+# be imported by module B when it is declared.
+#
+# Note that the build system will complain if you try to import a
+# module that hasn't been declared yet anyway.
+#
+
+# First, build the emugen host source-generation tool
+#
+# It will be used by other modules to generate wire protocol encode/decoder
+# source files (see all emugl-gen-decoder/encoder in common.mk)
+#
+include $(EMUGL_PATH)/host/tools/emugen/Android.mk
+include $(EMUGL_PATH)/shared/OpenglOsUtils/Android.mk
+include $(EMUGL_PATH)/shared/OpenglCodecCommon/Android.mk
+
+# System static libraries
+include $(EMUGL_PATH)/system/GLESv1_enc/Android.mk
+include $(EMUGL_PATH)/system/GLESv2_enc/Android.mk
+include $(EMUGL_PATH)/system/renderControl_enc/Android.mk
+include $(EMUGL_PATH)/system/OpenglSystemCommon/Android.mk
+include $(EMUGL_PATH)/tests/ut_rendercontrol_enc/Android.mk
+
+# System shared libraries
+include $(EMUGL_PATH)/system/GLESv1/Android.mk
+include $(EMUGL_PATH)/system/egl/Android.mk
+include $(EMUGL_PATH)/tests/gles_android_wrapper/Android.mk
+
+include $(EMUGL_PATH)/system/gralloc/Android.mk
+
+# Host static libraries
+include $(EMUGL_PATH)/host/libs/GLESv1_dec/Android.mk
+include $(EMUGL_PATH)/host/libs/GLESv2_dec/Android.mk
+include $(EMUGL_PATH)/host/libs/renderControl_dec/Android.mk
+include $(EMUGL_PATH)/tests/ut_rendercontrol_dec/Android.mk
+include $(EMUGL_PATH)/host/libs/Translator/GLcommon/Android.mk
+include $(EMUGL_PATH)/host/libs/Translator/GLES_CM/Android.mk
+include $(EMUGL_PATH)/host/libs/Translator/GLES_V2/Android.mk
+include $(EMUGL_PATH)/host/libs/Translator/EGL/Android.mk
+
+# Host shared libraries
+include $(EMUGL_PATH)/host/libs/libOpenglRender/Android.mk
+
+# Host executables
+include $(EMUGL_PATH)/host/renderer/Android.mk
+
+# Host unit-test for the renderer. this one uses its own small
+# EGL host wrapper.
+include $(EMUGL_PATH)/tests/EGL_host_wrapper/Android.mk
+include $(EMUGL_PATH)/tests/emulator_test_renderer/Android.mk
+include $(EMUGL_PATH)/tests/ut_renderer/Android.mk
+
+include $(EMUGL_PATH)/tests/translator_tests/MacCommon/Android.mk
+include $(EMUGL_PATH)/tests/translator_tests/GLES_CM/Android.mk
+include $(EMUGL_PATH)/tests/translator_tests/GLES_V2/Android.mk
+
+endif # BUILD_EMULATOR_OPENGL == true
diff --git a/tools/emulator/opengl/README b/tools/emulator/opengl/README
new file mode 100644
index 0000000..7147802
--- /dev/null
+++ b/tools/emulator/opengl/README
@@ -0,0 +1,106 @@
+This directory contains the modules related to hardware OpenGL ES emulation.
+
+For now, this feature is experimental, and *nothing* will be built unless
+you define BUILD_EMULATOR_OPENGL in your environment, for example with:
+
+  export BUILD_EMULATOR_OPENGL=true
+
+You can also define the following to enable the "gralloc" module, which
+corresponds to system-wide GLES emulation (by default, only a specific set
+of applications are enabled, see below):
+
+  export BUILD_EMULATOR_OPENGL_DRIVER=true
+
+
+I. Overview of components:
+==========================
+
+The 'emugen' tool is used to generate several source files related to the
+EGL/GLES command stream used between the guest and the host during emulation.
+
+  host/tools/emugen   -> emugen program
+
+Note that emugen is capable of generating, from a single set of specification
+files, three types of auto-generated sources:
+
+  - sources to encode commands into a byte stream.
+  - sources to decide the byte stream into commands.
+  - sources to wrap normal procedural EGL/GLES calls into context-aware ones.
+
+Modules under the system/ directory corresponds to code that runs on the
+guest, and implement the marshalling of EGL/GLES commands into a stream of
+bytes sent to the host through a fast pipe mechanism.
+
+   system/GLESv1_enc        -> encoder for GLES 1.1 commands
+   system/GLESv2_enc        -> encoder for GLES 2.0 commands
+   system/renderControl_enc -> encoder for rendering control commands
+   system/egl               -> emulator-specific guest EGL library
+   system/GLESv1            -> emulator-specific guest GLES 1.1 library
+   system/gralloc           -> emulator-specific gralloc module
+   system/OpenglSystemCommon -> library of common routines
+
+Modules under the host/ directory corresponds to code that runs on the
+host, and implement the decoding of the command stream, translation of
+EGL/GLES commands into desktop GL 2.0 ones, and rendering to an off-screen
+buffer.
+
+  host/libs/GLESv1_dec        -> decoder for GLES 1.1 commands
+  host/libs/GLESv2_dec        -> decoder for GLES 2.0 commands
+  host/libs/renderControl_dec -> decoder for rendering control commands
+
+  host/libs/Translator/EGL    -> translator for EGL commands
+  host/libs/Translator/GLES_CM -> translator for GLES 1.1 commands
+  host/libs/Translator/GLES_V2 -> translator for GLES 2.0 commands
+  host/libs/Translator/GLcommon -> library of common translation routines
+
+  host/libs/libOpenglRender -> rendering library (uses all host libs above)
+                               can be used by the 'renderer' program below,
+                               or directly linked into the emulator UI program.
+
+  host/renderer/ -> stand-alone renderer program executable.
+                    this can run in head-less mode and receive requests from
+                    several emulators at the same time. It is the receiving
+                    end of all command streams.
+
+Modules under the test/ directory correspond to test programs that are useful
+to debug the various modules described above:
+
+  tests/EGL_host_wrapper  -> a small library used to dynamically load the
+                             desktop libEGL.so or a replacement named by the
+                             ANDROID_EGL_LIB environment variable. This lib
+                             provides all EGL entry points.
+
+  tests/emulator_test_renderer -> a small program to run the rendering library
+                                  in a single SDL window on the host desktop.
+
+  tests/gles_android_wrapper -> guest EGL / GLES libraries that are run on
+                                the device to run some tests. Replace the
+                                system/egl and system/GLESv1 modules for now.
+
+  tests/translator_tests/GLES_CM -> desktop GLESv1 translation unit test
+  tests/translator_tests/GLES_V2 -> desktop GLESv2 translation unit test
+  tests/translator_tests/MacCommon -> used by translation tests on Mac only.
+
+  tests/ut_rendercontrol_enc -> guest library used by tests/ut_renderer
+  tests/ut_rendercontrol_dec -> host library used by tests/ut_renderer
+  tests/ut_renderer          -> unit-test for render control and rendering library.
+
+                                
+II. Build system considerations:
+--------------------------------
+
+The dependencies on the more than 20 components described in the previous
+section are pretty sophisticated, involving lots of auto-generated code and
+non-trivial placement for guest/device libraries.
+
+To simplify the development and maintenance of these modules, a set of
+helper GNU Make function is defined in common.mk, and included from the
+Android.mk in this directory.
+
+These functions all begin with the "emugl-" prefix, and can be used to
+declare modules, what information they export to other modules, or import
+from them, and also what kind of auto-generated sources they depend on.
+
+Look at the comments inside common.mk and the Android.mk of the modules
+to better understand what's happening.
+
diff --git a/tools/emulator/opengl/common.mk b/tools/emulator/opengl/common.mk
new file mode 100644
index 0000000..012ecf1
--- /dev/null
+++ b/tools/emulator/opengl/common.mk
@@ -0,0 +1,335 @@
+# This top-level build file is included by all modules that implement
+# the hardware OpenGL ES emulation for Android.
+#
+# We use it to ensure that all sub-Makefiles are included in the right
+# order for various variable definitions and usage to happen in the correct
+# order.
+#
+
+# The following macros are used to start a new GLES emulation module.
+#
+# This will define LOCAL_MODULE as $1, plus a few other variables
+# needed by the build system (e.g. LOCAL_MODULE_TAGS, LOCAL_MODULE_CLASS...)
+#
+# NOTE: You still need to define LOCAL_PATH before this
+#
+# Usage example:
+#
+#   $(call emugl-begin-static-library,<name>)
+#       LOCAL_SRC_FILES := ....
+#       LOCAL_C_INCLUDES += ....
+#   $(call emugl-end-module)
+#
+emugl-begin-static-library = $(call emugl-begin-module,$1,STATIC_LIBRARY)
+emugl-begin-shared-library = $(call emugl-begin-module,$1,SHARED_LIBRARY)
+emugl-begin-host-static-library = $(call emugl-begin-module,$1,HOST_STATIC_LIBRARY,HOST)
+emugl-begin-host-shared-library = $(call emugl-begin-module,$1,HOST_SHARED_LIBRARY,HOST)
+emugl-begin-host-executable = $(call emugl-begin-module,$1,HOST_EXECUTABLE,HOST)
+
+# Internal list of all declared modules (used for sanity checking)
+_emugl_modules :=
+_emugl_HOST_modules :=
+
+# do not use directly, see functions above instead
+emugl-begin-module = \
+    $(eval include $(CLEAR_VARS)) \
+    $(eval LOCAL_MODULE := $1) \
+    $(eval LOCAL_MODULE_TAGS := debug) \
+    $(eval LOCAL_MODULE_CLASS := $(patsubst HOST_%,%,$(patsubst %EXECUTABLE,%EXECUTABLES,$(patsubst %LIBRARY,%LIBRARIES,$2)))) \
+    $(eval LOCAL_IS_HOST_MODULE := $(if $3,true,))\
+    $(eval LOCAL_C_INCLUDES := $(EMUGL_COMMON_INCLUDES)) \
+    $(eval LOCAL_PRELINK_MODULE := false)\
+    $(eval _EMUGL_INCLUDE_TYPE := $(BUILD_$2)) \
+    $(call _emugl-init-module,$1,$2,$3)
+
+# Used to end a module definition, see function definitions above
+emugl-end-module = \
+    $(eval include $(_EMUGL_INCLUDE_TYPE))\
+    $(eval _EMUGL_INCLUDE_TYPE :=) \
+    $(eval _emugl_$(_emugl_HOST)modules += $(_emugl_MODULE))\
+    $(if $(EMUGL_DEBUG),$(call emugl-dump-module))
+
+# Managing module exports and imports.
+#
+# A module can 'import' another module, by calling emugl-import. This will
+# make the current LOCAL_MODULE inherit various definitions exported from
+# the imported module.
+#
+# Module exports are defined by calling emugl-export. Here is an example:
+#
+#      $(call emugl-begin-static-library,foo)
+#      LOCAL_SRC_FILES := foo.c
+#      $(call emugl-export,C_INCLUDES,$(LOCAL_PATH))
+#      $(call emugl-export,SHARED_LIBRARIES,libcutils)
+#      $(call emugl-end-module)
+#
+#      $(call emugl-begin-shared-library,bar)
+#      LOCAL_SRC_FILES := bar.cpp
+#      $(call emugl-import,foo)
+#      $(call emugl-end-module)
+#
+# Here, we define a static library named 'foo' which exports an include
+# path and a shared library requirement, and a shared library 'bar' which
+# imports it.
+#
+# What this means is that:
+#
+#    - 'bar' will automatically inherit foo's LOCAL_PATH in its LOCAL_C_INCLUDES
+#    - 'bar' will automatically inherit libcutils in its own LOCAL_SHARED_LIBRARIES
+#
+# Note that order of declaration matters. If 'foo' is defined after 'bar' in
+# the example above, nothing will work correctly because dependencies are
+# computed at import time.
+#
+#
+# IMPORTANT: Imports are transitive, i.e. when module A imports B,
+#            it automatically imports anything imported by B too.
+
+# This is the list of recognized export types we support for now.
+EMUGL_EXPORT_TYPES := \
+    CFLAGS \
+    LDLIBS \
+    LDFLAGS \
+    C_INCLUDES \
+    SHARED_LIBRARIES \
+    STATIC_LIBRARIES \
+    ADDITIONAL_DEPENDENCIES
+
+# Initialize a module in our database
+# $1: Module name
+# $2: Module type
+# $3: "HOST" for a host module, empty for a target one.
+_emugl-init-module = \
+    $(eval _emugl_HOST := $(if $3,HOST_,))\
+    $(eval _emugl_MODULE := $(_emugl_HOST)$1)\
+    $(if $(filter $(_emugl_$(_emugl_HOST)modules),$(_emugl_MODULE)),\
+        $(error There is already a $(if $3,host,) module named $1!)\
+    )\
+    $(eval _mod = $(_emugl_MODULE)) \
+    $(eval _emugl.$(_mod).type := $(patsubst HOST_%,%,$2))\
+    $(eval _emugl.$(_mod).imports :=) \
+    $(foreach _type,$(EMUGL_EXPORT_TYPES),\
+        $(eval _emugl.$(_mod).export.$(_type) :=)\
+    )
+
+# Called to indicate that a module exports a given local variable for its
+# users. This also adds this to LOCAL_$1
+# $1: Local variable type (e.g. CFLAGS, LDLIBS, etc...)
+# $2: Value(s) to append to the export
+emugl-export = \
+    $(eval _emugl.$(_emugl_MODULE).export.$1 += $2)\
+    $(eval LOCAL_$1 := $2 $(LOCAL_$1))
+
+emugl-export-outer = \
+    $(eval _emugl.$(_emugl_MODULE).export.$1 += $2)
+
+# Called to indicate that a module imports the exports of another module
+# $1: list of modules to import
+#
+emugl-import = \
+    $(foreach _imod,$1,\
+        $(call _emugl-module-import,$(_emugl_HOST)$(_imod))\
+    )
+
+_emugl-module-import = \
+    $(eval _mod := $(_emugl_MODULE))\
+    $(if $(filter-out $(_emugl_$(_emugl_HOST)modules),$1),\
+        $(info Unknown imported emugles module: $1)\
+        $(if $(_emugl_HOST),\
+            $(eval _names := $(patsubst HOST_%,%,$(_emugl_HOST_modules))),\
+            $(eval _names := $(_emugl_modules))\
+        )\
+        $(info Please one of the following names: $(_names))\
+        $(error Aborting)\
+    )\
+    $(if $(filter-out $(_emugl.$(_mod).imports),$1),\
+        $(eval _emugl.$(_mod).imports += $1)\
+        $(foreach _sub,$(_emugl.$1.imports),\
+            $(call _emugl-module-import,$(_sub))\
+        )\
+        $(foreach _type,$(EMUGL_EXPORT_TYPES),\
+            $(eval LOCAL_$(_type) := $(_emugl.$1.export.$(_type)) $(LOCAL_$(_type)))\
+        )\
+        $(if $(filter EXECUTABLE SHARED_LIBRARY,$(_emugl.$(_emugl_MODULE).type)),\
+            $(if $(filter STATIC_LIBRARY,$(_emugl.$1.type)),\
+                $(eval LOCAL_STATIC_LIBRARIES := $(1:HOST_%=%) $(LOCAL_STATIC_LIBRARIES))\
+            )\
+            $(if $(filter SHARED_LIBRARY,$(_emugl.$1.type)),\
+                $(eval LOCAL_SHARED_LIBRARIES := $(1:HOST_%=%) $(LOCAL_SHARED_LIBRARIES))\
+            )\
+        )\
+    )
+
+_emugl-dump-list = \
+    $(foreach _list_item,$(strip $1),$(info .    $(_list_item)))
+
+emugl-dump-module = \
+    $(info MODULE=$(_emugl_MODULE))\
+    $(info .  HOST=$(_emugl_HOST))\
+    $(info .  TYPE=$(_emugl.$(_emugl_MODULE).type))\
+    $(info .  IMPORTS=$(_emugl.$(_emugl_MODULE).imports))\
+    $(foreach _type,$(EMUGL_EXPORT_TYPES),\
+        $(if $(filter C_INCLUDES ADDITIONAL_DEPENDENCIES,$(_type)),\
+            $(info .  EXPORT.$(_type) :=)\
+            $(call _emugl-dump-list,$(_emugl.$(_emugl_MODULE).export.$(_type)))\
+            $(info .  LOCAL_$(_type)  :=)\
+            $(call _emugl-dump-list,$(LOCAL_$(_type)))\
+        ,\
+            $(info .  EXPORT.$(_type) := $(strip $(_emugl.$(_emugl_MODULE).export.$(_type))))\
+            $(info .  LOCAL_$(_type)  := $(strip $(LOCAL_$(_type))))\
+        )\
+    )\
+    $(info .  LOCAL_SRC_FILES := $(LOCAL_SRC_FILES))\
+
+# This function can be called to generate the decoder source files.
+# LOCAL_MODULE and LOCAL_MODULE_CLASS must be defined or the build will abort.
+# Source files will be stored in the local intermediates directory that will
+# be automatically added to your LOCAL_C_INCLUDES.
+#
+# Usage:
+#    $(call emugl-gen-decoder,<input-dir>,<basename>)
+#
+emugl-gen-decoder = \
+    $(eval _emugl_out := $(call local-intermediates-dir))\
+    $(call emugl-gen-decoder-generic,$(_emugl_out),$1,$2)\
+    $(call emugl-export,C_INCLUDES,$(_emugl_out))
+
+# This function can be called to generate the encoder source files.
+# LOCAL_MODULE and LOCAL_MODULE_CLASS must be defined or the build will abort.
+# Source files will be stored in the local intermediates directory that will
+# be automatically added to your LOCAL_C_INCLUDES.
+# Usage:
+#    $(call emugl-gen-encoder,<input-dir>,<basename>)
+#
+emugl-gen-encoder = \
+    $(eval _emugl_out := $(call local-intermediates-dir)) \
+    $(call emugl-gen-encoder-generic,$(_emugl_out),$1,$2) \
+    $(call emugl-export,C_INCLUDES,$(_emugl_out))
+
+
+# This function can be called to generate the wrapper source files.
+# LOCAL_MODULE and LOCAL_MODULE_CLASS must be defined or the build will abort.
+# Source files will be stored in the local intermediates directory that will
+# be automatically added to your LOCAL_C_INCLUDES.
+# Usage:
+#    $(call emugl-gen-wrapper,<input-dir>,<basename>)
+#
+emugl-gen-wrapper = \
+    $(eval _emugl_out := $(call local-intermediates-dir)) \
+    $(call emugl-gen-wrapper-generic,$(_emugl_out),$1,$2) \
+    $(call emugl-export,C_INCLUDES,$(_emugl_out))
+
+# IMPORTANT: EMUGL_EMUGEN is defined under host/tools/emugen/Android.mk
+#
+
+# DO NOT CALL DIRECTLY, USE emugl-gen-decoder instead.
+#
+# The following function can be called to generate wire protocol decoder
+# source files, Usage is:
+#
+#  $(call emugl-gen-decoder-generic,<dst-dir>,<src-dir>,<basename>)
+#
+#  <dst-dir> is the destination directory where the generated sources are stored
+#  <src-dir> is the source directory where to find <basename>.attrib, etc..
+#  <basename> is the emugen basename (see host/tools/emugen/README)
+#
+emugl-gen-decoder-generic = $(eval $(emugl-gen-decoder-generic-ev))
+
+define emugl-gen-decoder-generic-ev
+_emugl_dec := $$1/$$3
+_emugl_src := $$2/$$3
+GEN := $$(_emugl_dec)_dec.cpp \
+       $$(_emugl_dec)_dec.h \
+       $$(_emugl_dec)_opcodes.h \
+       $$(_emugl_dec)_server_context.h \
+       $$(_emugl_dec)_server_context.cpp
+
+$$(GEN): PRIVATE_PATH := $$(LOCAL_PATH)
+$$(GEN): PRIVATE_CUSTOM_TOOL := $$(EMUGL_EMUGEN) -D $$1 -i $$2 $$3
+$$(GEN): $$(EMUGL_EMUGEN) $$(_emugl_src).attrib $$(_emugl_src).in $$(_emugl_src).types
+	$$(transform-generated-source)
+
+$$(call emugl-export,ADDITIONAL_DEPENDENCIES,$$(GEN))
+LOCAL_GENERATED_SOURCES += $$(GEN)
+LOCAL_C_INCLUDES += $$1
+endef
+
+# DO NOT CALL DIRECTLY, USE emugl-gen-encoder instead.
+#
+# The following function can be called to generate wire protocol encoder
+# source files, Usage is:
+#
+#  $(call emugl-gen-encoder-generic,<dst-dir>,<src-dir>,<basename>)
+#
+#  <dst-dir> is the destination directory where the generated sources are stored
+#  <src-dir> is the source directory where to find <basename>.attrib, etc..
+#  <basename> is the emugen basename (see host/tools/emugen/README)
+#
+emugl-gen-encoder-generic = $(eval $(emugl-gen-encoder-generic-ev))
+
+define emugl-gen-encoder-generic-ev
+_emugl_enc := $$1/$$3
+_emugl_src := $$2/$$3
+GEN := $$(_emugl_enc)_entry.cpp \
+       $$(_emugl_enc)_enc.cpp \
+       $$(_emugl_enc)_enc.h \
+       $$(_emugl_enc)_ftable.h \
+       $$(_emugl_enc)_opcodes.h \
+       $$(_emugl_enc)_client_context.h \
+       $$(_emugl_enc)_client_context.cpp
+
+$$(GEN): PRIVATE_PATH := $$(LOCAL_PATH)
+$$(GEN): PRIVATE_CUSTOM_TOOL := $$(EMUGL_EMUGEN) -E $$1 -i $$2 $$3
+$$(GEN): $$(EMUGL_EMUGEN) $$(_emugl_src).attrib $$(_emugl_src).in $$(_emugl_src).types
+	$$(transform-generated-source)
+
+$$(call emugl-export,ADDITIONAL_DEPENDENCIES,$$(GEN))
+LOCAL_GENERATED_SOURCES += $$(GEN)
+LOCAL_C_INCLUDES += $$1
+endef
+
+
+# DO NOT CALL DIRECTLY, USE emugl-gen-wrapper instead.
+#
+# The following function can be called to generate GL library wrapper
+# Usage is:
+#
+#  $(call emugl-gen-wrapper-generic,<dst-dir>,<src-dir>,<basename>)
+#
+#  <dst-dir> is the destination directory where the generated sources are stored
+#  <src-dir> is the source directory where to find <basename>.attrib, etc..
+#  <basename> is the emugen basename (see host/tools/emugen/README)
+#
+emugl-gen-wrapper-generic = $(eval $(emugl-gen-wrapper-generic-ev))
+
+define emugl-gen-wrapper-generic-ev
+_emugl_wrap := $$1/$$3
+_emugl_src  := $$2/$$3
+GEN := $$(_emugl_wrap)_wrapper_entry.cpp \
+       $$(_emugl_wrap)_wrapper_context.cpp \
+       $$(_emugl_wrap)_wrapper_context.h \
+       $$(_emugl_wrap)_wrapper_proc.h
+
+$$(GEN): PRIVATE_PATH := $$(LOCAL_PATH)
+$$(GEN): PRIVATE_CUSTOM_TOOL := $$(EMUGL_EMUGEN) -W $$1 -i $$2 $$3
+$$(GEN): $$(EMUGL_EMUGEN) $$(_emugl_src).attrib $$(_emugl_src).in $$(_emugl_src).types
+	$$(transform-generated-source)
+
+$$(call emugl-export,ADDITIONAL_DEPENDENCIES,$$(GEN))
+LOCAL_GENERATED_SOURCES += $$(GEN)
+LOCAL_C_INCLUDES += $$1
+
+#ifneq ($$(HOST_OS),windows)
+$$(call emugl-export,LDFLAGS,-ldl)
+#endif
+
+endef
+
+# Call this function when your shared library must be placed in a non-standard
+# library path (i.e. not under /system/lib
+# $1: library sub-path,relative to /system/lib
+# For example: $(call emugl-set-shared-library-subpath,egl)
+emugl-set-shared-library-subpath = \
+    $(eval LOCAL_MODULE_PATH := $(TARGET_OUT_SHARED_LIBRARIES)/$1)\
+    $(call emugl-export-outer,ADDITIONAL_DEPENDENCIES,$(LOCAL_MODULE_PATH)/$(LOCAL_MODULE)$(TARGET_SHLIB_SUFFIX))
+
diff --git a/tools/emulator/opengl/host/libs/GLESv1_dec/Android.mk b/tools/emulator/opengl/host/libs/GLESv1_dec/Android.mk
index f5e2441..e9bc81c 100644
--- a/tools/emulator/opengl/host/libs/GLESv1_dec/Android.mk
+++ b/tools/emulator/opengl/host/libs/GLESv1_dec/Android.mk
@@ -1,45 +1,16 @@
-
 LOCAL_PATH := $(call my-dir)
 
-### GLESv1 Decoder ###########################################
-include $(CLEAR_VARS)
+$(call emugl-begin-host-shared-library,libGLESv1_dec)
 
-emulatorOpengl := $(LOCAL_PATH)/../../..
-EMUGEN := $(HOST_OUT_EXECUTABLES)/emugen
+$(call emugl-import, libOpenglCodecCommon)
+$(call emugl-export,C_INCLUDES,$(LOCAL_PATH))
+$(call emugl-export,LDLIBS,-ldl)
 
-LOCAL_IS_HOST_MODULE := true
-LOCAL_MODULE_CLASS := SHARED_LIBRARIES
-LOCAL_MODULE_TAGS := debug
-LOCAL_MODULE := libGLESv1_dec
+$(call emugl-gen-decoder,$(EMUGL_PATH)/system/GLESv1_enc,gl)
 
-intermediates := $(local-intermediates-dir)
+LOCAL_SRC_FILES := GLDecoder.cpp
 
-LOCAL_SRC_FILES := \
-        GLDecoder.cpp
+# for gl_types.h !
+$(call emugl-export,C_INCLUDES,$(EMUGL_PATH)/system/GLESv1_enc)
 
-LOCAL_C_INCLUDES += \
-    $(emulatorOpengl)/shared/OpenglCodecCommon \
-    $(emulatorOpengl)/host/include/libOpenglRender \
-    $(emulatorOpengl)/system/GLESv1_enc
-
-LOCAL_STATIC_LIBRARIES := \
-        libOpenglCodecCommon \
-        liblog
-
-# XXX - uncomment for debug
-#LOCAL_CFLAGS := -DDEBUG_PRINTOUT -O0 -g
-LOCAL_LDLIBS := -ldl
-
-
-GEN := $(intermediates)/gl_server_context.cpp $(intermediates)/gl_dec.cpp $(intermediates)/gl_dec.h
-
-$(GEN) : PRIVATE_PATH := $(LOCAL_PATH)
-$(GEN) : PRIVATE_CUSTOM_TOOL := $(EMUGEN) -D $(intermediates) -i $(emulatorOpengl)/system/GLESv1_enc gl
-$(GEN) : $(EMUGEN) \
-        $(emulatorOpengl)/system/GLESv1_enc/gl.attrib \
-        $(emulatorOpengl)/system/GLESv1_enc/gl.in \
-        $(emulatorOpengl)/system/GLESv1_enc/gl.types
-	$(transform-generated-source)
-
-LOCAL_GENERATED_SOURCES += $(GEN)
-include $(BUILD_HOST_SHARED_LIBRARY)
+$(call emugl-end-module)
diff --git a/tools/emulator/opengl/host/libs/GLESv1_dec/GLDecoder.cpp b/tools/emulator/opengl/host/libs/GLESv1_dec/GLDecoder.cpp
index 1bd5de3..facb3db 100644
--- a/tools/emulator/opengl/host/libs/GLESv1_dec/GLDecoder.cpp
+++ b/tools/emulator/opengl/host/libs/GLESv1_dec/GLDecoder.cpp
@@ -74,10 +74,18 @@
 
     set_glDrawElementsOffset(s_glDrawElementsOffset);
     set_glDrawElementsData(s_glDrawElementsData);
+    set_glFinishRoundTrip(s_glFinishRoundTrip);
 
     return 0;
 }
 
+int GLDecoder::s_glFinishRoundTrip(void *self)
+{
+    GLDecoder *ctx = (GLDecoder *)self;
+    ctx->glFinish();
+    return 0;
+}
+
 void GLDecoder::s_glVertexPointerOffset(void *self, GLint size, GLenum type, GLsizei stride, GLuint offset)
 {
     GLDecoder *ctx = (GLDecoder *)self;
diff --git a/tools/emulator/opengl/host/libs/GLESv1_dec/GLDecoder.h b/tools/emulator/opengl/host/libs/GLESv1_dec/GLDecoder.h
index 5ef946d..7df3d19 100644
--- a/tools/emulator/opengl/host/libs/GLESv1_dec/GLDecoder.h
+++ b/tools/emulator/opengl/host/libs/GLESv1_dec/GLDecoder.h
@@ -59,6 +59,8 @@
     static void s_glMatrixIndexPointerData(void * self, GLint size, GLenum type, GLsizei stride, void * data, GLuint datalen);
     static void s_glMatrixIndexPointerOffset(void * self, GLint size, GLenum type, GLsizei stride, GLuint offset);
 
+    static int s_glFinishRoundTrip(void *self);
+
     static void * s_getProc(const char *name, void *userData);
 
     GLDecoderContextData *m_contextData;
diff --git a/tools/emulator/opengl/host/libs/GLESv2_dec/Android.mk b/tools/emulator/opengl/host/libs/GLESv2_dec/Android.mk
index 72bbbc6..265bac6 100644
--- a/tools/emulator/opengl/host/libs/GLESv2_dec/Android.mk
+++ b/tools/emulator/opengl/host/libs/GLESv2_dec/Android.mk
@@ -1,47 +1,13 @@
 LOCAL_PATH := $(call my-dir)
 
-### GLESv2 Decoder ###########################################
-include $(CLEAR_VARS)
+$(call emugl-begin-host-shared-library,libGLESv2_dec)
+$(call emugl-import, libOpenglCodecCommon libOpenglOsUtils)
+$(call emugl-gen-decoder,$(EMUGL_PATH)/system/GLESv2_enc,gl2)
 
-emulatorOpengl := $(LOCAL_PATH)/../../..
-EMUGEN := $(BUILD_OUT_EXECUTABLES)/emugen
+# For gl2_types.h !
+$(call emugl-export,C_INCLUDES,$(EMUGL_PATH)/system/GLESv2_enc)
+$(call emugl-export,C_INCLUDES,$(LOCAL_PATH))
 
-LOCAL_IS_HOST_MODULE := true
-LOCAL_MODULE_CLASS := SHARED_LIBRARIES
-LOCAL_MODULE_TAGS := debug
-LOCAL_MODULE := libGLESv2_dec
+LOCAL_SRC_FILES := GL2Decoder.cpp
 
-intermediates := $(local-intermediates-dir)
-
-LOCAL_SRC_FILES := \
-        GL2Decoder.cpp
-
-LOCAL_C_INCLUDES += \
-    $(emulatorOpengl)/shared \
-    $(emulatorOpengl)/shared/OpenglCodecCommon \
-    $(emulatorOpengl)/host/include/libOpenglRender \
-    $(emulatorOpengl)/system/GLESv2_enc
-
-LOCAL_STATIC_LIBRARIES := \
-        libOpenglCodecCommon \
-	libOpenglOsUtils \
-        liblog
-
-# XXX - uncomment for debug
-#LOCAL_CFLAGS := -DDEBUG_PRINTOUT -O0 -g
-LOCAL_LDLIBS := -ldl
-
-
-GEN := $(intermediates)/gl2_dec.cpp $(intermediates)/gl2_dec.h $(intermediates)/gl2_server_context.cpp
-
-$(GEN) : PRIVATE_PATH := $(LOCAL_PATH)
-$(GEN) : PRIVATE_CUSTOM_TOOL := $(EMUGEN) -D $(intermediates) -i $(emulatorOpengl)/system/GLESv2_enc gl2
-$(GEN) : $(EMUGEN) \
-        $(emulatorOpengl)/system/GLESv2_enc/gl2.attrib \
-        $(emulatorOpengl)/system/GLESv2_enc/gl2.in \
-        $(emulatorOpengl)/system/GLESv2_enc/gl2.types
-	$(transform-generated-source)
-
-LOCAL_GENERATED_SOURCES += $(GEN)
-include $(BUILD_HOST_SHARED_LIBRARY)
-
+$(call emugl-end-module)
diff --git a/tools/emulator/opengl/host/libs/GLESv2_dec/GL2Decoder.h b/tools/emulator/opengl/host/libs/GLESv2_dec/GL2Decoder.h
index 970c08d..e626db3 100644
--- a/tools/emulator/opengl/host/libs/GLESv2_dec/GL2Decoder.h
+++ b/tools/emulator/opengl/host/libs/GLESv2_dec/GL2Decoder.h
@@ -5,7 +5,7 @@
 #define GLES2_LIBNAME     "libGLESv2.so"
 
 #include "gl2_dec.h"
-#include "OpenglOsUtils/osDynLibrary.h"
+#include "osDynLibrary.h"
 #include "GLDecoderContextData.h"
 
 
diff --git a/tools/emulator/opengl/host/libs/Translator/EGL/Android.mk b/tools/emulator/opengl/host/libs/Translator/EGL/Android.mk
index 2fd38fa..9fcf9ce 100644
--- a/tools/emulator/opengl/host/libs/Translator/EGL/Android.mk
+++ b/tools/emulator/opengl/host/libs/Translator/EGL/Android.mk
@@ -1,16 +1,14 @@
 LOCAL_PATH := $(call my-dir)
 
 ### EGL host implementation ########################
-include $(CLEAR_VARS)
-
-translator_path := $(LOCAL_PATH)/..
+$(call emugl-begin-host-shared-library,libEGL_translator)
+$(call emugl-import,libGLcommon)
 
 OS_SRCS:=
 
-
 ifeq ($(HOST_OS),linux)
     OS_SRCS = EglX11Api.cpp
-    LOCAL_LDLIBS := -lX11 -lGL -ldl -lpthread
+     LOCAL_LDLIBS += -lX11 -lGL -ldl -lpthread
 endif
 
 ifeq ($(HOST_OS),darwin)
@@ -18,12 +16,12 @@
               MacNative.m   \
               MacPixelFormatsAttribs.m
 
-    LOCAL_LDLIBS := -Wl,-framework,AppKit
+    LOCAL_LDLIBS += -Wl,-framework,AppKit
 endif
 
 ifeq ($(HOST_OS),windows)
     OS_SRCS = EglWindowsApi.cpp
-    LOCAL_LDLIBS := -lopengl32 -lgdi32
+    LOCAL_LDLIBS += -lopengl32 -lgdi32
 endif
 
 LOCAL_SRC_FILES :=            \
@@ -41,21 +39,5 @@
      EglThreadInfo.cpp        \
      EglDisplay.cpp
 
-
-LOCAL_C_INCLUDES += \
-                 $(translator_path)/include \
-                 $(translator_path)/../../../shared
-
-LOCAL_CFLAGS := -g -O0
-LOCAL_MODULE_TAGS := debug
-LOCAL_MODULE := libEGL_translator
-
-LOCAL_STATIC_LIBRARIES :=    \
-                 libGLcommon \
-                 libcutils   \
-                 libutils    \
-                 liblog      \
-                 libOpenglOsUtils
-
-include $(BUILD_HOST_SHARED_LIBRARY)
+$(call emugl-end-module)
 
diff --git a/tools/emulator/opengl/host/libs/Translator/EGL/EglConfig.cpp b/tools/emulator/opengl/host/libs/Translator/EGL/EglConfig.cpp
index 9fcdf64..fc8f585 100644
--- a/tools/emulator/opengl/host/libs/Translator/EGL/EglConfig.cpp
+++ b/tools/emulator/opengl/host/libs/Translator/EGL/EglConfig.cpp
@@ -67,7 +67,10 @@
                      m_trans_red_val(trans_red_val),
                      m_trans_green_val(trans_green_val),
                      m_trans_blue_val(trans_blue_val),
-                     m_nativeFormat(frmt){};
+                     m_conformant(((red_size + green_size + blue_size + alpha_size > 0)  && 
+                                  (caveat!=EGL_NON_CONFORMANT_CONFIG)) ?
+                                    m_renderable_type : 0),
+                     m_nativeFormat(frmt) {};
 
 
     EglConfig::EglConfig(const EglConfig& conf):m_buffer_size(conf.m_buffer_size),
@@ -98,7 +101,8 @@
                                                 m_trans_red_val(conf.m_trans_red_val),
                                                 m_trans_green_val(conf.m_trans_green_val),
                                                 m_trans_blue_val(conf.m_trans_blue_val),
-                                                m_nativeFormat(conf.m_nativeFormat){};
+                                                m_conformant(conf.m_conformant),
+                                                m_nativeFormat(conf.m_nativeFormat) {};
 
 
 
@@ -163,6 +167,7 @@
         break;
     case EGL_RENDERABLE_TYPE:
         *val = m_renderable_type;
+        break;
     case EGL_SAMPLE_BUFFERS:
         *val = m_sample_buffers_num;
         break;
@@ -187,6 +192,9 @@
     case EGL_TRANSPARENT_BLUE_VALUE:
         *val = m_trans_blue_val;
         break;
+    case EGL_CONFORMANT:
+        *val = m_conformant;
+        break;
     default:
         return false;
     }
@@ -283,6 +291,9 @@
    //mask
    if(dummy.m_surface_type != EGL_DONT_CARE &&
     ((dummy.m_surface_type & m_surface_type) != dummy.m_surface_type)) return false;
+   
+   if(dummy.m_conformant != EGL_DONT_CARE &&
+    ((dummy.m_conformant & m_conformant) != dummy.m_conformant)) return false;
 
    if(dummy.m_renderable_type != EGL_DONT_CARE &&
     ((dummy.m_renderable_type & m_renderable_type) != dummy.m_renderable_type)) return false;
diff --git a/tools/emulator/opengl/host/libs/Translator/EGL/EglConfig.h b/tools/emulator/opengl/host/libs/Translator/EGL/EglConfig.h
index 3336f0e..ad4e37d 100644
--- a/tools/emulator/opengl/host/libs/Translator/EGL/EglConfig.h
+++ b/tools/emulator/opengl/host/libs/Translator/EGL/EglConfig.h
@@ -91,6 +91,7 @@
     const EGLint                    m_trans_red_val;
     const EGLint                    m_trans_green_val;
     const EGLint                    m_trans_blue_val;
+    const EGLenum                   m_conformant;
 
     const EGLNativePixelFormatType  m_nativeFormat;
 };
diff --git a/tools/emulator/opengl/host/libs/Translator/EGL/EglContext.cpp b/tools/emulator/opengl/host/libs/Translator/EGL/EglContext.cpp
index 6710baa..1223168 100644
--- a/tools/emulator/opengl/host/libs/Translator/EGL/EglContext.cpp
+++ b/tools/emulator/opengl/host/libs/Translator/EGL/EglContext.cpp
@@ -29,7 +29,8 @@
 m_read(NULL),
 m_draw(NULL),
 m_destroy(false),
-m_version(ver)
+m_version(ver),
+m_mngr(mngr)
 {
     m_shareGroup = shared_context.Ptr()?
                    mngr->attachShareGroup(context,shared_context.Ptr()->getShareGroup().Ptr()):
@@ -37,6 +38,14 @@
     m_hndl = ++s_nextContextHndl;
 }
 
+EglContext::~EglContext()
+{
+    if (m_mngr)
+    {
+        m_mngr->deleteShareGroup(m_native);
+    }
+}
+
 void EglContext::setSurfaces(SurfacePtr read,SurfacePtr draw)
 {
     m_read = read;
diff --git a/tools/emulator/opengl/host/libs/Translator/EGL/EglContext.h b/tools/emulator/opengl/host/libs/Translator/EGL/EglContext.h
index 5b528ab..1f54631 100644
--- a/tools/emulator/opengl/host/libs/Translator/EGL/EglContext.h
+++ b/tools/emulator/opengl/host/libs/Translator/EGL/EglContext.h
@@ -53,7 +53,8 @@
     bool attachImage(unsigned int imageId,ImagePtr img);
     void detachImage(unsigned int imageId);
 
-    ~EglContext(){}
+    ~EglContext();
+
 private:
     static unsigned int  s_nextContextHndl;
     EGLNativeContextType m_native;
@@ -64,6 +65,7 @@
     SurfacePtr           m_draw;
     bool                 m_destroy;
     GLESVersion          m_version;
+    ObjectNameManager    *m_mngr;
     unsigned int         m_hndl;
     ImagesHndlMap        m_attachedImages;
 };
diff --git a/tools/emulator/opengl/host/libs/Translator/EGL/EglImp.cpp b/tools/emulator/opengl/host/libs/Translator/EGL/EglImp.cpp
index 1e47f0f..999d13a 100644
--- a/tools/emulator/opengl/host/libs/Translator/EGL/EglImp.cpp
+++ b/tools/emulator/opengl/host/libs/Translator/EGL/EglImp.cpp
@@ -69,6 +69,8 @@
                                                    {"eglCreateImageKHR" ,(__eglMustCastToProperFunctionPointerType)eglCreateImageKHR},
                                                    {"eglDestroyImageKHR",(__eglMustCastToProperFunctionPointerType)eglDestroyImageKHR}
                                                };
+static int s_eglExtentionsSize = sizeof(s_eglExtentions) /
+                                 sizeof(ExtentionDescriptor);
 
 /****************************************************************************************************************************************/
 //macros for accessing global egl info & tls objects
@@ -213,7 +215,7 @@
     VALIDATE_DISPLAY(display);
     static const char* vendor     = "Google";
     static const char* version    = "1.4";
-    static const char* extensions = "EGL_KHR_image_base EGL_KHR_gl_texture_2d_image";
+    static const char* extensions = "EGL_KHR_image_base EGL_KHR_gl_texture_2D_image";
     if(!EglValidate::stringName(name)) {
         RETURN_ERROR(NULL,EGL_BAD_PARAMETER);
     }
@@ -676,6 +678,7 @@
               EGLSurface read, EGLContext context) {
     VALIDATE_DISPLAY(display);
 
+
     bool releaseContext = EglValidate::releaseContext(context,read,draw);
     if(!releaseContext && EglValidate::badContextMatch(context,read,draw)) {
         RETURN_ERROR(EGL_FALSE,EGL_BAD_MATCH);
@@ -701,6 +704,20 @@
         EglSurface* newReadPtr = newReadSrfc.Ptr();
         EglContext* newCtx     = ctx.Ptr();
 
+        if (newCtx && prevCtx) {
+            if (newCtx == prevCtx) {
+                if (newDrawPtr == prevCtx->draw().Ptr() &&
+                    newReadPtr == prevCtx->read().Ptr()) {
+                    // nothing to do
+                    return EGL_TRUE;
+                }
+            }
+            else {
+                // Make sure previous context is detached from surfaces
+                releaseContext = true;
+            }
+        }
+
         //surfaces compitability check
         if(!((*ctx->getConfig()).compitableWith((*newDrawPtr->getConfig()))) ||
            !((*ctx->getConfig()).compitableWith((*newReadPtr->getConfig())))) {
@@ -743,7 +760,7 @@
     SurfacePtr  prevRead;
     SurfacePtr  prevDraw;
     //removing terminated surfaces & context
-    if(prevCtx) {
+    if(prevCtx && releaseContext) {
         prevRead = prevCtx->read();
         if(prevRead->destroy()){
             if(destroySurfaceIfNotCurrent(dpy,prevRead)) { //removes surface from the list if not current
@@ -943,7 +960,7 @@
        eglGetProcAddress(const char *procname){
     __eglMustCastToProperFunctionPointerType retVal = NULL;
     if(!strncmp(procname,"egl",3)) { //EGL proc
-        for(int i=0;i < EGL_EXTENSIONS;i++){
+        for(int i=0;i < s_eglExtentionsSize;i++){
             if(strcmp(procname,s_eglExtentions[i].name) == 0){
                 retVal = s_eglExtentions[i].address;
                 break;
diff --git a/tools/emulator/opengl/host/libs/Translator/EGL/EglValidate.cpp b/tools/emulator/opengl/host/libs/Translator/EGL/EglValidate.cpp
index a4b2cc6..d87f9b9 100644
--- a/tools/emulator/opengl/host/libs/Translator/EGL/EglValidate.cpp
+++ b/tools/emulator/opengl/host/libs/Translator/EGL/EglValidate.cpp
@@ -46,6 +46,7 @@
     case EGL_TRANSPARENT_RED_VALUE:
     case EGL_TRANSPARENT_GREEN_VALUE:
     case EGL_TRANSPARENT_BLUE_VALUE:
+    case EGL_CONFORMANT:
         return true;
     }
     return false;
diff --git a/tools/emulator/opengl/host/libs/Translator/EGL/EglX11Api.cpp b/tools/emulator/opengl/host/libs/Translator/EGL/EglX11Api.cpp
index a695d37..3aee4b4 100644
--- a/tools/emulator/opengl/host/libs/Translator/EGL/EglX11Api.cpp
+++ b/tools/emulator/opengl/host/libs/Translator/EGL/EglX11Api.cpp
@@ -39,16 +39,16 @@
 android::Mutex ErrorHandler::s_lock;
 
 ErrorHandler::ErrorHandler(EGLNativeDisplayType dpy){
-   s_lock.lock();
+   android::Mutex::Autolock mutex(s_lock);
    XSync(dpy,False);
    s_lastErrorCode = 0;
    m_oldErrorHandler = XSetErrorHandler(errorHandlerProc);
 }
 
 ErrorHandler::~ErrorHandler(){
+   android::Mutex::Autolock mutex(s_lock);
    XSetErrorHandler(m_oldErrorHandler);
    s_lastErrorCode = 0;
-   s_lock.unlock();
 }
 
 int ErrorHandler::errorHandlerProc(EGLNativeDisplayType dpy,XErrorEvent* event){
@@ -130,7 +130,11 @@
     IS_SUCCESS(glXGetFBConfigAttrib(dpy,*frmt,GLX_LEVEL,&level));
     IS_SUCCESS(glXGetFBConfigAttrib(dpy,*frmt,GLX_FBCONFIG_ID,&configId));
     IS_SUCCESS(glXGetFBConfigAttrib(dpy,*frmt,GLX_SAMPLES,&samples));
-
+    //Filter out configs that does not support RGBA
+    IS_SUCCESS(glXGetFBConfigAttrib(dpy,*frmt,GLX_RENDER_TYPE,&tmp));
+    if (!(tmp & GLX_RGBA_BIT)) {
+        return NULL;
+    }
 
     return new EglConfig(red,green,blue,alpha,caveat,configId,depth,level,pMaxWidth,pMaxHeight,
                               pMaxPixels,renderable,renderableType,visualId,visualType,samples,stencil,
diff --git a/tools/emulator/opengl/host/libs/Translator/GLES_CM/Android.mk b/tools/emulator/opengl/host/libs/Translator/GLES_CM/Android.mk
index b18492e..b32afff 100644
--- a/tools/emulator/opengl/host/libs/Translator/GLES_CM/Android.mk
+++ b/tools/emulator/opengl/host/libs/Translator/GLES_CM/Android.mk
@@ -1,38 +1,15 @@
 LOCAL_PATH := $(call my-dir)
 
 ### GLES_CM host implementation (On top of OpenGL) ########################
-include $(CLEAR_VARS)
+$(call emugl-begin-host-shared-library,libGLES_CM_translator)
 
-translator_path := $(LOCAL_PATH)/..
+$(call emugl-import,libGLcommon)
 
 LOCAL_SRC_FILES :=      \
      GLEScmImp.cpp      \
      GLEScmUtils.cpp    \
      TextureUtils.cpp   \
      GLEScmContext.cpp  \
-     GLEScmValidate.cpp 
+     GLEScmValidate.cpp
 
-LOCAL_C_INCLUDES += \
-                 $(translator_path)/include \
-                 $(translator_path)/../../../shared
-
-LOCAL_STATIC_LIBRARIES := \
-    libGLcommon           \
-    libOpenglOsUtils      \
-    libutils              \
-    libcutils
-
-LOCAL_CFLAGS := -g -O0
-LOCAL_MODULE_TAGS := debug
-LOCAL_MODULE := libGLES_CM_translator
-
-ifeq ($(HOST_OS),linux)
-    LOCAL_LDLIBS := -lGL -ldl
-endif
-
-ifeq ($(HOST_OS),windows)
-    LOCAL_LDLIBS := -lopengl32 -lgdi32
-endif
-
-include $(BUILD_HOST_SHARED_LIBRARY)
-
+$(call emugl-end-module)
diff --git a/tools/emulator/opengl/host/libs/Translator/GLES_V2/Android.mk b/tools/emulator/opengl/host/libs/Translator/GLES_V2/Android.mk
index 723bd38..acae242 100644
--- a/tools/emulator/opengl/host/libs/Translator/GLES_V2/Android.mk
+++ b/tools/emulator/opengl/host/libs/Translator/GLES_V2/Android.mk
@@ -1,9 +1,8 @@
 LOCAL_PATH := $(call my-dir)
 
 ### GLES_CM host implementation (On top of OpenGL) ########################
-include $(CLEAR_VARS)
-
-translator_path := $(LOCAL_PATH)/..
+$(call emugl-begin-host-shared-library,libGLES_V2_translator)
+$(call emugl-import, libGLcommon)
 
 LOCAL_SRC_FILES :=                    \
      GLESv2Imp.cpp                    \
@@ -11,27 +10,4 @@
      GLESv2Validate.cpp               \
      ShaderParser.cpp                 \
 
-LOCAL_C_INCLUDES += \
-                 $(translator_path)/include \
-
-LOCAL_STATIC_LIBRARIES := \
-    libGLcommon           \
-    libOpenglOsUtils      \
-    libutils              \
-    libcutils
-
-ifeq ($(HOST_OS),linux)
-    LOCAL_LDLIBS := -lGL -ldl
-endif
-
-ifeq ($(HOST_OS),windows)
-    LOCAL_LDLIBS := -lopengl32 -lgdi32
-endif
-
-LOCAL_CFLAGS := -g -O0
-LOCAL_MODULE_TAGS := debug
-LOCAL_MODULE := libGLES_V2_translator
-
-
-include $(BUILD_HOST_SHARED_LIBRARY)
-
+$(call emugl-end-module)
diff --git a/tools/emulator/opengl/host/libs/Translator/GLES_V2/GLESv2Imp.cpp b/tools/emulator/opengl/host/libs/Translator/GLES_V2/GLESv2Imp.cpp
index d708a25..7e2141c 100644
--- a/tools/emulator/opengl/host/libs/Translator/GLES_V2/GLESv2Imp.cpp
+++ b/tools/emulator/opengl/host/libs/Translator/GLES_V2/GLESv2Imp.cpp
@@ -141,7 +141,7 @@
     }
     ctx->bindBuffer(target,buffer);
     GLESbuffer* vbo = (GLESbuffer*)thrd->shareGroup->getObjectData(VERTEXBUFFER,buffer).Ptr();
-    vbo->wasBinded();
+    vbo->setBinded();
 }
 
 GL_APICALL void  GL_APIENTRY glBindFramebuffer(GLenum target, GLuint framebuffer){
@@ -1251,7 +1251,7 @@
     if (type==GL_HALF_FLOAT_OES)
         type = GL_HALF_FLOAT;
     const GLvoid* data = ctx->setPointer(indx,size,type,stride,ptr);
-    if(type != GL_FIXED) ctx->dispatcher().glVertexAttribPointer(indx,size,type,normalized,stride,ptr);
+    if(type != GL_FIXED) ctx->dispatcher().glVertexAttribPointer(indx,size,type,normalized,stride,data);
 }
 
 GL_APICALL void  GL_APIENTRY glViewport(GLint x, GLint y, GLsizei width, GLsizei height){
diff --git a/tools/emulator/opengl/host/libs/Translator/GLcommon/Android.mk b/tools/emulator/opengl/host/libs/Translator/GLcommon/Android.mk
index 0e9cb97..1c7615b 100644
--- a/tools/emulator/opengl/host/libs/Translator/GLcommon/Android.mk
+++ b/tools/emulator/opengl/host/libs/Translator/GLcommon/Android.mk
@@ -1,8 +1,9 @@
-
 LOCAL_PATH := $(call my-dir)
 
 ### EGL host implementation ########################
-include $(CLEAR_VARS)
+$(call emugl-begin-host-static-library,libGLcommon)
+
+$(call emugl-import,libOpenglOsUtils)
 
 translator_path := $(LOCAL_PATH)/..
 
@@ -18,25 +19,16 @@
      objectNameManager.cpp
 
 
-LOCAL_C_INCLUDES += \
-                 $(translator_path)/include \
-                 $(translator_path)/../../../shared
-
-LOCAL_STATIC_LIBRARIES := \
-    libOpenglOsUtils      \
-    libutils              \
-    libcutils
-
-LOCAL_CFLAGS := -g -O0
-LOCAL_MODULE_TAGS := debug
-LOCAL_MODULE := libGLcommon
 ifeq ($(HOST_OS),linux)
-    LOCAL_LDFLAGS := -Wl,--whole-archive
-    LOCAL_LDLIBS := -lGL -ldl
+#    $(call emugl-export,LDFLAGS,-Wl,--whole-archive)
+    $(call emugl-export,LDLIBS,-lGL -ldl)
 endif
 
 ifeq ($(HOST_OS),windows)
-    LOCAL_LDLIBS := -lopengl32 -lgdi32
+    $(call emugl-export,LDLIBS,-lopengl32 -lgdi32)
 endif
 
-include $(BUILD_HOST_STATIC_LIBRARY)
+$(call emugl-export,C_INCLUDES,$(LOCAL_PATH)/../include $(EMUGL_PATH)/shared)
+$(call emugl-export,STATIC_LIBRARIES, libcutils liblog)
+
+$(call emugl-end-module)
diff --git a/tools/emulator/opengl/host/libs/libOpenglRender/Android.mk b/tools/emulator/opengl/host/libs/libOpenglRender/Android.mk
index 55894c5..1e133b4 100644
--- a/tools/emulator/opengl/host/libs/libOpenglRender/Android.mk
+++ b/tools/emulator/opengl/host/libs/libOpenglRender/Android.mk
@@ -1,18 +1,11 @@
 LOCAL_PATH := $(call my-dir)
 
 ifneq ($(HOST_OS),darwin)
+
 ### libOpenglRender #################################################
-include $(CLEAR_VARS)
+$(call emugl-begin-host-shared-library,libOpenglRender)
 
-emulatorOpengl := $(LOCAL_PATH)/../../..
-
-LOCAL_IS_HOST_MODULE := true
-LOCAL_MODULE_CLASS := SHARED_LIBRARIES
-LOCAL_MODULE_TAGS := debug
-LOCAL_MODULE := libOpenglRender
-LOCAL_ADDITIONAL_DEPENDENCIES := \
-	$(HOST_OUT_SHARED_LIBRARIES)/lib_renderControl_dec$(HOST_SHLIB_SUFFIX) \
-	$(HOST_OUT_SHARED_LIBRARIES)/libGLESv1_dec$(HOST_SHLIB_SUFFIX)
+$(call emugl-import,libGLESv1_dec lib_renderControl_dec libOpenglCodecCommon libOpenglOsUtils)
 
 LOCAL_SRC_FILES := \
     render_api.cpp \
@@ -30,39 +23,8 @@
     ReadBuffer.cpp \
     RenderServer.cpp
 
-LOCAL_C_INCLUDES += \
-    $(emulatorOpengl)/host/include \
-    $(emulatorOpengl)/shared/OpenglCodecCommon \
-    $(emulatorOpengl)/shared/OpenglOsUtils \
-    $(emulatorOpengl)/host/include/libOpenglRender \
-    $(emulatorOpengl)/host/libs/GLESv1_dec \
-    $(emulatorOpengl)/system/GLESv1_enc \
-    $(emulatorOpengl)/system/renderControl_enc \
-	$(call intermediates-dir-for, SHARED_LIBRARIES, libGLESv1_dec, HOST) \
-	$(call intermediates-dir-for, SHARED_LIBRARIES, lib_renderControl_dec, HOST)
+$(call emugl-export,C_INCLUDES,$(EMUGL_PATH)/host/include)
 
-LOCAL_STATIC_LIBRARIES := \
-        libOpenglCodecCommon \
-        libOpenglOsUtils \
-        libcutils \
-        libutils \
-        liblog
+$(call emugl-end-module)
 
-LOCAL_SHARED_LIBRARIES := \
-        libGLESv1_dec \
-        lib_renderControl_dec
-
-ifeq ($(HOST_OS),windows)
-    LOCAL_LDLIBS := -lws2_32
-endif
-
-ifeq ($(HOST_OS),linux)
-    LOCAL_LDLIBS := -ldl -lpthread -lrt
-endif
-
-# XXX - uncomment for debug
-#LOCAL_CFLAGS := -O0 -g
-
-include $(BUILD_HOST_SHARED_LIBRARY)
 endif # HOST_OS != darwin
-
diff --git a/tools/emulator/opengl/host/libs/libOpenglRender/ColorBuffer.cpp b/tools/emulator/opengl/host/libs/libOpenglRender/ColorBuffer.cpp
index 774ad02..0a794ed 100644
--- a/tools/emulator/opengl/host/libs/libOpenglRender/ColorBuffer.cpp
+++ b/tools/emulator/opengl/host/libs/libOpenglRender/ColorBuffer.cpp
@@ -17,6 +17,10 @@
 #include "FrameBuffer.h"
 #include "EGLDispatch.h"
 #include "GLDispatch.h"
+#include "ThreadInfo.h"
+#ifdef WITH_GLES2
+#include "GL2Dispatch.h"
+#endif
 #include <stdio.h>
 
 ColorBuffer *ColorBuffer::create(int p_width, int p_height,
@@ -24,17 +28,38 @@
 {
     FrameBuffer *fb = FrameBuffer::getFB();
 
+    GLenum texInternalFormat = 0;
+
+    switch(p_internalFormat) {
+        case GL_RGB:
+        case GL_RGB565_OES:
+            texInternalFormat = GL_RGB;
+            break;
+
+        case GL_RGBA:
+        case GL_RGB5_A1_OES:
+        case GL_RGBA4_OES:
+            texInternalFormat = GL_RGBA;
+            break;
+
+        default:
+            return NULL;
+            break;
+    }
+
     if (!fb->bind_locked()) {
         return NULL;
     }
 
     ColorBuffer *cb = new ColorBuffer();
 
+
     s_gl.glGenTextures(1, &cb->m_tex);
     s_gl.glBindTexture(GL_TEXTURE_2D, cb->m_tex);
-    s_gl.glTexImage2D(GL_TEXTURE_2D, 0, p_internalFormat,
+    s_gl.glTexImage2D(GL_TEXTURE_2D, 0, texInternalFormat,
                       p_width, p_height, 0,
-                      GL_RGBA, GL_UNSIGNED_BYTE, NULL);
+                      texInternalFormat,
+                      GL_UNSIGNED_BYTE, NULL);
     s_gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
     s_gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
     s_gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
@@ -88,6 +113,17 @@
     fb->unbind_locked();
 }
 
+void ColorBuffer::subUpdate(int x, int y, int width, int height, GLenum p_format, GLenum p_type, void *pixels)
+{
+    FrameBuffer *fb = FrameBuffer::getFB();
+    if (!fb->bind_locked()) return;
+    s_gl.glBindTexture(GL_TEXTURE_2D, m_tex);
+    s_gl.glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
+    s_gl.glTexSubImage2D(GL_TEXTURE_2D, 0, x, y,
+                         width, height, p_format, p_type, pixels);
+    fb->unbind_locked();
+}
+
 bool ColorBuffer::blitFromPbuffer(EGLSurface p_pbufSurface)
 {
     FrameBuffer *fb = FrameBuffer::getFB();
@@ -134,6 +170,27 @@
     return true;
 }
 
+bool ColorBuffer::bindToTexture()
+{
+    if (m_eglImage) {
+        RenderThreadInfo *tInfo = getRenderThreadInfo();
+        if (tInfo->currContext.Ptr()) {
+#ifdef WITH_GLES2
+            if (tInfo->currContext->isGL2()) {
+                s_gl2.glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, m_eglImage);
+            }
+            else {
+                s_gl.glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, m_eglImage);
+            }
+#else
+            s_gl.glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, m_eglImage);
+#endif
+            return true;
+        }
+    }
+    return false;
+}
+
 bool ColorBuffer::bind_fbo()
 {
     if (m_fbo) {
diff --git a/tools/emulator/opengl/host/libs/libOpenglRender/ColorBuffer.h b/tools/emulator/opengl/host/libs/libOpenglRender/ColorBuffer.h
index 550c6d1..25761ce 100644
--- a/tools/emulator/opengl/host/libs/libOpenglRender/ColorBuffer.h
+++ b/tools/emulator/opengl/host/libs/libOpenglRender/ColorBuffer.h
@@ -33,8 +33,10 @@
     GLuint getHeight() const { return m_height; }
 
     void update(GLenum p_format, GLenum p_type, void *pixels);
+    void subUpdate(int x, int y, int width, int height, GLenum p_format, GLenum p_type, void *pixels);
     bool blitFromPbuffer(EGLSurface p_pbufSurface);
     bool post();
+    bool bindToTexture();
 
 private:
     ColorBuffer();
diff --git a/tools/emulator/opengl/host/libs/libOpenglRender/EGLDispatch.cpp b/tools/emulator/opengl/host/libs/libOpenglRender/EGLDispatch.cpp
index 635f94a..6a920fb 100644
--- a/tools/emulator/opengl/host/libs/libOpenglRender/EGLDispatch.cpp
+++ b/tools/emulator/opengl/host/libs/libOpenglRender/EGLDispatch.cpp
@@ -27,6 +27,7 @@
 
     osUtils::dynLibrary *lib = osUtils::dynLibrary::open(libName);
     if (!lib) {
+        printf("Failed to open %s\n", libName);
         return NULL;
     }
 
@@ -64,16 +65,21 @@
     s_egl.eglSwapBuffers = (eglSwapBuffers_t) lib->findSymbol("eglSwapBuffers");
     s_egl.eglCopyBuffers = (eglCopyBuffers_t) lib->findSymbol("eglCopyBuffers");
     s_egl.eglGetProcAddress = (eglGetProcAddress_t) lib->findSymbol("eglGetProcAddress");
-    s_egl.eglLockSurfaceKHR = (eglLockSurfaceKHR_t) lib->findSymbol("eglLockSurfaceKHR");
-    s_egl.eglUnlockSurfaceKHR = (eglUnlockSurfaceKHR_t) lib->findSymbol("eglUnlockSurfaceKHR");
-    s_egl.eglCreateImageKHR = (eglCreateImageKHR_t) lib->findSymbol("eglCreateImageKHR");
-    s_egl.eglDestroyImageKHR = (eglDestroyImageKHR_t) lib->findSymbol("eglDestroyImageKHR");
-    s_egl.eglCreateSyncKHR = (eglCreateSyncKHR_t) lib->findSymbol("eglCreateSyncKHR");
-    s_egl.eglDestroySyncKHR = (eglDestroySyncKHR_t) lib->findSymbol("eglDestroySyncKHR");
-    s_egl.eglClientWaitSyncKHR = (eglClientWaitSyncKHR_t) lib->findSymbol("eglClientWaitSyncKHR");
-    s_egl.eglSignalSyncKHR = (eglSignalSyncKHR_t) lib->findSymbol("eglSignalSyncKHR");
-    s_egl.eglGetSyncAttribKHR = (eglGetSyncAttribKHR_t) lib->findSymbol("eglGetSyncAttribKHR");
-    s_egl.eglSetSwapRectangleANDROID = (eglSetSwapRectangleANDROID_t) lib->findSymbol("eglSetSwapRectangleANDROID");
+
+#define INIT_EGL_EXT_FUNC(name) \
+    if (s_egl.eglGetProcAddress) s_egl.name = (name ## _t) s_egl.eglGetProcAddress(#name); \
+    if (!s_egl.name || !s_egl.eglGetProcAddress) s_egl.name = (name ## _t) lib->findSymbol(#name)
+
+    INIT_EGL_EXT_FUNC(eglLockSurfaceKHR);
+    INIT_EGL_EXT_FUNC(eglUnlockSurfaceKHR);
+    INIT_EGL_EXT_FUNC(eglCreateImageKHR);
+    INIT_EGL_EXT_FUNC(eglDestroyImageKHR);
+    INIT_EGL_EXT_FUNC(eglCreateSyncKHR);
+    INIT_EGL_EXT_FUNC(eglDestroySyncKHR);
+    INIT_EGL_EXT_FUNC(eglClientWaitSyncKHR);
+    INIT_EGL_EXT_FUNC(eglSignalSyncKHR);
+    INIT_EGL_EXT_FUNC(eglGetSyncAttribKHR);
+    INIT_EGL_EXT_FUNC(eglSetSwapRectangleANDROID);
 
     return true;
 }
diff --git a/tools/emulator/opengl/host/libs/libOpenglRender/FBConfig.cpp b/tools/emulator/opengl/host/libs/libOpenglRender/FBConfig.cpp
index 81ba067..fdf5433 100644
--- a/tools/emulator/opengl/host/libs/libOpenglRender/FBConfig.cpp
+++ b/tools/emulator/opengl/host/libs/libOpenglRender/FBConfig.cpp
@@ -196,7 +196,7 @@
     memcpy(buffer, s_configAttribs, s_numConfigAttribs * sizeof(GLuint));
     for (int i=0; i<s_numConfigs; i++) {
         memcpy(buffer+(i+1)*s_numConfigAttribs,
-               &s_fbConfigs[i]->m_attribValues,
+               s_fbConfigs[i]->m_attribValues,
                s_numConfigAttribs * sizeof(GLuint));
     }
 }
@@ -222,21 +222,63 @@
     // Query the max matching configs in the backend
     //
     EGLConfig *matchedConfigs = new EGLConfig[nConfigs];
-    s_egl.eglChooseConfig(dpy, attribs, matchedConfigs, nConfigs, &nConfigs);
+
+    //
+    //Until we have EGLImage implementation, we force pbuf configs
+    //
+    bool needToAddPbufAttr = true;
+    int attribCnt = 0;
+    EGLint * attrib_p = attribs;
+    if (attribs) {
+        while (attrib_p[0] != EGL_NONE) {
+            if (attrib_p[0] == EGL_SURFACE_TYPE) {
+                attrib_p[1] = EGL_PBUFFER_BIT; //replace whatever was there before
+                needToAddPbufAttr = false;
+            }
+            attrib_p += 2;
+            attribCnt += 2;
+        }
+    }
+    EGLint * newAttribs = new EGLint[attribCnt + 1 + ((needToAddPbufAttr) ? 2 : 0)];
+    attrib_p = newAttribs;
+    if (needToAddPbufAttr) {
+        *(attrib_p++) = EGL_SURFACE_TYPE;
+        *(attrib_p++) = EGL_PBUFFER_BIT;
+    }
+    memcpy(attrib_p, attribs, attribCnt*sizeof(EGLint));
+    attrib_p += attribCnt;
+    *attrib_p = EGL_NONE;
+
+#if 0
+    if (newAttribs) {
+        EGLint * attrib_p = newAttribs;
+        while (attrib_p[0] != EGL_NONE) {
+            DBG("attr: 0x%x %d, ", attrib_p[0], attrib_p[1]);
+            attrib_p += 2;
+        }
+    }
+#endif
+
+    s_egl.eglChooseConfig(dpy, newAttribs, matchedConfigs, nConfigs, &nConfigs);
+
+    delete newAttribs;
 
     //
     // From all matchedConfigs we need only config_size FBConfigs, so we intersect both lists compating the CONFIG_ID attribute
     //
     uint32_t nVerifiedCfgs = 0;
     for (int matchedIdx=0; matchedIdx<nConfigs; matchedIdx++) {
-        if (nVerifiedCfgs >= configs_size) break; //We have enouhgt configs
+        if ((configs_size > 0) && (nVerifiedCfgs >= configs_size)) break; //We have enouhgt configs
         int sCfgId;
         s_egl.eglGetConfigAttrib(dpy, matchedConfigs[matchedIdx], EGL_CONFIG_ID, &sCfgId);
         for (int fbIdx=0; fbIdx<s_numConfigs; fbIdx++) {
             int dCfgId = s_fbConfigs[fbIdx]->m_attribValues[4]; //CONFIG_ID
             if (sCfgId == dCfgId) {
                 //This config matches the requested attributes and filtered into fbConfigs, so we're happy with it
-                configs[nVerifiedCfgs++] = fbIdx;
+                if (nVerifiedCfgs < configs_size) {
+                    configs[nVerifiedCfgs] = fbIdx;
+                }
+                nVerifiedCfgs++;
                 break;
             }
         }
diff --git a/tools/emulator/opengl/host/libs/libOpenglRender/FrameBuffer.cpp b/tools/emulator/opengl/host/libs/libOpenglRender/FrameBuffer.cpp
index a0f32c8..1caaf10 100644
--- a/tools/emulator/opengl/host/libs/libOpenglRender/FrameBuffer.cpp
+++ b/tools/emulator/opengl/host/libs/libOpenglRender/FrameBuffer.cpp
@@ -97,6 +97,7 @@
     //
     if (!init_egl_dispatch()) {
         // Failed to load EGL
+        printf("Failed to init_egl_dispatch\n");
         return false;
     }
 
@@ -105,6 +106,7 @@
     //
     if (!init_gl_dispatch()) {
         // Failed to load GLES
+        ERR("Failed to init_gl_dispatch\n");
         return false;
     }
 
@@ -113,6 +115,7 @@
     //
     FrameBuffer *fb = new FrameBuffer(p_x, p_y, p_width, p_height);
     if (!fb) {
+        ERR("Failed to create fb\n");
         return false;
     }
 
@@ -135,10 +138,18 @@
     //
     fb->m_eglDisplay = s_egl.eglGetDisplay(EGL_DEFAULT_DISPLAY);
     if (fb->m_eglDisplay == EGL_NO_DISPLAY) {
+        ERR("Failed to Initialize backend EGL display\n");
         delete fb;
         return false;
     }
-    s_egl.eglInitialize(fb->m_eglDisplay, &fb->m_caps.eglMajor, &fb->m_caps.eglMinor);
+
+    if (!s_egl.eglInitialize(fb->m_eglDisplay, &fb->m_caps.eglMajor, &fb->m_caps.eglMinor)) {
+        ERR("Failed to eglInitialize\n");
+        delete fb;
+        return false;
+    }
+
+    DBG("egl: %d %d\n", fb->m_caps.eglMajor, fb->m_caps.eglMinor);
     s_egl.eglBindAPI(EGL_OPENGL_ES_API);
 
     fb->m_nativeWindow = p_window;
@@ -162,16 +173,26 @@
     // Create EGL context and Surface attached to the native window, for
     // framebuffer post rendering.
     //
+#if 0
     GLint configAttribs[] = {
         EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
         EGL_RENDERABLE_TYPE, EGL_OPENGL_ES_BIT,
         EGL_NONE
     };
-
+#else
+    GLint configAttribs[] = {
+        EGL_RED_SIZE, 1,
+        EGL_GREEN_SIZE, 1,
+        EGL_BLUE_SIZE, 1,
+        EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
+        EGL_NONE
+    };
+#endif
     EGLConfig eglConfig;
     int n;
     if (!s_egl.eglChooseConfig(fb->m_eglDisplay, configAttribs,
                                &eglConfig, 1, &n)) {
+        ERR("Failed on eglChooseConfig\n");
         delete fb;
         return false;
     }
@@ -181,6 +202,7 @@
                                                   (EGLNativeWindowType)p_window,
                                                   NULL);
     if (fb->m_eglSurface == EGL_NO_SURFACE) {
+        ERR("Failed to create surface\n");
         delete fb;
         return false;
     }
@@ -202,6 +224,7 @@
 
     // Make the context current
     if (!fb->bind_locked()) {
+        ERR("Failed to make current\n");
         delete fb;
         return false;
     }
@@ -238,6 +261,7 @@
     //
     InitConfigStatus configStatus = FBConfig::initConfigList(fb);
     if (configStatus == INIT_CONFIG_FAILED) {
+        ERR("Failed: Initialize set of configs\n");
         delete fb;
         return false;
     }
@@ -398,6 +422,21 @@
     m_colorbuffers.erase(p_colorbuffer);
 }
 
+bool FrameBuffer::flushWindowSurfaceColorBuffer(HandleType p_surface)
+{
+    android::Mutex::Autolock mutex(m_lock);
+
+    WindowSurfaceMap::iterator w( m_windows.find(p_surface) );
+    if (w == m_windows.end()) {
+        // bad surface handle
+        return false;
+    }
+
+    (*w).second->flushColorBuffer();
+
+    return true;
+}
+
 bool FrameBuffer::setWindowSurfaceColorBuffer(HandleType p_surface,
                                               HandleType p_colorbuffer)
 {
@@ -420,6 +459,36 @@
     return true;
 }
 
+bool FrameBuffer::updateColorBuffer(HandleType p_colorbuffer,
+                                    int x, int y, int width, int height,
+                                    GLenum format, GLenum type, void *pixels)
+{
+    android::Mutex::Autolock mutex(m_lock);
+
+    ColorBufferMap::iterator c( m_colorbuffers.find(p_colorbuffer) );
+    if (c == m_colorbuffers.end()) {
+        // bad colorbuffer handle
+        return false;
+    }
+
+    (*c).second->subUpdate(x, y, width, height, format, type, pixels);
+
+    return true;
+}
+
+bool FrameBuffer::bindColorBufferToTexture(HandleType p_colorbuffer)
+{
+    android::Mutex::Autolock mutex(m_lock);
+
+    ColorBufferMap::iterator c( m_colorbuffers.find(p_colorbuffer) );
+    if (c == m_colorbuffers.end()) {
+        // bad colorbuffer handle
+        return false;
+    }
+
+    return (*c).second->bindToTexture();
+}
+
 bool FrameBuffer::bindContext(HandleType p_context,
                               HandleType p_drawSurface,
                               HandleType p_readSurface)
@@ -495,6 +564,7 @@
     tinfo->currContext = ctx;
     tinfo->currDrawSurf = draw;
     tinfo->currReadSurf = read;
+    tinfo->m_glDec.setContextData(&ctx->decoderContextData());
 
     return true;
 }
@@ -510,6 +580,7 @@
 
     if (!s_egl.eglMakeCurrent(m_eglDisplay, m_eglSurface,
                               m_eglSurface, m_eglContext)) {
+        ERR("eglMakeCurrent failed\n");
         return false;
     }
 
diff --git a/tools/emulator/opengl/host/libs/libOpenglRender/FrameBuffer.h b/tools/emulator/opengl/host/libs/libOpenglRender/FrameBuffer.h
index e30fba8..128d73f 100644
--- a/tools/emulator/opengl/host/libs/libOpenglRender/FrameBuffer.h
+++ b/tools/emulator/opengl/host/libs/libOpenglRender/FrameBuffer.h
@@ -67,6 +67,11 @@
 
     bool  bindContext(HandleType p_context, HandleType p_drawSurface, HandleType p_readSurface);
     bool  setWindowSurfaceColorBuffer(HandleType p_surface, HandleType p_colorbuffer);
+    bool  flushWindowSurfaceColorBuffer(HandleType p_surface);
+    bool  bindColorBufferToTexture(HandleType p_colorbuffer);
+    bool updateColorBuffer(HandleType p_colorbuffer,
+                           int x, int y, int width, int height,
+                           GLenum format, GLenum type, void *pixels);
 
     bool post(HandleType p_colorbuffer);
 
diff --git a/tools/emulator/opengl/host/libs/libOpenglRender/RenderContext.h b/tools/emulator/opengl/host/libs/libOpenglRender/RenderContext.h
index 3962ada..9cbb5fc 100644
--- a/tools/emulator/opengl/host/libs/libOpenglRender/RenderContext.h
+++ b/tools/emulator/opengl/host/libs/libOpenglRender/RenderContext.h
@@ -18,6 +18,7 @@
 
 #include "SmartPtr.h"
 #include <EGL/egl.h>
+#include "GLDecoderContextData.h"
 
 class RenderContext;
 typedef SmartPtr<RenderContext> RenderContextPtr;
@@ -33,6 +34,8 @@
     EGLContext getEGLContext() const { return m_ctx; }
     bool isGL2() const { return m_isGL2; }
 
+    GLDecoderContextData & decoderContextData() { return m_contextData; }
+
 private:
     RenderContext();
 
@@ -40,6 +43,7 @@
     EGLContext m_ctx;
     int        m_config;
     bool       m_isGL2;
+    GLDecoderContextData    m_contextData;
 };
 
 #endif
diff --git a/tools/emulator/opengl/host/libs/libOpenglRender/RenderControl.cpp b/tools/emulator/opengl/host/libs/libOpenglRender/RenderControl.cpp
index 891c89b..9c973e9 100644
--- a/tools/emulator/opengl/host/libs/libOpenglRender/RenderControl.cpp
+++ b/tools/emulator/opengl/host/libs/libOpenglRender/RenderControl.cpp
@@ -17,6 +17,9 @@
 #include "FrameBuffer.h"
 #include "FBConfig.h"
 #include "EGLDispatch.h"
+#include "GLDispatch.h"
+#include "GL2Dispatch.h"
+#include "ThreadInfo.h"
 
 static const GLint rendererVersion = 1;
 
@@ -58,6 +61,38 @@
     return len;
 }
 
+static EGLint rcGetGLString(EGLenum name, void* buffer, EGLint bufferSize)
+{
+    RenderThreadInfo *tInfo = getRenderThreadInfo();
+    if (!tInfo || !tInfo->currContext.Ptr()) {
+        return 0;
+    }
+
+    const char *str = NULL;
+#ifdef WITH_GLES2
+    if (tInfo->currContext->isGL2()) {
+        str = (const char *)s_gl2.glGetString(name);
+    }
+    else {
+#endif
+        str = (const char *)s_gl.glGetString(name);
+#ifdef WITH_GLES2
+    }
+#endif
+
+    if (!str) {
+        return 0;
+    }
+
+    int len = strlen(str) + 1;
+    if (!buffer || len > bufferSize) {
+        return -len;
+    }
+
+    strcpy((char *)buffer, str);
+    return len;
+}
+
 static EGLint rcGetNumConfigs(uint32_t* numAttribs)
 {
     if (numAttribs) {
@@ -189,6 +224,15 @@
     fb->DestroyColorBuffer( colorbuffer );
 }
 
+static void rcFlushWindowColorBuffer(uint32_t windowSurface)
+{
+    FrameBuffer *fb = FrameBuffer::getFB();
+    if (!fb) {
+        return;
+    }
+    fb->flushWindowSurfaceColorBuffer(windowSurface);
+}
+
 static void rcSetWindowColorBuffer(uint32_t windowSurface,
                                    uint32_t colorBuffer)
 {
@@ -229,7 +273,12 @@
 
 static void rcBindTexture(uint32_t colorBuffer)
 {
-   // XXX: TBD - should be implemented
+    FrameBuffer *fb = FrameBuffer::getFB();
+    if (!fb) {
+        return;
+    }
+
+    fb->bindColorBufferToTexture(colorBuffer);
 }
 
 static EGLint rcColorBufferCacheFlush(uint32_t colorBuffer,
@@ -252,7 +301,12 @@
                                 GLint width, GLint height,
                                 GLenum format, GLenum type, void* pixels)
 {
-   // XXX: TBD - should be implemented
+    FrameBuffer *fb = FrameBuffer::getFB();
+    if (!fb) {
+        return;
+    }
+
+    fb->updateColorBuffer(colorBuffer, x, y, width, height, format, type, pixels);
 }
 
 void initRenderControlContext(renderControl_decoder_context_t *dec)
@@ -260,6 +314,7 @@
     dec->set_rcGetRendererVersion(rcGetRendererVersion);
     dec->set_rcGetEGLVersion(rcGetEGLVersion);
     dec->set_rcQueryEGLString(rcQueryEGLString);
+    dec->set_rcGetGLString(rcGetGLString);
     dec->set_rcGetNumConfigs(rcGetNumConfigs);
     dec->set_rcGetConfigs(rcGetConfigs);
     dec->set_rcChooseConfig(rcChooseConfig);
@@ -271,6 +326,7 @@
     dec->set_rcCreateColorBuffer(rcCreateColorBuffer);
     dec->set_rcDestroyColorBuffer(rcDestroyColorBuffer);
     dec->set_rcSetWindowColorBuffer(rcSetWindowColorBuffer);
+    dec->set_rcFlushWindowColorBuffer(rcFlushWindowColorBuffer);
     dec->set_rcMakeCurrent(rcMakeCurrent);
     dec->set_rcFBPost(rcFBPost);
     dec->set_rcFBSetSwapInterval(rcFBSetSwapInterval);
diff --git a/tools/emulator/opengl/host/libs/libOpenglRender/RenderServer.cpp b/tools/emulator/opengl/host/libs/libOpenglRender/RenderServer.cpp
index 95dbc3c..cc63283 100644
--- a/tools/emulator/opengl/host/libs/libOpenglRender/RenderServer.cpp
+++ b/tools/emulator/opengl/host/libs/libOpenglRender/RenderServer.cpp
@@ -32,6 +32,7 @@
 
     server->m_listenSock = new TcpStream();
     if (server->m_listenSock->listen(port) < 0) {
+        ERR("RenderServer::create failed to listen on port %d\n", port);
         delete server;
         return NULL;
     }
@@ -48,6 +49,7 @@
             break;
         }
 
+        DBG("\n\n\n\n Got new stream!!!! \n\n\n\n\n");
         // check if we have been requested to exit while waiting on accept
         if (m_exit) {
             break;
diff --git a/tools/emulator/opengl/host/libs/libOpenglRender/RenderThread.cpp b/tools/emulator/opengl/host/libs/libOpenglRender/RenderThread.cpp
index 8dd60d5..ad5df38 100644
--- a/tools/emulator/opengl/host/libs/libOpenglRender/RenderThread.cpp
+++ b/tools/emulator/opengl/host/libs/libOpenglRender/RenderThread.cpp
@@ -15,6 +15,7 @@
 */
 #include "RenderThread.h"
 #include "RenderControl.h"
+#include "ThreadInfo.h"
 #include "ReadBuffer.h"
 #include "TimeUtils.h"
 #include "GLDispatch.h"
@@ -41,10 +42,11 @@
 
 int RenderThread::Main()
 {
+    RenderThreadInfo * tInfo = getRenderThreadInfo();
     //
     // initialize decoders
     //
-    m_glDec.initGL( gl_dispatch_get_proc_func, NULL );
+    tInfo->m_glDec.initGL( gl_dispatch_get_proc_func, NULL );
     initRenderControlContext( &m_rcDec );
 
     ReadBuffer readBuf(m_stream, STREAM_BUFFER_SIZE);
@@ -79,7 +81,7 @@
             //
             // try to process some of the command buffer using the GLES decoder
             //
-            size_t last = m_glDec.decode(readBuf.buf(), readBuf.validData(), m_stream);
+            size_t last = tInfo->m_glDec.decode(readBuf.buf(), readBuf.validData(), m_stream);
             if (last > 0) {
                 progress = true;
                 readBuf.consume(last);
diff --git a/tools/emulator/opengl/host/libs/libOpenglRender/RenderThread.h b/tools/emulator/opengl/host/libs/libOpenglRender/RenderThread.h
index 2ca5755..ad5cde3 100644
--- a/tools/emulator/opengl/host/libs/libOpenglRender/RenderThread.h
+++ b/tools/emulator/opengl/host/libs/libOpenglRender/RenderThread.h
@@ -32,7 +32,6 @@
 
 private:
     IOStream *m_stream;
-    GLDecoder   m_glDec;
     renderControl_decoder_context_t m_rcDec;
 };
 
diff --git a/tools/emulator/opengl/host/libs/libOpenglRender/ThreadInfo.h b/tools/emulator/opengl/host/libs/libOpenglRender/ThreadInfo.h
index 82d2980..cabeb56 100644
--- a/tools/emulator/opengl/host/libs/libOpenglRender/ThreadInfo.h
+++ b/tools/emulator/opengl/host/libs/libOpenglRender/ThreadInfo.h
@@ -18,12 +18,14 @@
 
 #include "RenderContext.h"
 #include "WindowSurface.h"
+#include "GLDecoder.h"
 
 struct RenderThreadInfo
 {
     RenderContextPtr currContext;
     WindowSurfacePtr currDrawSurf;
     WindowSurfacePtr currReadSurf;
+    GLDecoder        m_glDec;
 };
 
 RenderThreadInfo *getRenderThreadInfo();
diff --git a/tools/emulator/opengl/host/libs/libOpenglRender/WindowSurface.cpp b/tools/emulator/opengl/host/libs/libOpenglRender/WindowSurface.cpp
index e8d7180..21b92e2 100644
--- a/tools/emulator/opengl/host/libs/libOpenglRender/WindowSurface.cpp
+++ b/tools/emulator/opengl/host/libs/libOpenglRender/WindowSurface.cpp
@@ -65,10 +65,15 @@
     //     and either there is no need for depth or stencil buffer
     //     or GL_KHR_gl_renderbuffer_image present.
     //
+#if 0
+    //XXX: This path should be implemented
     win->m_useEGLImage =
          (caps.has_eglimage_texture_2d &&
           (caps.has_eglimage_renderbuffer ||
            (fbconf->getDepthSize() + fbconf->getStencilSize() == 0)) );
+#else
+    win->m_useEGLImage = false;
+#endif
 
     if (win->m_useEGLImage) {
     }
@@ -118,12 +123,11 @@
 }
 
 //
-// setColorBuffer - this function is called when a new color buffer needs to
-//    be attached to the surface. The function should make sure that the
+// flushColorBuffer - The function makes sure that the
 //    previous attached color buffer is updated, if copy or blit should be done
 //    in order to update it - it is being done here.
 //
-void WindowSurface::setColorBuffer(ColorBufferPtr p_colorBuffer)
+void WindowSurface::flushColorBuffer()
 {
     if (m_attachedColorBuffer.Ptr() != NULL) {
 
@@ -138,9 +142,18 @@
             }
         }
         else {
+            //TODO: EGLImage
         }
     }
+}
 
+//
+// setColorBuffer - this function is called when a new color buffer needs to
+//    be attached to the surface. The function doesn't make sure that the
+//    previous attached color buffer is updated, this is done by flushColorBuffer
+//
+void WindowSurface::setColorBuffer(ColorBufferPtr p_colorBuffer)
+{
     m_attachedColorBuffer = p_colorBuffer;
 }
 
@@ -221,5 +234,4 @@
     s_egl.eglMakeCurrent(fb->getDisplay(), prevDrawSurf,
                          prevReadSurf, prevContext);
 
-    free(data);
 }
diff --git a/tools/emulator/opengl/host/libs/libOpenglRender/WindowSurface.h b/tools/emulator/opengl/host/libs/libOpenglRender/WindowSurface.h
index 3a01a35..2a496df 100644
--- a/tools/emulator/opengl/host/libs/libOpenglRender/WindowSurface.h
+++ b/tools/emulator/opengl/host/libs/libOpenglRender/WindowSurface.h
@@ -37,6 +37,7 @@
     EGLSurface getEGLSurface() const { return m_eglSurface; }
 
     void setColorBuffer(ColorBufferPtr p_colorBuffer);
+    void flushColorBuffer();
     void bind(RenderContextPtr p_ctx, SurfaceBindType p_bindType);
 
 private:
diff --git a/tools/emulator/opengl/host/libs/libOpenglRender/render_api.cpp b/tools/emulator/opengl/host/libs/libOpenglRender/render_api.cpp
index 2551f6f..da9682b 100644
--- a/tools/emulator/opengl/host/libs/libOpenglRender/render_api.cpp
+++ b/tools/emulator/opengl/host/libs/libOpenglRender/render_api.cpp
@@ -121,14 +121,14 @@
         // flag the thread it should exit
         s_renderThread->flagNeedExit();
 
-        // open a dummy connection to the renderer to make it 
+        // open a dummy connection to the renderer to make it
         // realize the exit request
         IOStream *dummy = createRenderThread(8);
         if (dummy) {
             // wait for the thread to exit
             int status;
             ret = s_renderThread->wait(&status);
-    
+
             delete dummy;
         }
 
@@ -143,10 +143,12 @@
 {
     TcpStream *stream = new TcpStream(p_stream_buffer_size);
     if (!stream) {
+        ERR("createRenderThread failed to create stream\n");
         return NULL;
     }
 
     if (stream->connect("localhost", s_renderPort) < 0) {
+        ERR("createRenderThread failed to connect\n");
         delete stream;
         return NULL;
     }
diff --git a/tools/emulator/opengl/host/libs/renderControl_dec/Android.mk b/tools/emulator/opengl/host/libs/renderControl_dec/Android.mk
index 373d2f4..889b5dd 100644
--- a/tools/emulator/opengl/host/libs/renderControl_dec/Android.mk
+++ b/tools/emulator/opengl/host/libs/renderControl_dec/Android.mk
@@ -1,36 +1,8 @@
-
 LOCAL_PATH := $(call my-dir)
 
-### renderControl Decoder ###########################################
-include $(CLEAR_VARS)
-
-emulatorOpengl := $(LOCAL_PATH)/../../..
-EMUGEN := $(BUILD_OUT_EXECUTABLES)/emugen
-
-LOCAL_IS_HOST_MODULE := true
-LOCAL_MODULE_CLASS := SHARED_LIBRARIES
-LOCAL_MODULE_TAGS := debug
-LOCAL_MODULE := lib_renderControl_dec
-LOCAL_SRC_FILES := 
-#LOCAL_CFLAGS += -DDEBUG_PRINTOUT -O0 -g
-intermediates := $(local-intermediates-dir)
-
-LOCAL_STATIC_LIBRARIES := \
-	libOpenglCodecCommon \
-    liblog
-LOCAL_C_INCLUDES += $(emulatorOpengl)/shared/OpenglCodecCommon \
-                    $(emulatorOpengl)/host/include/libOpenglRender \
-                    $(emulatorOpengl)/system/renderControl_enc
-
-#we use only *_dec.h as a sentinel for the other generated headers
-GEN := $(intermediates)/renderControl_dec.cpp $(intermediates)/renderControl_dec.h
-$(GEN): PRIVATE_PATH := $(LOCAL_PATH)
-$(GEN): PRIVATE_CUSTOM_TOOL := $(EMUGEN) -D $(intermediates) -i $(emulatorOpengl)/system/renderControl_enc renderControl
-$(GEN): $(EMUGEN) \
-	$(emulatorOpengl)/system/renderControl_enc/renderControl.attrib \
-	$(emulatorOpengl)/system/renderControl_enc/renderControl.in \
-	$(emulatorOpengl)/system/renderControl_enc/renderControl.types
-	$(transform-generated-source)
-
-LOCAL_GENERATED_SOURCES += $(GEN)
-include $(BUILD_HOST_SHARED_LIBRARY)
+$(call emugl-begin-host-shared-library,lib_renderControl_dec)
+$(call emugl-import,libOpenglCodecCommon)
+$(call emugl-gen-decoder,$(EMUGL_PATH)/system/renderControl_enc,renderControl)
+# For renderControl_types.h
+$(call emugl-export,C_INCLUDES,$(EMUGL_PATH)/system/renderControl_enc)
+$(call emugl-end-module)
diff --git a/tools/emulator/opengl/host/renderer/main.cpp b/tools/emulator/opengl/host/renderer/main.cpp
index ccc5d6a..73efe59 100644
--- a/tools/emulator/opengl/host/renderer/main.cpp
+++ b/tools/emulator/opengl/host/renderer/main.cpp
@@ -19,6 +19,11 @@
 #include <stdlib.h>
 #include "FrameBuffer.h"
 
+#include <sys/types.h>
+#include <unistd.h>
+#include <codec_defs.h>
+
+
 static void printUsage(const char *progName)
 {
     fprintf(stderr, "Usage: %s -windowid <windowid> [options]\n", progName);
@@ -33,7 +38,7 @@
 
 int main(int argc, char *argv[])
 {
-    int portNum = 4141;
+    int portNum = CODEC_SERVER_PORT;
     int winX = 0;
     int winY = 0;
     int winWidth = 320;
@@ -84,6 +89,9 @@
         printUsage(argv[0]);
     }
 
+    printf("renderer pid %d , press any key to continue...\n", getpid());
+    getchar();
+
     //
     // initialize Framebuffer
     //
@@ -95,7 +103,7 @@
     }
 
     //
-    // Create and run a render server listening to the givven port number
+    // Create and run a render server listening to the given port number
     //
     RenderServer *server = RenderServer::create(portNum);
     if (!server) {
diff --git a/tools/emulator/opengl/host/tools/emugen/Android.mk b/tools/emulator/opengl/host/tools/emugen/Android.mk
index fcd7b24..9a9751d 100644
--- a/tools/emulator/opengl/host/tools/emugen/Android.mk
+++ b/tools/emulator/opengl/host/tools/emugen/Android.mk
@@ -1,10 +1,16 @@
-
 LOCAL_PATH:=$(call my-dir)
 
-include $(CLEAR_VARS)
+$(call emugl-begin-host-executable,emugen)
 
-LOCAL_MODULE_TAGS := debug
-LOCAL_SRC_FILES := ApiGen.cpp EntryPoint.cpp main.cpp strUtils.cpp TypeFactory.cpp
-LOCAL_MODULE := emugen
+    LOCAL_SRC_FILES := \
+        ApiGen.cpp \
+        EntryPoint.cpp \
+        main.cpp \
+        strUtils.cpp \
+        TypeFactory.cpp
 
-include $(BUILD_HOST_EXECUTABLE)
+$(call emugl-end-module)
+
+# The location of the emugen host tool that is used to generate wire
+# protocol encoders/ decoders. This variable is used by other emugl modules.
+EMUGL_EMUGEN := $(LOCAL_BUILT_MODULE)
diff --git a/tools/emulator/opengl/host/tools/emugen/ApiGen.cpp b/tools/emulator/opengl/host/tools/emugen/ApiGen.cpp
index f019994..8cc097c 100644
--- a/tools/emulator/opengl/host/tools/emugen/ApiGen.cpp
+++ b/tools/emulator/opengl/host/tools/emugen/ApiGen.cpp
@@ -79,6 +79,38 @@
     return 0;
 }
 
+int ApiGen::genFuncTable(const std::string &filename, SideType side)
+{
+    FILE *fp = fopen(filename.c_str(), "wt");
+    if (fp == NULL) {
+        perror(filename.c_str());
+        return -1;
+    }
+    printHeader(fp);
+
+    fprintf(fp, "#ifndef __%s_%s_ftable_t_h\n", m_basename.c_str(), sideString(side));
+    fprintf(fp, "#define __%s_%s_ftable_t_h\n", m_basename.c_str(), sideString(side));
+    fprintf(fp, "\n\n");
+    fprintf(fp, "static struct _%s_funcs_by_name {\n", m_basename.c_str());
+    fprintf(fp,
+            "\tconst char *name;\n" \
+            "\tvoid *proc;\n" \
+            "} %s_funcs_by_name[] = {\n", m_basename.c_str());
+
+
+    for (size_t i = 0; i < size(); i++) {
+        EntryPoint *e = &at(i);
+        if (e->notApi()) continue;
+        fprintf(fp, "\t{\"%s\", (void*)%s},\n", e->name().c_str(), e->name().c_str());
+    }
+    fprintf(fp, "};\n");
+    fprintf(fp, "static int %s_num_funcs = sizeof(%s_funcs_by_name) / sizeof(struct _%s_funcs_by_name);\n",
+            m_basename.c_str(), m_basename.c_str(), m_basename.c_str());
+    fprintf(fp, "\n\n#endif\n");
+    return 0;
+}
+
+
 int ApiGen::genContext(const std::string & filename, SideType side)
 {
     FILE *fp = fopen(filename.c_str(), "wt");
@@ -155,27 +187,32 @@
     fprintf(fp, "#include \"%s_%s_context.h\"\n", m_basename.c_str(), sideString(side));
     fprintf(fp, "\n");
 
+    fprintf(fp, "#ifndef GL_TRUE\n");
     fprintf(fp, "extern \"C\" {\n");
 
     for (size_t i = 0; i < size(); i++) {
         fprintf(fp, "\t"); at(i).print(fp, false); fprintf(fp, ";\n");
     }
     fprintf(fp, "};\n\n");
+    fprintf(fp, "#endif\n");
 
+    fprintf(fp, "#ifndef GET_CONTEXT\n");
     fprintf(fp, "static %s_%s_context_t::CONTEXT_ACCESSOR_TYPE *getCurrentContext = NULL;\n",
             m_basename.c_str(), sideString(side));
 
     fprintf(fp,
-            "void %s_%s_context_t::setContextAccessor(CONTEXT_ACCESSOR_TYPE *f) { getCurrentContext = f; }\n\n",
+            "void %s_%s_context_t::setContextAccessor(CONTEXT_ACCESSOR_TYPE *f) { getCurrentContext = f; }\n",
             m_basename.c_str(), sideString(side));
+    fprintf(fp, "#define GET_CONTEXT %s_%s_context_t * ctx = getCurrentContext() \n",
+                m_basename.c_str(), sideString(side));
+    fprintf(fp, "#endif\n\n");
 
 
     for (size_t i = 0; i < size(); i++) {
         EntryPoint *e = &at(i);
         e->print(fp);
         fprintf(fp, "{\n");
-        fprintf(fp, "\t %s_%s_context_t * ctx = getCurrentContext(); \n",
-                m_basename.c_str(), sideString(side));
+        fprintf(fp, "\tGET_CONTEXT; \n");
 
         bool shouldReturn = !e->retval().isVoid();
         bool shouldCallWithContext = (side == CLIENT_SIDE);
@@ -311,6 +348,7 @@
         e->print(fp, true, "_enc", /* classname + "::" */"", "void *self");
         fprintf(fp, "{\n");
 
+//      fprintf(fp, "\n\tDBG(\">>>> %s\\n\");\n", e->name().c_str());
         fprintf(fp, "\n\t%s *ctx = (%s *)self;\n\n",
                 classname.c_str(),
                 classname.c_str());
@@ -417,6 +455,7 @@
                 }
             }
         }
+//XXX       fprintf(fp, "\n\tDBG(\"<<<< %s\\n\");\n", e->name().c_str());
         // todo - return value for pointers
         if (e->retval().isPointer()) {
             fprintf(stderr, "WARNING: %s : return value of pointer is unsupported\n",
diff --git a/tools/emulator/opengl/host/tools/emugen/ApiGen.h b/tools/emulator/opengl/host/tools/emugen/ApiGen.h
index 18f974b..1627ef6 100644
--- a/tools/emulator/opengl/host/tools/emugen/ApiGen.h
+++ b/tools/emulator/opengl/host/tools/emugen/ApiGen.h
@@ -67,6 +67,7 @@
     int genOpcodes(const std::string &filename);
     int genAttributesTemplate(const std::string &filename);
     int genProcTypes(const std::string &filename, SideType side);
+    int genFuncTable(const std::string &filename, SideType side);
 
     int genContext(const std::string &filename, SideType side);
     int genContextImpl(const std::string &filename, SideType side);
diff --git a/tools/emulator/opengl/host/tools/emugen/EntryPoint.cpp b/tools/emulator/opengl/host/tools/emugen/EntryPoint.cpp
index f766dd9..0341027 100644
--- a/tools/emulator/opengl/host/tools/emugen/EntryPoint.cpp
+++ b/tools/emulator/opengl/host/tools/emugen/EntryPoint.cpp
@@ -34,6 +34,7 @@
 {
     m_unsupported = false;
     m_customDecoder = false;
+    m_notApi = false;
     m_vars.empty();
 }
 
@@ -57,9 +58,10 @@
         case ST_TYPE:
             if (str == "const") {
                 pos = last;
+                *vartype = "const ";
             } else {
                 // must be a type name;
-                *vartype = str;
+                *vartype += str;
                 state = ST_NAME;
                 pos = last;
             }
@@ -312,6 +314,8 @@
             setUnsupported(true);
         } else if (flag == "custom_decoder") {
             setCustomDecoder(true);
+        } else if (flag == "not_api") {
+            setNotApi(true);
         } else {
             fprintf(stderr, "WARNING: %u: unknown flag %s\n", (unsigned int)lc, flag.c_str());
         }
diff --git a/tools/emulator/opengl/host/tools/emugen/EntryPoint.h b/tools/emulator/opengl/host/tools/emugen/EntryPoint.h
index c417bda..77b8a7f 100644
--- a/tools/emulator/opengl/host/tools/emugen/EntryPoint.h
+++ b/tools/emulator/opengl/host/tools/emugen/EntryPoint.h
@@ -45,6 +45,8 @@
     void setUnsupported(bool state) { m_unsupported = state; }
     bool customDecoder() { return m_customDecoder; }
     void setCustomDecoder(bool state) { m_customDecoder = state; }
+    bool notApi() const { return m_notApi; }
+    void setNotApi(bool state) { m_notApi = state; }
     int setAttribute(const std::string &line, size_t lc);
 
 private:
@@ -54,6 +56,7 @@
     VarsArray m_vars;
     bool m_unsupported;
     bool m_customDecoder;
+    bool m_notApi;
 
     void err(unsigned int lc, const char *msg) {
         fprintf(stderr, "line %d: %s\n", lc, msg);
diff --git a/tools/emulator/opengl/host/tools/emugen/README b/tools/emulator/opengl/host/tools/emugen/README
index 6fa9ec9..4d2c28d 100644
--- a/tools/emulator/opengl/host/tools/emugen/README
+++ b/tools/emulator/opengl/host/tools/emugen/README
@@ -324,5 +324,6 @@
 		       	 custom implementation. The call to the
 		       	 deocder function includes a pointer to the
 		       	 context
+    not_api - the function is not native gl api
 
 
diff --git a/tools/emulator/opengl/host/tools/emugen/TypeFactory.cpp b/tools/emulator/opengl/host/tools/emugen/TypeFactory.cpp
index 166b21a..8884225 100644
--- a/tools/emulator/opengl/host/tools/emugen/TypeFactory.cpp
+++ b/tools/emulator/opengl/host/tools/emugen/TypeFactory.cpp
@@ -134,6 +134,8 @@
                     lc, name.c_str(), lc);
         }
         g_varMap.insert(std::pair<std::string, VarType>(name, VarType(g_typeId++, name, v ,printString,isPointer)));
+        std::string constName = "const " + name;
+        g_varMap.insert(std::pair<std::string, VarType>(constName, VarType(g_typeId++, constName, v ,printString,isPointer))); //add a const type
     }
     g_initialized = true;
     return 0;
diff --git a/tools/emulator/opengl/host/tools/emugen/main.cpp b/tools/emulator/opengl/host/tools/emugen/main.cpp
index bbc9d90..96377f2 100644
--- a/tools/emulator/opengl/host/tools/emugen/main.cpp
+++ b/tools/emulator/opengl/host/tools/emugen/main.cpp
@@ -125,6 +125,7 @@
         apiEntries.genContextImpl(encoderDir + "/" + baseName + "_client_context.cpp", ApiGen::CLIENT_SIDE);
 
         apiEntries.genProcTypes(encoderDir + "/" + baseName + "_client_proc.h", ApiGen::CLIENT_SIDE);
+        apiEntries.genFuncTable(encoderDir + "/" + baseName + "_ftable.h", ApiGen::CLIENT_SIDE);
 
         apiEntries.genEntryPoints(encoderDir + "/" + baseName + "_entry.cpp", ApiGen::CLIENT_SIDE);
         apiEntries.genEncoderHeader(encoderDir + "/" + baseName + "_enc.h");
diff --git a/tools/emulator/opengl/shared/OpenglCodecCommon/Android.mk b/tools/emulator/opengl/shared/OpenglCodecCommon/Android.mk
index af8c163..986f9c6 100644
--- a/tools/emulator/opengl/shared/OpenglCodecCommon/Android.mk
+++ b/tools/emulator/opengl/shared/OpenglCodecCommon/Android.mk
@@ -1,38 +1,33 @@
-
+# This build script corresponds to a library containing many definitions
+# common to both the guest and the host. They relate to
+#
 LOCAL_PATH := $(call my-dir)
-emulatorOpengl := $(LOCAL_PATH)/../..
 
-### OpenglCodecCommon ##############################################
+### CodecCommon  guest ##############################################
+$(call emugl-begin-static-library,libOpenglCodecCommon)
 
-include $(CLEAR_VARS)
-
-OpenglCodecCommon := \
+LOCAL_SRC_FILES := \
         GLClientState.cpp \
         glUtils.cpp \
         TcpStream.cpp \
         TimeUtils.cpp
 
-LOCAL_SRC_FILES :=  $(OpenglCodecCommon)
-
-LOCAL_C_INCLUDES += $(emulatorOpengl)/host/include/libOpenglRender 
-
 LOCAL_CFLAGS += -DLOG_TAG=\"eglCodecCommon\"
-LOCAL_MODULE_TAGS := debug
-LOCAL_MODULE := libOpenglCodecCommon
 
-include $(BUILD_STATIC_LIBRARY)
+$(call emugl-export,SHARED_LIBRARIES,libcutils)
+$(call emugl-export,C_INCLUDES,$(LOCAL_PATH))
+$(call emugl-end-module)
 
 ### OpenglCodecCommon  host ##############################################
-include $(CLEAR_VARS)
+$(call emugl-begin-host-static-library,libOpenglCodecCommon)
 
-LOCAL_SRC_FILES :=  $(OpenglCodecCommon)
+LOCAL_SRC_FILES := \
+        GLClientState.cpp \
+        glUtils.cpp \
+        TcpStream.cpp \
+        TimeUtils.cpp
 
-LOCAL_C_INCLUDES += $(emulatorOpengl)/host/include/libOpenglRender 
+$(call emugl-export,STATIC_LIBRARIES,libcutils)
+$(call emugl-export,C_INCLUDES,$(LOCAL_PATH))
+$(call emugl-end-module)
 
-LOCAL_MODULE_TAGS := debug
-LOCAL_MODULE := libOpenglCodecCommon
-LOCAL_PRELINK_MODULE := false
-
-# XXX - enable the next line for host debugging - JR
-# LOCAL_CFLAGS := -O0 -g
-include $(BUILD_HOST_STATIC_LIBRARY)
diff --git a/tools/emulator/opengl/shared/OpenglCodecCommon/GLClientState.cpp b/tools/emulator/opengl/shared/OpenglCodecCommon/GLClientState.cpp
index a7e2ea0..dcfe9fe 100644
--- a/tools/emulator/opengl/shared/OpenglCodecCommon/GLClientState.cpp
+++ b/tools/emulator/opengl/shared/OpenglCodecCommon/GLClientState.cpp
@@ -70,7 +70,7 @@
     m_states[location].enabled = state;
 }
 
-void GLClientState::setState(int location, int size, GLenum type, GLboolean normalized, GLsizei stride, void *data)
+void GLClientState::setState(int location, int size, GLenum type, GLboolean normalized, GLsizei stride, const void *data)
 {
     if (!validLocation(location)) {
         return;
@@ -78,7 +78,7 @@
     m_states[location].size = size;
     m_states[location].type = type;
     m_states[location].stride = stride;
-    m_states[location].data = data;
+    m_states[location].data = (void*)data;
     m_states[location].bufferObject = m_currentArrayVbo;
     m_states[location].elementSize = glSizeof(type) * size;
     m_states[location].normalized = normalized;
diff --git a/tools/emulator/opengl/shared/OpenglCodecCommon/GLClientState.h b/tools/emulator/opengl/shared/OpenglCodecCommon/GLClientState.h
index 9e4c916..b7fcff5 100644
--- a/tools/emulator/opengl/shared/OpenglCodecCommon/GLClientState.h
+++ b/tools/emulator/opengl/shared/OpenglCodecCommon/GLClientState.h
@@ -79,7 +79,7 @@
     GLuint currentArrayVbo() { return m_currentArrayVbo; }
     GLuint currentIndexVbo() { return m_currentIndexVbo; }
     void enable(int location, int state);
-    void setState(int  location, int size, GLenum type, GLboolean normalized, GLsizei stride, void *data);
+    void setState(int  location, int size, GLenum type, GLboolean normalized, GLsizei stride, const void *data);
     void setBufferObject(int location, GLuint id);
     const VertexAttribState  *getState(int location);
     const VertexAttribState  *getStateAndEnableDirty(int location, bool *enableChanged);
diff --git a/tools/emulator/opengl/shared/OpenglCodecCommon/TcpStream.cpp b/tools/emulator/opengl/shared/OpenglCodecCommon/TcpStream.cpp
index e774c62..f144a9f 100644
--- a/tools/emulator/opengl/shared/OpenglCodecCommon/TcpStream.cpp
+++ b/tools/emulator/opengl/shared/OpenglCodecCommon/TcpStream.cpp
@@ -148,12 +148,11 @@
 {
     if (!valid()) return NULL;
     if (!buf) {
-      ERR("TcpStream::readFully failed, buf=NULL");
       return NULL;  // do not allow NULL buf in that implementation
     }
     size_t res = len;
     while (res > 0) {
-        ssize_t stat = ::recv(m_sock, (char *)(buf) + len - res, len, 0);
+        ssize_t stat = ::recv(m_sock, (char *)(buf) + len - res, res, 0);
         if (stat == 0) {
             // client shutdown;
             return NULL;
@@ -161,7 +160,6 @@
             if (errno == EINTR) {
                 continue;
             } else {
-                ERR("TcpStream::readFully failed (buf 0x%x): %s\n", buf, strerror(errno));
                 return NULL;
             }
         } else {
@@ -175,7 +173,6 @@
 {
     if (!valid()) return NULL;
     if (!buf) {
-      ERR("TcpStream::read failed, buf=NULL");
       return NULL;  // do not allow NULL buf in that implementation
     }
 
diff --git a/tools/emulator/opengl/shared/OpenglOsUtils/Android.mk b/tools/emulator/opengl/shared/OpenglOsUtils/Android.mk
index 44a9994..5a53a23 100644
--- a/tools/emulator/opengl/shared/OpenglOsUtils/Android.mk
+++ b/tools/emulator/opengl/shared/OpenglOsUtils/Android.mk
@@ -1,42 +1,48 @@
+# This build script corresponds to a small library containing
+# OS-specific support functions for:
+#   - thread-local storage
+#   - dynamic library loading
+#   - child process creation and wait  (probably not needed in guest)
+#
 LOCAL_PATH := $(call my-dir)
-emulatorOpengl := $(LOCAL_PATH)/../..
 
-### OpenglOsUtils ##############################################
+### Guest library ##############################################
+$(call emugl-begin-static-library,libOpenglOsUtils)
 
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := \
-        osProcessUnix.cpp \
-        osThreadUnix.cpp \
-        osDynLibrary.cpp
-
-LOCAL_MODULE_TAGS := debug
-LOCAL_MODULE := libOpenglOsUtils
-
-include $(BUILD_STATIC_LIBRARY)
-
-### OpenglOsUtils  host ##############################################
-include $(CLEAR_VARS)
-
-ifneq ($(HOST_OS),windows)
+    $(call emugl-export,C_INCLUDES,$(LOCAL_PATH))
+    $(call emugl-export,LDLIBS,-ldl)
 
     LOCAL_SRC_FILES := \
         osProcessUnix.cpp \
         osThreadUnix.cpp \
         osDynLibrary.cpp
 
-    LOCAL_LDLIBS := -ldl
+$(call emugl-end-module)
 
-else # !linux
 
-    LOCAL_SRC_FILES := \
-        osProcessWin.cpp \
-        osThreadWin.cpp \
-        osDynLibrary.cpp
+### Host library ##############################################
+$(call emugl-begin-host-static-library,libOpenglOsUtils)
 
-endif # windows
+    $(call emugl-export,C_INCLUDES,$(LOCAL_PATH))
 
-LOCAL_MODULE_TAGS := debug
-LOCAL_MODULE := libOpenglOsUtils
+    LOCAL_SRC_FILES := osDynLibrary.cpp
 
-include $(BUILD_HOST_STATIC_LIBRARY)
+    ifeq ($(HOST_OS),windows)
+        LOCAL_SRC_FILES += \
+            osProcessWin.cpp \
+            osThreadWin.cpp
+
+        $(call emugl-export,LDLIBS,-lws2_32)
+    else
+        LOCAL_SRC_FILES += \
+            osProcessUnix.cpp \
+            osThreadUnix.cpp
+
+        $(call emugl-export,LDLIBS,-ldl)
+    endif
+
+    ifeq ($(HOST_OS),linux)
+        $(call emugl-export,LDLIBS,-lpthread -lrt)
+    endif
+
+$(call emugl-end-module)
diff --git a/tools/emulator/opengl/shared/OpenglOsUtils/osDynLibrary.cpp b/tools/emulator/opengl/shared/OpenglOsUtils/osDynLibrary.cpp
index 65107e3..e8e6ab7 100644
--- a/tools/emulator/opengl/shared/OpenglOsUtils/osDynLibrary.cpp
+++ b/tools/emulator/opengl/shared/OpenglOsUtils/osDynLibrary.cpp
@@ -36,6 +36,10 @@
 #endif
 
     if (lib->m_lib == NULL) {
+        printf("Failed to load %s\n", p_libName);
+#ifndef _WIN32
+        printf("error %s\n", dlerror()); //only on linux
+#endif
         delete lib;
         return NULL;
     }
diff --git a/tools/emulator/opengl/system/GLESv1/Android.mk b/tools/emulator/opengl/system/GLESv1/Android.mk
new file mode 100644
index 0000000..9119c07
--- /dev/null
+++ b/tools/emulator/opengl/system/GLESv1/Android.mk
@@ -0,0 +1,58 @@
+LOCAL_PATH := $(call my-dir)
+
+### GLESv1 implementation ###########################################
+$(call emugl-begin-shared-library,libGLESv1_CM_emulation)
+$(call emugl-import,libOpenglSystemCommon libGLESv1_enc lib_renderControl_enc)
+
+LOCAL_CFLAGS += -DLOG_TAG=\"GLES_emulation\" -DGL_GLEXT_PROTOTYPES
+
+LOCAL_SRC_FILES := gl.cpp
+LOCAL_STATIC_LIBRARIES += libqemu
+LOCAL_MODULE_PATH := $(TARGET_OUT_SHARED_LIBRARIES)/egl
+
+$(call emugl-end-module)
+
+#
+# include $(CLEAR_VARS)
+#
+# # add additional depencies to ensure that the generated code that we depend on
+# # is generated
+# LOCAL_ADDITIONAL_DEPENDENCIES := \
+# 	$(TARGET_OUT_SHARED_LIBRARIES)/lib_renderControl_enc$(TARGET_SHLIB_SUFFIX) \
+# 	$(TARGET_OUT_SHARED_LIBRARIES)/libGLESv1_enc$(TARGET_SHLIB_SUFFIX)
+#
+# LOCAL_SRC_FILES := \
+#         gl.cpp
+#
+#
+# LOCAL_PRELINK_MODULE := false
+# LOCAL_CFLAGS += -DLOG_TAG=\"GLES_emulation\" -DGL_GLEXT_PROTOTYPES
+# LOCAL_C_INCLUDES +=  \
+#         $(emulatorOpengl)/host/include/libOpenglRender \
+#         $(emulatorOpengl)/shared/OpenglCodecCommon \
+#         $(emulatorOpengl)/system/OpenglSystemCommon \
+#         $(emulatorOpengl)/system/GLESv1_enc \
+#         $(emulatorOpengl)/system/renderControl_enc \
+# 		$(call intermediates-dir-for, SHARED_LIBRARIES, lib_renderControl_enc) \
+# 		$(call intermediates-dir-for, SHARED_LIBRARIES, libGLESv1_enc)
+#
+# LOCAL_MODULE_TAGS := debug
+# LOCAL_MODULE_PATH := $(TARGET_OUT_SHARED_LIBRARIES)/egl
+# LOCAL_MODULE := libGLESv1_CM_emulation
+# LOCAL_MODULE_CLASS := SHARED_LIBRARIES
+#
+#
+# LOCAL_STATIC_LIBRARIES := \
+#     libOpenglCodecCommon  \
+# 	libqemu
+#
+# LOCAL_SHARED_LIBRARIES := \
+#     libcutils \
+# 	libutils \
+# 	libdl \
+#     libOpenglSystemCommon \
+# 	libGLESv1_enc	\
+# 	lib_renderControl_enc
+#
+#
+# include $(BUILD_SHARED_LIBRARY)
diff --git a/tools/emulator/opengl/system/GLESv1/gl.cpp b/tools/emulator/opengl/system/GLESv1/gl.cpp
new file mode 100644
index 0000000..d57624f
--- /dev/null
+++ b/tools/emulator/opengl/system/GLESv1/gl.cpp
@@ -0,0 +1,102 @@
+#include "EGLClientIface.h"
+#include "HostConnection.h"
+#include "GLEncoder.h"
+#include "GLES/gl.h"
+#include "GLES/glext.h"
+#include "ErrorLog.h"
+#include <private/ui/android_natives_priv.h>
+#include "gralloc_cb.h"
+
+
+//XXX: fix this macro to get the context from fast tls path
+#define GET_CONTEXT gl_client_context_t * ctx = HostConnection::get()->glEncoder();
+
+#include "gl_entry.cpp"
+
+//The functions table
+#include "gl_ftable.h"
+
+static EGLClient_eglInterface * s_egl = NULL;
+static EGLClient_glesInterface * s_gl = NULL;
+
+#define DEFINE_AND_VALIDATE_HOST_CONNECTION(ret) \
+    HostConnection *hostCon = HostConnection::get(); \
+    if (!hostCon) { \
+        LOGE("egl: Failed to get host connection\n"); \
+        return ret; \
+    } \
+    renderControl_encoder_context_t *rcEnc = hostCon->rcEncoder(); \
+    if (!rcEnc) { \
+        LOGE("egl: Failed to get renderControl encoder context\n"); \
+        return ret; \
+    }
+
+//GL extensions
+void glEGLImageTargetTexture2DOES(void * self, GLenum target, GLeglImageOES image)
+{
+    DBG("glEGLImageTargetTexture2DOES");
+    //TODO: check error - we don't have a way to set gl error
+    android_native_buffer_t* native_buffer = (android_native_buffer_t*)image;
+
+    if (native_buffer->common.magic != ANDROID_NATIVE_BUFFER_MAGIC) {
+        return;
+    }
+
+    if (native_buffer->common.version != sizeof(android_native_buffer_t)) {
+        return;
+    }
+
+    DEFINE_AND_VALIDATE_HOST_CONNECTION();
+    rcEnc->rcBindTexture(rcEnc, ((cb_handle_t *)(native_buffer->handle))->hostHandle);
+
+    return;
+}
+
+void * getProcAddress(const char * procname)
+{
+    // search in GL function table
+    for (int i=0; i<gl_num_funcs; i++) {
+        if (!strcmp(gl_funcs_by_name[i].name, procname)) {
+            return gl_funcs_by_name[i].proc;
+        }
+    }
+    return NULL;
+}
+
+void finish()
+{
+    glFinish();
+}
+
+const GLubyte *my_glGetString (void *self, GLenum name)
+{
+    if (s_egl) {
+        return (const GLubyte*)s_egl->getGLString(name);
+    }
+    return NULL;
+}
+
+void init()
+{
+    GET_CONTEXT;
+    ctx->set_glEGLImageTargetTexture2DOES(glEGLImageTargetTexture2DOES);
+    ctx->set_glGetString(my_glGetString);
+}
+
+extern "C" {
+EGLClient_glesInterface * init_emul_gles(EGLClient_eglInterface *eglIface)
+{
+    s_egl = eglIface;
+
+    if (!s_gl) {
+        s_gl = new EGLClient_glesInterface();
+        s_gl->getProcAddress = getProcAddress;
+        s_gl->finish = finish;
+        s_gl->init = init;
+    }
+
+    return s_gl;
+}
+} //extern
+
+
diff --git a/tools/emulator/opengl/system/GLESv1_enc/Android.mk b/tools/emulator/opengl/system/GLESv1_enc/Android.mk
index c8fd18b..25c8c49 100644
--- a/tools/emulator/opengl/system/GLESv1_enc/Android.mk
+++ b/tools/emulator/opengl/system/GLESv1_enc/Android.mk
@@ -1,46 +1,18 @@
 LOCAL_PATH := $(call my-dir)
-emulatorOpengl := $(LOCAL_PATH)/../..
 
 ### GLESv1_enc Encoder ###########################################
-include $(CLEAR_VARS)
+$(call emugl-begin-shared-library,libGLESv1_enc)
 
+LOCAL_CFLAGS += -DLOG_TAG=\"emuglGLESv1_enc\"
 
 LOCAL_SRC_FILES := \
         GLEncoder.cpp \
         GLEncoderUtils.cpp
 
-LOCAL_MODULE_TAGS := debug
-LOCAL_MODULE := libGLESv1_enc
-LOCAL_MODULE_CLASS := SHARED_LIBRARIES
+$(call emugl-gen-encoder,$(LOCAL_PATH),gl)
 
-glesv1_intermediates := $(local-intermediates-dir)
+$(call emugl-import,libOpenglCodecCommon)
+$(call emugl-export,C_INCLUDES,$(LOCAL_PATH))
+$(call emugl-export,C_INCLUDES,$(intermediates))
 
-LOCAL_PRELINK_MODULE := false
-LOCAL_CFLAGS += -DLOG_TAG=\"egl_GLESv1_enc\"
-LOCAL_C_INCLUDES +=  \
-    $(emulatorOpengl)/shared/OpenglCodecCommon \
-    $(emulatorOpengl)/host/include/libOpenglRender \
-    $(glesv1_intermediates)
-
-LOCAL_STATIC_LIBRARIES := \
-        libOpenglCodecCommon
-LOCAL_SHARED_LIBRARIES := libcutils
-
-EMUGEN := $(HOST_OUT_EXECUTABLES)/emugen
-
-GEN_GL := \
-	$(glesv1_intermediates)/gl_entry.cpp \
-	$(glesv1_intermediates)/gl_enc.cpp \
-	$(glesv1_intermediates)/gl_enc.h
-
-$(GEN_GL) : PRIVATE_PATH := $(LOCAL_PATH)
-$(GEN_GL) : PRIVATE_CUSTOM_TOOL := \
-        $(EMUGEN) -E $(glesv1_intermediates) -i $(PRIVATE_PATH) gl
-$(GEN_GL) : $(EMUGEN) \
-        $(LOCAL_PATH)/gl.attrib \
-        $(LOCAL_PATH)/gl.in \
-        $(LOCAL_PATH)//gl.types
-	$(transform-generated-source)
-
-LOCAL_GENERATED_SOURCES += $(GEN_GL)
-include $(BUILD_SHARED_LIBRARY)
+$(call emugl-end-module)
diff --git a/tools/emulator/opengl/system/GLESv1_enc/GLEncoder.cpp b/tools/emulator/opengl/system/GLESv1_enc/GLEncoder.cpp
index 2095af5..9142bef 100644
--- a/tools/emulator/opengl/system/GLESv1_enc/GLEncoder.cpp
+++ b/tools/emulator/opengl/system/GLESv1_enc/GLEncoder.cpp
@@ -16,7 +16,6 @@
 #include "GLEncoder.h"
 #include "glUtils.h"
 #include "FixedBuffer.h"
-
 #include <cutils/log.h>
 #include <assert.h>
 
@@ -25,6 +24,18 @@
 static GLubyte *gVersionString= (GLubyte *) "OpenGL ES-CM 1.0";
 static GLubyte *gExtensionsString= (GLubyte *) ""; // no extensions at this point;
 
+#define DEFINE_AND_VALIDATE_HOST_CONNECTION(ret) \
+    HostConnection *hostCon = HostConnection::get(); \
+    if (!hostCon) { \
+        LOGE("egl: Failed to get host connection\n"); \
+        return ret; \
+    } \
+    renderControl_encoder_context_t *rcEnc = hostCon->rcEncoder(); \
+    if (!rcEnc) { \
+        LOGE("egl: Failed to get renderControl encoder context\n"); \
+        return ret; \
+    }
+
 
 GLint * GLEncoder::getCompressedTextureFormats()
 {
@@ -115,7 +126,7 @@
     ctx->m_stream->flush();
 }
 
-GLubyte *GLEncoder::s_glGetString(void *self, GLenum name)
+const GLubyte *GLEncoder::s_glGetString(void *self, GLenum name)
 {
     GLubyte *retval =  (GLubyte *) "";
     switch(name) {
@@ -139,32 +150,32 @@
 {
     GLEncoder *ctx = (GLEncoder *)self;
     ctx->m_glPixelStorei_enc(ctx, param, value);
-    assert(ctx->m_state != NULL);
+    LOG_ASSERT(ctx->m_state, "GLEncoder::s_glPixelStorei");
     ctx->m_state->setPixelStore(param, value);
 }
 
-void GLEncoder::s_glVertexPointer(void *self, int size, GLenum type, GLsizei stride, void *data)
+void GLEncoder::s_glVertexPointer(void *self, int size, GLenum type, GLsizei stride, const void *data)
 {
     GLEncoder *ctx = (GLEncoder *)self;
     assert(ctx->m_state != NULL);
     ctx->m_state->setState(GLClientState::VERTEX_LOCATION, size, type, false, stride, data);
 }
 
-void GLEncoder::s_glNormalPointer(void *self, GLenum type, GLsizei stride, void *data)
+void GLEncoder::s_glNormalPointer(void *self, GLenum type, GLsizei stride, const void *data)
 {
     GLEncoder *ctx = (GLEncoder *)self;
     assert(ctx->m_state != NULL);
     ctx->m_state->setState(GLClientState::NORMAL_LOCATION, 3, type, false, stride, data);
 }
 
-void GLEncoder::s_glColorPointer(void *self, int size, GLenum type, GLsizei stride, void *data)
+void GLEncoder::s_glColorPointer(void *self, int size, GLenum type, GLsizei stride, const void *data)
 {
     GLEncoder *ctx = (GLEncoder *)self;
     assert(ctx->m_state != NULL);
     ctx->m_state->setState(GLClientState::COLOR_LOCATION, size, type, false, stride, data);
 }
 
-void GLEncoder::s_glPointsizePointer(void *self, GLenum type, GLsizei stride, void *data)
+void GLEncoder::s_glPointsizePointer(void *self, GLenum type, GLsizei stride, const void *data)
 {
     GLEncoder *ctx = (GLEncoder *)self;
     assert(ctx->m_state != NULL);
@@ -178,7 +189,7 @@
     ctx->m_state->setActiveTexture(texture - GL_TEXTURE0);
 }
 
-void GLEncoder::s_glTexcoordPointer(void *self, int size, GLenum type, GLsizei stride, void *data)
+void GLEncoder::s_glTexcoordPointer(void *self, int size, GLenum type, GLsizei stride, const void *data)
 {
     GLEncoder *ctx = (GLEncoder *)self;
     assert(ctx->m_state != NULL);
@@ -186,7 +197,7 @@
     ctx->m_state->setState(loc, size, type, false, stride, data);
 }
 
-void GLEncoder::s_glMatrixIndexPointerOES(void *self, int size, GLenum type, GLsizei stride, void * data)
+void GLEncoder::s_glMatrixIndexPointerOES(void *self, int size, GLenum type, GLsizei stride, const void * data)
 {
     GLEncoder *ctx = (GLEncoder *)self;
     assert(ctx->m_state != NULL);
@@ -194,7 +205,7 @@
     ctx->m_state->setState(loc, size, type, false, stride, data);
 }
 
-void GLEncoder::s_glWeightPointerOES(void * self, int size, GLenum type, GLsizei stride, void * data)
+void GLEncoder::s_glWeightPointerOES(void * self, int size, GLenum type, GLsizei stride, const void * data)
 {
     GLEncoder *ctx = (GLEncoder *)self;
     assert(ctx->m_state != NULL);
@@ -362,7 +373,7 @@
     ctx->m_glDrawArrays_enc(ctx, mode, /*first*/ 0, count);
 }
 
-void GLEncoder::s_glDrawElements(void *self, GLenum mode, GLsizei count, GLenum type, void *indices)
+void GLEncoder::s_glDrawElements(void *self, GLenum mode, GLsizei count, GLenum type, const void *indices)
 {
 
     GLEncoder *ctx = (GLEncoder *)self;
@@ -395,7 +406,7 @@
             LOGE("glDrawElements: indirect index arrays, with immidate-mode data array is not supported\n");
         }
     } else {
-        void *adjustedIndices = indices;
+        void *adjustedIndices = (void*)indices;
         int minIndex = 0, maxIndex = 0;
 
         switch(type) {
@@ -440,6 +451,7 @@
 
 GLEncoder::GLEncoder(IOStream *stream) : gl_encoder_context_t(stream)
 {
+    m_initialized = false;
     m_state = NULL;
     m_compressedTextureFormats = NULL;
     // overrides;
@@ -467,6 +479,7 @@
     m_glDrawArrays_enc = set_glDrawArrays(s_glDrawArrays);
     m_glDrawElements_enc = set_glDrawElements(s_glDrawElements);
     set_glGetString(s_glGetString);
+    set_glFinish(s_glFinish);
 
 }
 
@@ -480,3 +493,10 @@
     assert(m_state != NULL);
     return m_state->pixelDataSize(width, height, format, type, pack);
 }
+
+void GLEncoder::s_glFinish(void *self)
+{
+    GLEncoder *ctx = (GLEncoder *)self;
+    ctx->glFinishRoundTrip(self);
+}
+
diff --git a/tools/emulator/opengl/system/GLESv1_enc/GLEncoder.h b/tools/emulator/opengl/system/GLESv1_enc/GLEncoder.h
index 3223ae9..6275820 100644
--- a/tools/emulator/opengl/system/GLESv1_enc/GLEncoder.h
+++ b/tools/emulator/opengl/system/GLESv1_enc/GLEncoder.h
@@ -30,8 +30,13 @@
     }
     void flush() { m_stream->flush(); }
     size_t pixelDataSize(GLsizei width, GLsizei height, GLenum format, GLenum type, int pack);
+
+    void setInitialized(){ m_initialized = true; };
+    bool isInitialized(){ return m_initialized; };
+
 private:
 
+    bool    m_initialized;
     GLClientState *m_state;
     FixedBuffer m_fixedBuffer;
     GLint *m_compressedTextureFormats;
@@ -71,22 +76,26 @@
     static void s_glGetPointerv(void *self, GLenum pname, GLvoid **params);
 
     static void s_glFlush(void * self);
-    static GLubyte * s_glGetString(void *self, GLenum name);
-    static void s_glVertexPointer(void *self, int size, GLenum type, GLsizei stride, void *data);
-    static void s_glNormalPointer(void *self, GLenum type, GLsizei stride, void *data);
-    static void s_glColorPointer(void *self, int size, GLenum type, GLsizei stride, void *data);
-    static void s_glPointsizePointer(void *self, GLenum type, GLsizei stride, void *data);
+    static const GLubyte * s_glGetString(void *self, GLenum name);
+    static void s_glVertexPointer(void *self, int size, GLenum type, GLsizei stride, const void *data);
+    static void s_glNormalPointer(void *self, GLenum type, GLsizei stride, const void *data);
+    static void s_glColorPointer(void *self, int size, GLenum type, GLsizei stride, const void *data);
+    static void s_glPointsizePointer(void *self, GLenum type, GLsizei stride, const void *data);
     static void s_glClientActiveTexture(void *self, GLenum texture);
-    static void s_glTexcoordPointer(void *self, int size, GLenum type, GLsizei stride, void *data);
-    static void s_glMatrixIndexPointerOES(void *self, int size, GLenum type, GLsizei stride, void * data);
-    static void s_glWeightPointerOES(void *self, int size, GLenum type, GLsizei stride, void * data);
+    static void s_glTexcoordPointer(void *self, int size, GLenum type, GLsizei stride, const void *data);
+    static void s_glMatrixIndexPointerOES(void *self, int size, GLenum type, GLsizei stride, const void * data);
+    static void s_glWeightPointerOES(void *self, int size, GLenum type, GLsizei stride, const void * data);
     static void s_glDisableClientState(void *self, GLenum state);
     static void s_glEnableClientState(void *self, GLenum state);
     static GLboolean s_glIsEnabled(void *self, GLenum cap);
     static void s_glBindBuffer(void *self, GLenum target, GLuint id);
     static void s_glDrawArrays(void *self, GLenum mode, GLint first, GLsizei count);
-    static void s_glDrawElements(void *self, GLenum mode, GLsizei count, GLenum type, void *indices);
+    static void s_glDrawElements(void *self, GLenum mode, GLsizei count, GLenum type, const void *indices);
     static void s_glPixelStorei(void *self, GLenum param, GLint value);
+
+    static void s_glFinish(void *self);
+    static void s_glEGLImageTargetTexture2DOES(void * self, GLenum target, GLeglImageOES image);
     void sendVertexData(unsigned first, unsigned count);
+
 };
 #endif
diff --git a/tools/emulator/opengl/system/GLESv1_enc/gl.attrib b/tools/emulator/opengl/system/GLESv1_enc/gl.attrib
index 374009c..d3d97fc 100644
--- a/tools/emulator/opengl/system/GLESv1_enc/gl.attrib
+++ b/tools/emulator/opengl/system/GLESv1_enc/gl.attrib
@@ -268,70 +268,90 @@
 	len data datalen
 	custom_pack data glUtilsPackPointerData((unsigned char *)ptr, (unsigned char *)data, size, type, stride, datalen)
 	flag custom_decoder
+	flag not_api
 
 #void glColorPointerData(GLint size, GLenum type, GLsizei stride, void *data, GLuint datalen)
 glColorPointerData
 	len data datalen
 	flag custom_decoder
 	custom_pack data glUtilsPackPointerData((unsigned char *)ptr, (unsigned char *)data, size, type, stride, datalen)
+	flag not_api
 
 #void glNormalPointerData(GLenum type, GLsizei stride, void *data, GLuint datalen)
 glNormalPointerData
 	len data datalen
 	flag custom_decoder
 	custom_pack data glUtilsPackPointerData((unsigned char *)ptr, (unsigned char *)data, 3, type, stride, datalen)
+	flag not_api
 
 #void glPointSizePointerData(GLenum type, GLsizei stride, void *data, GLuint datalen)
 glPointSizePointerData
 	len data datalen
 	flag custom_decoder
 	custom_pack data glUtilsPackPointerData((unsigned char *)ptr, (unsigned char *)data, 1, type, stride, datalen)
+	flag not_api
 
 #void glTexCoordPointerData(GLint size, GLenum type, GLsizei stride, void *data, GLuint datalen)
 glTexCoordPointerData
 	len data datalen
 	flag custom_decoder
 	custom_pack data glUtilsPackPointerData((unsigned char *)ptr, (unsigned char *)data, size, type, stride, datalen)
+	flag not_api
 
 #void glWeightPointerData(GLint size, GLenum type, GLsizei stride,  void * data, GLuint datalen)
 glWeightPointerData
-  len data datalen
-  custom_pack data glUtilsPackPointerData((unsigned char *)ptr, (unsigned char*)data, size, type, stride, datalen)
-  flag custom_decoder
+  	len data datalen
+  	custom_pack data glUtilsPackPointerData((unsigned char *)ptr, (unsigned char*)data, size, type, stride, datalen)
+  	flag custom_decoder
+	flag not_api
 
 #void glMatrixIndexPointerData(GLint size, GLenum type, GLsizei stride,  void * data, GLuint datalen)
 glMatrixIndexPointerData
-  len data datalen
-  custom_pack data glUtilsPackPointerData((unsigned char *)ptr, (unsigned char*)data, size, type, stride, datalen)
-  flag custom_decoder
+	len data datalen
+  	custom_pack data glUtilsPackPointerData((unsigned char *)ptr, (unsigned char*)data, size, type, stride, datalen)
+  	flag custom_decoder
+	flag not_api
 
 glVertexPointerOffset
 	flag custom_decoder
+	flag not_api
 glNormalPointerOffset
 	flag custom_decoder
+	flag not_api
 glTexCoordPointerOffset
 	flag custom_decoder
+	flag not_api
 glPointSizePointerOffset
 	flag custom_decoder
+	flag not_api
 glColorPointerOffset
 	flag custom_decoder
+	flag not_api
 glWeightPointerOffset
-  flag custom_decoder
+    flag custom_decoder
+	flag not_api
 glMatrixIndexPointerOffset
-  flag custom_decoder
+    flag custom_decoder
+	flag not_api
 
 glDrawElementsData
 	len data datalen
 	flag custom_decoder
+	flag not_api
 
 glDrawElementsOffset
 	flag custom_decoder
+	flag not_api
 
 glGetCompressedTextureFormats
 	dir formats out
 	len formats (count * sizeof(GLint))
 	flag custom_decoder
+	flag not_api
 
+glFinishRoundTrip
+	flag custom_decoder
+	flag not_api
 
 #gles1 extensions
 
@@ -513,32 +533,26 @@
 
 #void glTexGenfvOES(GLenum coord, GLenum pname, GLfloat *params)
 glTexGenfvOES
-	dir params out
 	len params (glUtilsParamSize(pname) * sizeof(GLfloat))
 
 #void glTexGenivOES(GLenum coord, GLenum pname, GLint *params)
 glTexGenivOES
-	dir params out
 	len params (glUtilsParamSize(pname) * sizeof(GLint))
 
 #void glTexGenxvOES(GLenum coord, GLenum pname, GLfixed *params)
 glTexGenxvOES
-	dir params out
 	len params (glUtilsParamSize(pname) * sizeof(GLfixed))
 
 #void glGetTexGenfvOES(GLenum coord, GLenum pname, GLfloat *params)
 glGetTexGenfvOES
-	dir params out
 	len params (glUtilsParamSize(pname) * sizeof(GLfloat))
 
 #void glGetTexGenivOES(GLenum coord, GLenum pname, GLint *params)
 glGetTexGenivOES
-	dir params out
 	len params (glUtilsParamSize(pname) * sizeof(GLint))
 
 #void glGetTexGenxvOES(GLenum coord, GLenum pname, GLfixed *params)
 glGetTexGenxvOES
-	dir params out
 	len params (glUtilsParamSize(pname) * sizeof(GLfixed))
 
 #void glDeleteVertexArraysOES(GLsizei n, const GLuint *arrays)
@@ -660,4 +674,3 @@
 #void glExtGetProgramBinarySourceQCOM(GLuint program, GLenum shadertype, GLchar *source, GLint *length)
 glExtGetProgramBinarySourceQCOM
 	flag unsupported
-
diff --git a/tools/emulator/opengl/system/GLESv1_enc/gl.in b/tools/emulator/opengl/system/GLESv1_enc/gl.in
index 0b0e2d2..4340608 100644
--- a/tools/emulator/opengl/system/GLESv1_enc/gl.in
+++ b/tools/emulator/opengl/system/GLESv1_enc/gl.in
@@ -68,7 +68,7 @@
 GL_ENTRY(void, glDrawElements, GLenum mode, GLsizei count, GLenum type, const GLvoid *indices)
 GL_ENTRY(void, glEnable, GLenum cap)
 GL_ENTRY(void, glEnableClientState, GLenum array)
-GL_ENTRY(GLint, glFinish, void)
+GL_ENTRY(void, glFinish, void)
 GL_ENTRY(void, glFlush, void)
 GL_ENTRY(void, glFogx, GLenum pname, GLfixed param)
 GL_ENTRY(void, glFogxv, GLenum pname, const GLfixed *params)
@@ -76,7 +76,7 @@
 GL_ENTRY(void, glFrustumx, GLfixed left, GLfixed right, GLfixed bottom, GLfixed top, GLfixed zNear, GLfixed zFar)
 GL_ENTRY(void, glGetBooleanv, GLenum pname, GLboolean *params)
 GL_ENTRY(void, glGetBufferParameteriv, GLenum target, GLenum pname, GLint *params)
-GL_ENTRY(void, glClipPlanex, GLenum pname, GLfixed * eqn)
+GL_ENTRY(void, glClipPlanex, GLenum pname, const GLfixed * eqn)
 GL_ENTRY(void, glGenBuffers, GLsizei n, GLuint *buffers)
 GL_ENTRY(void, glGenTextures, GLsizei n, GLuint *textures)
 GL_ENTRY(GLenum, glGetError, void)
@@ -163,7 +163,7 @@
 GL_ENTRY(void, glDrawElementsData, GLenum mode, GLsizei count, GLenum type, void *data, GLuint datalen)
 GL_ENTRY(void, glGetCompressedTextureFormats, int count, GLint *formats);
 
-
+GL_ENTRY(int, glFinishRoundTrip, void)
 
 #opengl extensions
 
@@ -248,7 +248,7 @@
 GL_ENTRY(void, glFrustumfOES, GLfloat left, GLfloat right, GLfloat bottom, GLfloat top, GLfloat zNear, GLfloat zFar)
 GL_ENTRY(void, glOrthofOES, GLfloat left, GLfloat right, GLfloat bottom, GLfloat top, GLfloat zNear, GLfloat zFar)
 GL_ENTRY(void, glClipPlanefOES, GLenum plane, const GLfloat *equation)
-GL_ENTRY(void, glClipPlanefIMG, GLenum plane, GLfloat *equation)
+GL_ENTRY(void, glClipPlanefIMG, GLenum plane, const GLfloat *equation)
 GL_ENTRY(void, glGetClipPlanefOES, GLenum pname, GLfloat * eqn)
 GL_ENTRY(void, glClearDepthfOES, GLclampf depth)
 GL_ENTRY(void, glTexGenfOES, GLenum coord, GLenum pname, GLfloat param)
diff --git a/tools/emulator/opengl/system/GLESv2_enc/Android.mk b/tools/emulator/opengl/system/GLESv2_enc/Android.mk
index bc9eef4..2a4d2f4 100644
--- a/tools/emulator/opengl/system/GLESv2_enc/Android.mk
+++ b/tools/emulator/opengl/system/GLESv2_enc/Android.mk
@@ -1,49 +1,18 @@
 LOCAL_PATH := $(call my-dir)
-emulatorOpengl := $(LOCAL_PATH)/../..
 
 ### GLESv2_enc Encoder ###########################################
-include $(CLEAR_VARS)
-
+$(call emugl-begin-shared-library,libGLESv2_enc)
 
 LOCAL_SRC_FILES := \
-	GL2EncoderUtils.cpp \
-        GL2Encoder.cpp 
+    GL2EncoderUtils.cpp \
+    GL2Encoder.cpp
 
+LOCAL_CFLAGS += -DLOG_TAG=\"emuglGLESv2_enc\"
 
-LOCAL_MODULE_TAGS := debug
-LOCAL_MODULE := libGLESv2_enc
-LOCAL_MODULE_CLASS := SHARED_LIBRARIES
+$(call emugl-gen-encoder,$(LOCAL_PATH),gl2)
+$(call emugl-export,C_INCLUDES,$(LOCAL_PATH))
+$(call emugl-import,libOpenglCodecCommon)
 
-glesv2_intermediates := $(local-intermediates-dir)
-
-LOCAL_PRELINK_MODULE := false
-LOCAL_CFLAGS += -DLOG_TAG=\"egl_GLESv2_enc\"
-LOCAL_C_INCLUDES +=  \
-    $(emulatorOpengl)/shared/OpenglCodecCommon \
-    $(emulatorOpengl)/host/include/libOpenglRender \
-    $(glesv2_intermediates)
-
-LOCAL_STATIC_LIBRARIES := \
-        libOpenglCodecCommon
-LOCAL_SHARED_LIBRARIES := libcutils
-
-EMUGEN := $(HOST_OUT_EXECUTABLES)/emugen
-
-GEN_GL2 := \
-	$(glesv2_intermediates)/gl2_entry.cpp \
-	$(glesv2_intermediates)/gl2_enc.cpp \
-	$(glesv2_intermediates)/gl2_enc.h
-
-$(GEN_GL2) : PRIVATE_PATH := $(LOCAL_PATH)
-$(GEN_GL2) : PRIVATE_CUSTOM_TOOL := \
-        $(EMUGEN) -E $(glesv2_intermediates) -i $(PRIVATE_PATH) gl2
-$(GEN_GL2) : $(EMUGEN) \
-        $(LOCAL_PATH)/gl2.attrib \
-        $(LOCAL_PATH)/gl2.in \
-        $(LOCAL_PATH)/gl2.types
-	$(transform-generated-source)
-
-LOCAL_GENERATED_SOURCES += $(GEN_GL2)
-include $(BUILD_SHARED_LIBRARY)
+$(call emugl-end-module)
 
 
diff --git a/tools/emulator/opengl/system/GLESv2_enc/GL2Encoder.cpp b/tools/emulator/opengl/system/GLESv2_enc/GL2Encoder.cpp
index 8c982ce..bdb9a42 100644
--- a/tools/emulator/opengl/system/GLESv2_enc/GL2Encoder.cpp
+++ b/tools/emulator/opengl/system/GLESv2_enc/GL2Encoder.cpp
@@ -26,6 +26,7 @@
     m_glGetVertexAttribfv_enc = set_glGetVertexAttribfv(s_glGetVertexAttribfv);
     m_glGetVertexAttribPointerv = set_glGetVertexAttribPointerv(s_glGetVertexAttribPointerv);
     set_glShaderSource(s_glShaderSource);
+    set_glFinish(s_glFinish);
 }
 
 GL2Encoder::~GL2Encoder()
@@ -40,7 +41,7 @@
     ctx->m_stream->flush();
 }
 
-GLubyte *GL2Encoder::s_glGetString(void *self, GLenum name)
+const GLubyte *GL2Encoder::s_glGetString(void *self, GLenum name)
 {
     GLubyte *retval =  (GLubyte *) "";
     switch(name) {
@@ -78,7 +79,7 @@
     ctx->m_glBindBuffer_enc(self, target, id);
 }
 
-void GL2Encoder::s_glVertexAtrribPointer(void *self, GLuint indx, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLvoid * ptr)
+void GL2Encoder::s_glVertexAtrribPointer(void *self, GLuint indx, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid * ptr)
 {
     GL2Encoder *ctx = (GL2Encoder *)self;
     assert(ctx->m_state != NULL);
@@ -232,7 +233,7 @@
 }
 
 
-void GL2Encoder::s_glDrawElements(void *self, GLenum mode, GLsizei count, GLenum type, void *indices)
+void GL2Encoder::s_glDrawElements(void *self, GLenum mode, GLsizei count, GLenum type, const void *indices)
 {
 
     GL2Encoder *ctx = (GL2Encoder *)self;
@@ -266,7 +267,7 @@
             LOGE("glDrawElements: indirect index arrays, with immidate-mode data array is not supported\n");
         }
     } else {
-        void *adjustedIndices = indices;
+        void *adjustedIndices = (void*)indices;
         int minIndex = 0, maxIndex = 0;
 
         switch(type) {
@@ -324,14 +325,21 @@
     return m_compressedTextureFormats;
 }
 
-void GL2Encoder::s_glShaderSource(void *self, GLuint shader, GLsizei count, GLstr *string, GLint *length)
+void GL2Encoder::s_glShaderSource(void *self, GLuint shader, GLsizei count, const GLstr *string, const GLint *length)
 {
 
-    int len = glUtilsCalcShaderSourceLen(string, length, count);
+    int len = glUtilsCalcShaderSourceLen((char**)string, (GLint*)length, count);
     char *str = new char[len + 1];
-    glUtilsPackStrings(str, string, length, count);
+    glUtilsPackStrings(str, (char**)string, (GLint*)length, count);
 
     GL2Encoder *ctx = (GL2Encoder *)self;
     ctx->glShaderString(ctx, shader, str, len + 1);
     delete str;
 }
+
+void GL2Encoder::s_glFinish(void *self)
+{
+    GL2Encoder *ctx = (GL2Encoder *)self;
+    ctx->glFinishRoundTrip(self);
+}
+
diff --git a/tools/emulator/opengl/system/GLESv2_enc/GL2Encoder.h b/tools/emulator/opengl/system/GLESv2_enc/GL2Encoder.h
index f628aca..59a9100 100644
--- a/tools/emulator/opengl/system/GLESv2_enc/GL2Encoder.h
+++ b/tools/emulator/opengl/system/GLESv2_enc/GL2Encoder.h
@@ -51,7 +51,7 @@
     static void s_glPixelStorei(void *self, GLenum param, GLint value);
 
     glGetString_client_proc_t m_glGetString_enc;
-    static GLubyte * s_glGetString(void *self, GLenum name);
+    static const GLubyte * s_glGetString(void *self, GLenum name);
 
     glBindBuffer_client_proc_t m_glBindBuffer_enc;
     static void s_glBindBuffer(void *self, GLenum target, GLuint id);
@@ -60,7 +60,7 @@
     static void s_glDrawArrays(void *self, GLenum mode, GLint first, GLsizei count);
 
     glDrawElements_client_proc_t m_glDrawElements_enc;
-    static void s_glDrawElements(void *self, GLenum mode, GLsizei count, GLenum type, void *indices);
+    static void s_glDrawElements(void *self, GLenum mode, GLsizei count, GLenum type, const void *indices);
 
 
     glGetIntegerv_client_proc_t m_glGetIntegerv_enc;
@@ -74,7 +74,7 @@
 
     glVertexAttribPointer_client_proc_t m_glVertexAttribPointer_enc;
     static void s_glVertexAtrribPointer(void *self, GLuint indx, GLint size, GLenum type,
-                                        GLboolean normalized, GLsizei stride, GLvoid * ptr);
+                                        GLboolean normalized, GLsizei stride, const GLvoid * ptr);
 
     glEnableVertexAttribArray_client_proc_t m_glEnableVertexAttribArray_enc;
     static void s_glEnableVertexAttribArray(void *self, GLuint index);
@@ -91,6 +91,8 @@
     glGetVertexAttribPointerv_client_proc_t m_glGetVertexAttribPointerv;
     static void s_glGetVertexAttribPointerv(void *self, GLuint index, GLenum pname, GLvoid **pointer);
 
-    static void s_glShaderSource(void *self, GLuint shader, GLsizei count, GLstr *string, GLint *length);
+    static void s_glShaderSource(void *self, GLuint shader, GLsizei count, const GLstr *string, const GLint *length);
+
+    static void s_glFinish(void *self);
 };
 #endif
diff --git a/tools/emulator/opengl/system/GLESv2_enc/gl2.attrib b/tools/emulator/opengl/system/GLESv2_enc/gl2.attrib
index fca7d61..c724405 100644
--- a/tools/emulator/opengl/system/GLESv2_enc/gl2.attrib
+++ b/tools/emulator/opengl/system/GLESv2_enc/gl2.attrib
@@ -547,3 +547,8 @@
 glShaderString
 	len string len
 	flag custom_decoder
+	
+glFinishRoundTrip
+	flag custom_decoder
+	flag not_api
+
diff --git a/tools/emulator/opengl/system/GLESv2_enc/gl2.in b/tools/emulator/opengl/system/GLESv2_enc/gl2.in
index ad23663..14b9d19 100644
--- a/tools/emulator/opengl/system/GLESv2_enc/gl2.in
+++ b/tools/emulator/opengl/system/GLESv2_enc/gl2.in
@@ -42,8 +42,7 @@
 GL_ENTRY(void, glDrawElements, GLenum mode, GLsizei count, GLenum type, const GLvoid* indices)
 GL_ENTRY(void, glEnable, GLenum cap)
 GL_ENTRY(void, glEnableVertexAttribArray, GLuint index)
-# divert from the Opengl definition. Make glFinish retrun a value to ensure round trip.
-GL_ENTRY(GLint, glFinish, void)
+GL_ENTRY(void, glFinish, void)
 GL_ENTRY(void, glFlush, void)
 GL_ENTRY(void, glFramebufferRenderbuffer, GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer)
 GL_ENTRY(void, glFramebufferTexture2D, GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level)
@@ -212,5 +211,4 @@
 GL_ENTRY(void, glDrawElementsData, GLenum mode, GLsizei count, GLenum type, void *data, GLuint datalen)
 GL_ENTRY(void, glGetCompressedTextureFormats, int count, GLint *formats)
 GL_ENTRY(void, glShaderString, GLuint shader, GLstr string, GLsizei len)
-
-
+GL_ENTRY(int, glFinishRoundTrip, void)
diff --git a/tools/emulator/opengl/system/OpenglSystemCommon/Android.mk b/tools/emulator/opengl/system/OpenglSystemCommon/Android.mk
index 760bb72..f1635ad 100644
--- a/tools/emulator/opengl/system/OpenglSystemCommon/Android.mk
+++ b/tools/emulator/opengl/system/OpenglSystemCommon/Android.mk
@@ -1,29 +1,15 @@
 LOCAL_PATH := $(call my-dir)
-emulatorOpengl := $(LOCAL_PATH)/../..
 
-### OpenglSystemCommon ##############################################
-include $(CLEAR_VARS)
-
-# add additional depencies to ensure that the generated code that we depend on
-# is generated
-LOCAL_ADDITIONAL_DEPENDENCIES := \
-	$(TARGET_OUT_SHARED_LIBRARIES)/lib_renderControl_enc$(TARGET_SHLIB_SUFFIX) \
-	$(TARGET_OUT_SHARED_LIBRARIES)/libGLESv1_enc$(TARGET_SHLIB_SUFFIX)
+$(call emugl-begin-shared-library,libOpenglSystemCommon)
+$(call emugl-import,libGLESv1_enc lib_renderControl_enc)
 
 LOCAL_SRC_FILES := \
-        HostConnection.cpp \
-        QemuPipeStream.cpp \
-        ThreadInfo.cpp
+    HostConnection.cpp \
+    QemuPipeStream.cpp \
+    ThreadInfo.cpp
 
-LOCAL_C_INCLUDES += \
-        $(emulatorOpengl)/host/include/libOpenglRender \
-        $(emulatorOpengl)/shared/OpenglCodecCommon \
-        $(emulatorOpengl)/system/GLESv1_enc \
-        $(emulatorOpengl)/system/renderControl_enc \
-		$(call intermediates-dir-for, SHARED_LIBRARIES, lib_renderControl_enc) \
-		$(call intermediates-dir-for, SHARED_LIBRARIES, libGLESv1_enc)
+$(call emugl-export,C_INCLUDES,$(LOCAL_PATH))
 
-LOCAL_MODULE_TAGS := debug
-LOCAL_MODULE := libOpenglSystemCommon
+LOCAL_STATIC_LIBRARIES += libqemu
 
-include $(BUILD_STATIC_LIBRARY)
+$(call emugl-end-module)
diff --git a/tools/emulator/opengl/system/OpenglSystemCommon/EGLClientIface.h b/tools/emulator/opengl/system/OpenglSystemCommon/EGLClientIface.h
index df66ba6..1089340 100644
--- a/tools/emulator/opengl/system/OpenglSystemCommon/EGLClientIface.h
+++ b/tools/emulator/opengl/system/OpenglSystemCommon/EGLClientIface.h
@@ -5,10 +5,12 @@
 
 typedef struct {
     EGLThreadInfo* (*getThreadInfo)();
+    const char* (*getGLString)(int glEnum);
 } EGLClient_eglInterface;
 
 typedef struct {
     void* (*getProcAddress)(const char *funcName);
+    void (*init)();
     void (*finish)();
 } EGLClient_glesInterface;
 
diff --git a/tools/emulator/opengl/system/OpenglSystemCommon/HostConnection.cpp b/tools/emulator/opengl/system/OpenglSystemCommon/HostConnection.cpp
index bfb43f9..1745554 100644
--- a/tools/emulator/opengl/system/OpenglSystemCommon/HostConnection.cpp
+++ b/tools/emulator/opengl/system/OpenglSystemCommon/HostConnection.cpp
@@ -20,7 +20,7 @@
 #include <cutils/log.h>
 
 #define STREAM_BUFFER_SIZE  4*1024*1024
-#define STREAM_PORT_NUM     4141
+#define STREAM_PORT_NUM     22468
 
 /* Set to 1 to use a QEMU pipe, or 0 for a TCP connection */
 #define  USE_QEMU_PIPE  1
@@ -56,6 +56,22 @@
             return NULL;
         }
 
+#if 0
+            TcpStream *stream = new TcpStream(STREAM_BUFFER_SIZE);
+            if (stream) {
+                if (stream->connect("10.0.2.2", STREAM_PORT_NUM) < 0) {
+                    LOGE("Failed to connect to host (TcpStream)!!!\n");
+                    delete stream;
+                    stream = NULL;
+                }
+                else {
+                    con->m_stream = stream;
+                    LOGE("Established TCP connection with HOST\n");
+                }
+            }
+            if (!stream)
+#endif
+
         if (useQemuPipe) {
             QemuPipeStream *stream = new QemuPipeStream(STREAM_BUFFER_SIZE);
             if (!stream) {
@@ -64,7 +80,7 @@
                 return NULL;
             }
             if (stream->connect() < 0) {
-                LOGE("Failed to connect to host !!!\n");
+                LOGE("Failed to connect to host (QemuPipeStream)!!!\n");
                 delete con;
                 return NULL;
             }
@@ -80,13 +96,13 @@
             }
 
             if (stream->connect("10.0.2.2", STREAM_PORT_NUM) < 0) {
-                LOGE("Failed to connect to host !!!\n");
+                LOGE("Failed to connect to host (TcpStream)!!!\n");
                 delete con;
                 return NULL;
             }
             con->m_stream = stream;
         }
-        LOGD("Host Connection established \n");
+        LOGD("HostConnection::get() New Host Connection established %p, tid %d\n", con, gettid());
         tinfo->hostConn = con;
     }
 
@@ -97,6 +113,7 @@
 {
     if (!m_glEnc) {
         m_glEnc = new GLEncoder(m_stream);
+        DBG("HostConnection::glEncoder new encoder %p, tid %d", m_glEnc, gettid());
         m_glEnc->setContextAccessor(s_getGLContext);
     }
     return m_glEnc;
diff --git a/tools/emulator/opengl/system/OpenglSystemCommon/QemuPipeStream.cpp b/tools/emulator/opengl/system/OpenglSystemCommon/QemuPipeStream.cpp
index 1a339ba..3f92724 100644
--- a/tools/emulator/opengl/system/OpenglSystemCommon/QemuPipeStream.cpp
+++ b/tools/emulator/opengl/system/OpenglSystemCommon/QemuPipeStream.cpp
@@ -84,6 +84,7 @@
 
 int QemuPipeStream::writeFully(const void *buf, size_t len)
 {
+    //DBG(">> QemuPipeStream::writeFully %d\n", len);
     if (!valid()) return -1;
 
     size_t res = len;
@@ -107,11 +108,13 @@
         ERR("QemuPipeStream::writeFully failed: %s\n", strerror(errno));
         break;
     }
+    //DBG("<< QemuPipeStream::writeFully %d\n", len );
     return retval;
 }
 
 const unsigned char *QemuPipeStream::readFully(void *buf, size_t len)
 {
+    //DBG(">> QemuPipeStream::readFully %d\n", len);
     if (!valid()) return NULL;
     if (!buf) {
         ERR("QemuPipeStream::readFully failed, buf=NULL");
@@ -135,11 +138,13 @@
             res -= stat;
         }
     }
+    //DBG("<< QemuPipeStream::readFully %d\n", len);
     return (const unsigned char *)buf;
 }
 
 const unsigned char *QemuPipeStream::read( void *buf, size_t *inout_len)
 {
+    //DBG(">> QemuPipeStream::read %d\n", *inout_len);
     if (!valid()) return NULL;
     if (!buf) {
       ERR("QemuPipeStream::read failed, buf=NULL");
@@ -153,6 +158,7 @@
         return (const unsigned char *)buf;
     }
 
+    //DBG("<< QemuPipeStream::read %d\n", *inout_len);
     return NULL;
 }
 
diff --git a/tools/emulator/opengl/system/OpenglSystemCommon/gralloc_cb.h b/tools/emulator/opengl/system/OpenglSystemCommon/gralloc_cb.h
index 3bfabc8..117378d 100644
--- a/tools/emulator/opengl/system/OpenglSystemCommon/gralloc_cb.h
+++ b/tools/emulator/opengl/system/OpenglSystemCommon/gralloc_cb.h
@@ -6,7 +6,7 @@
 #include <cutils/native_handle.h>
 
 #define BUFFER_HANDLE_MAGIC ((int)0xabfabfab)
-#define CB_HANDLE_NUM_INTS(nfds) ((sizeof(cb_handle_t) - (nfds)*sizeof(int)) / sizeof(int))
+#define CB_HANDLE_NUM_INTS(nfds) (int)((sizeof(cb_handle_t) - (nfds)*sizeof(int)) / sizeof(int))
 
 //
 // Our buffer handle structure
@@ -14,13 +14,15 @@
 struct cb_handle_t : public native_handle {
 
     cb_handle_t(int p_fd, int p_ashmemSize, int p_usage,
-                int p_width, int p_height, int p_glFormat) :
+                int p_width, int p_height,
+                int p_glFormat, int p_glType) :
         fd(p_fd),
         magic(BUFFER_HANDLE_MAGIC),
         usage(p_usage),
         width(p_width),
         height(p_height),
         glFormat(p_glFormat),
+        glType(p_glType),
         ashmemSize(p_ashmemSize),
         ashmemBase(NULL),
         ashmemBasePid(0),
@@ -32,7 +34,7 @@
         hostHandle(0)
     {
         version = sizeof(native_handle);
-        numFds = 1;
+        numFds = 0;
         numInts = CB_HANDLE_NUM_INTS(numFds);
     }
 
@@ -40,11 +42,21 @@
         magic = 0;
     }
 
+    void setFd(int p_fd) {
+        if (p_fd >= 0) {
+            numFds = 1;
+        }
+        else {
+            numFds = 0;
+        }
+        fd = p_fd;
+        numInts = CB_HANDLE_NUM_INTS(numFds);
+    }
+
     bool validate() const {
         return (version == sizeof(native_handle) &&
                 magic == BUFFER_HANDLE_MAGIC &&
-                numInts == CB_HANDLE_NUM_INTS(1) &&
-                numFds == 1);
+                numInts == CB_HANDLE_NUM_INTS(numFds));
     }
 
     bool canBePosted() {
@@ -60,6 +72,7 @@
     int width;              // buffer width
     int height;             // buffer height
     int glFormat;           // OpenGL format enum used for host h/w color buffer
+    int glType;             // OpenGL type enum used when uploading to host
     int ashmemSize;         // ashmem region size for the buffer (0 unless is HW_FB buffer or
                             //                                    s/w access is needed)
     int ashmemBase;         // CPU address of the mapped ashmem region
diff --git a/tools/emulator/opengl/system/egl/Android.mk b/tools/emulator/opengl/system/egl/Android.mk
index 10a52bc..fb9e4d8 100644
--- a/tools/emulator/opengl/system/egl/Android.mk
+++ b/tools/emulator/opengl/system/egl/Android.mk
@@ -29,13 +29,13 @@
 		$(call intermediates-dir-for, SHARED_LIBRARIES, libGLESv1_enc)
 
 LOCAL_MODULE_TAGS := debug
+LOCAL_MODULE_PATH := $(TARGET_OUT_SHARED_LIBRARIES)/egl
 LOCAL_MODULE := libEGL_emulation
 LOCAL_MODULE_CLASS := SHARED_LIBRARIES
-
+LOCAL_PRELINK_MODULE := false
 
 LOCAL_STATIC_LIBRARIES := \
-    libOpenglSystemCommon \
-    libOpenglCodecCommon \
+    libOpenglCodecCommon  \
 	libqemu
 
 LOCAL_SHARED_LIBRARIES := \
@@ -43,9 +43,29 @@
 	libutils \
 	libdl	\
     libGLESv1_enc \
+    libOpenglSystemCommon \
     lib_renderControl_enc
 
 
 include $(BUILD_SHARED_LIBRARY)
 
+#### egl.cfg ####
+
+# Ensure that this file is only copied to emulator-specific builds.
+# Other builds are device-specific and will provide their own
+# version of this file to point to the appropriate HW EGL libraries.
+#
+ifneq (,$(filter full full_x86 sdk sdk_x86,$(TARGET_PRODUCT)))
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := egl.cfg
+LOCAL_SRC_FILES := $(LOCAL_MODULE)
+
+LOCAL_MODULE_PATH := $(TARGET_OUT)/lib/egl
+LOCAL_MODULE_TAGS := debug
+LOCAL_MODULE_CLASS := ETC
+
+include $(BUILD_PREBUILT)
+endif # TARGET_PRODUCT in 'full sdk full_x86 sdk_x86'
+
 endif # of ifneq (,$(BUILD_EMULATOR_OPENGL_DRIVER))
diff --git a/tools/emulator/opengl/system/egl/egl.cfg b/tools/emulator/opengl/system/egl/egl.cfg
new file mode 100644
index 0000000..9d3f2dc
--- /dev/null
+++ b/tools/emulator/opengl/system/egl/egl.cfg
@@ -0,0 +1 @@
+0 0 emulation
diff --git a/tools/emulator/opengl/system/egl/egl.cpp b/tools/emulator/opengl/system/egl/egl.cpp
index 5427363..d8ef8aa 100644
--- a/tools/emulator/opengl/system/egl/egl.cpp
+++ b/tools/emulator/opengl/system/egl/egl.cpp
@@ -19,19 +19,63 @@
 #include "egl_ftable.h"
 #include <cutils/log.h>
 #include "gralloc_cb.h"
+#include "GLClientState.h"
 
 #include <private/ui/android_natives_priv.h>
 
 template<typename T>
-static T setError(GLint error, T returnValue) {
+static T setErrorFunc(GLint error, T returnValue) {
     getEGLThreadInfo()->eglError = error;
     return returnValue;
 }
 
+const char *  eglStrError(EGLint err)
+{
+    switch (err){
+        case EGL_SUCCESS:           return "EGL_SUCCESS";
+        case EGL_NOT_INITIALIZED:   return "EGL_NOT_INITIALIZED";
+        case EGL_BAD_ACCESS:        return "EGL_BAD_ACCESS";
+        case EGL_BAD_ALLOC:         return "EGL_BAD_ALLOC";
+        case EGL_BAD_ATTRIBUTE:     return "EGL_BAD_ATTRIBUTE";
+        case EGL_BAD_CONFIG:        return "EGL_BAD_CONFIG";
+        case EGL_BAD_CONTEXT:       return "EGL_BAD_CONTEXT";
+        case EGL_BAD_CURRENT_SURFACE: return "EGL_BAD_CURRENT_SURFACE";
+        case EGL_BAD_DISPLAY:       return "EGL_BAD_DISPLAY";
+        case EGL_BAD_MATCH:         return "EGL_BAD_MATCH";
+        case EGL_BAD_NATIVE_PIXMAP: return "EGL_BAD_NATIVE_PIXMAP";
+        case EGL_BAD_NATIVE_WINDOW: return "EGL_BAD_NATIVE_WINDOW";
+        case EGL_BAD_PARAMETER:     return "EGL_BAD_PARAMETER";
+        case EGL_BAD_SURFACE:       return "EGL_BAD_SURFACE";
+        case EGL_CONTEXT_LOST:      return "EGL_CONTEXT_LOST";
+        default: return "UNKNOWN";
+    }
+}
+
+#define LOG_EGL_ERRORS 1
+
+#ifdef LOG_EGL_ERRORS
+
+#define setErrorReturn(error, retVal)     \
+    {                                                \
+        LOGE("tid %d: %s(%d): error 0x%x (%s)", gettid(), __FUNCTION__, __LINE__, error, eglStrError(error));     \
+        return setErrorFunc(error, retVal);            \
+    }
+
+#define RETURN_ERROR(ret,err)           \
+    LOGE("tid %d: %s(%d): error 0x%x (%s)", gettid(), __FUNCTION__, __LINE__, err, eglStrError(err));    \
+    getEGLThreadInfo()->eglError = err;    \
+    return ret;
+
+#else //!LOG_EGL_ERRORS
+
+#define setErrorReturn(error, retVal) return setErrorFunc(error, retVal);
+
 #define RETURN_ERROR(ret,err)           \
     getEGLThreadInfo()->eglError = err; \
     return ret;
 
+#endif //LOG_EGL_ERRORS
+
 #define VALIDATE_CONFIG(cfg,ret) \
     if(((int)cfg<0)||((int)cfg>s_display.getNumConfigs())) { \
         RETURN_ERROR(ret,EGL_BAD_CONFIG); \
@@ -39,15 +83,13 @@
 
 #define VALIDATE_DISPLAY(dpy,ret) \
     if ((dpy) != (EGLDisplay)&s_display) { \
-        getEGLThreadInfo()->eglError = EGL_BAD_DISPLAY; \
-        return ret; \
+        RETURN_ERROR(ret, EGL_BAD_DISPLAY);    \
     }
 
 #define VALIDATE_DISPLAY_INIT(dpy,ret) \
     VALIDATE_DISPLAY(dpy, ret)    \
     if (!s_display.initialized()) {        \
-        getEGLThreadInfo()->eglError = EGL_NOT_INITIALIZED;    \
-        return ret; \
+        RETURN_ERROR(ret, EGL_NOT_INITIALIZED);    \
     }
 
 #define DEFINE_HOST_CONNECTION \
@@ -75,9 +117,9 @@
     if (surface != EGL_NO_SURFACE) {    \
         egl_surface_t* s( static_cast<egl_surface_t*>(surface) );    \
         if (!s->isValid())    \
-            return setError(EGL_BAD_SURFACE, EGL_FALSE);    \
+            setErrorReturn(EGL_BAD_SURFACE, EGL_FALSE);    \
         if (s->dpy != (EGLDisplay)&s_display)    \
-            return setError(EGL_BAD_DISPLAY, EGL_FALSE);    \
+            setErrorReturn(EGL_BAD_DISPLAY, EGL_FALSE);    \
     }
 
 
@@ -91,13 +133,8 @@
         NEVER_CURRENT   =   0x00020000
     };
 
-    EGLContext_t(EGLDisplay dpy, EGLConfig config) : dpy(dpy), config(config),
-        read(EGL_NO_SURFACE), draw(EGL_NO_SURFACE),
-        rcContext(0) {
-            flags = 0;
-            version = 1;
-        };
-    ~EGLContext_t(){};
+    EGLContext_t(EGLDisplay dpy, EGLConfig config);
+    ~EGLContext_t();
     uint32_t            flags;
     EGLDisplay          dpy;
     EGLConfig           config;
@@ -105,8 +142,41 @@
     EGLSurface          draw;
     EGLint                version;
     uint32_t             rcContext;
+    const char*         versionString;
+    const char*         vendorString;
+    const char*         rendererString;
+    const char*         extensionString;
+
+    GLClientState * getClientState(){ return clientState; }
+private:
+    GLClientState    *    clientState;
 };
 
+EGLContext_t::EGLContext_t(EGLDisplay dpy, EGLConfig config) :
+    dpy(dpy),
+    config(config),
+    read(EGL_NO_SURFACE),
+    draw(EGL_NO_SURFACE),
+    rcContext(0),
+    versionString(NULL),
+    vendorString(NULL),
+    rendererString(NULL),
+    extensionString(NULL)
+{
+    flags = 0;
+    version = 1;
+    clientState = new GLClientState();
+};
+
+EGLContext_t::~EGLContext_t()
+{
+    delete clientState;
+    delete [] versionString;
+    delete [] vendorString;
+    delete [] rendererString;
+    delete [] extensionString;
+}
+
 // ----------------------------------------------------------------------------
 //egl_surface_t
 
@@ -117,7 +187,8 @@
     EGLDisplay          dpy;
     EGLConfig           config;
 
-    egl_surface_t(EGLDisplay dpy, EGLConfig config);
+
+    egl_surface_t(EGLDisplay dpy, EGLConfig config, EGLint surfaceType);
     virtual     ~egl_surface_t();
 
     virtual     EGLBoolean         rcCreate() = 0;
@@ -126,22 +197,51 @@
     virtual     EGLBoolean  connect() { return EGL_TRUE; }
     virtual     void        disconnect() {}
     virtual     EGLBoolean     swapBuffers() { return EGL_TRUE; }
+    virtual     EGLint        getSwapBehavior() const;
 
     void         setRcSurface(uint32_t handle){ rcSurface = handle; }
     uint32_t     getRcSurface(){ return rcSurface; }
 
     virtual     EGLBoolean    isValid(){ return valid; }
-    virtual     EGLint      getWidth() const = 0;
-    virtual     EGLint      getHeight() const = 0;
+    EGLint        getSurfaceType(){ return surfaceType; }
+
+    void        setWidth(EGLint w){ width = w; }
+    EGLint      getWidth(){ return width; }
+    void         setHeight(EGLint h){ height = h; }
+    EGLint      getHeight(){ return height; }
+    void        setTextureFormat(EGLint _texFormat){ texFormat = _texFormat; }
+    EGLint        getTextureFormat(){ return texFormat; }
+    void         setTextureTarget(EGLint _texTarget){ texTarget = _texTarget; }
+    EGLint        getTextureTarget(){ return texTarget; }
+
+private:
+    //
+    //Surface attributes
+    //
+    EGLint     width;
+    EGLint     height;
+    EGLint    texFormat;
+    EGLint    texTarget;
 
 protected:
+    EGLint        surfaceType;
     EGLBoolean    valid;
     uint32_t     rcSurface; //handle to surface created via remote control
+
+
 };
 
-egl_surface_t::egl_surface_t(EGLDisplay dpy, EGLConfig config)
-    : dpy(dpy), config(config), valid(EGL_FALSE), rcSurface(0)
+egl_surface_t::egl_surface_t(EGLDisplay dpy, EGLConfig config, EGLint surfaceType)
+    : dpy(dpy), config(config), surfaceType(surfaceType), valid(EGL_FALSE), rcSurface(0)
 {
+    width = 0;
+    height = 0;
+    texFormat = EGL_NO_TEXTURE;
+    texTarget = EGL_NO_TEXTURE;
+}
+
+EGLint egl_surface_t::getSwapBehavior() const {
+        return EGL_BUFFER_PRESERVED;
 }
 
 egl_surface_t::~egl_surface_t()
@@ -154,7 +254,7 @@
 struct egl_window_surface_t : public egl_surface_t {
 
     egl_window_surface_t(
-            EGLDisplay dpy, EGLConfig config,
+            EGLDisplay dpy, EGLConfig config, EGLint surfType,
             ANativeWindow* window);
 
     ~egl_window_surface_t();
@@ -166,30 +266,27 @@
     virtual     void        disconnect();
     virtual     EGLBoolean  swapBuffers();
 
-    virtual     EGLint      getWidth() const    { return width;  }
-    virtual     EGLint      getHeight() const   { return height; }
-
-
 private:
     ANativeWindow*     nativeWindow;
-    int width;
-    int height;
     android_native_buffer_t*   buffer;
 
 };
 
 
 egl_window_surface_t::egl_window_surface_t (
-            EGLDisplay dpy, EGLConfig config,
+            EGLDisplay dpy, EGLConfig config, EGLint surfType,
             ANativeWindow* window)
-    : egl_surface_t(dpy, config),
+    : egl_surface_t(dpy, config, surfType),
     nativeWindow(window),
     buffer(NULL)
 {
     // keep a reference on the window
     nativeWindow->common.incRef(&nativeWindow->common);
-    nativeWindow->query(nativeWindow, NATIVE_WINDOW_WIDTH, &width);
-    nativeWindow->query(nativeWindow, NATIVE_WINDOW_HEIGHT, &height);
+    EGLint w,h;
+    nativeWindow->query(nativeWindow, NATIVE_WINDOW_WIDTH, &w);
+    setWidth(w);
+    nativeWindow->query(nativeWindow, NATIVE_WINDOW_HEIGHT, &h);
+    setHeight(h);
 }
 
 egl_window_surface_t::~egl_window_surface_t() {
@@ -199,7 +296,7 @@
 EGLBoolean egl_window_surface_t::rcCreate()
 {
     DEFINE_AND_VALIDATE_HOST_CONNECTION(EGL_FALSE);
-    uint32_t rcSurface = rcEnc->rcCreateWindowSurface(rcEnc, (uint32_t)config, getWidth(), getHeight());
+    rcSurface = rcEnc->rcCreateWindowSurface(rcEnc, (uint32_t)config, getWidth(), getHeight());
     if (!rcSurface) {
         LOGE("rcCreateWindowSurface returned 0");
         return EGL_FALSE;
@@ -226,7 +323,7 @@
 {
     // dequeue a buffer
     if (nativeWindow->dequeueBuffer(nativeWindow, &buffer) != NO_ERROR) {
-        return setError(EGL_BAD_ALLOC, EGL_FALSE);
+        setErrorReturn(EGL_BAD_ALLOC, EGL_FALSE);
     }
     buffer->common.incRef(&buffer->common);
 
@@ -248,17 +345,19 @@
 EGLBoolean egl_window_surface_t::swapBuffers()
 {
     if (!buffer) {
-        return setError(EGL_BAD_ACCESS, EGL_FALSE);
+        setErrorReturn(EGL_BAD_ACCESS, EGL_FALSE);
     }
 
     DEFINE_AND_VALIDATE_HOST_CONNECTION(EGL_FALSE);
 
+    rcEnc->rcFlushWindowColorBuffer(rcEnc, rcSurface);
+
     //post the back buffer
     nativeWindow->queueBuffer(nativeWindow, buffer);
 
     // dequeue a new buffer
     if (nativeWindow->dequeueBuffer(nativeWindow, &buffer)) {
-        return setError(EGL_BAD_ALLOC, EGL_FALSE);
+        setErrorReturn(EGL_BAD_ALLOC, EGL_FALSE);
     }
 
     rcEnc->rcSetWindowColorBuffer(rcEnc, rcSurface, ((cb_handle_t *)(buffer->handle))->hostHandle);
@@ -271,15 +370,10 @@
 
 struct egl_pbuffer_surface_t : public egl_surface_t {
 
-    int width;
-    int height;
     GLenum    format;
 
-    virtual     EGLint      getWidth() const    { return width;  }
-    virtual     EGLint      getHeight() const   { return height; }
-
     egl_pbuffer_surface_t(
-            EGLDisplay dpy, EGLConfig config,
+            EGLDisplay dpy, EGLConfig config, EGLint surfType,
             int32_t w, int32_t h, GLenum format);
 
     virtual ~egl_pbuffer_surface_t();
@@ -295,11 +389,12 @@
 };
 
 egl_pbuffer_surface_t::egl_pbuffer_surface_t(
-        EGLDisplay dpy, EGLConfig config,
+        EGLDisplay dpy, EGLConfig config, EGLint surfType,
         int32_t w, int32_t h, GLenum pixelFormat)
-    : egl_surface_t(dpy, config),
-    width(w), height(h), format(pixelFormat)
+    : egl_surface_t(dpy, config, surfType), format(pixelFormat)
 {
+    setWidth(w);
+    setHeight(h);
 }
 
 egl_pbuffer_surface_t::~egl_pbuffer_surface_t()
@@ -348,14 +443,79 @@
     return EGL_TRUE;
 }
 
+static const char *getGLString(int glEnum)
+{
+    EGLThreadInfo *tInfo = getEGLThreadInfo();
+    if (!tInfo || !tInfo->currentContext) {
+        return NULL;
+    }
+
+    const char** strPtr = NULL;
+
+#define GL_VENDOR                         0x1F00
+#define GL_RENDERER                       0x1F01
+#define GL_VERSION                        0x1F02
+#define GL_EXTENSIONS                     0x1F03
+
+    switch(glEnum) {
+        case GL_VERSION:
+            strPtr = &tInfo->currentContext->versionString;
+            break;
+        case GL_VENDOR:
+            strPtr = &tInfo->currentContext->vendorString;
+            break;
+        case GL_RENDERER:
+            strPtr = &tInfo->currentContext->rendererString;
+            break;
+        case GL_EXTENSIONS:
+            strPtr = &tInfo->currentContext->extensionString;
+            break;
+    }
+
+    if (!strPtr) {
+        return NULL;
+    }
+
+    if (*strPtr != NULL) {
+        //
+        // string is already cached
+        //
+        return *strPtr;
+    }
+
+    //
+    // first query of that string - need to query host
+    //
+    DEFINE_AND_VALIDATE_HOST_CONNECTION(NULL);
+    char *hostStr = NULL;
+    int n = rcEnc->rcGetGLString(rcEnc, glEnum, NULL, 0);
+    if (n < 0) {
+        hostStr = new char[-n+1];
+        n = rcEnc->rcGetGLString(rcEnc, glEnum, hostStr, -n);
+        if (n <= 0) {
+            delete [] hostStr;
+            hostStr = NULL;
+        }
+    }
+
+    //
+    // keep the string in the context and return its value
+    //
+    *strPtr = hostStr;
+    return hostStr;
+}
+
 // ----------------------------------------------------------------------------
 
 // The one and only supported display object.
 static eglDisplay s_display;
 
 static EGLClient_eglInterface s_eglIface = {
-    getThreadInfo: getEGLThreadInfo
+    getThreadInfo: getEGLThreadInfo,
+    getGLString: getGLString
 };
+
+#define DBG_FUNC DBG("%s\n", __FUNCTION__)
 EGLDisplay eglGetDisplay(EGLNativeDisplayType display_id)
 {
     //
@@ -474,7 +634,7 @@
     }
 
     DEFINE_AND_VALIDATE_HOST_CONNECTION(EGL_FALSE);
-    *num_config = rcEnc->rcChooseConfig(rcEnc, (EGLint*)attrib_list, attribs_size, (uint32_t*)configs, config_size);
+    *num_config = rcEnc->rcChooseConfig(rcEnc, (EGLint*)attrib_list, attribs_size * sizeof(EGLint), (uint32_t*)configs, config_size*sizeof(EGLint));
 
     return EGL_TRUE;
 }
@@ -499,27 +659,27 @@
     VALIDATE_DISPLAY_INIT(dpy, NULL);
     VALIDATE_CONFIG(config, EGL_FALSE);
     if (win == 0) {
-        return setError(EGL_BAD_MATCH, EGL_NO_SURFACE);
+        setErrorReturn(EGL_BAD_MATCH, EGL_NO_SURFACE);
     }
 
     EGLint surfaceType;
     if (s_display.getConfigAttrib(config, EGL_SURFACE_TYPE, &surfaceType) == EGL_FALSE)    return EGL_FALSE;
 
     if (!(surfaceType & EGL_WINDOW_BIT)) {
-        return setError(EGL_BAD_MATCH, EGL_NO_SURFACE);
+        setErrorReturn(EGL_BAD_MATCH, EGL_NO_SURFACE);
     }
 
     if (static_cast<ANativeWindow*>(win)->common.magic != ANDROID_NATIVE_WINDOW_MAGIC) {
-        return setError(EGL_BAD_NATIVE_WINDOW, EGL_NO_SURFACE);
+        setErrorReturn(EGL_BAD_NATIVE_WINDOW, EGL_NO_SURFACE);
     }
 
     egl_surface_t* surface;
-    surface = new egl_window_surface_t(&s_display, config, static_cast<ANativeWindow*>(win));
+    surface = new egl_window_surface_t(&s_display, config, surfaceType, static_cast<ANativeWindow*>(win));
     if (!surface)
-        return setError(EGL_BAD_ALLOC, EGL_NO_SURFACE);
+        setErrorReturn(EGL_BAD_ALLOC, EGL_NO_SURFACE);
     if (!surface->rcCreate()) {
         delete surface;
-        return setError(EGL_BAD_ALLOC, EGL_NO_SURFACE);
+        setErrorReturn(EGL_BAD_ALLOC, EGL_NO_SURFACE);
     }
 
     return surface;
@@ -534,30 +694,54 @@
     if (s_display.getConfigAttrib(config, EGL_SURFACE_TYPE, &surfaceType) == EGL_FALSE)    return EGL_FALSE;
 
     if (!(surfaceType & EGL_PBUFFER_BIT)) {
-        return setError(EGL_BAD_MATCH, EGL_NO_SURFACE);
+        setErrorReturn(EGL_BAD_MATCH, EGL_NO_SURFACE);
     }
 
     int32_t w = 0;
     int32_t h = 0;
+    EGLint texFormat = EGL_NO_TEXTURE;
+    EGLint texTarget = EGL_NO_TEXTURE;
     while (attrib_list[0]) {
-        if (attrib_list[0] == EGL_WIDTH)  w = attrib_list[1];
-        if (attrib_list[0] == EGL_HEIGHT) h = attrib_list[1];
+        switch (attrib_list[0]) {
+            case EGL_WIDTH:
+                w = attrib_list[1];
+                break;
+            case EGL_HEIGHT:
+                h = attrib_list[1];
+                break;
+            case EGL_TEXTURE_FORMAT:
+                texFormat = attrib_list[1];
+                break;
+            case EGL_TEXTURE_TARGET:
+                texTarget = attrib_list[1];
+                break;
+            default:
+                break;
+        };
         attrib_list+=2;
     }
+    if (((texFormat == EGL_NO_TEXTURE)&&(texTarget != EGL_NO_TEXTURE)) ||
+        ((texFormat != EGL_NO_TEXTURE)&&(texTarget == EGL_NO_TEXTURE))) {
+        setErrorReturn(EGL_BAD_MATCH, EGL_NO_SURFACE);
+    }
     // TODO: check EGL_TEXTURE_FORMAT - need to support eglBindTexImage
 
     GLenum pixelFormat;
-    if (s_display.getConfigPixelFormat(config, &pixelFormat) == EGL_FALSE)
-        return setError(EGL_BAD_MATCH, EGL_NO_SURFACE);
+    if (s_display.getConfigGLPixelFormat(config, &pixelFormat) == EGL_FALSE)
+        setErrorReturn(EGL_BAD_MATCH, EGL_NO_SURFACE);
 
-    egl_surface_t* surface = new egl_pbuffer_surface_t(dpy, config, w, h, pixelFormat);
+    egl_surface_t* surface = new egl_pbuffer_surface_t(dpy, config, surfaceType, w, h, pixelFormat);
     if (!surface)
-        return setError(EGL_BAD_ALLOC, EGL_NO_SURFACE);
+        setErrorReturn(EGL_BAD_ALLOC, EGL_NO_SURFACE);
     if (!surface->rcCreate()) {
         delete surface;
-        return setError(EGL_BAD_ALLOC, EGL_NO_SURFACE);
+        setErrorReturn(EGL_BAD_ALLOC, EGL_NO_SURFACE);
     }
 
+    //setup attributes
+    surface->setTextureFormat(texFormat);
+    surface->setTextureTarget(texTarget);
+
     return surface;
 }
 
@@ -602,9 +786,19 @@
         case EGL_HEIGHT:
             *value = surface->getHeight();
             break;
+        case EGL_TEXTURE_FORMAT:
+            *value = surface->getTextureFormat();
+            break;
+        case EGL_TEXTURE_TARGET:
+            *value = surface->getTextureTarget();
+            break;
+        case EGL_SWAP_BEHAVIOR:
+            *value = surface->getSwapBehavior();
+            break;
             //TODO: complete other attributes
         default:
-            ret = setError(EGL_BAD_ATTRIBUTE, EGL_FALSE);
+            LOGE("eglQuerySurface %x  EGL_BAD_ATTRIBUTE", attribute);
+            ret = setErrorFunc(EGL_BAD_ATTRIBUTE, EGL_FALSE);
             break;
     }
 
@@ -614,7 +808,7 @@
 EGLBoolean eglBindAPI(EGLenum api)
 {
     if (api != EGL_OPENGL_ES_API)
-        return setError(EGL_BAD_PARAMETER, EGL_FALSE);
+        setErrorReturn(EGL_BAD_PARAMETER, EGL_FALSE);
     return EGL_TRUE;
 }
 
@@ -651,11 +845,35 @@
     return 0;
 }
 
-EGLBoolean eglBindTexImage(EGLDisplay dpy, EGLSurface surface, EGLint buffer)
+EGLBoolean eglBindTexImage(EGLDisplay dpy, EGLSurface eglSurface, EGLint buffer)
 {
-    //TODO
-    LOGW("%s not implemented", __FUNCTION__);
-    return 0;
+    VALIDATE_DISPLAY_INIT(dpy, EGL_FALSE);
+    VALIDATE_SURFACE_RETURN(eglSurface, EGL_FALSE);
+    if (eglSurface == EGL_NO_SURFACE) {
+        setErrorReturn(EGL_BAD_SURFACE, EGL_FALSE);
+    }
+
+    if (buffer != EGL_BACK_BUFFER) {
+        setErrorReturn(EGL_BAD_PARAMETER, EGL_FALSE);
+    }
+
+    egl_surface_t* surface( static_cast<egl_surface_t*>(eglSurface) );
+
+    if (surface->getTextureFormat() == EGL_NO_TEXTURE) {
+        setErrorReturn(EGL_BAD_MATCH, EGL_FALSE);
+    }
+
+    if (!(surface->getSurfaceType() & EGL_PBUFFER_BIT)) {
+        setErrorReturn(EGL_BAD_SURFACE, EGL_FALSE);
+    }
+
+    //It's now safe to cast to pbuffer surface
+    egl_pbuffer_surface_t* pbSurface = (egl_pbuffer_surface_t*)surface;
+
+    DEFINE_AND_VALIDATE_HOST_CONNECTION(EGL_FALSE);
+    rcEnc->rcBindTexture(rcEnc, pbSurface->getRcColorBuffer());
+
+    return GL_TRUE;
 }
 
 EGLBoolean eglReleaseTexImage(EGLDisplay dpy, EGLSurface surface, EGLint buffer)
@@ -667,9 +885,11 @@
 
 EGLBoolean eglSwapInterval(EGLDisplay dpy, EGLint interval)
 {
-    //TODO
-    LOGW("%s not implemented", __FUNCTION__);
-    return 0;
+    VALIDATE_DISPLAY_INIT(dpy, EGL_FALSE);
+
+    DEFINE_AND_VALIDATE_HOST_CONNECTION(EGL_FALSE);
+    rcEnc->rcFBSetSwapInterval(rcEnc, interval); //TODO: implement on the host
+    return EGL_TRUE;
 }
 
 EGLContext eglCreateContext(EGLDisplay dpy, EGLConfig config, EGLContext share_context, const EGLint *attrib_list)
@@ -678,7 +898,7 @@
     VALIDATE_CONFIG(config, EGL_NO_CONTEXT);
 
     EGLint version = 1; //default
-    while (attrib_list[0]) {
+    while (attrib_list && attrib_list[0]) {
         if (attrib_list[0] == EGL_CONTEXT_CLIENT_VERSION) version = attrib_list[1];
         attrib_list+=2;
     }
@@ -688,19 +908,19 @@
         EGLContext_t * shareCtx = static_cast<EGLContext_t*>(share_context);
         rcShareCtx = shareCtx->rcContext;
         if (shareCtx->dpy != dpy)
-            return setError(EGL_BAD_MATCH, EGL_NO_CONTEXT);
+            setErrorReturn(EGL_BAD_MATCH, EGL_NO_CONTEXT);
     }
 
     DEFINE_AND_VALIDATE_HOST_CONNECTION(EGL_NO_CONTEXT);
     uint32_t rcContext = rcEnc->rcCreateContext(rcEnc, (uint32_t)config, rcShareCtx, version);
     if (!rcContext) {
         LOGE("rcCreateContext returned 0");
-        return setError(EGL_BAD_ALLOC, EGL_NO_CONTEXT);
+        setErrorReturn(EGL_BAD_ALLOC, EGL_NO_CONTEXT);
     }
 
     EGLContext_t * context = new EGLContext_t(dpy, config);
     if (!context)
-        return setError(EGL_BAD_ALLOC, EGL_NO_CONTEXT);
+        setErrorReturn(EGL_BAD_ALLOC, EGL_NO_CONTEXT);
 
     context->version = version;
     context->rcContext = rcContext;
@@ -738,9 +958,9 @@
     VALIDATE_SURFACE_RETURN(read, EGL_FALSE);
 
     if ((read == EGL_NO_SURFACE && draw == EGL_NO_SURFACE) && (ctx != EGL_NO_CONTEXT))
-        return setError(EGL_BAD_MATCH, EGL_FALSE);
+        setErrorReturn(EGL_BAD_MATCH, EGL_FALSE);
     if ((read != EGL_NO_SURFACE || draw != EGL_NO_SURFACE) && (ctx == EGL_NO_CONTEXT))
-        return setError(EGL_BAD_MATCH, EGL_FALSE);
+        setErrorReturn(EGL_BAD_MATCH, EGL_FALSE);
 
     EGLContext_t * context = static_cast<EGLContext_t*>(ctx);
     uint32_t ctxHandle = (context) ? context->rcContext : 0;
@@ -762,13 +982,13 @@
 
     if (context && (context->flags & EGLContext_t::IS_CURRENT) && (context != tInfo->currentContext)) {
         //context is current to another thread
-        return setError(EGL_BAD_ACCESS, EGL_FALSE);
+        setErrorReturn(EGL_BAD_ACCESS, EGL_FALSE);
     }
 
     DEFINE_AND_VALIDATE_HOST_CONNECTION(EGL_FALSE);
     if (rcEnc->rcMakeCurrent(rcEnc, ctxHandle, drawHandle, readHandle) == EGL_FALSE) {
         LOGE("rcMakeCurrent returned EGL_FALSE");
-        return setError(EGL_BAD_CONTEXT, EGL_FALSE);
+        setErrorReturn(EGL_BAD_CONTEXT, EGL_FALSE);
     }
 
     //
@@ -784,6 +1004,8 @@
         context->draw = draw;
         context->read = read;
         context->flags |= EGLContext_t::IS_CURRENT;
+        //set the client state
+        hostCon->glEncoder()->setClientState(context->getClientState());
     }
 
     if (tInfo->currentContext)
@@ -792,6 +1014,18 @@
     //Now make current
     tInfo->currentContext = context;
 
+    //Check maybe we need to init the encoder, if it's first eglMakeCurrent
+    if (tInfo->currentContext) {
+        if (!hostCon->glEncoder()->isInitialized()) {
+            if (tInfo->currentContext->version == 2) {
+                s_display.gles2_iface()->init();
+            }
+            else {
+                s_display.gles_iface()->init();
+            }
+            hostCon->glEncoder()->setInitialized();
+        }
+    }
 
     //connect the color buffer
     if (drawSurf)
@@ -817,7 +1051,7 @@
         case EGL_DRAW:
             return context->draw;
         default:
-            return setError(EGL_BAD_PARAMETER, EGL_NO_SURFACE);
+            setErrorReturn(EGL_BAD_PARAMETER, EGL_NO_SURFACE);
     }
 }
 
@@ -855,7 +1089,9 @@
                 *value = EGL_BACK_BUFFER; //single buffer not supported
             break;
         default:
-            return setError(EGL_BAD_ATTRIBUTE, EGL_FALSE);
+            LOGE("eglQueryContext %x  EGL_BAD_ATTRIBUTE", attribute);
+            setErrorReturn(EGL_BAD_ATTRIBUTE, EGL_FALSE);
+            break;
     }
 
     return ret;
@@ -887,15 +1123,15 @@
 {
     VALIDATE_DISPLAY_INIT(dpy, EGL_FALSE);
     if (eglSurface == EGL_NO_SURFACE)
-        return setError(EGL_BAD_SURFACE, EGL_FALSE);
+        setErrorReturn(EGL_BAD_SURFACE, EGL_FALSE);
 
     DEFINE_AND_VALIDATE_HOST_CONNECTION(EGL_FALSE);
 
     egl_surface_t* d = static_cast<egl_surface_t*>(eglSurface);
     if (!d->isValid())
-        return setError(EGL_BAD_SURFACE, EGL_FALSE);
+        setErrorReturn(EGL_BAD_SURFACE, EGL_FALSE);
     if (d->dpy != dpy)
-        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
+        setErrorReturn(EGL_BAD_DISPLAY, EGL_FALSE);
 
     // post the surface
     d->swapBuffers();
@@ -927,19 +1163,19 @@
     VALIDATE_DISPLAY_INIT(dpy, EGL_NO_IMAGE_KHR);
 
     if (ctx != EGL_NO_CONTEXT) {
-        return setError(EGL_BAD_CONTEXT, EGL_NO_IMAGE_KHR);
+        setErrorReturn(EGL_BAD_CONTEXT, EGL_NO_IMAGE_KHR);
     }
     if (target != EGL_NATIVE_BUFFER_ANDROID) {
-        return setError(EGL_BAD_PARAMETER, EGL_NO_IMAGE_KHR);
+        setErrorReturn(EGL_BAD_PARAMETER, EGL_NO_IMAGE_KHR);
     }
 
     android_native_buffer_t* native_buffer = (android_native_buffer_t*)buffer;
 
     if (native_buffer->common.magic != ANDROID_NATIVE_BUFFER_MAGIC)
-        return setError(EGL_BAD_PARAMETER, EGL_NO_IMAGE_KHR);
+        setErrorReturn(EGL_BAD_PARAMETER, EGL_NO_IMAGE_KHR);
 
     if (native_buffer->common.version != sizeof(android_native_buffer_t))
-        return setError(EGL_BAD_PARAMETER, EGL_NO_IMAGE_KHR);
+        setErrorReturn(EGL_BAD_PARAMETER, EGL_NO_IMAGE_KHR);
 
     switch (native_buffer->format) {
         case HAL_PIXEL_FORMAT_RGBA_8888:
@@ -951,7 +1187,7 @@
         case HAL_PIXEL_FORMAT_RGBA_4444:
             break;
         default:
-            return setError(EGL_BAD_PARAMETER, EGL_NO_IMAGE_KHR);
+            setErrorReturn(EGL_BAD_PARAMETER, EGL_NO_IMAGE_KHR);
     }
 
     native_buffer->common.incRef(&native_buffer->common);
@@ -965,10 +1201,10 @@
     android_native_buffer_t* native_buffer = (android_native_buffer_t*)img;
 
     if (native_buffer->common.magic != ANDROID_NATIVE_BUFFER_MAGIC)
-        return setError(EGL_BAD_PARAMETER, EGL_FALSE);
+        setErrorReturn(EGL_BAD_PARAMETER, EGL_FALSE);
 
     if (native_buffer->common.version != sizeof(android_native_buffer_t))
-        return setError(EGL_BAD_PARAMETER, EGL_FALSE);
+        setErrorReturn(EGL_BAD_PARAMETER, EGL_FALSE);
 
     native_buffer->common.decRef(&native_buffer->common);
 
diff --git a/tools/emulator/opengl/system/egl/eglDisplay.cpp b/tools/emulator/opengl/system/egl/eglDisplay.cpp
index 30974a7..78025b1 100644
--- a/tools/emulator/opengl/system/egl/eglDisplay.cpp
+++ b/tools/emulator/opengl/system/egl/eglDisplay.cpp
@@ -83,6 +83,7 @@
                                          &s_gles_lib);
         if (!m_gles_iface) {
             pthread_mutex_unlock(&m_lock);
+            LOGE("Failed to load gles1 iface");
             return false;
         }
 
@@ -100,6 +101,7 @@
         HostConnection *hcon = HostConnection::get();
         if (!hcon) {
             pthread_mutex_unlock(&m_lock);
+            LOGE("Failed to establish connection with the host\n");
             return false;
         }
 
@@ -109,6 +111,7 @@
         renderControl_encoder_context_t *rcEnc = hcon->rcEncoder();
         if (!rcEnc) {
             pthread_mutex_unlock(&m_lock);
+            LOGE("Failed to get renderControl encoder instance");
             return false;
         }
 
@@ -147,7 +150,7 @@
 
         uint32_t nInts = m_numConfigAttribs * (m_numConfigs + 1);
         EGLint tmp_buf[nInts];
-        m_configs = new EGLint[nInts-1];
+        m_configs = new EGLint[nInts-m_numConfigAttribs];
         if (!m_configs) {
             pthread_mutex_unlock(&m_lock);
             return false;
@@ -162,21 +165,34 @@
 
         //Fill the attributes vector.
         //The first m_numConfigAttribs values of tmp_buf are the actual attributes enums.
-        for (int i=0; i<m_numConfigAttribs; i++)
-        {
+        for (int i=0; i<m_numConfigAttribs; i++) {
             m_attribs.add(tmp_buf[i], i);
         }
 
         //Copy the actual configs data to m_configs
-        memcpy(m_configs, tmp_buf + m_numConfigAttribs, m_numConfigs*sizeof(EGLint));
+        memcpy(m_configs, tmp_buf + m_numConfigAttribs, m_numConfigs*m_numConfigAttribs*sizeof(EGLint));
 
         m_initialized = true;
     }
     pthread_mutex_unlock(&m_lock);
 
+    processConfigs();
+
     return true;
 }
 
+void eglDisplay::processConfigs()
+{
+    for (int i=0; i<m_numConfigs; i++) {
+        EGLConfig config = (EGLConfig)i;
+        //Setup the EGL_NATIVE_VISUAL_ID attribute
+        PixelFormat format;
+        if (getConfigNativePixelFormat(config, &format)) {
+            setConfigAttrib(config, EGL_NATIVE_VISUAL_ID, format);
+        }
+    }
+}
+
 void eglDisplay::terminate()
 {
     pthread_mutex_lock(&m_lock);
@@ -207,12 +223,14 @@
 {
     void *lib = dlopen(libName, RTLD_NOW);
     if (!lib) {
+        LOGE("Failed to dlopen %s", libName);
         return NULL;
     }
 
     init_emul_gles_t init_gles_func = (init_emul_gles_t)dlsym(lib,"init_emul_gles");
     if (!init_gles_func) {
-        dlclose((void*)libName);
+        LOGE("Failed to find init_emul_gles");
+        dlclose((void*)lib);
         return NULL;
     }
 
@@ -390,7 +408,41 @@
     return ret;
 }
 
-EGLBoolean eglDisplay::getConfigPixelFormat(EGLConfig config, GLenum * format)
+void eglDisplay::dumpConfig(EGLConfig config)
+{
+    EGLint value = 0;
+    DBG("^^^^^^^^^^ dumpConfig %d ^^^^^^^^^^^^^^^^^^", (int)config);
+    for (int i=0; i<m_numConfigAttribs; i++) {
+        getAttribValue(config, i, &value);
+        DBG("{%d}[%d] %d\n", (int)config, i, value);
+    }
+}
+
+/* To set the value of attribute <a> of config <c> use the following formula:
+ * *(m_configs + (int)c*m_numConfigAttribs + a) = value;
+ */
+EGLBoolean eglDisplay::setAttribValue(EGLConfig config, EGLint attribIdx, EGLint value)
+{
+    if (attribIdx == ATTRIBUTE_NONE)
+    {
+        LOGE("[%s] Bad attribute idx\n", __FUNCTION__);
+        return EGL_FALSE;
+    }
+    *(m_configs + (int)config*m_numConfigAttribs + attribIdx) = value;
+    return EGL_TRUE;
+}
+
+EGLBoolean eglDisplay::setConfigAttrib(EGLConfig config, EGLint attrib, EGLint value)
+{
+    //Though it seems that valueFor() is thread-safe, we don't take chanses
+    pthread_mutex_lock(&m_lock);
+    EGLBoolean ret = setAttribValue(config, m_attribs.valueFor(attrib), value);
+    pthread_mutex_unlock(&m_lock);
+    return ret;
+}
+
+
+EGLBoolean eglDisplay::getConfigNativePixelFormat(EGLConfig config, PixelFormat * format)
 {
     EGLint redSize, blueSize, greenSize, alphaSize;
 
@@ -404,11 +456,35 @@
     }
 
     //calculate the GL internal format
-    if ((redSize==8)&&(blueSize==8)&&(greenSize==8)&&(alphaSize==8)) *format = GL_RGBA;
-    else if ((redSize==8)&&(blueSize==8)&&(greenSize==8)&&(alphaSize==0)) *format = GL_RGB;
-    else if ((redSize==5)&&(blueSize==6)&&(greenSize==5)&&(alphaSize==0)) *format = GL_RGB565_OES;
-    else if ((redSize==5)&&(blueSize==5)&&(greenSize==5)&&(alphaSize==1)) *format = GL_RGB5_A1_OES;
-    else if ((redSize==4)&&(blueSize==4)&&(greenSize==4)&&(alphaSize==4)) *format = GL_RGBA4_OES;
+    if ((redSize==8)&&(greenSize==8)&&(blueSize==8)&&(alphaSize==8)) *format = PIXEL_FORMAT_RGBA_8888; //XXX: BGR?
+    else if ((redSize==8)&&(greenSize==8)&&(blueSize==8)&&(alphaSize==0)) *format = PIXEL_FORMAT_RGBX_8888; //XXX or PIXEL_FORMAT_RGB_888
+    else if ((redSize==5)&&(greenSize==6)&&(blueSize==5)&&(alphaSize==0)) *format = PIXEL_FORMAT_RGB_565;
+    else if ((redSize==5)&&(greenSize==5)&&(blueSize==5)&&(alphaSize==1)) *format = PIXEL_FORMAT_RGBA_5551;
+    else if ((redSize==4)&&(greenSize==4)&&(blueSize==4)&&(alphaSize==4)) *format = PIXEL_FORMAT_RGBA_4444;
+    else {
+        return EGL_FALSE;
+    }
+    return EGL_TRUE;
+}
+EGLBoolean eglDisplay::getConfigGLPixelFormat(EGLConfig config, GLenum * format)
+{
+    EGLint redSize, blueSize, greenSize, alphaSize;
+
+    if ( !(getAttribValue(config, m_attribs.valueFor(EGL_RED_SIZE), &redSize) &&
+        getAttribValue(config, m_attribs.valueFor(EGL_BLUE_SIZE), &blueSize) &&
+        getAttribValue(config, m_attribs.valueFor(EGL_GREEN_SIZE), &greenSize) &&
+        getAttribValue(config, m_attribs.valueFor(EGL_ALPHA_SIZE), &alphaSize)) )
+    {
+        LOGE("Couldn't find value for one of the pixel format attributes");
+        return EGL_FALSE;
+    }
+
+    //calculate the GL internal format
+    if ((redSize==8)&&(blueSize==8)&&(blueSize==8)&&(alphaSize==8)) *format = GL_RGBA;
+    else if ((redSize==8)&&(greenSize==8)&&(blueSize==8)&&(alphaSize==0)) *format = GL_RGB;
+    else if ((redSize==5)&&(greenSize==6)&&(blueSize==5)&&(alphaSize==0)) *format = GL_RGB565_OES;
+    else if ((redSize==5)&&(greenSize==5)&&(blueSize==5)&&(alphaSize==1)) *format = GL_RGB5_A1_OES;
+    else if ((redSize==4)&&(greenSize==4)&&(blueSize==4)&&(alphaSize==4)) *format = GL_RGBA4_OES;
     else return EGL_FALSE;
 
     return EGL_TRUE;
diff --git a/tools/emulator/opengl/system/egl/eglDisplay.h b/tools/emulator/opengl/system/egl/eglDisplay.h
index 6f36854..934c699 100644
--- a/tools/emulator/opengl/system/egl/eglDisplay.h
+++ b/tools/emulator/opengl/system/egl/eglDisplay.h
@@ -23,6 +23,8 @@
 #include "EGLClientIface.h"
 #include <utils/KeyedVector.h>
 
+#include <ui/PixelFormat.h>
+
 #define ATTRIBUTE_NONE -1
 //FIXME: are we in this namespace?
 using namespace android;
@@ -46,13 +48,18 @@
 
     int     getNumConfigs(){ return m_numConfigs; }
     EGLBoolean  getConfigAttrib(EGLConfig config, EGLint attrib, EGLint * value);
-    EGLBoolean getConfigPixelFormat(EGLConfig config, GLenum * format);
+    EGLBoolean  setConfigAttrib(EGLConfig config, EGLint attrib, EGLint value);
+    EGLBoolean getConfigGLPixelFormat(EGLConfig config, GLenum * format);
+    EGLBoolean getConfigNativePixelFormat(EGLConfig config, PixelFormat * format);
 
+    void     dumpConfig(EGLConfig config);
 private:
     EGLClient_glesInterface *loadGLESClientAPI(const char *libName,
                                                EGLClient_eglInterface *eglIface,
                                                void **libHandle);
     EGLBoolean getAttribValue(EGLConfig config, EGLint attribIdxi, EGLint * value);
+    EGLBoolean setAttribValue(EGLConfig config, EGLint attribIdxi, EGLint value);
+    void     processConfigs();
 
 private:
     pthread_mutex_t m_lock;
diff --git a/tools/emulator/opengl/system/gralloc/Android.mk b/tools/emulator/opengl/system/gralloc/Android.mk
index 7a7c340..9340185 100644
--- a/tools/emulator/opengl/system/gralloc/Android.mk
+++ b/tools/emulator/opengl/system/gralloc/Android.mk
@@ -31,12 +31,12 @@
 LOCAL_MODULE := gralloc.goldfish
 
 LOCAL_STATIC_LIBRARIES := \
-    libOpenglSystemCommon \
     libOpenglCodecCommon \
     libqemu
 
 LOCAL_SHARED_LIBRARIES := \
     libcutils \
+    libOpenglSystemCommon \
     libGLESv1_enc \
     lib_renderControl_enc
 
diff --git a/tools/emulator/opengl/system/gralloc/gralloc.cpp b/tools/emulator/opengl/system/gralloc/gralloc.cpp
index abc01a0..774d7b6 100644
--- a/tools/emulator/opengl/system/gralloc/gralloc.cpp
+++ b/tools/emulator/opengl/system/gralloc/gralloc.cpp
@@ -29,6 +29,7 @@
 #include <cutils/log.h>
 
 
+#define DBG_FUNC DBG("%s\n", __FUNCTION__)
 //
 // our private gralloc module structure
 //
@@ -120,6 +121,7 @@
     int ashmem_size = 0;
     *pStride = 0;
     GLenum glFormat = 0;
+    GLenum glType = 0;
 
     int bpp = 0;
     switch (format) {
@@ -128,22 +130,27 @@
         case HAL_PIXEL_FORMAT_BGRA_8888:
             bpp = 4;
             glFormat = GL_RGBA;
+            glType = GL_UNSIGNED_BYTE;
             break;
         case HAL_PIXEL_FORMAT_RGB_888:
             bpp = 3;
             glFormat = GL_RGB;
+            glType = GL_UNSIGNED_BYTE;
             break;
         case HAL_PIXEL_FORMAT_RGB_565:
             bpp = 2;
             glFormat = GL_RGB565_OES;
+            glType = GL_UNSIGNED_SHORT_5_6_5;
             break;
         case HAL_PIXEL_FORMAT_RGBA_5551:
             bpp = 2;
             glFormat = GL_RGB5_A1_OES;
+            glType = GL_UNSIGNED_SHORT_5_5_5_1;
             break;
         case HAL_PIXEL_FORMAT_RGBA_4444:
             bpp = 2;
             glFormat = GL_RGBA4_OES;
+            glType = GL_UNSIGNED_SHORT_4_4_4_4;
             break;
 
         default:
@@ -163,7 +170,7 @@
         *pStride = bpr / bpp;
     }
 
-    LOGD("gralloc_alloc ashmem_size=%d\n", ashmem_size);
+    LOGD("gralloc_alloc ashmem_size=%d, tid %d\n", ashmem_size, gettid());
 
     //
     // Allocate space in ashmem if needed
@@ -180,7 +187,8 @@
         }
     }
 
-    cb_handle_t *cb = new cb_handle_t(fd, ashmem_size, usage, w, h, glFormat);
+    cb_handle_t *cb = new cb_handle_t(fd, ashmem_size, usage,
+                                      w, h, glFormat, glType);
 
     if (ashmem_size > 0) {
         //
@@ -193,6 +201,8 @@
             delete cb;
             return err;
         }
+
+        cb->setFd(fd);
     }
 
     //
@@ -268,7 +278,7 @@
            n->next->prev = n->prev;
        }
        if (n->prev) {
-           n->prev = n->next;
+           n->prev->next = n->next;
        }
        else {
            grdev->allocListHead = n->next;
@@ -299,6 +309,11 @@
     return 0;
 }
 
+static int fb_compositionComplete(struct framebuffer_device_t* dev)
+{
+    return 0;
+}
+
 //
 // Framebuffer device functions
 //
@@ -548,7 +563,7 @@
         }
 
         if (cb->lockedWidth < cb->width || cb->lockedHeight < cb->height) {
-            int bpp = glUtilsPixelBitSize(cb->glFormat, GL_UNSIGNED_BYTE) >> 3;
+            int bpp = glUtilsPixelBitSize(cb->glFormat, cb->glType) >> 3;
             char *tmpBuf = new char[cb->lockedWidth * cb->lockedHeight * bpp];
 
             int dst_line_len = cb->lockedWidth * bpp;
@@ -564,7 +579,7 @@
             rcEnc->rcUpdateColorBuffer(rcEnc, cb->hostHandle,
                                        cb->lockedLeft, cb->lockedTop,
                                        cb->lockedWidth, cb->lockedHeight,
-                                       cb->glFormat, GL_UNSIGNED_BYTE,
+                                       cb->glFormat, cb->glType,
                                        tmpBuf);
 
             delete [] tmpBuf;
@@ -572,7 +587,7 @@
         else {
             rcEnc->rcUpdateColorBuffer(rcEnc, cb->hostHandle, 0, 0,
                                        cb->width, cb->height,
-                                       cb->glFormat, GL_UNSIGNED_BYTE,
+                                       cb->glFormat, cb->glType,
                                        cpu_addr);
         }
     }
@@ -650,6 +665,7 @@
         if (NULL == dev) {
             return -ENOMEM;
         }
+        memset(dev, 0, sizeof(fb_device_t));
 
         // Initialize our device structure
         //
@@ -659,7 +675,8 @@
         dev->device.common.close = fb_close;
         dev->device.setSwapInterval = fb_setSwapInterval;
         dev->device.post            = fb_post;
-        dev->device.setUpdateRect   = 0; //XXX: fb_setUpdateRect;
+        dev->device.setUpdateRect   = fb_setUpdateRect;
+        dev->device.compositionComplete = fb_compositionComplete; //XXX: this is a dummy
 
         const_cast<uint32_t&>(dev->device.flags) = 0;
         const_cast<uint32_t&>(dev->device.width) = width;
@@ -695,11 +712,15 @@
             id: GRALLOC_HARDWARE_MODULE_ID,
             name: "Graphics Memory Allocator Module",
             author: "The Android Open Source Project",
-            methods: &gralloc_module_methods
+            methods: &gralloc_module_methods,
+            dso: NULL,
+            reserved: {0, }
         },
         registerBuffer: gralloc_register_buffer,
         unregisterBuffer: gralloc_unregister_buffer,
         lock: gralloc_lock,
         unlock: gralloc_unlock,
+        perform: NULL,
+        reserved_proc : {NULL, }
     }
 };
diff --git a/tools/emulator/opengl/system/renderControl_enc/Android.mk b/tools/emulator/opengl/system/renderControl_enc/Android.mk
index 497ec81..96f15a2 100644
--- a/tools/emulator/opengl/system/renderControl_enc/Android.mk
+++ b/tools/emulator/opengl/system/renderControl_enc/Android.mk
@@ -1,38 +1,7 @@
 LOCAL_PATH := $(call my-dir)
 
-emulatorOpengl := $(LOCAL_PATH)/../..
-EMUGEN := $(HOST_OUT_EXECUTABLES)/emugen
-#### renderControl  ####
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES :=  
-LOCAL_MODULE_TAGS := debug
-LOCAL_MODULE := lib_renderControl_enc
-LOCAL_PRELINK_MODULE := false
-LOCAL_MODULE_CLASS := SHARED_LIBRARIES
-
-rc_intermediates := $(local-intermediates-dir)
-
-LOCAL_C_INCLUDES += $(emulatorOpengl)/shared/OpenglCodecCommon \
-                    $(emulatorOpengl)/host/include/libOpenglRender
-
-LOCAL_STATIC_LIBRARIES := \
-        libOpenglCodecCommon
-LOCAL_SHARED_LIBRARIES := libcutils
-
-RC_GEN := \
-	$(rc_intermediates)/renderControl_enc.cpp \
-	$(rc_intermediates)/renderControl_enc.h
-
-$(RC_GEN) : PRIVATE_PATH = $(LOCAL_PATH)
-$(RC_GEN) : PRIVATE_CUSTOM_TOOL := \
-        $(EMUGEN) -i $(PRIVATE_PATH) -E $(rc_intermediates) renderControl
-$(RC_GEN) : $(EMUGEN) \
-        $(LOCAL_PATH)/renderControl.in \
-        $(LOCAL_PATH)/renderControl.attrib \
-        $(LOCAL_PATH)/renderControl.types
-	$(transform-generated-source)
-
-LOCAL_GENERATED_SOURCES += $(RC_GEN)
-include $(BUILD_SHARED_LIBRARY)
-
+$(call emugl-begin-shared-library,lib_renderControl_enc)
+$(call emugl-gen-encoder,$(LOCAL_PATH),renderControl)
+$(call emugl-export,C_INCLUDES,$(LOCAL_PATH))
+$(call emugl-import,libOpenglCodecCommon)
+$(call emugl-end-module)
diff --git a/tools/emulator/opengl/system/renderControl_enc/README b/tools/emulator/opengl/system/renderControl_enc/README
index b8ffc49..df870f6 100644
--- a/tools/emulator/opengl/system/renderControl_enc/README
+++ b/tools/emulator/opengl/system/renderControl_enc/README
@@ -81,6 +81,9 @@
 void rcDestroyColorBuffer(uint32_t colorbuffer);
        destroyes a colorBuffer object.
 
+void rcFlushWindowColorBuffer(uint32_t windowSurface, uint32_t colorBuffer);
+	   This flushes the current window color buffer
+
 void rcSetWindowColorBuffer(uint32_t windowSurface, uint32_t colorBuffer);
        This set the target color buffer for a windowSurface, when set the
        previous target colorBuffer gets updated before switching to the new
diff --git a/tools/emulator/opengl/system/renderControl_enc/renderControl.attrib b/tools/emulator/opengl/system/renderControl_enc/renderControl.attrib
index a77d21f..4197d64 100644
--- a/tools/emulator/opengl/system/renderControl_enc/renderControl.attrib
+++ b/tools/emulator/opengl/system/renderControl_enc/renderControl.attrib
@@ -12,6 +12,10 @@
     dir buffer out
     len buffer bufferSize
 
+rcGetGLString
+    dir buffer out
+    len buffer bufferSize
+
 rcGetNumConfigs
     dir numAttribs out
     len numAttribs sizeof(uint32_t)
diff --git a/tools/emulator/opengl/system/renderControl_enc/renderControl.in b/tools/emulator/opengl/system/renderControl_enc/renderControl.in
index c91a662..37a8e90 100644
--- a/tools/emulator/opengl/system/renderControl_enc/renderControl.in
+++ b/tools/emulator/opengl/system/renderControl_enc/renderControl.in
@@ -1,6 +1,7 @@
 GL_ENRTY(GLint, rcGetRendererVersion)
 GL_ENTRY(EGLint, rcGetEGLVersion, EGLint *major, EGLint *minor)
 GL_ENTRY(EGLint, rcQueryEGLString, EGLenum name, void *buffer, EGLint bufferSize)
+GL_ENTRY(EGLint, rcGetGLString, EGLenum name, void *buffer, EGLint bufferSize)
 GL_ENTRY(EGLint, rcGetNumConfigs, uint32_t *numAttribs)
 GL_ENTRY(EGLint, rcGetConfigs, uint32_t bufSize, GLuint *buffer)
 GL_ENTRY(EGLint, rcChooseConfig, EGLint *attribs, uint32_t attribs_size, uint32_t *configs, uint32_t configs_size)
@@ -12,6 +13,7 @@
 GL_ENTRY(uint32_t, rcCreateColorBuffer, uint32_t width, uint32_t height, GLenum internalFormat)
 GL_ENTRY(void, rcDestroyColorBuffer, uint32_t colorbuffer)
 GL_ENTRY(void, rcSetWindowColorBuffer, uint32_t windowSurface, uint32_t colorBuffer)
+GL_ENTRY(void, rcFlushWindowColorBuffer, uint32_t windowSurface)
 GL_ENTRY(EGLint, rcMakeCurrent, uint32_t context, uint32_t drawSurf, uint32_t readSurf)
 GL_ENTRY(void, rcFBPost, uint32_t colorBuffer)
 GL_ENTRY(void, rcFBSetSwapInterval, EGLint interval)
diff --git a/tools/emulator/opengl/tests/EGL_host_wrapper/Android.mk b/tools/emulator/opengl/tests/EGL_host_wrapper/Android.mk
index d22be81..19d8794 100644
--- a/tools/emulator/opengl/tests/EGL_host_wrapper/Android.mk
+++ b/tools/emulator/opengl/tests/EGL_host_wrapper/Android.mk
@@ -2,19 +2,15 @@
 
 LOCAL_PATH := $(call my-dir)
 
-include $(CLEAR_VARS)
+$(call emugl-begin-host-static-library,libEGL_host_wrapper)
 
 LOCAL_SRC_FILES :=  \
         egl.cpp \
         egl_dispatch.cpp
 
-LOCAL_MODULE := libEGL_host_wrapper
-LOCAL_MODULE_TAGS := debug
+$(call emugl-export,LDLIBS,-ldl -pthread)
+$(call emugl-export,C_INCLUDES,$(LOCAL_PATH))
 
-OS_LDLIBS := -ldl -lpthread
+$(call emugl-end-module)
 
-LOCAL_LDLIBS := $(OS_LDLIBS)
-
-include $(BUILD_HOST_SHARED_LIBRARY) 
-
-endif # HOST_OS == linux
\ No newline at end of file
+endif # HOST_OS == linux
diff --git a/tools/emulator/opengl/tests/emulator_test_renderer/Android.mk b/tools/emulator/opengl/tests/emulator_test_renderer/Android.mk
index d0b9086..8ec1b9f 100644
--- a/tools/emulator/opengl/tests/emulator_test_renderer/Android.mk
+++ b/tools/emulator/opengl/tests/emulator_test_renderer/Android.mk
@@ -2,16 +2,11 @@
 
 # For now, OS X is not supported
 ifneq ($(HOST_OS),darwin)
-# test opengl renderer driver ###########################
-include $(CLEAR_VARS)
 
-emulatorOpengl := $(LOCAL_PATH)/../..
+$(call emugl-begin-host-executable,emulator_test_renderer)
+$(call emugl-import,libOpenglRender)
 
-LOCAL_MODULE := emulator_test_renderer
-LOCAL_MODULE_TAGS := debug
-
-LOCAL_SRC_FILES := \
-    main.cpp
+LOCAL_SRC_FILES := main.cpp
 
 PREBUILT := $(HOST_PREBUILT_TAG)
 SDL_CONFIG ?= prebuilt/$(PREBUILT)/sdl/bin/sdl-config
@@ -21,16 +16,8 @@
 LOCAL_CFLAGS += $(SDL_CFLAGS) -g -O0
 LOCAL_LDLIBS += $(SDL_LDLIBS)
 
-LOCAL_C_INCLUDES := $(emulatorOpengl)/host/include \
-                    $(emulatorOpengl)/host/include/libOpenglRender \
-                    $(emulatorOpengl)/shared/OpenglCodecCommon \
-                    $(emulatorOpengl)/host/libs/libOpenglRender
-
-LOCAL_SHARED_LIBRARIES := libOpenglRender \
-        libGLESv1_dec \
-        lib_renderControl_dec
-
 LOCAL_STATIC_LIBRARIES += libSDL libSDLmain
 
-include $(BUILD_HOST_EXECUTABLE)
+$(call emugl-end-module)
+
 endif # HOST_OS != darwin
diff --git a/tools/emulator/opengl/tests/emulator_test_renderer/main.cpp b/tools/emulator/opengl/tests/emulator_test_renderer/main.cpp
index 744acf4..898cbd7 100644
--- a/tools/emulator/opengl/tests/emulator_test_renderer/main.cpp
+++ b/tools/emulator/opengl/tests/emulator_test_renderer/main.cpp
@@ -26,7 +26,7 @@
 int main(int argc, char *argv[])
 #endif
 {
-    int portNum = 4141;
+    int portNum = 22468;
     int winWidth = 320;
     int winHeight = 480;
     FBNativeWindowType windowId = NULL;
diff --git a/tools/emulator/opengl/tests/gles_android_wrapper/Android.mk b/tools/emulator/opengl/tests/gles_android_wrapper/Android.mk
index ad85036..ad38c4d 100644
--- a/tools/emulator/opengl/tests/gles_android_wrapper/Android.mk
+++ b/tools/emulator/opengl/tests/gles_android_wrapper/Android.mk
@@ -1,5 +1,15 @@
 LOCAL_PATH := $(call my-dir)
 
+#### libGLESv1_CM_emul.so
+$(call emugl-begin-shared-library,libGLESv1_CM_emul)
+$(call emugl-import,libGLESv1_enc)
+$(call emugl-gen-wrapper,$(EMUGL_PATH)/system/GLESv1_enc,gl)
+$(call emugl-set-shared-library-subpath,egl)
+
+LOCAL_SRC_FILES += glesv1_emul_ifc.cpp
+
+$(call emugl-end-module)
+
 emulatorOpengl := $(LOCAL_PATH)/../..
 logTag := -DLOG_TAG=\"eglWrapper\"
 EMUGEN = $(BUILD_OUT_EXECUTABLES)/emugen
@@ -7,80 +17,104 @@
 #debugFlags = -g -O0
 
 #### libGLESv1_CM_emul.so
-include $(CLEAR_VARS)
-
-
-
-LOCAL_MODULE := libGLESv1_CM_emul
-LOCAL_MODULE_PATH := $(TARGET_OUT_SHARED_LIBRARIES)/egl
-LOCAL_MODULE_CLASS := SHARED_LIBRARIES
-LOCAL_SRC_FILES := glesv1_emul_ifc.cpp
-
-LOCAL_PRELINK_MODULE := false
-LOCAL_MODULE_TAGS := debug
-LOCAL_SHARED_LIBRARIES := libdl libcutils
-LOCAL_CFLAGS += $(debugFlags)
-
-LOCAL_C_INCLUDES += \
-	$(emulatorOpengl)/system/GLESv1_enc \
-	$(emulatorOpengl)/shared/OpenglCodecCommon
-
-glesv1_emul_intermediates := $(local-intermediates-dir)
-
-GEN_GLESv1_emul := \
-	$(glesv1_emul_intermediates)/gl_wrapper_entry.cpp \
-	$(glesv1_emul_intermediates)/gl_wrapper_context.cpp
-$(GEN_GLESv1_emul) : PRIVATE_PATH := $(LOCAL_PATH)
-$(GEN_GLESv1_emul) : PRIVATE_CUSTOM_TOOL := \
-	$(EMUGEN) -W $(glesv1_emul_intermediates) -i $(emulatorOpengl)/system/GLESv1_enc gl
-$(GEN_GLESv1_emul) : $(EMUGEN) \
-	$(emulatorOpengl)/system/GLESv1_enc/gl.in \
-	$(emulatorOpengl)/system/GLESv1_enc/gl.attrib \
-	$(emulatorOpengl)/system/GLESv1_enc/gl.types
-	$(transform-generated-source)
-
-LOCAL_GENERATED_SOURCES += $(GEN_GLESv1_emul)
-
-include $(BUILD_SHARED_LIBRARY)
+# include $(CLEAR_VARS)
+#
+#
+#
+# LOCAL_MODULE := libGLESv1_CM_emul
+# LOCAL_MODULE_PATH := $(TARGET_OUT_SHARED_LIBRARIES)/egl
+# LOCAL_MODULE_CLASS := SHARED_LIBRARIES
+# LOCAL_SRC_FILES := glesv1_emul_ifc.cpp
+#
+# LOCAL_PRELINK_MODULE := false
+# LOCAL_MODULE_TAGS := debug
+# LOCAL_SHARED_LIBRARIES := libdl libcutils
+# LOCAL_CFLAGS += $(debugFlags)
+#
+# LOCAL_C_INCLUDES += \
+# 	$(emulatorOpengl)/system/GLESv1_enc \
+# 	$(emulatorOpengl)/shared/OpenglCodecCommon
+#
+# glesv1_emul_intermediates := $(local-intermediates-dir)
+#
+# GEN_GLESv1_emul := \
+# 	$(glesv1_emul_intermediates)/gl_wrapper_entry.cpp \
+# 	$(glesv1_emul_intermediates)/gl_wrapper_context.cpp
+# $(GEN_GLESv1_emul) : PRIVATE_PATH := $(LOCAL_PATH)
+# $(GEN_GLESv1_emul) : PRIVATE_CUSTOM_TOOL := \
+# 	$(EMUGEN) -W $(glesv1_emul_intermediates) -i $(emulatorOpengl)/system/GLESv1_enc gl
+# $(GEN_GLESv1_emul) : $(EMUGEN) \
+# 	$(emulatorOpengl)/system/GLESv1_enc/gl.in \
+# 	$(emulatorOpengl)/system/GLESv1_enc/gl.attrib \
+# 	$(emulatorOpengl)/system/GLESv1_enc/gl.types
+# 	$(transform-generated-source)
+#
+# LOCAL_GENERATED_SOURCES += $(GEN_GLESv1_emul)
+#
+# include $(BUILD_SHARED_LIBRARY)
 
 #### libGLESv2_CM_emul.so
-include $(CLEAR_VARS)
+$(call emugl-begin-shared-library, libGLESv2_emul)
+$(call emugl-import,libGLESv2_enc)
+$(call emugl-gen-wrapper,$(EMUGL_PATH)/system/GLESv2_enc,gl2)
+LOCAL_SRC_FILES += glesv2_emul_ifc.cpp
+$(call emugl-set-shared-library-subpath,egl)
+$(call emugl-end-module)
 
-LOCAL_MODULE := libGLESv2_emul
-LOCAL_MODULE_PATH := $(TARGET_OUT_SHARED_LIBRARIES)/egl
-LOCAL_MODULE_CLASS := SHARED_LIBRARIES
-LOCAL_SRC_FILES := glesv2_emul_ifc.cpp
-
-LOCAL_PRELINK_MODULE := false
-LOCAL_MODULE_TAGS := debug
-LOCAL_SHARED_LIBRARIES := libdl libcutils
-LOCAL_CFLAGS += $(debugFlags)
-
-LOCAL_C_INCLUDES += \
-	$(emulatorOpengl)/system/GLESv2_enc \
-	$(emulatorOpengl)/shared/OpenglCodecCommon
-
-glesv2_emul_intermediates := $(local-intermediates-dir)
-
-GEN_GLESv2_emul := \
-	$(glesv2_emul_intermediates)/gl2_wrapper_entry.cpp \
-	$(glesv2_emul_intermediates)/gl2_wrapper_context.cpp
-
-$(GEN_GLESv2_emul) : PRIVATE_PATH := $(LOCAL_PATH)
-$(GEN_GLESv2_emul) : PRIVATE_CUSTOM_TOOL := \
-	$(EMUGEN) -W $(glesv2_emul_intermediates) -i $(emulatorOpengl)/system/GLESv2_enc gl2
-$(GEN_GLESv2_emul) : $(EMUGEN) \
-	$(emulatorOpengl)/system/GLESv2_enc/gl2.in \
-	$(emulatorOpengl)/system/GLESv2_enc/gl2.attrib \
-	$(emulatorOpengl)/system/GLESv2_enc/gl2.types
-	$(transform-generated-source)
-
-LOCAL_GENERATED_SOURCES += $(GEN_GLESv2_emul)
-
-include $(BUILD_SHARED_LIBRARY)
+# include $(CLEAR_VARS)
+#
+# LOCAL_MODULE := libGLESv2_emul
+# LOCAL_MODULE_PATH := $(TARGET_OUT_SHARED_LIBRARIES)/egl
+# LOCAL_MODULE_CLASS := SHARED_LIBRARIES
+# LOCAL_SRC_FILES := glesv2_emul_ifc.cpp
+#
+# LOCAL_PRELINK_MODULE := false
+# LOCAL_MODULE_TAGS := debug
+# LOCAL_SHARED_LIBRARIES := libdl libcutils
+# LOCAL_CFLAGS += $(debugFlags)
+#
+# LOCAL_C_INCLUDES += \
+# 	$(emulatorOpengl)/system/GLESv2_enc \
+# 	$(emulatorOpengl)/shared/OpenglCodecCommon
+#
+# glesv2_emul_intermediates := $(local-intermediates-dir)
+#
+# GEN_GLESv2_emul := \
+# 	$(glesv2_emul_intermediates)/gl2_wrapper_entry.cpp \
+# 	$(glesv2_emul_intermediates)/gl2_wrapper_context.cpp
+#
+# $(GEN_GLESv2_emul) : PRIVATE_PATH := $(LOCAL_PATH)
+# $(GEN_GLESv2_emul) : PRIVATE_CUSTOM_TOOL := \
+# 	$(EMUGEN) -W $(glesv2_emul_intermediates) -i $(emulatorOpengl)/system/GLESv2_enc gl2
+# $(GEN_GLESv2_emul) : $(EMUGEN) \
+# 	$(emulatorOpengl)/system/GLESv2_enc/gl2.in \
+# 	$(emulatorOpengl)/system/GLESv2_enc/gl2.attrib \
+# 	$(emulatorOpengl)/system/GLESv2_enc/gl2.types
+# 	$(transform-generated-source)
+#
+# LOCAL_GENERATED_SOURCES += $(GEN_GLESv2_emul)
+#
+# include $(BUILD_SHARED_LIBRARY)
 
 
 ##### libEGL_emul.so ###########
+
+# THE FOLLOWING DOESN'T WORK YET
+#
+# $(call emugl-begin-shared-library,libEGL_emul)
+# $(call emugl-import,libut_rendercontrol_enc libGLESv1_enc libGLESv2_enc libOpenglSystemCommon)
+#
+# $(call emugl-set-shared-library-subpath,egl)
+# LOCAL_CFLAGS += $(logTag)
+#
+# LOCAL_SRC_FILES :=  \
+#         egl.cpp \
+#         egl_dispatch.cpp \
+#         ServerConnection.cpp \
+#         ThreadInfo.cpp
+#
+# $(call emugl-end-module)
+
 include $(CLEAR_VARS)
 
 LOCAL_SRC_FILES :=  \
@@ -127,8 +161,11 @@
 	libcutils \
 	libGLESv1_enc \
 	libGLESv2_enc \
+	libOpenglSystemCommon \
 	libut_rendercontrol_enc
-LOCAL_STATIC_LIBRARIES := libOpenglCodecCommon libOpenglSystemCommon libqemu
+
+LOCAL_STATIC_LIBRARIES := libOpenglCodecCommon \
+						  libqemu
 
 include $(BUILD_SHARED_LIBRARY)
 
@@ -139,6 +176,7 @@
 # version of this file to point to the appropriate HW EGL libraries.
 #
 ifneq (,$(filter full full_x86 sdk sdk_x86,$(TARGET_PRODUCT)))
+ifeq (,$(BUILD_EMULATOR_OPENGL_DRIVER))
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := egl.cfg
@@ -149,6 +187,7 @@
 LOCAL_MODULE_CLASS := ETC
 
 include $(BUILD_PREBUILT)
+endif # building 'real' driver BUILD_EMULATOR_OPENGL_DRIVER
 endif # TARGET_PRODUCT in 'full sdk full_x86 sdk_x86'
 
 #### gles_emul.cfg ####
diff --git a/tools/emulator/opengl/tests/translator_tests/GLES_CM/Android.mk b/tools/emulator/opengl/tests/translator_tests/GLES_CM/Android.mk
index a411ccf..c1cda0a 100644
--- a/tools/emulator/opengl/tests/translator_tests/GLES_CM/Android.mk
+++ b/tools/emulator/opengl/tests/translator_tests/GLES_CM/Android.mk
@@ -1,7 +1,7 @@
 LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
 
-translator_path := $(LOCAL_PATH)/../../../host/libs/Translator
+$(call emugl-begin-host-executable,triangleCM)
+$(call emugl-import,libEGL_translator libGLES_CM_translator)
 
 PREBUILT := $(HOST_PREBUILT_TAG)
 SDL_CONFIG ?= prebuilt/$(PREBUILT)/sdl/bin/sdl-config
@@ -11,27 +11,50 @@
 LOCAL_SRC_FILES:= \
         triangleCM.cpp
 
-
-LOCAL_SHARED_LIBRARIES := \
-    libEGL_translator     \
-    libGLES_CM_translator
-
 LOCAL_CFLAGS += $(SDL_CFLAGS) -g -O0
 LOCAL_LDLIBS += $(SDL_LDLIBS)
 
-
-LOCAL_MODULE:= triangleCM
-LOCAL_MODULE_TAGS := debug
-LOCAL_STATIC_LIBRARIES += libSDL libSDLmain 
+LOCAL_STATIC_LIBRARIES += libSDL libSDLmain
 
 ifeq ($(HOST_OS),darwin)
-
-LOCAL_LDLIBS += -Wl,-framework,AudioToolbox -Wl,-framework,AudioUnit
-LOCAL_STATIC_LIBRARIES += libMac_view
-LOCAL_C_INCLUDES += \
-                 $(LOCAL_PATH)/../MacCommon \
-                 $(translator_path)/include 
+$(call emugl-import,libMac_view)
 endif
 
-include $(BUILD_HOST_EXECUTABLE)
+$(call emugl-end-module)
+
+# include $(CLEAR_VARS)
+#
+# translator_path := $(LOCAL_PATH)/../../../host/libs/Translator
+#
+# PREBUILT := $(HOST_PREBUILT_TAG)
+# SDL_CONFIG ?= prebuilt/$(PREBUILT)/sdl/bin/sdl-config
+# SDL_CFLAGS := $(shell $(SDL_CONFIG) --cflags)
+# SDL_LDLIBS := $(filter-out %.a %.lib,$(shell $(SDL_CONFIG) --static-libs))
+#
+# LOCAL_SRC_FILES:= \
+#         triangleCM.cpp
+#
+#
+# LOCAL_SHARED_LIBRARIES := \
+#     libEGL_translator     \
+#     libGLES_CM_translator
+#
+# LOCAL_CFLAGS += $(SDL_CFLAGS) -g -O0
+# LOCAL_LDLIBS += $(SDL_LDLIBS)
+#
+#
+# LOCAL_MODULE:= triangleCM
+# LOCAL_MODULE_TAGS := debug
+# LOCAL_STATIC_LIBRARIES += libSDL libSDLmain
+#
+# ifeq ($(HOST_OS),darwin)
+#
+# LOCAL_LDLIBS += -Wl,-framework,AudioToolbox -Wl,-framework,AudioUnit
+# LOCAL_STATIC_LIBRARIES += libMac_view
+# LOCAL_C_INCLUDES += \
+#                  $(LOCAL_PATH)/../MacCommon \
+#                  $(translator_path)/include
+# endif
+#
+# include $(BUILD_HOST_EXECUTABLE)
 
diff --git a/tools/emulator/opengl/tests/translator_tests/GLES_V2/Android.mk b/tools/emulator/opengl/tests/translator_tests/GLES_V2/Android.mk
index 5cb5c4a..8edea7a 100644
--- a/tools/emulator/opengl/tests/translator_tests/GLES_V2/Android.mk
+++ b/tools/emulator/opengl/tests/translator_tests/GLES_V2/Android.mk
@@ -1,7 +1,7 @@
 LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
 
-translator_path := $(LOCAL_PATH)/../../../host/libs/Translator
+$(call emugl-begin-host-executable,triangleV2)
+$(call emugl-import,libEGL_translator libGLES_V2_translator)
 
 PREBUILT := $(HOST_PREBUILT_TAG)
 SDL_CONFIG ?= prebuilt/$(PREBUILT)/sdl/bin/sdl-config
@@ -11,28 +11,51 @@
 LOCAL_SRC_FILES:= \
         triangleV2.cpp
 
-
-LOCAL_SHARED_LIBRARIES := \
-    libEGL_translator     \
-    libGLES_V2_translator
-
 LOCAL_CFLAGS += $(SDL_CFLAGS) -g -O0
 LOCAL_LDLIBS += $(SDL_LDLIBS)
 
-
-LOCAL_MODULE:= triangleV2
-LOCAL_MODULE_TAGS := debug
 LOCAL_STATIC_LIBRARIES += libSDL libSDLmain
 
 ifeq ($(HOST_OS),darwin)
-
-LOCAL_LDLIBS += -Wl,-framework,AudioToolbox -Wl,-framework,AudioUnit
-LOCAL_C_INCLUDES += \
-                 $(translator_path)/include \
-                 $(LOCAL_PATH)/../MacCommon
-LOCAL_STATIC_LIBRARIES += libMac_view
-
+$(call emugl-import,libMac_view)
 endif
 
-include $(BUILD_HOST_EXECUTABLE)
+$(call emugl-end-module)
+
+# include $(CLEAR_VARS)
+#
+# translator_path := $(LOCAL_PATH)/../../../host/libs/Translator
+#
+# PREBUILT := $(HOST_PREBUILT_TAG)
+# SDL_CONFIG ?= prebuilt/$(PREBUILT)/sdl/bin/sdl-config
+# SDL_CFLAGS := $(shell $(SDL_CONFIG) --cflags)
+# SDL_LDLIBS := $(filter-out %.a %.lib,$(shell $(SDL_CONFIG) --static-libs))
+#
+# LOCAL_SRC_FILES:= \
+#         triangleV2.cpp
+#
+#
+# LOCAL_SHARED_LIBRARIES := \
+#     libEGL_translator     \
+#     libGLES_V2_translator
+#
+# LOCAL_CFLAGS += $(SDL_CFLAGS) -g -O0
+# LOCAL_LDLIBS += $(SDL_LDLIBS)
+#
+#
+# LOCAL_MODULE:= triangleV2
+# LOCAL_MODULE_TAGS := debug
+# LOCAL_STATIC_LIBRARIES += libSDL libSDLmain
+#
+# ifeq ($(HOST_OS),darwin)
+#
+# LOCAL_LDLIBS += -Wl,-framework,AudioToolbox -Wl,-framework,AudioUnit
+# LOCAL_C_INCLUDES += \
+#                  $(translator_path)/include \
+#                  $(LOCAL_PATH)/../MacCommon
+# LOCAL_STATIC_LIBRARIES += libMac_view
+#
+# endif
+#
+# include $(BUILD_HOST_EXECUTABLE)
 
diff --git a/tools/emulator/opengl/tests/translator_tests/MacCommon/Android.mk b/tools/emulator/opengl/tests/translator_tests/MacCommon/Android.mk
index e72ed82..6e849a1 100644
--- a/tools/emulator/opengl/tests/translator_tests/MacCommon/Android.mk
+++ b/tools/emulator/opengl/tests/translator_tests/MacCommon/Android.mk
@@ -1,20 +1,30 @@
-
 LOCAL_PATH := $(call my-dir)
 
 ifeq ($(HOST_OS),darwin)
-include $(CLEAR_VARS)
+$(call emugl-begin-host-static-library,libMac_view)
 
+LIBMACVIEW_FRAMEWORKS := AppKit AudioToolbox AudioUnit
+LIBMACVIEW_PREFIX := -Wl,-framework,
 
-LOCAL_LDLIBS := -Wl,-framework,AppKit
+$(call emugl-export,LDLIBS,$(foreach _framework,$(LIBMACVIEW_FRAMEWORKS),$(LIBMACVIEW_PREFIX)$(_framework)))
+LOCAL_SRC_FILES := setup_gl.m
+LOCAL_CFLAGS += -g -O0
+$(call emugl-end-module)
+endif # HOST_OS == darwin
 
-LOCAL_SRC_FILES :=  setup_gl.m
-
-
-
-LOCAL_CFLAGS := -g -O0
-LOCAL_MODULE_TAGS := debug
-LOCAL_MODULE := libMac_view
-
-
-include $(BUILD_HOST_STATIC_LIBRARY)
-endif
+# include $(CLEAR_VARS)
+#
+#
+# LOCAL_LDLIBS := -Wl,-framework,AppKit
+#
+# LOCAL_SRC_FILES :=  setup_gl.m
+#
+#
+#
+# LOCAL_CFLAGS := -g -O0
+# LOCAL_MODULE_TAGS := debug
+# LOCAL_MODULE := libMac_view
+#
+#
+# include $(BUILD_HOST_STATIC_LIBRARY)
+# endif
diff --git a/tools/emulator/opengl/tests/ut_rendercontrol_dec/Android.mk b/tools/emulator/opengl/tests/ut_rendercontrol_dec/Android.mk
index 673fd11..a5a01e8 100644
--- a/tools/emulator/opengl/tests/ut_rendercontrol_dec/Android.mk
+++ b/tools/emulator/opengl/tests/ut_rendercontrol_dec/Android.mk
@@ -1,38 +1,7 @@
-
 LOCAL_PATH := $(call my-dir)
 
-### ut_rendercontrol Decoder ###########################################
-include $(CLEAR_VARS)
-
-emulatorOpengl := $(LOCAL_PATH)/../..
-EMUGEN := $(HOST_OUT_EXECUTABLES)/emugen
-
-LOCAL_IS_HOST_MODULE := true
-LOCAL_MODULE_CLASS := SHARED_LIBRARIES
-LOCAL_MODULE_TAGS := debug
-LOCAL_MODULE := libut_rendercontrol_dec
-LOCAL_SRC_FILES := 
-#LOCAL_CFLAGS += -DDEBUG_PRINTOUT -O0 -g
-intermediates := $(local-intermediates-dir)
-
-LOCAL_STATIC_LIBRARIES := \
-	libOpenglCodecCommon \
-    liblog
-
-LOCAL_C_INCLUDES += \
-    $(emulatorOpengl)/shared/OpenglCodecCommon \
-    $(emulatorOpengl)/host/include/libOpenglRender \
-    $(emulatorOpengl)/tests/ut_rendercontrol_enc
-
-#we use only *_dec.h as a sentinel for the other generated headers
-GEN := $(intermediates)/ut_rendercontrol_dec.cpp $(intermediates)/ut_rendercontrol_dec.h
-$(GEN): PRIVATE_PATH := $(LOCAL_PATH)
-$(GEN): PRIVATE_CUSTOM_TOOL := $(EMUGEN) -D $(intermediates) -i $(emulatorOpengl)/tests/ut_rendercontrol_enc ut_rendercontrol
-$(GEN): $(EMUGEN) \
-	$(emulatorOpengl)/tests/ut_rendercontrol_enc/ut_rendercontrol.attrib \
-	$(emulatorOpengl)/tests/ut_rendercontrol_enc/ut_rendercontrol.in \
-	$(emulatorOpengl)/tests/ut_rendercontrol_enc/ut_rendercontrol.types
-	$(transform-generated-source)
-
-LOCAL_GENERATED_SOURCES += $(GEN)
-include $(BUILD_HOST_SHARED_LIBRARY)
+$(call emugl-begin-host-shared-library,libut_rendercontrol_dec)
+$(call emugl-import, libOpenglCodecCommon)
+$(call emugl-gen-decoder,$(EMUGL_PATH)/tests/ut_rendercontrol_enc,ut_rendercontrol)
+$(call emugl-export,C_INCLUDES,$(EMUGL_PATH)/tests/ut_rendercontrol_enc)
+$(call emugl-end-module)
diff --git a/tools/emulator/opengl/tests/ut_rendercontrol_enc/Android.mk b/tools/emulator/opengl/tests/ut_rendercontrol_enc/Android.mk
index 29a4857..ae234b2 100644
--- a/tools/emulator/opengl/tests/ut_rendercontrol_enc/Android.mk
+++ b/tools/emulator/opengl/tests/ut_rendercontrol_enc/Android.mk
@@ -1,39 +1,8 @@
 LOCAL_PATH := $(call my-dir)
 
-emulatorOpengl := $(LOCAL_PATH)/../..
-EMUGEN := $(BUILD_OUT_EXECUTABLES)/emugen
-#### ut_rendercontrol  ####
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES :=  
-LOCAL_MODULE_TAGS := debug
-LOCAL_MODULE := libut_rendercontrol_enc
-LOCAL_PRELINK_MODULE := false
-LOCAL_MODULE_CLASS := SHARED_LIBRARIES
-
-ut_intermediates := $(local-intermediates-dir)
-
-LOCAL_C_INCLUDES += \
-    $(emulatorOpengl)/shared/OpenglCodecCommon \
-    $(emulatorOpengl)/host/include/libOpenglRender
-
-LOCAL_STATIC_LIBRARIES := \
-        libOpenglCodecCommon
-LOCAL_SHARED_LIBRARIES := libcutils
-
-UT_GEN := \
-	$(ut_intermediates)/ut_rendercontrol_enc.cpp \
-	$(ut_intermediates)/ut_rendercontrol_enc.h
-
-$(UT_GEN) : PRIVATE_PATH = $(LOCAL_PATH)
-$(UT_GEN) : PRIVATE_CUSTOM_TOOL := \
-        $(EMUGEN) -i $(PRIVATE_PATH) -E $(ut_intermediates) ut_rendercontrol
-$(UT_GEN) : $(EMUGEN) \
-        $(LOCAL_PATH)/ut_rendercontrol.in \
-        $(LOCAL_PATH)/ut_rendercontrol.attrib \
-        $(LOCAL_PATH)/ut_rendercontrol.types
-	$(transform-generated-source)
-
-LOCAL_GENERATED_SOURCES += $(UT_GEN)
-include $(BUILD_SHARED_LIBRARY)
+$(call emugl-begin-shared-library,libut_rendercontrol_enc)
+$(call emugl-import,libOpenglCodecCommon)
+$(call emugl-gen-encoder,$(LOCAL_PATH),ut_rendercontrol)
+$(call emugl-export,C_INCLUDES,$(LOCAL_PATH))
+$(call emugl-end-module)
 
diff --git a/tools/emulator/opengl/tests/ut_renderer/Android.mk b/tools/emulator/opengl/tests/ut_renderer/Android.mk
index e4c43a2..fe8e7ac 100644
--- a/tools/emulator/opengl/tests/ut_renderer/Android.mk
+++ b/tools/emulator/opengl/tests/ut_renderer/Android.mk
@@ -1,29 +1,9 @@
-# Building this module breaks the Linux build because
-# libxcb.so is not installed in the i686-linux-glibc2.7-4.4.3
-# prebuilt sysroot. Since rebuilding it will take some time, here's a
-# quick fix to unbreak it.
-#
-ifneq (,$(BUILD_EMULATOR_OPENGL))
-
 LOCAL_PATH:=$(call my-dir)
 
-# ut_renderer test program ###########################
-
-include $(CLEAR_VARS)
-
 ifeq ($(HOST_OS), linux)
 
-emulatorOpengl := $(LOCAL_PATH)/../..
-
-LOCAL_MODULE := ut_renderer
-LOCAL_MODULE_TAGS := debug
-
-# add additional depencies to ensure that the generated code that we depend on
-# is generated
-LOCAL_ADDITIONAL_DEPENDENCIES := \
-	$(HOST_OUT_SHARED_LIBRARIES)/libut_rendercontrol_dec$(HOST_SHLIB_SUFFIX) \
-	$(HOST_OUT_SHARED_LIBRARIES)/libGLESv1_dec$(HOST_SHLIB_SUFFIX) \
-	$(HOST_OUT_SHARED_LIBRARIES)/libGLESv2_dec$(HOST_SHLIB_SUFFIX)
+$(call emugl-begin-host-executable,ut_renderer)
+$(call emugl-import,libut_rendercontrol_dec libGLESv1_dec libGLESv2_dec libEGL_host_wrapper)
 
 LOCAL_SRC_FILES := ut_renderer.cpp \
         RenderingThread.cpp \
@@ -31,38 +11,20 @@
 	Renderer.cpp \
 	RendererContext.cpp \
 	RendererSurface.cpp \
-	X11Windowing.cpp 
+	X11Windowing.cpp
 
 # define PVR_WAR to support imgtec PVR opengl-ES implementation
 #
-# specifically this MACRO enables code that work arounds a bug 
+# specifically this MACRO enables code that work arounds a bug
 # in the implementation where glTextureParameter(...,GL_TEXTURE_RECT,...)
-# is called would cause a crash if the texture dimensions have not been 
+# is called would cause a crash if the texture dimensions have not been
 # defined yet.
 
-LOCAL_CFLAGS := -DPVR_WAR 
+LOCAL_CFLAGS += -DPVR_WAR
 #LOCAL_CFLAGS += -g -O0
 
-LOCAL_C_INCLUDES := $(emulatorOpengl)/shared/OpenglCodecCommon \
-	$(emulatorOpengl)/shared \
-        $(emulatorOpengl)/host/include/libOpenglRender \
-	$(call intermediates-dir-for, SHARED_LIBRARIES, libut_rendercontrol_dec, HOST) \
-	$(call intermediates-dir-for, SHARED_LIBRARIES, libGLESv1_dec, HOST) \
-	$(call intermediates-dir-for, SHARED_LIBRARIES, libGLESv2_dec, HOST) \
-        $(emulatorOpengl)/host/libs/GLESv1_dec \
-        $(emulatorOpengl)/host/libs/GLESv2_dec \
-        $(emulatorOpengl)/system/GLESv1_enc \
-        $(emulatorOpengl)/system/GLESv2_enc \
-        $(emulatorOpengl)/tests/ut_rendercontrol_enc
+LOCAL_LDLIBS += -lpthread -lX11 -lrt
 
-LOCAL_SHARED_LIBRARIES := libut_rendercontrol_dec libGLESv1_dec libGLESv2_dec libEGL_host_wrapper
-LOCAL_STATIC_LIBRARIES := \
-    libOpenglCodecCommon \
-    libcutils
-
-LOCAL_LDLIBS := -lpthread -lX11 -lrt
-include $(BUILD_HOST_EXECUTABLE)
+$(call emugl-end-module)
 
 endif # HOST_OS == linux
-
-endif # BUILD_EMULATOR_OPENGL
diff --git a/tools/emulator/opengl/tests/ut_renderer/RendererContext.cpp b/tools/emulator/opengl/tests/ut_renderer/RendererContext.cpp
index 26f2e35..0f93acd 100644
--- a/tools/emulator/opengl/tests/ut_renderer/RendererContext.cpp
+++ b/tools/emulator/opengl/tests/ut_renderer/RendererContext.cpp
@@ -56,7 +56,7 @@
     return m_tex2DBind[m_activeTexture];
 }
 
-void RendererContext::addPendingCropRect(int *rect)
+void RendererContext::addPendingCropRect(const int *rect)
 {
     PendingCropRect *r = new PendingCropRect;
     r->texture = m_tex2DBind[m_activeTexture];
diff --git a/tools/emulator/opengl/tests/ut_renderer/RendererContext.h b/tools/emulator/opengl/tests/ut_renderer/RendererContext.h
index 6daf918..bb24a2e 100644
--- a/tools/emulator/opengl/tests/ut_renderer/RendererContext.h
+++ b/tools/emulator/opengl/tests/ut_renderer/RendererContext.h
@@ -51,7 +51,7 @@
     }
     bool isTex2DEnable(int texunit) { return m_tex2DEnable[texunit]; }
     GLuint getTex2DBind();
-    void addPendingCropRect(int *rect);
+    void addPendingCropRect(const int *rect);
     PendingCropRectSet &getPendingCropRects() { return m_pendingCropRects; }
 
     void setClientActiveTexture(GLenum texture) { m_clientActiveTexture = texture - GL_TEXTURE0; }
diff --git a/tools/emulator/opengl/tests/ut_renderer/RenderingThread.cpp b/tools/emulator/opengl/tests/ut_renderer/RenderingThread.cpp
index 546c62d..ddd8405 100644
--- a/tools/emulator/opengl/tests/ut_renderer/RenderingThread.cpp
+++ b/tools/emulator/opengl/tests/ut_renderer/RenderingThread.cpp
@@ -27,7 +27,7 @@
 __thread RenderingThread * RenderingThread::m_tls;
 
 #ifdef PVR_WAR
-void RenderingThread::s_glTexParameteriv(GLenum target, GLenum param, int *p)
+void RenderingThread::s_glTexParameteriv(GLenum target, GLenum param, const int *p)
 {
     if (target == GL_TEXTURE_2D && param == GL_TEXTURE_CROP_RECT_OES) {
         m_tls->m_currentContext->addPendingCropRect(p);
@@ -64,28 +64,28 @@
     m_tls->fixTextureEnable();
 }
 
-void RenderingThread::s_glDrawTexfvOES(GLfloat *coords)
+void RenderingThread::s_glDrawTexfvOES(const GLfloat *coords)
 {
     m_tls->applyPendingCropRects();
     m_tls->m_glDrawTexfvOES(coords);
     m_tls->fixTextureEnable();
 }
 
-void RenderingThread::s_glDrawTexsvOES(GLshort *coords)
+void RenderingThread::s_glDrawTexsvOES(const GLshort *coords)
 {
     m_tls->applyPendingCropRects();
     m_tls->m_glDrawTexsvOES(coords);
     m_tls->fixTextureEnable();
 }
 
-void RenderingThread::s_glDrawTexivOES(GLint *coords)
+void RenderingThread::s_glDrawTexivOES(const GLint *coords)
 {
     m_tls->applyPendingCropRects();
     m_tls->m_glDrawTexivOES(coords);
     m_tls->fixTextureEnable();
 }
 
-void RenderingThread::s_glDrawTexxvOES(GLfixed *coords)
+void RenderingThread::s_glDrawTexxvOES(const GLfixed *coords)
 {
     m_tls->applyPendingCropRects();
     m_tls->m_glDrawTexxvOES(coords);
diff --git a/tools/emulator/opengl/tests/ut_renderer/RenderingThread.h b/tools/emulator/opengl/tests/ut_renderer/RenderingThread.h
index ca8f6f4..549d4af 100644
--- a/tools/emulator/opengl/tests/ut_renderer/RenderingThread.h
+++ b/tools/emulator/opengl/tests/ut_renderer/RenderingThread.h
@@ -73,15 +73,15 @@
     static int s_makeCurrent(uint32_t pid, uint32_t drawSurface, uint32_t readSurface, uint32_t ctx);
     static void s_swapBuffers(uint32_t pid, uint32_t surface);
 #ifdef PVR_WAR
-    static void s_glTexParameteriv(GLenum target, GLenum param, int *p);
+    static void s_glTexParameteriv(GLenum target, GLenum param, const int *p);
     static void s_glDrawTexfOES(GLfloat x, GLfloat y, GLfloat z, GLfloat w, GLfloat h);
     static void s_glDrawTexsOES(GLshort x, GLshort y, GLshort z, GLshort w, GLshort h);
     static void s_glDrawTexiOES(GLint x, GLint y, GLint z, GLint w, GLint h);
     static void s_glDrawTexxOES(GLfixed x, GLfixed y, GLfixed z, GLfixed w, GLfixed h);
-    static void s_glDrawTexfvOES(GLfloat *coords);
-    static void s_glDrawTexsvOES(GLshort *coords);
-    static void s_glDrawTexivOES(GLint *coords);
-    static void s_glDrawTexxvOES(GLfixed *coords);
+    static void s_glDrawTexfvOES(const GLfloat *coords);
+    static void s_glDrawTexsvOES(const GLshort *coords);
+    static void s_glDrawTexivOES(const GLint *coords);
+    static void s_glDrawTexxvOES(const GLfixed *coords);
 
     static void s_glActiveTexture(GLenum texture);
     static void s_glBindTexture(GLenum target, GLuint texture);